<commit_before>//helper by Michael Leonffu

module.exports = {
	generateUniqueList: function(data){

		// data = [
		// 	{
		// 		teams:{
		// 			red1: 123,
		// 			red2: 123,
		// 			blue1: 123,
		// 			blue2: 123
		// 		}
		// 	}
		// ]

		var uniqueList = []
		for (var i = 0; i < data.length; i++) {
			if(-1 == uniqueList.indexOf(String(data[i].teams.red1))){
				uniqueList.push(String(data[i].teams.red1))
			}
			if(-1 == uniqueList.indexOf(String(data[i].teams.red2))){
				uniqueList.push(String(data[i].teams.red2))
			}
			if(-1 == uniqueList.indexOf(String(data[i].teams.blue1))){
				uniqueList.push(String(data[i].teams.blue1))
			}
			if(-1 == uniqueList.indexOf(String(data[i].teams.blue2))){
				uniqueList.push(String(data[i].teams.blue2))
			}
		}
		return uniqueList
	},

	formattingMatchData: function(data){
		// matchData: [
		// 	{
		// 		matchNumber: 123,
		// 		teams: {
		// 			red1: 123,
		// 			red2: 123,
		// 			blue1: 123,
		// 			blue2: 123
		// 		},
		// 		winner: 'abc', //'blue', 'red', 'tie'
		// 		score:{
		// 			auto:{
		// 				red: 123, //red alliance autonomous score
		// 				blue: 123 //blue alliance autonomous score
		// 			},
		// 			driver:{
		// 				red: 123, //red alliance tele-op score
		// 				blue: 123 //blue alliance tele-op score
		// 			},
		// 			end:{
		// 				red: 123, //red alliance end-game score
		// 				blue: 123 //blue alliance end-game score
		// 			},
		// 			total:{
		// 				red: 123, //red alliance total score
		// 				blue: 123 //blue alliance total score
		// 			},
		// 			penalty:{
		// 				red: 123, //red alliance penalty score
		// 				blue: 123 //blue alliance penalty score
		// 			},
		// 			final:{
		// 				red: 123, //red alliance final score
		// 				blue: 123 //blue alliance final score
		// 			}
		// 		}
		// 	}
		// ]

		// to be

		// matchData: [
		// 	{
		// 		matchNumber: 123,
		// 		teams: [123, 123],
		// 		score:{
		// 			auto: 123,
		// 			driver: 123,
		// 			end: 123,
		// 			total: 123,
		// 			penalty: 123,
		// 			final: 123
		// 		}
		// 	}
		// ]

		var formattedData = []

		for (var i = 0; i < data.length; i++) {
			//data[i]

			formattedData.push(
				//for red half
				{
					matchNumber: data[i].matchNumber,
					teams: [data[i].teams.red1, data[i].teams.red2],
					score:{
						auto: data[i].score.auto.red,
						driver: data[i].score.driver.red,
						end: data[i].score.end.red,
						total: data[i].score.total.red,
						penalty: data[i].score.penalty.red,
						final: data[i].score.final.red
					},
				},
				//for blue half
				{
					matchNumber: data[i].matchNumber,
					teams: [data[i].teams.blue1, data[i].teams.blue2],
					score:{
						auto: data[i].score.auto.blue,
						driver: data[i].score.driver.blue,
						end: data[i].score.end.blue,
						total: data[i].score.total.blue,
						penalty: data[i].score.penalty.blue,
						final: data[i].score.final.blue
					}
				}
			)
		}

		return formattedData
	}
}

<commit_msg>Addded formattingNeuralSimpleOPR to helper<commit_after>//helper by Michael Leonffu

module.exports = {
	generateUniqueList: function(data){

		// data = [
		// 	{
		// 		teams:{
		// 			red1: 123,
		// 			red2: 123,
		// 			blue1: 123,
		// 			blue2: 123
		// 		}
		// 	}
		// ]

		var uniqueList = []
		for (var i = 0; i < data.length; i++) {
			if(-1 == uniqueList.indexOf(String(data[i].teams.red1))){
				uniqueList.push(String(data[i].teams.red1))
			}
			if(-1 == uniqueList.indexOf(String(data[i].teams.red2))){
				uniqueList.push(String(data[i].teams.red2))
			}
			if(-1 == uniqueList.indexOf(String(data[i].teams.blue1))){
				uniqueList.push(String(data[i].teams.blue1))
			}
			if(-1 == uniqueList.indexOf(String(data[i].teams.blue2))){
				uniqueList.push(String(data[i].teams.blue2))
			}
		}
		return uniqueList
	},

	formattingMatchData: function(data){
		// matchData: [
		// 	{
		// 		matchNumber: 123,
		// 		teams: {
		// 			red1: 123,
		// 			red2: 123,
		// 			blue1: 123,
		// 			blue2: 123
		// 		},
		// 		winner: 'abc', //'blue', 'red', 'tie'
		// 		score:{
		// 			auto:{
		// 				red: 123, //red alliance autonomous score
		// 				blue: 123 //blue alliance autonomous score
		// 			},
		// 			driver:{
		// 				red: 123, //red alliance tele-op score
		// 				blue: 123 //blue alliance tele-op score
		// 			},
		// 			end:{
		// 				red: 123, //red alliance end-game score
		// 				blue: 123 //blue alliance end-game score
		// 			},
		// 			total:{
		// 				red: 123, //red alliance total score
		// 				blue: 123 //blue alliance total score
		// 			},
		// 			penalty:{
		// 				red: 123, //red alliance penalty score
		// 				blue: 123 //blue alliance penalty score
		// 			},
		// 			final:{
		// 				red: 123, //red alliance final score
		// 				blue: 123 //blue alliance final score
		// 			}
		// 		}
		// 	}
		// ]

		// to be

		// matchData: [
		// 	{
		// 		matchNumber: 123,
		// 		teams: [123, 123],
		// 		score:{
		// 			auto: 123,
		// 			driver: 123,
		// 			end: 123,
		// 			total: 123,
		// 			penalty: 123,
		// 			final: 123
		// 		}
		// 	}
		// ]

		var formattedData = []

		for (var i = 0; i < data.length; i++) {
			//data[i]

			formattedData.push(
				//for red half
				{
					matchNumber: data[i].matchNumber,
					teams: [data[i].teams.red1, data[i].teams.red2],
					score:{
						auto: data[i].score.auto.red,
						driver: data[i].score.driver.red,
						end: data[i].score.end.red,
						total: data[i].score.total.red,
						penalty: data[i].score.penalty.red,
						final: data[i].score.final.red
					},
				},
				//for blue half
				{
					matchNumber: data[i].matchNumber,
					teams: [data[i].teams.blue1, data[i].teams.blue2],
					score:{
						auto: data[i].score.auto.blue,
						driver: data[i].score.driver.blue,
						end: data[i].score.end.blue,
						total: data[i].score.total.blue,
						penalty: data[i].score.penalty.blue,
						final: data[i].score.final.blue
					}
				}
			)
		}

		return formattedData
	}

	formattingNeuralSimpleOPR: function(data){
		var formattedData = []

		//Formatting it to only use combined alliance OPR to predict the score and the winner of the games

		// data: {
		// 	matchData: [],
		// 	juice: {}
		// }

		//to

		// formattedData = [		RECYLCE TO BETTER FORMATTER LATTEr
		// 	{
		// 		input: {
		// 			redAuto: .123,
		// 			redDriver: .123,
		// 			redEnd: .123,
		// 			redTotal: .123,
		// 			redPenalty: .123,
		// 			redFinal: .123,
		// 			redOPRTotal: .123,

		// 			blueAuto: .123,
		// 			blueDriver: .123,
		// 			blueEnd: .123,
		// 			blueTotal: .123,
		// 			bluePenalty: .123,
		// 			blueFinal: .123,
		// 			blueOPRTotal: .123
		// 		},
		// 		output: {
		// 			red: 123,
		// 			blue 123
		// 		}
		// 	}
		// ]

		// formattedData = [
		// 	{
		// 		input: {
		// 			redOPRTotal: .123,
		// 			blueOPRTotal: .123
		// 		},
		// 		output: {
		// 			redTotal: .123,
		// 			blueTotal: .123,
		// 			red: 123,
		// 			blue 123
		// 		}
		// 	}
		// ]

		for (var i = 0; i < data.matchData.length; i++) {

			//data.matchData[i]

		}

		return formattedData
	}
}

<|endoftext|>


<commit_before>var style = ["pulldown", "reveal", "shutter-vertical", "shutter-horizontal", "inline", "inline-animated"];
var colour = ["text", "default", "primary", "success", "warning", "danger"];
var size = ["xs", "sm", "md", "lg"];
var align = ["left", "center", "right", "full"];
var tint = ["tint-dark", "tint-light", "tint-solid"];

$(document).ready(function() {
  redoCodebox();

  var initialHeight = $('.snippet-content').css("max-height");
  var initialWidth = $('.snippet-content').css("width");

  $.each($(".snippet-expander").attr("class").split(" "), function (index, variant) {
    $(".demo." + variant.split("snippet-")[1]).addClass("active");
  });

  $( "#exampletext" ).keyup(function() {
    $(".snippet-content").text($(this).val());
    redoCodebox();
  });

  $( "#expand" ).keyup(function() {
    $(".snippet-expander").attr("data-expand", $(this).val());
    redoCodebox();
  });

  $( "#collapse" ).keyup(function() {
    $(".snippet-expander").attr("data-collapse", $(this).val());
    redoCodebox();
  });

  $( "#box-height" ).keyup(function() {
    $(".snippet-content").css("max-height", $(this).val());
    $('.snippet-reveal').css("line-height", Math.min($(this).val(), (".snippet-content")[0].scrollHeight));
    redoCodebox();
  });

  $( "#length" ).keyup(function() {
    $(".snippet-expander").attr("data-length", $(this).val());
    redoCodebox();
  });

  $( "#speed" ).keyup(function() {
    $(".snippet-expander").attr("data-speed", $(this).val());
    redoCodebox();
  });

  $('.snippet-content').each(function() {
    if ($(this)[0].scrollHeight <= parseInt($(this).css('max-height')) + 10) {
      $(this).siblings('.snippet-expander').hide();
    }
    $(this).siblings('.snippet-shutter-vertical').css("border-width", parseInt(initialHeight) / 2 + " 0 ");
    $(this).siblings('.snippet-shutter-horizontal').css("border-width", " 0 " + parseInt(initialWidth) / 2);
  });

  $('.demo').click(function() {
    var classes = $(this).attr('class').split(' ')
    var variant = classes.pop();
    var type = classes.pop();
    $(this).addClass("active")
    var excluded = $.map($(eval(type)).not([variant]), function(value, index) {
      $(".demo." + type + "." + value).removeClass("active")
      return ["snippet-" + value];
    });

    if (type == "style") {
      if (variant == "reveal") {
        $('.snippet-expander').css("line-height", initialHeight);
      } else if (variant == "shutter-horizontal") {
        $('.snippet-expander').css("line-height", "initial");
      }

      if (variant == "reveal") {
        $('.snippet-expander').removeClass("initial");
      } else {
        $('.snippet-expander').addClass("initial")
      }

      if (variant == "shutter-vertical") {
        $('.snippet-expander').css("border-width", parseInt(initialHeight) / 2 + " 0 ");
      } else {
        $('.snippet-expander').css("border-width", " 0 " + parseInt(initialWidth) / 2);
      }

      if (variant == "shutter-horizontal") {
        $('.snippet-expander').css("padding-top", parseInt(initialHeight) / 2);
      } else {
        $('.snippet-expander').css("padding-top", "0px");
      }

      if (variant == "inline" || variant == "inline-animated") {
        $(".alignment-group").hide();
        $(".colour-group").hide();
        $(".size-group").hide();
        $(".tint-group").hide();
      } else {
        $(".alignment-group").show();
        $(".colour-group").show();
        $(".size-group").show();
        $(".tint-group").show();
      }
    }

    $(".snippet-expander").removeClass(excluded.join(" ")).addClass("snippet-" + variant)
    redoCodebox();
  });
});

function redoCodebox() {
  $(".codebox").text(
    "
" +
    "\n\t
...
" +
    "\n\t

" +
    "\n
"
  );
}
<commit_msg>Hide control if inline by default<commit_after>var style = ["pulldown", "reveal", "shutter-vertical", "shutter-horizontal", "inline", "inline-animated"];
var colour = ["text", "default", "primary", "success", "warning", "danger"];
var size = ["xs", "sm", "md", "lg"];
var align = ["left", "center", "right", "full"];
var tint = ["tint-dark", "tint-light", "tint-solid"];

$(document).ready(function() {
  redoCodebox();

  var initialHeight = $('.snippet-content').css("max-height");
  var initialWidth = $('.snippet-content').css("width");

  $.each($(".snippet-expander").attr("class").split(" "), function (index, variant) {
    $(".demo." + variant.split("snippet-")[1]).addClass("active");
  });

  $( "#exampletext" ).keyup(function() {
    $(".snippet-content").text($(this).val());
    redoCodebox();
  });

  $( "#expand" ).keyup(function() {
    $(".snippet-expander").attr("data-expand", $(this).val());
    redoCodebox();
  });

  $( "#collapse" ).keyup(function() {
    $(".snippet-expander").attr("data-collapse", $(this).val());
    redoCodebox();
  });

  $( "#box-height" ).keyup(function() {
    $(".snippet-content").css("max-height", $(this).val());
    $('.snippet-reveal').css("line-height", Math.min($(this).val(), (".snippet-content")[0].scrollHeight));
    redoCodebox();
  });

  $( "#length" ).keyup(function() {
    $(".snippet-expander").attr("data-length", $(this).val());
    redoCodebox();
  });

  $( "#speed" ).keyup(function() {
    $(".snippet-expander").attr("data-speed", $(this).val());
    redoCodebox();
  });

  $('.snippet-content').each(function() {
    if ($(this)[0].scrollHeight <= parseInt($(this).css('max-height')) + 10) {
      $(this).siblings('.snippet-expander').hide();
    }
    $(this).siblings('.snippet-shutter-vertical').css("border-width", parseInt(initialHeight) / 2 + " 0 ");
    $(this).siblings('.snippet-shutter-horizontal').css("border-width", " 0 " + parseInt(initialWidth) / 2);
  });

  if ($(".snippet-expander").hasClass("snippet-inline") || $(".snippet-expander").hasClass("snippet-inline-animated")) {
    $(".alignment-group").hide();
    $(".colour-group").hide();
    $(".size-group").hide();
    $(".tint-group").hide();
  } else {
    $(".alignment-group").show();
    $(".colour-group").show();
    $(".size-group").show();
    $(".tint-group").show();
  }

  $('.demo').click(function() {
    var classes = $(this).attr('class').split(' ')
    var variant = classes.pop();
    var type = classes.pop();
    $(this).addClass("active")
    var excluded = $.map($(eval(type)).not([variant]), function(value, index) {
      $(".demo." + type + "." + value).removeClass("active")
      return ["snippet-" + value];
    });

    if (type == "style") {
      if (variant == "reveal") {
        $('.snippet-expander').css("line-height", initialHeight);
      } else if (variant == "shutter-horizontal") {
        $('.snippet-expander').css("line-height", "initial");
      }

      if (variant == "reveal") {
        $('.snippet-expander').removeClass("initial");
      } else {
        $('.snippet-expander').addClass("initial")
      }

      if (variant == "shutter-vertical") {
        $('.snippet-expander').css("border-width", parseInt(initialHeight) / 2 + " 0 ");
      } else {
        $('.snippet-expander').css("border-width", " 0 " + parseInt(initialWidth) / 2);
      }

      if (variant == "shutter-horizontal") {
        $('.snippet-expander').css("padding-top", parseInt(initialHeight) / 2);
      } else {
        $('.snippet-expander').css("padding-top", "0px");
      }

      if (variant == "inline" || variant == "inline-animated") {
        $(".alignment-group").hide();
        $(".colour-group").hide();
        $(".size-group").hide();
        $(".tint-group").hide();
      } else {
        $(".alignment-group").show();
        $(".colour-group").show();
        $(".size-group").show();
        $(".tint-group").show();
      }
    }

    $(".snippet-expander").removeClass(excluded.join(" ")).addClass("snippet-" + variant)
    redoCodebox();
  });
});

function redoCodebox() {
  $(".codebox").text(
    "
" +
    "\n\t
...
" +
    "\n\t

" +
    "\n
"
  );
}
<|endoftext|>


<commit_before><commit_msg>jsAPI: fix errorObj<commit_after><|endoftext|>


<commit_before>const util = require('util');
const ValidationFail = require('../../Error/ValidationFail');
const Input = require('../../Input');
const BaseText = require('./BaseText');

/**
 * Text input
 *
 * ```javascript
 * const input = Input.create('myInput: text');
 * input.setValue('Some text');
 * ```
 *
 * ```javascript
 * // vector
 * const input = Input.create('myInput: text[]');
 * input.setValue(['A', 'B', 'C']);
 * ```
 *
 * *This input can also be created using the alias:* `string`
 *
 *
Property Summary

 *
 * Property Name | Description | Defined by Default | Default Value
 * --- | --- | :---: | :---:
 * min | minimum number of characters | ::off:: | ::none::
 * max | maximum number of characters | ::off:: | ::none::
 *
 * All properties including the inherited ones can be listed via
 * {@link registeredPropertyNames}
 */
class Text extends BaseText{

  /**
   * Implements input's validations
   *
   * @param {null|number} at - index used when input has been created as a vector that
   * tells which value should be used
   * @return {Promise<*>} value held by the input based on the current context (at)
   * @protected
   */
  _validation(at){

    // calling super class validations
    return super._validation(at).then((value) => {

      // min property
      if (this.hasProperty('min') && value.length < this.property('min')){
        throw new ValidationFail(util.format('Value is too short, it needs to have at least %d characters', this.property('min')), Text.errorCodes[0]);
      }
      // max property
      else if (this.hasProperty('max') && value.length > this.property('max')){
        throw new ValidationFail(util.format('Value is too long, maximum is %d characters', this.property('max')), Text.errorCodes[1]);
      }

      return value;
    });
  }

  static errorCodes = [
    '64358b78-ec83-4494-b734-0b1bdac43720',
    'c7ff4423-2c27-4538-acd7-923dada7f4d3',
  ];
}

// registering the input
Input.registerInput(Text);

// also, registering as 'string' for convenience
Input.registerInput(Text, 'string');

// registering properties
Input.registerProperty(Text, 'min');
Input.registerProperty(Text, 'max');

module.exports = Text;
<commit_msg>improved Text input documentation<commit_after>const util = require('util');
const ValidationFail = require('../../Error/ValidationFail');
const Input = require('../../Input');
const BaseText = require('./BaseText');

/**
 * Text input.
 *
 * ```javascript
 * const input = Input.create('myInput: text');
 * input.setValue('Some text');
 * ```
 *
 * ```javascript
 * // vector
 * const input = Input.create('myInput: text[]');
 * input.setValue(['A', 'B', 'C']);
 * ```
 *
 * *This input can also be created using the alias:* `string`
 *
 *
Property Summary

 *
 * Property Name | Description | Defined by Default | Default Value
 * --- | --- | :---: | :---:
 * min | minimum number of characters | ::off:: | ::none::
 * max | maximum number of characters | ::off:: | ::none::
 *
 * All properties including the inherited ones can be listed via
 * {@link registeredPropertyNames}
 */
class Text extends BaseText{

  /**
   * Implements input's validations
   *
   * @param {null|number} at - index used when input has been created as a vector that
   * tells which value should be used
   * @return {Promise<*>} value held by the input based on the current context (at)
   * @protected
   */
  _validation(at){

    // calling super class validations
    return super._validation(at).then((value) => {

      // min property
      if (this.hasProperty('min') && value.length < this.property('min')){
        throw new ValidationFail(util.format('Value is too short, it needs to have at least %d characters', this.property('min')), Text.errorCodes[0]);
      }
      // max property
      else if (this.hasProperty('max') && value.length > this.property('max')){
        throw new ValidationFail(util.format('Value is too long, maximum is %d characters', this.property('max')), Text.errorCodes[1]);
      }

      return value;
    });
  }

  static errorCodes = [
    '64358b78-ec83-4494-b734-0b1bdac43720',
    'c7ff4423-2c27-4538-acd7-923dada7f4d3',
  ];
}

// registering the input
Input.registerInput(Text);

// also, registering as 'string' for convenience
Input.registerInput(Text, 'string');

// registering properties
Input.registerProperty(Text, 'min');
Input.registerProperty(Text, 'max');

module.exports = Text;
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');
var stringUtils = require('utils/string_utils');

App.MainAdminClusterController = Em.Controller.extend({
  name:'mainAdminClusterController',
  services: [],
  repositories: [],
  upgradeVersion: '',
  /**
   * get the newest version of HDP from server
   */
  updateUpgradeVersion: function(){
    if(App.router.get('clusterController.isLoaded')){
      App.ajax.send({
        name: 'cluster.update_upgrade_version',
        sender: this,
        success: 'updateUpgradeVersionSuccessCallback',
        error: 'updateUpgradeVersionErrorCallback'
      });
    }
  }.observes('App.router.clusterController.isLoaded', 'App.currentStackVersion'),

  updateUpgradeVersionSuccessCallback: function(data) {
    var upgradeVersion = this.get('upgradeVersion') || App.defaultStackVersion;
    var currentVersion = App.get('currentStackVersionNumber');
    upgradeVersion = upgradeVersion.replace(/HDP-/, '');
    data.items.mapProperty('Versions.stack_version').forEach(function(version){
      upgradeVersion = (stringUtils.compareVersions(upgradeVersion, version) === -1) ? version : upgradeVersion;
    });
    var currentStack = data.items.findProperty('Versions.stack_version', currentVersion);
    var upgradeStack = data.items.findProperty('Versions.stack_version', upgradeVersion);
    var minUpgradeVersion = upgradeStack.Versions.min_upgrade_version;
    if(minUpgradeVersion && (stringUtils.compareVersions(minUpgradeVersion, currentVersion) === 1)){
      upgradeVersion = currentVersion;
      upgradeStack = currentStack;
    }
    upgradeVersion = 'HDP-' + upgradeVersion;
    this.set('upgradeVersion', upgradeVersion);
    if(currentStack && upgradeStack) {
      this.parseServicesInfo(currentStack, upgradeStack);
    }
    else {
      console.log('HDP stack doesn\'t have services with defaultStackVersion');
    }
  },

  updateUpgradeVersionErrorCallback: function(request, ajaxOptions, error) {
    console.log('Error message is: ' + request.responseText);
    console.log('HDP stack doesn\'t have services with defaultStackVersion');
  },

  /**
   * get the installed repositories of HDP from server
   */
  loadRepositories: function(){
    if(App.router.get('clusterController.isLoaded')){
      var nameVersionCombo = App.get('currentStackVersion');
      var stackName = nameVersionCombo.split('-')[0];
      var stackVersion = nameVersionCombo.split('-')[1];
      App.ajax.send({
        name: 'cluster.load_repositories',
        sender: this,
        data: {
          stackName: stackName,
          stackVersion: stackVersion
        },
        success: 'loadRepositoriesSuccessCallback',
        error: 'loadRepositoriesErrorCallback'
      });
    }
  }.observes('App.router.clusterController.isLoaded'),

  loadRepositoriesSuccessCallback: function (data) {
    var allRepos = [];
    data.items.forEach(function(os) {
      var repo = Em.Object.create({
        baseUrl: os.repositories[0].Repositories.base_url,
        osType: os.repositories[0].Repositories.os_type
      });
      allRepos.push(repo);
    }, this);
    allRepos.stackVersion = App.get('currentStackVersionNumber');
    this.set('repositories', allRepos);
  },

  loadRepositoriesErrorCallback: function(request, ajaxOptions, error) {
    console.log('Error message is: ' + request.responseText);
  },

  /**
   * parse services info(versions, description) by version
   */
  parseServicesInfo: function (currentStack, upgradeStack) {
    var result = [];
    var installedServices = App.Service.find().mapProperty('serviceName');
    var displayOrderConfig = require('data/services');
    if(currentStack.stackServices.length && upgradeStack.stackServices.length){
      // loop through all the service components
      for (var i = 0; i < displayOrderConfig.length; i++) {
        var entry = currentStack.stackServices.
          findProperty("StackServices.service_name", displayOrderConfig[i].serviceName);
        if (entry) {
          entry = entry.StackServices;
          if (installedServices.contains(entry.service_name)) {
            var myService = Em.Object.create({
              serviceName: entry.service_name,
              displayName: displayOrderConfig[i].displayName,
              isDisabled: displayOrderConfig[i].isDisabled,
              isSelected: true,
              isInstalled: false,
              isHidden: displayOrderConfig[i].isHidden,
              description: entry.comments,
              version: entry.service_version,
              newVersion: ''
            });
            // it's possible that there is no corresponding service in the new stack
            var matchedService = upgradeStack.stackServices.findProperty("StackServices.service_name", displayOrderConfig[i].serviceName);
            if (matchedService) {
              myService.newVersion = matchedService.StackServices.service_version;
            }
            //From 1.3.0 for Hive we display only "Hive" (but it install HCat and WebHCat as well)
            if (this.get('upgradeVersion').replace(/HDP-/, '') >= '1.3.0' && displayOrderConfig[i].serviceName == 'HIVE') {
              myService.set('displayName', 'Hive');
            }
            result.push(myService);
          }
        }
        else {
          console.warn('Service not found - ', displayOrderConfig[i].serviceName);
        }
      }
    }
    this.set('services', result);
  }
});<commit_msg>AMBARI-4624 Added service(s) summary is absent on admin/cluster page. (Mikhail Bayuk via ababiichuk)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');
var stringUtils = require('utils/string_utils');

App.MainAdminClusterController = Em.Controller.extend({
  name:'mainAdminClusterController',
  services: [],
  repositories: [],
  upgradeVersion: '',
  /**
   * get the newest version of HDP from server
   */
  updateUpgradeVersion: function(){
    if(App.router.get('clusterController.isLoaded')){
      App.ajax.send({
        name: 'cluster.update_upgrade_version',
        sender: this,
        success: 'updateUpgradeVersionSuccessCallback',
        error: 'updateUpgradeVersionErrorCallback'
      });
    }
  }.observes('App.router.clusterController.isLoaded', 'App.currentStackVersion','App.router.mainServiceController.content.length'),

  updateUpgradeVersionSuccessCallback: function(data) {
    var upgradeVersion = this.get('upgradeVersion') || App.defaultStackVersion;
    var currentVersion = App.get('currentStackVersionNumber');
    upgradeVersion = upgradeVersion.replace(/HDP-/, '');
    data.items.mapProperty('Versions.stack_version').forEach(function(version){
      upgradeVersion = (stringUtils.compareVersions(upgradeVersion, version) === -1) ? version : upgradeVersion;
    });
    var currentStack = data.items.findProperty('Versions.stack_version', currentVersion);
    var upgradeStack = data.items.findProperty('Versions.stack_version', upgradeVersion);
    var minUpgradeVersion = upgradeStack.Versions.min_upgrade_version;
    if(minUpgradeVersion && (stringUtils.compareVersions(minUpgradeVersion, currentVersion) === 1)){
      upgradeVersion = currentVersion;
      upgradeStack = currentStack;
    }
    upgradeVersion = 'HDP-' + upgradeVersion;
    this.set('upgradeVersion', upgradeVersion);
    if(currentStack && upgradeStack) {
      this.parseServicesInfo(currentStack, upgradeStack);
    }
    else {
      console.log('HDP stack doesn\'t have services with defaultStackVersion');
    }
  },

  updateUpgradeVersionErrorCallback: function(request, ajaxOptions, error) {
    console.log('Error message is: ' + request.responseText);
    console.log('HDP stack doesn\'t have services with defaultStackVersion');
  },

  /**
   * get the installed repositories of HDP from server
   */
  loadRepositories: function(){
    if(App.router.get('clusterController.isLoaded')){
      var nameVersionCombo = App.get('currentStackVersion');
      var stackName = nameVersionCombo.split('-')[0];
      var stackVersion = nameVersionCombo.split('-')[1];
      App.ajax.send({
        name: 'cluster.load_repositories',
        sender: this,
        data: {
          stackName: stackName,
          stackVersion: stackVersion
        },
        success: 'loadRepositoriesSuccessCallback',
        error: 'loadRepositoriesErrorCallback'
      });
    }
  }.observes('App.router.clusterController.isLoaded'),

  loadRepositoriesSuccessCallback: function (data) {
    var allRepos = [];
    data.items.forEach(function(os) {
      var repo = Em.Object.create({
        baseUrl: os.repositories[0].Repositories.base_url,
        osType: os.repositories[0].Repositories.os_type
      });
      allRepos.push(repo);
    }, this);
    allRepos.stackVersion = App.get('currentStackVersionNumber');
    this.set('repositories', allRepos);
  },

  loadRepositoriesErrorCallback: function(request, ajaxOptions, error) {
    console.log('Error message is: ' + request.responseText);
  },

  /**
   * parse services info(versions, description) by version
   */
  parseServicesInfo: function (currentStack, upgradeStack) {
    var result = [];
    var installedServices = App.Service.find().mapProperty('serviceName');
    var displayOrderConfig = require('data/services');
    if(currentStack.stackServices.length && upgradeStack.stackServices.length){
      // loop through all the service components
      for (var i = 0; i < displayOrderConfig.length; i++) {
        var entry = currentStack.stackServices.
          findProperty("StackServices.service_name", displayOrderConfig[i].serviceName);
        if (entry) {
          entry = entry.StackServices;
          if (installedServices.contains(entry.service_name)) {
            var myService = Em.Object.create({
              serviceName: entry.service_name,
              displayName: displayOrderConfig[i].displayName,
              isDisabled: displayOrderConfig[i].isDisabled,
              isSelected: true,
              isInstalled: false,
              isHidden: displayOrderConfig[i].isHidden,
              description: entry.comments,
              version: entry.service_version,
              newVersion: ''
            });
            // it's possible that there is no corresponding service in the new stack
            var matchedService = upgradeStack.stackServices.findProperty("StackServices.service_name", displayOrderConfig[i].serviceName);
            if (matchedService) {
              myService.newVersion = matchedService.StackServices.service_version;
            }
            //From 1.3.0 for Hive we display only "Hive" (but it install HCat and WebHCat as well)
            if (this.get('upgradeVersion').replace(/HDP-/, '') >= '1.3.0' && displayOrderConfig[i].serviceName == 'HIVE') {
              myService.set('displayName', 'Hive');
            }
            result.push(myService);
          }
        }
        else {
          console.warn('Service not found - ', displayOrderConfig[i].serviceName);
        }
      }
    }
    this.set('services', result);
  }
});
<|endoftext|>


<commit_before>var Mocha = require('mocha'),
    should=require('should'),
    fs=require('fs'),
    debug = require('debug')('mocha:verify:multi'),
    async = require('async'),
    chalk = require('chalk');

var reporters = [
    "dot", "doc", "spec", "json", "progress",
    "list", "tap", "landing", "xunit", "min",
    "json-stream", "markdown", "nyan"
];

var now = new Date();

var reportersWithOptions = []
    .concat(reporters.map(function (reporter) {
        var outFilename = tempName(reporter + '-stdout');
        var options = {};
        options[reporter] = {
            stdout: outFilename
        };
        return {
            testName: reporter + ' (with options.stdout)',
            outFilename: outFilename,
            options: options
        };
    }))
    .concat(reporters.map(function (reporter) {
        var outFilename = tempName(reporter + '-str');
        var options = {};
        options[reporter] = outFilename;
        return {
            testName: reporter + ' (with options as string)',
            outFilename: outFilename,
            options: options
        };
    }));

should(process.env.multi).not.be.ok;

function tempName(reporter) {
    return "/tmp/mocha-multi." + reporter + "." + (+now);
}

process.setMaxListeners(reportersWithOptions.length);

async.eachSeries(reportersWithOptions, function(reporter, next) {
    debug("reporter %s", reporter.testName);
    debug("reporterOptions %j", reporter.options);
    var mocha = new Mocha({
        ui: 'bdd',
        reporter: "mocha-multi",
        reporterOptions: reporter.options
    });
    mocha.addFile("test/dummy-spec.js");
    mocha.run(function onRun(failures){
        debug("done running %j", reporter.testName);
        process.nextTick(next);
    });
}, function(err, results) {
    reportersWithOptions.forEach(function(reporter) {
        fs.statSync.bind(fs, reporter.outFilename).should.not.throw();
        fs.unlinkSync(reporter.outFilename);
        console.log(chalk.green("%s OK"), reporter.testName);
    });
});
<commit_msg>Format tweak for var declarations.<commit_after>var Mocha = require('mocha'),
    should=require('should'),
    fs=require('fs'),
    debug = require('debug')('mocha:verify:multi'),
    async = require('async'),
    chalk = require('chalk');

var reporters = [
    "dot", "doc", "spec", "json", "progress",
    "list", "tap", "landing", "xunit", "min",
    "json-stream", "markdown", "nyan"
], now = new Date();

var reportersWithOptions = []
    .concat(reporters.map(function (reporter) {
        var outFilename = tempName(reporter + '-stdout');
        var options = {};
        options[reporter] = {
            stdout: outFilename
        };
        return {
            testName: reporter + ' (with options.stdout)',
            outFilename: outFilename,
            options: options
        };
    }))
    .concat(reporters.map(function (reporter) {
        var outFilename = tempName(reporter + '-str');
        var options = {};
        options[reporter] = outFilename;
        return {
            testName: reporter + ' (with options as string)',
            outFilename: outFilename,
            options: options
        };
    }));

should(process.env.multi).not.be.ok;

function tempName(reporter) {
    return "/tmp/mocha-multi." + reporter + "." + (+now);
}

process.setMaxListeners(reportersWithOptions.length);

async.eachSeries(reportersWithOptions, function(reporter, next) {
    debug("reporter %s", reporter.testName);
    debug("reporterOptions %j", reporter.options);
    var mocha = new Mocha({
        ui: 'bdd',
        reporter: "mocha-multi",
        reporterOptions: reporter.options
    });
    mocha.addFile("test/dummy-spec.js");
    mocha.run(function onRun(failures){
        debug("done running %j", reporter.testName);
        process.nextTick(next);
    });
}, function(err, results) {
    reportersWithOptions.forEach(function(reporter) {
        fs.statSync.bind(fs, reporter.outFilename).should.not.throw();
        fs.unlinkSync(reporter.outFilename);
        console.log(chalk.green("%s OK"), reporter.testName);
    });
});
<|endoftext|>


<commit_before>'use strict';

if (typeof window !== 'undefined' && typeof exports === 'undefined') {
    if (typeof window.utils !== 'object') {
        window.utils = {};
    }
}

if (typeof exports !== 'undefined') {
    var _ = require('underscore');
}

(function(exports) {
    //
    // Message Text Formatting
    //

    function encodeEntities(value) {
        return value.
            replace(/&/g, '&').
            replace(surrogatePairRegexp, function(value) {
                var hi = value.charCodeAt(0),
                    low = value.charCodeAt(1);
                return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
            }).
            replace(nonAlphanumericRegexp, function(value) {
                return '&#' + value.charCodeAt(0) + ';';
            }).
            replace(/</g, '<').
            replace(/>/g, '>');
    }

    function getBaseUrl() {
        var parts = window.location.pathname.split('/');

        parts = _.filter(parts, function(part) {
            return part.length;
        });

        if (parts.length) {
            parts.splice(parts.length - 1, 1);
        }

        var path = window.location.origin;

        if (parts.length) {
            path = path + '/' + parts.join('/');
        }

        return path + '/';
    }

    function trim(text) {
        return text.trim();
    }

    function mentions(text) {
        var mentionPattern = /\B@([\w\.]+)(?!@)\b/g;
        return text.replace(mentionPattern, '@$1');
    }

    function roomLinks(text, data) {
        if (!data.rooms) {
            return text;
        }

        var slugPattern = /\B(\#[a-z0-9_]+)\b/g;

        return text.replace(slugPattern, function(slug) {
            var s = slug.substring(1);
            var room = data.rooms.find(function(room) {
                return room.attributes.slug === s;
            });

            if (!room) {
                return slug;
            }

            return '#' + s + '';
        });
    }

    function uploads(text) {
        var pattern = /^\s*(upload:\/\/[-A-Z0-9+&*@#\/%?=~_|!:,.;'"!()]*)\s*$/i;

        return text.replace(pattern, function(url) {
            return getBaseUrl() + url.substring(9);
        });
    }

    function links(text) {
        if (imagePattern.test(text)) {
            return text.replace(imagePattern, function(url) {
                var uri = encodeEntities(_.unescape(url));
                return '';
            });
        } else {
            return text.replace(linkPattern, function(url) {
                var uri = encodeEntities(_.unescape(url));
                return '' + url + '';
            });
        }
    }

    function emotes(text, data) {
        var regex = new RegExp('\\B(:[a-z0-9_\\+\\-]+:?)[\\b]?', 'ig');

        return text.replace(regex, function(group) {
            var key = group.split(':')[1];
            var emote = _.find(data.emotes, function(emote) {
                return emote.emote === key;
            });

            if (!emote) {
                return group;
            }

            var image = _.escape(emote.image),
                emo = _.escape(':' + emote.emote + ':'),
                size = _.escape(emote.size || 20);

            return '';
        });
    }

    function replacements(text, data) {
        _.each(data.replacements, function(replacement) {
            text = text.replace(new RegExp(replacement.regex, 'ig'), replacement.template);
        });
        return text;
    }

    var surrogatePairRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
        // Match everything outside of normal chars and " (quote character)
        nonAlphanumericRegexp = /([^\#-~| |!])/g,
        imagePattern = /^\s*((https?|ftp):\/\/[-A-Z0-9\u00a1-\uffff+&@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9\u00a1-\uffff+&@#\/%=~_|][.](jpe?g|png|gif))\s*$/i,
        linkPattern = /((https?|ftp):\/\/[-A-Z0-9\u00a1-\uffff+&*@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9\u00a1-\uffff+&@#\/%=~_|])/ig;

    exports.format = function(text, data) {
        var pipeline = [
            trim,
            mentions,
            roomLinks,
            uploads,
            links,
            emotes,
            replacements
        ];

        _.each(pipeline, function(func) {
            text = func(text, data);
        });

        return text;
    };

})(typeof exports === 'undefined' ? window.utils.message = {} : exports);
<commit_msg>Require closing colon for emotes<commit_after>'use strict';

if (typeof window !== 'undefined' && typeof exports === 'undefined') {
    if (typeof window.utils !== 'object') {
        window.utils = {};
    }
}

if (typeof exports !== 'undefined') {
    var _ = require('underscore');
}

(function(exports) {
    //
    // Message Text Formatting
    //

    function encodeEntities(value) {
        return value.
            replace(/&/g, '&').
            replace(surrogatePairRegexp, function(value) {
                var hi = value.charCodeAt(0),
                    low = value.charCodeAt(1);
                return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
            }).
            replace(nonAlphanumericRegexp, function(value) {
                return '&#' + value.charCodeAt(0) + ';';
            }).
            replace(/</g, '<').
            replace(/>/g, '>');
    }

    function getBaseUrl() {
        var parts = window.location.pathname.split('/');

        parts = _.filter(parts, function(part) {
            return part.length;
        });

        if (parts.length) {
            parts.splice(parts.length - 1, 1);
        }

        var path = window.location.origin;

        if (parts.length) {
            path = path + '/' + parts.join('/');
        }

        return path + '/';
    }

    function trim(text) {
        return text.trim();
    }

    function mentions(text) {
        var mentionPattern = /\B@([\w\.]+)(?!@)\b/g;
        return text.replace(mentionPattern, '@$1');
    }

    function roomLinks(text, data) {
        if (!data.rooms) {
            return text;
        }

        var slugPattern = /\B(\#[a-z0-9_]+)\b/g;

        return text.replace(slugPattern, function(slug) {
            var s = slug.substring(1);
            var room = data.rooms.find(function(room) {
                return room.attributes.slug === s;
            });

            if (!room) {
                return slug;
            }

            return '#' + s + '';
        });
    }

    function uploads(text) {
        var pattern = /^\s*(upload:\/\/[-A-Z0-9+&*@#\/%?=~_|!:,.;'"!()]*)\s*$/i;

        return text.replace(pattern, function(url) {
            return getBaseUrl() + url.substring(9);
        });
    }

    function links(text) {
        if (imagePattern.test(text)) {
            return text.replace(imagePattern, function(url) {
                var uri = encodeEntities(_.unescape(url));
                return '';
            });
        } else {
            return text.replace(linkPattern, function(url) {
                var uri = encodeEntities(_.unescape(url));
                return '' + url + '';
            });
        }
    }

    function emotes(text, data) {
        var regex = new RegExp('\\B(:[a-z0-9_\\+\\-]+:)[\\b]?', 'ig');

        return text.replace(regex, function(group) {
            var key = group.split(':')[1];
            var emote = _.find(data.emotes, function(emote) {
                return emote.emote === key;
            });

            if (!emote) {
                return group;
            }

            var image = _.escape(emote.image),
                emo = _.escape(':' + emote.emote + ':'),
                size = _.escape(emote.size || 20);

            return '';
        });
    }

    function replacements(text, data) {
        _.each(data.replacements, function(replacement) {
            text = text.replace(new RegExp(replacement.regex, 'ig'), replacement.template);
        });
        return text;
    }

    var surrogatePairRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
        // Match everything outside of normal chars and " (quote character)
        nonAlphanumericRegexp = /([^\#-~| |!])/g,
        imagePattern = /^\s*((https?|ftp):\/\/[-A-Z0-9\u00a1-\uffff+&@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9\u00a1-\uffff+&@#\/%=~_|][.](jpe?g|png|gif))\s*$/i,
        linkPattern = /((https?|ftp):\/\/[-A-Z0-9\u00a1-\uffff+&*@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9\u00a1-\uffff+&@#\/%=~_|])/ig;

    exports.format = function(text, data) {
        var pipeline = [
            trim,
            mentions,
            roomLinks,
            uploads,
            links,
            emotes,
            replacements
        ];

        _.each(pipeline, function(func) {
            text = func(text, data);
        });

        return text;
    };

})(typeof exports === 'undefined' ? window.utils.message = {} : exports);
<|endoftext|>


<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

/*
 * Dependencies
 *
 * /dev/lib/jquery/plugins/jqmodal.sakai-edited.js
 */

require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai_global.addpeople
     *
     * @class addpeople
     *
     * @description
     * addpeople widget
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.addpeople = function(tuid, showSettings, widgetData){

        /////////////////////////////
        // CONFIGURATION VARIABLES //
        /////////////////////////////

        var $rootel = $("#" + tuid);

        // Containers
        var $addpeopleContainer = $("#addpeople_container", $rootel);
        var $addpeopleContactsContainer = $("#addpeople_contacts_container", $rootel);
        var $addpeopleSelectedContactsContainer = $("#addpeople_selected_contacts_container", $rootel);
        var $addpeopleMembersAutoSuggest = $("#addpeople_members_autosuggest", $rootel);

        // Templates
        var addpeopleContactsTemplate = "addpeople_contacts_template";
        var addpeopleSelectedContactsTemplate = "addpeople_selected_contacts_template";

        // Elements
        var $addpeopleSelectAllContacts = $("#addpeople_select_all_contacts", $rootel);
        var addpeopleCheckbox = ".addpeople_checkbox";
        var addpeopleSelectedCheckbox = ".addpeople_selected_checkbox";
        var addpeopleSelectedPermissions = ".addpeople_selected_permissions";
        var $addpeopleSelectedAllPermissions = $("#addpeople_selected_all_permissions", $rootel);
        var $addpeopleSelectAllSelectedContacts = $("#addpeople_select_all_selected_contacts", $rootel);
        var $addpeopleFinishAdding = $(".addpeople_finish_adding", $rootel);
        var $addpeopleRemoveSelected = $(".addpeople_remove_selected", $rootel);
        var $addpeopleMembersAutoSuggestField = $("#addpeople_members_autosuggest_field", $rootel);

        var selectedUsers = {};
        var currentTemplate = false;
        var hasbeenInit = false;

        ///////////////
        // RENDERING //
        ///////////////

        var renderContacts = function(){
            if ($addpeopleContactsContainer.text() === "") {
                var groups = sakai.api.Groups.getMemberships(sakai.data.me.groups);
                groups = groups.entry;
                if (sakai_global.group && sakai_global.group.groupData && sakai_global.group.groupData["sakai:group-id"]) {
                    groups = _.without(groups, sakai_global.group.groupData["sakai:group-id"]);
                }
                $addpeopleContactsContainer.html(sakai.api.Util.TemplateRenderer(addpeopleContactsTemplate, {
                    "contacts": sakai.data.me.mycontacts,
                    "groups": groups,
                    "sakai": sakai
                }));
            }
        };

        var renderSelectedContacts = function(){
            $addpeopleSelectedContactsContainer.html(sakai.api.Util.TemplateRenderer(addpeopleSelectedContactsTemplate, {"contacts":selectedUsers, "roles": currentTemplate.roles}));
            enableDisableControls(true);
        };

        /////////////
        // UTILITY //
        /////////////

        var enableDisableControls = function(disable){
            if(disable){
                $addpeopleRemoveSelected.attr("disabled","disabled");
                $addpeopleSelectedAllPermissions.attr("disabled","disabled");
            }else{
                $addpeopleRemoveSelected.removeAttr("disabled");
                $addpeopleSelectedAllPermissions.removeAttr("disabled");
            }
        };

        var decideEnableDisableControls = function(el){
            if($("." + el.currentTarget.className + ":checked").length){
                enableDisableControls(false);
            }else{
                enableDisableControls(true);
            }
            $addpeopleSelectAllSelectedContacts.removeAttr("checked");
        };

        /**
         * Fire an event that indicates the addpeople widget is done adding users.
         * The object containing this userdata is giving to the event
         * Also hide the overlay
         */
        var finishAdding = function(){
            if (sakai_global.group) {
                var managerSelected = false;
                var permissionsToDelete = [];
                $.each(selectedUsers, function(index, user){
                    if (user.originalPermission && user.permission !== user.originalPermission) {
                        permissionsToDelete.push(user);
                    }

                    $.each(currentTemplate.roles, function(i, role){
                        if (user.permission == role.title || user.permission == role.id) {
                            user.permission = role.id;
                            if (role.allowManage) {
                                managerSelected = true;
                            }
                        }
                    });
                });
            }
            if (managerSelected || !sakai_global.group) {
                $(window).trigger("sakai.addpeople.usersswitchedpermission", [tuid.replace("addpeople", ""), permissionsToDelete]);
                $(window).trigger("sakai.addpeople.usersselected", [tuid.replace("addpeople", ""), selectedUsers]);
                $addpeopleContainer.jqmHide();
            } else {
                sakai.api.Util.notification.show(sakai.api.i18n.Widgets.getValueForKey("addpeople","","MANAGE_PARTICIPANTS"), sakai.api.i18n.Widgets.getValueForKey("addpeople","","SELECT_AT_LEAST_ONE_MANAGER"));
            }
        };

        /**
         * Check/Uncheck all items in the list and enable/disable buttons
         */
        var checkAll = function(el, peopleContainer){
            if($(el).is(":checked")){
                $(peopleContainer).attr("checked","checked");
                if (peopleContainer !== addpeopleSelectedCheckbox) {
                    $(peopleContainer).change();
                    renderSelectedContacts();
                }else{
                    enableDisableControls(false);
                }
            }else{
                $(peopleContainer).removeAttr("checked");
                if (peopleContainer !== addpeopleSelectedCheckbox) {
                    $(peopleContainer).removeAttr("checked");
                    $(peopleContainer).change();
                    renderSelectedContacts();
                    $addpeopleSelectAllSelectedContacts.removeAttr("checked");
                } else {
                    enableDisableControls(true);
                }
            }
        };

        /**
         * Construct a user object when adding a user to the list of selected users
         */
        var constructSelecteduser = function(){
            $addpeopleSelectAllSelectedContacts.removeAttr("checked");
            if ($(this).is(":checked")) {
                if (!selectedUsers[$(this)[0].id.split("_")[0]]) {
                    var userObj = {
                        userid: $(this)[0].id.split("_")[0],
                        roleid: $(this).val(),
                        name: $(this).nextAll(".s3d-entity-displayname").text(),
                        dottedname: sakai.api.Util.applyThreeDots($(this).nextAll(".s3d-entity-displayname").text(), 80),
                        permission: currentTemplate.joinRole,
                        picture: $(this).next().children("img").attr("src"),
                        tmpsrc:"checklistadded"
                    };
                    selectedUsers[userObj.userid] = userObj;
                    renderSelectedContacts();
                }
            }else{
                delete selectedUsers[$(this)[0].id.split("_")[0]];
                renderSelectedContacts();
                $addpeopleSelectAllSelectedContacts.removeAttr("checked");
                $addpeopleSelectAllContacts.removeAttr("checked");
            }
        };

        /**
         * Batch change the permission setting for a specific selection of users
         */
        var changeSelectedPermission = function(){
            var selectedPermission = $(this).val();
            $.each($addpeopleSelectedContactsContainer.find("input:checked"), function(index, item){
                $(item).nextAll("select").val(selectedPermission);
                selectedUsers[$(item)[0].id.split("_")[0]].permission = selectedPermission;
            });
        };

        /**
         * Change the permission setting for a specific user
         */
        var changePermission = function(){
            var userid = $(this)[0].id.split("_")[0];
            selectedUsers[userid].permission = $(this).val();
        };

        /**
         * Removes all users that are selected from the list of users to be added as a member (manager or viewer)
         */
        var removeSelected = function(){
            var managerLeft = false;
            $.each($addpeopleSelectedContactsContainer.find("input:not(:checked)"), function(index, user){
                $.each(currentTemplate.roles, function(i, role){
                    if (role.allowManage) {
                        if ($(user).nextAll("select").val() == role.id) {
                            managerLeft = true;
                        }
                    }
                });
            });
            if (managerLeft) {
                var usersToDelete = [];
                $.each($addpeopleSelectedContactsContainer.find("input:checked"), function(index, item){
                    usersToDelete.push({
                        "userid": $(item)[0].id.split("_")[0],
                        "permission": $(item).nextAll("select").val()
                    });
                    delete selectedUsers[$(item)[0].id.split("_")[0]];
                    $("#" + $(item)[0].id.split("_")[0] + "_chk").removeAttr("checked");
                    $addpeopleSelectAllContacts.removeAttr("checked");
                    $(item).parent().next().remove();
                    $(item).parent().remove();
                });
                sakai.api.Groups.removeUsersFromGroup(sakai_global.group.groupData["sakai:group-id"], false, usersToDelete, sakai.data.me);
                $addpeopleSelectAllSelectedContacts.removeAttr("checked");
            } else {
                sakai.api.Util.notification.show(sakai.api.i18n.Widgets.getValueForKey("addpeople", "", "MANAGE_PARTICIPANTS"), sakai.api.i18n.Widgets.getValueForKey("addpeople", "", "SELECT_AT_LEAST_ONE_MANAGER"));
            }
        };

        ////////////////////
        // INITIALIZATION //
        ////////////////////

        /**
         * Get the list of selected users/groups from the autosuggest plugin
         * @return {Object} returnValue An object containing a list of displayNames and an Array of userID's to be added to the members list
         */
        var createAutoSuggestedUser = function(userData) {
            var pictureURL = "";
            var userid = userData.attributes.value;
            if (userData.attributes.picture) {
                pictureURL = "/~" + userid + "/public/profile/" + userData.attributes.picture;
            } else {
                if (userData.attributes.type=== "group") {
                    pictureURL = "/dev/images/group_avatar_icon_35x35_nob.png";
                } else {
                    pictureURL = "/dev/images/default_User_icon_35x35.png";
                }
            }
            var userObj = {
                userid: userid,
                name: userData.attributes.name,
                dottedname: sakai.api.Util.applyThreeDots(userData.attributes.name, 80),
                permission: currentTemplate.joinRole,
                picture: pictureURL,
                tmpsrc:"autsuggestadded"
            };
            selectedUsers[userObj.userid] = userObj;
            renderSelectedContacts();
            $(".as-close").click();
        };

        /**
         * Clears the input field, closes the autosuggest and then hides the modal/overlay, called onHide in jqm
         */
        var resetAutosuggest = function(h){
            sakai.api.Util.AutoSuggest.reset($addpeopleMembersAutoSuggestField);
            for(user in selectedUsers){
                if(selectedUsers.hasOwnProperty(user) && selectedUsers[user].tmpsrc){
                    delete selectedUsers[user];
                }
            }
            $("ul",$addpeopleSelectedContactsContainer).empty();
            $(addpeopleCheckbox).add($addpeopleSelectAllContacts).removeAttr("checked");
            h.w.hide();
            if (h.o) {
                h.o.remove();
            }
        };

        var prepareSelectedContacts = function(success, data){
            for(var role in data){
                for(var user in data[role].results){
                    if (data[role].results.hasOwnProperty(user)) {
                        var userObj = {};
                        if (data[role].results[user].hasOwnProperty("sakai:group-id")) {
                            userObj = {
                                userid: data[role].results[user]["sakai:group-id"],
                                name: data[role].results[user]["sakai:group-title"],
                                dottedname: sakai.api.Util.applyThreeDots(data[role].results[user]["sakai:group-title"], 80)
                            };
                        } else {
                            userObj = {
                                userid: data[role].results[user]["rep:userId"],
                                name: sakai.api.User.getDisplayName(data[role].results[user]),
                                dottedname: sakai.api.Util.applyThreeDots(sakai.api.User.getDisplayName(data[role].results[user]), 80)
                            };
                        }

                        $.each(currentTemplate.roles, function(i, r){
                            if (currentTemplate.roles[i].title === role) {
                                userObj.permission = currentTemplate.roles[i].id;
                                userObj.originalPermission = currentTemplate.roles[i].id;
                            }
                        });
                        if (data[role].results[user].picture) {
                            userObj.picture = "/~" + data[role].results[user]["rep:userId"] + "/public/profile/" + $.parseJSON(data[role].results[user].picture).name;
                        }
                        else {
                            if (data[role].results[user]["sakai:group-id"]) {
                                userObj.picture = "/dev/images/group_avatar_icon_35x35_nob.png";
                            }
                            else {
                                userObj.picture = "/dev/images/default_User_icon_35x35.png";
                            }
                        }
                        selectedUsers[userObj.userid] = userObj;
                    }
                }
            }
            renderSelectedContacts();
        };

        var fetchMembers = function(){
            sakai.api.Groups.getMembers(sakai_global.group.groupData["sakai:group-id"], "", prepareSelectedContacts, true);
        };

        /**
         * Initialize the modal dialog
         */
        var initializeJQM = function(){
            $addpeopleContainer.jqm({
                modal: true,
                overlay: 20,
                toTop: true,
                onHide: resetAutosuggest
            });
        };

        var showDialog = function(){
            $addpeopleContainer.jqmShow();
        };

        var addBinding = function(){
            // Unbind all
            $(addpeopleCheckbox).die();
            $(addpeopleSelectedPermissions).die();
            $addpeopleFinishAdding.unbind("click", finishAdding);
            $addpeopleRemoveSelected.unbind("click", removeSelected);

            // Bind all
            $addpeopleSelectAllContacts.bind("click", function(){
                checkAll(this, addpeopleCheckbox);
            });
            $addpeopleSelectAllSelectedContacts.bind("click", function(){
                checkAll(this, addpeopleSelectedCheckbox);
            });
            $(addpeopleSelectedCheckbox).live("change", decideEnableDisableControls, $rootel);
            $addpeopleSelectedAllPermissions.bind("change", changeSelectedPermission);
            $(addpeopleCheckbox).live("change", constructSelecteduser, $rootel);
            $(addpeopleSelectedPermissions).live("change", changePermission, $rootel);
            $addpeopleFinishAdding.bind("click", finishAdding);
            $addpeopleRemoveSelected.bind("click", removeSelected);
        };

        var loadRoles = function(){
            currentTemplate = sakai.api.Groups.getTemplate(widgetData.category, widgetData.id);
            $("#addpeople_selected_all_permissions", $rootel).html(sakai.api.Util.TemplateRenderer("addpeople_selected_permissions_template", {"roles": currentTemplate.roles}));
        };

        ////////////
        // EVENTS //
        ////////////

        $(window).bind("init.addpeople.sakai", function(e, initTuid){
            if (initTuid + "addpeople" === tuid || sakai_global.group) {
                if (!hasbeenInit) {
                    if (!widgetData) {
                        widgetData = {
                            "category": sakai_global.group.groupData["sakai:category"],
                            "id": sakai_global.group.groupData["sakai:templateid"]
                        };
                    }
                    loadRoles();
                    addBinding();
                    sakai.api.Util.AutoSuggest.setup($addpeopleMembersAutoSuggestField, {"asHtmlID": tuid,"resultClick":createAutoSuggestedUser},function(){$addpeopleMembersAutoSuggest.show();});
                    initializeJQM();
                    hasbeenInit = true;
                }
                if(sakai_global.group){
                    fetchMembers();
                }
                showDialog();
                sakai.api.User.getContacts(renderContacts);
            }
        });
    };

    sakai.api.Widgets.widgetLoader.informOnLoad("addpeople");

});
<commit_msg>SAKIII-3454 Don't show the current group in the addpeople dialog - filtering was broken<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

/*
 * Dependencies
 *
 * /dev/lib/jquery/plugins/jqmodal.sakai-edited.js
 */

require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai_global.addpeople
     *
     * @class addpeople
     *
     * @description
     * addpeople widget
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.addpeople = function(tuid, showSettings, widgetData){

        /////////////////////////////
        // CONFIGURATION VARIABLES //
        /////////////////////////////

        var $rootel = $("#" + tuid);

        // Containers
        var $addpeopleContainer = $("#addpeople_container", $rootel);
        var $addpeopleContactsContainer = $("#addpeople_contacts_container", $rootel);
        var $addpeopleSelectedContactsContainer = $("#addpeople_selected_contacts_container", $rootel);
        var $addpeopleMembersAutoSuggest = $("#addpeople_members_autosuggest", $rootel);

        // Templates
        var addpeopleContactsTemplate = "addpeople_contacts_template";
        var addpeopleSelectedContactsTemplate = "addpeople_selected_contacts_template";

        // Elements
        var $addpeopleSelectAllContacts = $("#addpeople_select_all_contacts", $rootel);
        var addpeopleCheckbox = ".addpeople_checkbox";
        var addpeopleSelectedCheckbox = ".addpeople_selected_checkbox";
        var addpeopleSelectedPermissions = ".addpeople_selected_permissions";
        var $addpeopleSelectedAllPermissions = $("#addpeople_selected_all_permissions", $rootel);
        var $addpeopleSelectAllSelectedContacts = $("#addpeople_select_all_selected_contacts", $rootel);
        var $addpeopleFinishAdding = $(".addpeople_finish_adding", $rootel);
        var $addpeopleRemoveSelected = $(".addpeople_remove_selected", $rootel);
        var $addpeopleMembersAutoSuggestField = $("#addpeople_members_autosuggest_field", $rootel);

        var selectedUsers = {};
        var currentTemplate = false;
        var hasbeenInit = false;

        ///////////////
        // RENDERING //
        ///////////////

        var renderContacts = function(){
            if ($addpeopleContactsContainer.text() === "") {
                var groups = sakai.api.Groups.getMemberships(sakai.data.me.groups);
                groups = groups.entry;
                if (sakai_global.group && sakai_global.group.groupData && sakai_global.group.groupData["sakai:group-id"]) {
                    groups = _.reject(groups, function(group) {
                        return group["sakai:group-id"] === sakai_global.group.groupData["sakai:group-id"];
                    });
                }
                $addpeopleContactsContainer.html(sakai.api.Util.TemplateRenderer(addpeopleContactsTemplate, {
                    "contacts": sakai.data.me.mycontacts,
                    "groups": groups,
                    "sakai": sakai
                }));
            }
        };

        var renderSelectedContacts = function(){
            $addpeopleSelectedContactsContainer.html(sakai.api.Util.TemplateRenderer(addpeopleSelectedContactsTemplate, {"contacts":selectedUsers, "roles": currentTemplate.roles}));
            enableDisableControls(true);
        };

        /////////////
        // UTILITY //
        /////////////

        var enableDisableControls = function(disable){
            if(disable){
                $addpeopleRemoveSelected.attr("disabled","disabled");
                $addpeopleSelectedAllPermissions.attr("disabled","disabled");
            }else{
                $addpeopleRemoveSelected.removeAttr("disabled");
                $addpeopleSelectedAllPermissions.removeAttr("disabled");
            }
        };

        var decideEnableDisableControls = function(el){
            if($("." + el.currentTarget.className + ":checked").length){
                enableDisableControls(false);
            }else{
                enableDisableControls(true);
            }
            $addpeopleSelectAllSelectedContacts.removeAttr("checked");
        };

        /**
         * Fire an event that indicates the addpeople widget is done adding users.
         * The object containing this userdata is giving to the event
         * Also hide the overlay
         */
        var finishAdding = function(){
            if (sakai_global.group) {
                var managerSelected = false;
                var permissionsToDelete = [];
                $.each(selectedUsers, function(index, user){
                    if (user.originalPermission && user.permission !== user.originalPermission) {
                        permissionsToDelete.push(user);
                    }

                    $.each(currentTemplate.roles, function(i, role){
                        if (user.permission == role.title || user.permission == role.id) {
                            user.permission = role.id;
                            if (role.allowManage) {
                                managerSelected = true;
                            }
                        }
                    });
                });
            }
            if (managerSelected || !sakai_global.group) {
                $(window).trigger("sakai.addpeople.usersswitchedpermission", [tuid.replace("addpeople", ""), permissionsToDelete]);
                $(window).trigger("sakai.addpeople.usersselected", [tuid.replace("addpeople", ""), selectedUsers]);
                $addpeopleContainer.jqmHide();
            } else {
                sakai.api.Util.notification.show(sakai.api.i18n.Widgets.getValueForKey("addpeople","","MANAGE_PARTICIPANTS"), sakai.api.i18n.Widgets.getValueForKey("addpeople","","SELECT_AT_LEAST_ONE_MANAGER"));
            }
        };

        /**
         * Check/Uncheck all items in the list and enable/disable buttons
         */
        var checkAll = function(el, peopleContainer){
            if($(el).is(":checked")){
                $(peopleContainer).attr("checked","checked");
                if (peopleContainer !== addpeopleSelectedCheckbox) {
                    $(peopleContainer).change();
                    renderSelectedContacts();
                }else{
                    enableDisableControls(false);
                }
            }else{
                $(peopleContainer).removeAttr("checked");
                if (peopleContainer !== addpeopleSelectedCheckbox) {
                    $(peopleContainer).removeAttr("checked");
                    $(peopleContainer).change();
                    renderSelectedContacts();
                    $addpeopleSelectAllSelectedContacts.removeAttr("checked");
                } else {
                    enableDisableControls(true);
                }
            }
        };

        /**
         * Construct a user object when adding a user to the list of selected users
         */
        var constructSelecteduser = function(){
            $addpeopleSelectAllSelectedContacts.removeAttr("checked");
            if ($(this).is(":checked")) {
                if (!selectedUsers[$(this)[0].id.split("_")[0]]) {
                    var userObj = {
                        userid: $(this)[0].id.split("_")[0],
                        roleid: $(this).val(),
                        name: $(this).nextAll(".s3d-entity-displayname").text(),
                        dottedname: sakai.api.Util.applyThreeDots($(this).nextAll(".s3d-entity-displayname").text(), 80),
                        permission: currentTemplate.joinRole,
                        picture: $(this).next().children("img").attr("src"),
                        tmpsrc:"checklistadded"
                    };
                    selectedUsers[userObj.userid] = userObj;
                    renderSelectedContacts();
                }
            }else{
                delete selectedUsers[$(this)[0].id.split("_")[0]];
                renderSelectedContacts();
                $addpeopleSelectAllSelectedContacts.removeAttr("checked");
                $addpeopleSelectAllContacts.removeAttr("checked");
            }
        };

        /**
         * Batch change the permission setting for a specific selection of users
         */
        var changeSelectedPermission = function(){
            var selectedPermission = $(this).val();
            $.each($addpeopleSelectedContactsContainer.find("input:checked"), function(index, item){
                $(item).nextAll("select").val(selectedPermission);
                selectedUsers[$(item)[0].id.split("_")[0]].permission = selectedPermission;
            });
        };

        /**
         * Change the permission setting for a specific user
         */
        var changePermission = function(){
            var userid = $(this)[0].id.split("_")[0];
            selectedUsers[userid].permission = $(this).val();
        };

        /**
         * Removes all users that are selected from the list of users to be added as a member (manager or viewer)
         */
        var removeSelected = function(){
            var managerLeft = false;
            $.each($addpeopleSelectedContactsContainer.find("input:not(:checked)"), function(index, user){
                $.each(currentTemplate.roles, function(i, role){
                    if (role.allowManage) {
                        if ($(user).nextAll("select").val() == role.id) {
                            managerLeft = true;
                        }
                    }
                });
            });
            if (managerLeft) {
                var usersToDelete = [];
                $.each($addpeopleSelectedContactsContainer.find("input:checked"), function(index, item){
                    usersToDelete.push({
                        "userid": $(item)[0].id.split("_")[0],
                        "permission": $(item).nextAll("select").val()
                    });
                    delete selectedUsers[$(item)[0].id.split("_")[0]];
                    $("#" + $(item)[0].id.split("_")[0] + "_chk").removeAttr("checked");
                    $addpeopleSelectAllContacts.removeAttr("checked");
                    $(item).parent().next().remove();
                    $(item).parent().remove();
                });
                sakai.api.Groups.removeUsersFromGroup(sakai_global.group.groupData["sakai:group-id"], false, usersToDelete, sakai.data.me);
                $addpeopleSelectAllSelectedContacts.removeAttr("checked");
            } else {
                sakai.api.Util.notification.show(sakai.api.i18n.Widgets.getValueForKey("addpeople", "", "MANAGE_PARTICIPANTS"), sakai.api.i18n.Widgets.getValueForKey("addpeople", "", "SELECT_AT_LEAST_ONE_MANAGER"));
            }
        };

        ////////////////////
        // INITIALIZATION //
        ////////////////////

        /**
         * Get the list of selected users/groups from the autosuggest plugin
         * @return {Object} returnValue An object containing a list of displayNames and an Array of userID's to be added to the members list
         */
        var createAutoSuggestedUser = function(userData) {
            var pictureURL = "";
            var userid = userData.attributes.value;
            if (userData.attributes.picture) {
                pictureURL = "/~" + userid + "/public/profile/" + userData.attributes.picture;
            } else {
                if (userData.attributes.type=== "group") {
                    pictureURL = "/dev/images/group_avatar_icon_35x35_nob.png";
                } else {
                    pictureURL = "/dev/images/default_User_icon_35x35.png";
                }
            }
            var userObj = {
                userid: userid,
                name: userData.attributes.name,
                dottedname: sakai.api.Util.applyThreeDots(userData.attributes.name, 80),
                permission: currentTemplate.joinRole,
                picture: pictureURL,
                tmpsrc:"autsuggestadded"
            };
            selectedUsers[userObj.userid] = userObj;
            renderSelectedContacts();
            $(".as-close").click();
        };

        /**
         * Clears the input field, closes the autosuggest and then hides the modal/overlay, called onHide in jqm
         */
        var resetAutosuggest = function(h){
            sakai.api.Util.AutoSuggest.reset($addpeopleMembersAutoSuggestField);
            for(user in selectedUsers){
                if(selectedUsers.hasOwnProperty(user) && selectedUsers[user].tmpsrc){
                    delete selectedUsers[user];
                }
            }
            $("ul",$addpeopleSelectedContactsContainer).empty();
            $(addpeopleCheckbox).add($addpeopleSelectAllContacts).removeAttr("checked");
            h.w.hide();
            if (h.o) {
                h.o.remove();
            }
        };

        var prepareSelectedContacts = function(success, data){
            for(var role in data){
                for(var user in data[role].results){
                    if (data[role].results.hasOwnProperty(user)) {
                        var userObj = {};
                        if (data[role].results[user].hasOwnProperty("sakai:group-id")) {
                            userObj = {
                                userid: data[role].results[user]["sakai:group-id"],
                                name: data[role].results[user]["sakai:group-title"],
                                dottedname: sakai.api.Util.applyThreeDots(data[role].results[user]["sakai:group-title"], 80)
                            };
                        } else {
                            userObj = {
                                userid: data[role].results[user]["rep:userId"],
                                name: sakai.api.User.getDisplayName(data[role].results[user]),
                                dottedname: sakai.api.Util.applyThreeDots(sakai.api.User.getDisplayName(data[role].results[user]), 80)
                            };
                        }

                        $.each(currentTemplate.roles, function(i, r){
                            if (currentTemplate.roles[i].title === role) {
                                userObj.permission = currentTemplate.roles[i].id;
                                userObj.originalPermission = currentTemplate.roles[i].id;
                            }
                        });
                        if (data[role].results[user].picture) {
                            userObj.picture = "/~" + data[role].results[user]["rep:userId"] + "/public/profile/" + $.parseJSON(data[role].results[user].picture).name;
                        }
                        else {
                            if (data[role].results[user]["sakai:group-id"]) {
                                userObj.picture = "/dev/images/group_avatar_icon_35x35_nob.png";
                            }
                            else {
                                userObj.picture = "/dev/images/default_User_icon_35x35.png";
                            }
                        }
                        selectedUsers[userObj.userid] = userObj;
                    }
                }
            }
            renderSelectedContacts();
        };

        var fetchMembers = function(){
            sakai.api.Groups.getMembers(sakai_global.group.groupData["sakai:group-id"], "", prepareSelectedContacts, true);
        };

        /**
         * Initialize the modal dialog
         */
        var initializeJQM = function(){
            $addpeopleContainer.jqm({
                modal: true,
                overlay: 20,
                toTop: true,
                onHide: resetAutosuggest
            });
        };

        var showDialog = function(){
            $addpeopleContainer.jqmShow();
        };

        var addBinding = function(){
            // Unbind all
            $(addpeopleCheckbox).die();
            $(addpeopleSelectedPermissions).die();
            $addpeopleFinishAdding.unbind("click", finishAdding);
            $addpeopleRemoveSelected.unbind("click", removeSelected);

            // Bind all
            $addpeopleSelectAllContacts.bind("click", function(){
                checkAll(this, addpeopleCheckbox);
            });
            $addpeopleSelectAllSelectedContacts.bind("click", function(){
                checkAll(this, addpeopleSelectedCheckbox);
            });
            $(addpeopleSelectedCheckbox).live("change", decideEnableDisableControls, $rootel);
            $addpeopleSelectedAllPermissions.bind("change", changeSelectedPermission);
            $(addpeopleCheckbox).live("change", constructSelecteduser, $rootel);
            $(addpeopleSelectedPermissions).live("change", changePermission, $rootel);
            $addpeopleFinishAdding.bind("click", finishAdding);
            $addpeopleRemoveSelected.bind("click", removeSelected);
        };

        var loadRoles = function(){
            currentTemplate = sakai.api.Groups.getTemplate(widgetData.category, widgetData.id);
            $("#addpeople_selected_all_permissions", $rootel).html(sakai.api.Util.TemplateRenderer("addpeople_selected_permissions_template", {"roles": currentTemplate.roles}));
        };

        ////////////
        // EVENTS //
        ////////////

        $(window).bind("init.addpeople.sakai", function(e, initTuid){
            if (initTuid + "addpeople" === tuid || sakai_global.group) {
                if (!hasbeenInit) {
                    if (!widgetData) {
                        widgetData = {
                            "category": sakai_global.group.groupData["sakai:category"],
                            "id": sakai_global.group.groupData["sakai:templateid"]
                        };
                    }
                    loadRoles();
                    addBinding();
                    sakai.api.Util.AutoSuggest.setup($addpeopleMembersAutoSuggestField, {"asHtmlID": tuid,"resultClick":createAutoSuggestedUser},function(){$addpeopleMembersAutoSuggest.show();});
                    initializeJQM();
                    hasbeenInit = true;
                }
                if(sakai_global.group){
                    fetchMembers();
                }
                showDialog();
                sakai.api.User.getContacts(renderContacts);
            }
        });
    };

    sakai.api.Widgets.widgetLoader.informOnLoad("addpeople");

});
<|endoftext|>


<commit_before>const gulp = require('gulp');
const filter = require('gulp-filter');
const useref = require('gulp-useref');
const rev = require('gulp-rev');
const revReplace = require('gulp-rev-replace');
const uglify = require('gulp-uglify');
const cssnano = require('gulp-cssnano');
const htmlmin = require('gulp-htmlmin');
const sourcemaps = require('gulp-sourcemaps');
const uglifySaveLicense = require('uglify-save-license');
<% if (framework === 'angular1' && modules === 'inject') { -%>
const inject = require('gulp-inject');
<% } -%>
<% if (framework === 'angular1') { -%>
const ngAnnotate = require('gulp-ng-annotate');
<% } -%>

const conf = require('../conf/gulp.conf');

gulp.task('build', build);

function build() {
<% if (framework === 'angular1' && modules === 'inject') { -%>
  const partialsInjectFile = gulp.src(conf.path.tmp('templateCacheHtml.js'), {read: false});
  const partialsInjectOptions = {
    starttag: '<!-- inject:partials -->',
    ignorePath: conf.paths.tmp,
    addRootSlash: false
  };

<% } -%>
  const htmlFilter = filter('*.html', {restore: true});
  const jsFilter = filter('**/*.js', {restore: true});
  const cssFilter = filter('**/*.css', {restore: true});

  return gulp.src(conf.path.tmp('/index.html'))
<% if (framework === 'angular1' && modules === 'inject') { -%>
    .pipe(inject(partialsInjectFile, partialsInjectOptions))
<% } -%>
    .pipe(useref())
    .pipe(jsFilter)
    .pipe(sourcemaps.init())
<% if (framework === 'angular1') { -%>
    .pipe(ngAnnotate())
<% } -%>
    .pipe(uglify({preserveComments: uglifySaveLicense})).on('error', conf.errorHandler('Uglify'))
    .pipe(rev())
    .pipe(sourcemaps.write('maps'))
    .pipe(jsFilter.restore)
    .pipe(cssFilter)
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(rev())
    .pipe(sourcemaps.write('maps'))
    .pipe(cssFilter.restore)
    .pipe(revReplace())
    .pipe(htmlFilter)
    .pipe(htmlmin())
    .pipe(htmlFilter.restore)
    .pipe(gulp.dest(conf.path.dist()));
}
<commit_msg>Add relative path since gulp-filter update to 4.0.0<commit_after>const gulp = require('gulp');
const filter = require('gulp-filter');
const useref = require('gulp-useref');
const rev = require('gulp-rev');
const revReplace = require('gulp-rev-replace');
const uglify = require('gulp-uglify');
const cssnano = require('gulp-cssnano');
const htmlmin = require('gulp-htmlmin');
const sourcemaps = require('gulp-sourcemaps');
const uglifySaveLicense = require('uglify-save-license');
<% if (framework === 'angular1' && modules === 'inject') { -%>
const inject = require('gulp-inject');
<% } -%>
<% if (framework === 'angular1') { -%>
const ngAnnotate = require('gulp-ng-annotate');
<% } -%>

const conf = require('../conf/gulp.conf');

gulp.task('build', build);

function build() {
<% if (framework === 'angular1' && modules === 'inject') { -%>
  const partialsInjectFile = gulp.src(conf.path.tmp('templateCacheHtml.js'), {read: false});
  const partialsInjectOptions = {
    starttag: '<!-- inject:partials -->',
    ignorePath: conf.paths.tmp,
    addRootSlash: false
  };

<% } -%>
  const htmlFilter = filter(conf.path.tmp('*.html'), {restore: true});
  const jsFilter = filter(conf.path.tmp('**/*.js'), {restore: true});
  const cssFilter = filter(conf.path.tmp('**/*.css'), {restore: true});

  return gulp.src(conf.path.tmp('/index.html'))
<% if (framework === 'angular1' && modules === 'inject') { -%>
    .pipe(inject(partialsInjectFile, partialsInjectOptions))
<% } -%>
    .pipe(useref())
    .pipe(jsFilter)
    .pipe(sourcemaps.init())
<% if (framework === 'angular1') { -%>
    .pipe(ngAnnotate())
<% } -%>
    .pipe(uglify({preserveComments: uglifySaveLicense})).on('error', conf.errorHandler('Uglify'))
    .pipe(rev())
    .pipe(sourcemaps.write('maps'))
    .pipe(jsFilter.restore)
    .pipe(cssFilter)
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(rev())
    .pipe(sourcemaps.write('maps'))
    .pipe(cssFilter.restore)
    .pipe(revReplace())
    .pipe(htmlFilter)
    .pipe(htmlmin())
    .pipe(htmlFilter.restore)
    .pipe(gulp.dest(conf.path.dist()));
}
<|endoftext|>


<commit_before>var _ = require('underscore');
var $ = require('jquery');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var EditorWidgetView = require('./widget-view');
var template = require('./widgets-view.tpl');
var widgetPlaceholderTemplate = require('./widgets-placeholder.tpl');
var widgetsErrorTemplate = require('./widgets-content-error.tpl');
var widgetsNotReadyTemplate = require('./widgets-content-not-ready.tpl');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var AddWidgetsView = require('builder/components/modals/add-widgets/add-widgets-view');
var TipsyTooltipView = require('builder/components/tipsy-tooltip-view');

require('jquery-ui');

var STATES = {
  loading: 'loading',
  ready: 'ready'
};

var REQUIRED_OPTS = [
  'userActions',
  'analysisDefinitionNodesCollection',
  'layerDefinitionsCollection',
  'widgetDefinitionsCollection',
  'userModel',
  'stackLayoutModel',
  'configModel',
  'modals'
];

/**
 * View to render widgets definitions overview
 */
module.exports = CoreView.extend({

  module: 'editor:widgets:widgets-view',

  events: {
    'click .js-add': '_addWidget'
  },

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this.viewModel = new Backbone.Model({
      state: STATES.loading
    });

    this._initViewState();
    this._initBinds();

    var callback = this._onAllQueryGeometryLoaded.bind(this);
    this._layerDefinitionsCollection.loadAllQueryGeometryModels(callback);
  },

  render: function () {
    this._destroySortable();
    this.clearSubViews();
    this.$el.empty();

    this._initViews();

    return this;
  },

  _initViewState: function () {
    this._viewState = new Backbone.Model({
      anyGeometryData: true
    });

    this._setViewState();
  },

  _initViews: function () {
    if (this._isLoading()) {
      this.$el.append(widgetsNotReadyTemplate());
    } else {
      if (!this._viewState.get('anyGeometryData')) {
        this._showNoGeometryData();
      } else {
        if (this._widgetDefinitionsCollection.size() > 0) {
          this.$el.append(template);
          _.each(this._widgetDefinitionsCollection.sortBy('order'), this._addWidgetItem, this);
          this._initSortable();
        } else {
          this.$el.append(widgetPlaceholderTemplate());
        }

        var tooltip = new TipsyTooltipView({
          el: this.$('.js-add'),
          gravity: 'w',
          title: function () {
            return _t('editor.widgets.add-widget.tooltip');
          },
          offset: 8
        });
        this.addView(tooltip);
      }
    }
  },

  _initBinds: function () {
    this.listenTo(this._widgetDefinitionsCollection, 'destroy successAdd', this.render, this);
    this.listenTo(this.viewModel, 'change:state', this.render, this);
    this.listenTo(this._viewState, 'change', this.render);
  },

  _showNoGeometryData: function () {
    this.$el.append(
      widgetsErrorTemplate({
        body: _t('editor.widgets.no-geometry-data')
      })
    );
  },

  _onAllQueryGeometryLoaded: function () {
    this.viewModel.set('state', STATES.ready);
  },

  _isLoading: function () {
    return this.viewModel.get('state') === STATES.loading;
  },

  _isReady: function () {
    return this.viewModel.get('state') === STATES.ready;
  },

  _setViewState: function () {
    this._layerDefinitionsCollection.isThereAnyGeometryData()
      .then(function (anyGeometry) {
        this._viewState.set('anyGeometryData', anyGeometry);
      }.bind(this));
  },

  _initSortable: function () {
    this.$('.js-widgets').sortable({
      axis: 'y',
      items: '> li.BlockList-item',
      opacity: 0.8,
      update: this._onSortableFinish.bind(this),
      forcePlaceholderSize: false
    }).disableSelection();
  },

  _destroySortable: function () {
    if (this.$('.js-widgets').data('ui-sortable')) {
      this.$('.js-widgets').sortable('destroy');
    }
  },

  _onSortableFinish: function () {
    var self = this;
    this.$('.js-widgets > .js-widgetItem').each(function (index, item) {
      var modelCid = $(item).data('model-cid');
      var widgetDefModel = self._widgetDefinitionsCollection.get(modelCid);
      widgetDefModel.set('order', index);
      self._userActions.saveWidget(widgetDefModel);
    });
  },

  _addWidget: function () {
    if (this.$('.js-add').hasClass('is-disabled')) return;

    var self = this;

    this._modals.create(function (modalModel) {
      return new AddWidgetsView({
        modalModel: modalModel,
        userModel: self._userModel,
        userActions: self._userActions,
        configModel: self._configModel,
        analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection,
        layerDefinitionsCollection: self._layerDefinitionsCollection,
        widgetDefinitionsCollection: self._widgetDefinitionsCollection
      });
    }, {
      breadcrumbsEnabled: true
    });
  },

  _addWidgetItem: function (model) {
    var view = new EditorWidgetView({
      model: model,
      layer: this._layerDefinitionsCollection.get(model.get('layer_id')),
      modals: this._modals,
      userActions: this._userActions,
      stackLayoutModel: this._stackLayoutModel
    });
    this.addView(view);
    this.$('.js-widgets').append(view.render().el);
  },

  clean: function () {
    this._destroySortable();
    CoreView.prototype.clean.apply(this);
  }
});
<commit_msg>Refactor<commit_after>var _ = require('underscore');
var $ = require('jquery');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var EditorWidgetView = require('./widget-view');
var template = require('./widgets-view.tpl');
var widgetPlaceholderTemplate = require('./widgets-placeholder.tpl');
var widgetsErrorTemplate = require('./widgets-content-error.tpl');
var widgetsNotReadyTemplate = require('./widgets-content-not-ready.tpl');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var AddWidgetsView = require('builder/components/modals/add-widgets/add-widgets-view');
var TipsyTooltipView = require('builder/components/tipsy-tooltip-view');

require('jquery-ui');

var STATES = {
  loading: 'loading',
  ready: 'ready'
};

var REQUIRED_OPTS = [
  'userActions',
  'analysisDefinitionNodesCollection',
  'layerDefinitionsCollection',
  'widgetDefinitionsCollection',
  'userModel',
  'stackLayoutModel',
  'configModel',
  'modals'
];

/**
 * View to render widgets definitions overview
 */
module.exports = CoreView.extend({

  module: 'editor:widgets:widgets-view',

  events: {
    'click .js-add': '_addWidget'
  },

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this.viewModel = new Backbone.Model({
      state: STATES.loading
    });

    this._initViewState();
    this._initBinds();

    var callback = this._onAllQueryGeometryLoaded.bind(this);
    this._layerDefinitionsCollection.loadAllQueryGeometryModels(callback);
  },

  render: function () {
    this._destroySortable();
    this.clearSubViews();
    this.$el.empty();

    this._initViews();

    return this;
  },

  _initViewState: function () {
    this._viewState = new Backbone.Model({
      anyGeometryData: true
    });

    this._setViewState();
  },

  _initViews: function () {
    if (this._isLoading()) {
      this.$el.append(widgetsNotReadyTemplate());
      return;
    }

    if (!this._viewState.get('anyGeometryData')) {
      this._showNoGeometryData();
      return;
    }

    if (this._widgetDefinitionsCollection.size() > 0) {
      this.$el.append(template);
      _.each(this._widgetDefinitionsCollection.sortBy('order'), this._addWidgetItem, this);
      this._initSortable();
      this._addTooltip();
      return;
    }

    this.$el.append(widgetPlaceholderTemplate());
    this._addTooltip();
  },

  _initBinds: function () {
    this.listenTo(this._widgetDefinitionsCollection, 'destroy successAdd change', this.render, this);
    this.listenTo(this.viewModel, 'change:state', this.render, this);
    this.listenTo(this._viewState, 'change', this.render);
  },

  _showNoGeometryData: function () {
    this.$el.append(
      widgetsErrorTemplate({
        body: _t('editor.widgets.no-geometry-data')
      })
    );
  },

  _onAllQueryGeometryLoaded: function () {
    this.viewModel.set('state', STATES.ready);
  },

  _addTooltip: function () {
    var tooltip = new TipsyTooltipView({
      el: this.$('.js-add'),
      gravity: 'w',
      title: function () {
        return _t('editor.widgets.add-widget.tooltip');
      },
      offset: 8
    });

    this.addView(tooltip);
  },

  _isLoading: function () {
    return this.viewModel.get('state') === STATES.loading;
  },

  _isReady: function () {
    return this.viewModel.get('state') === STATES.ready;
  },

  _setViewState: function () {
    this._layerDefinitionsCollection.isThereAnyGeometryData()
      .then(function (anyGeometry) {
        this._viewState.set('anyGeometryData', anyGeometry);
      }.bind(this));
  },

  _initSortable: function () {
    this.$('.js-widgets').sortable({
      axis: 'y',
      items: '> li.BlockList-item',
      opacity: 0.8,
      update: this._onSortableFinish.bind(this),
      forcePlaceholderSize: false
    }).disableSelection();
  },

  _destroySortable: function () {
    if (this.$('.js-widgets').data('ui-sortable')) {
      this.$('.js-widgets').sortable('destroy');
    }
  },

  _onSortableFinish: function () {
    var self = this;
    this.$('.js-widgets > .js-widgetItem').each(function (index, item) {
      var modelCid = $(item).data('model-cid');
      var widgetDefModel = self._widgetDefinitionsCollection.get(modelCid);
      widgetDefModel.set('order', index);
      self._userActions.saveWidget(widgetDefModel);
    });
  },

  _addWidget: function () {
    if (this.$('.js-add').hasClass('is-disabled')) return;

    var self = this;

    this._modals.create(function (modalModel) {
      return new AddWidgetsView({
        modalModel: modalModel,
        userModel: self._userModel,
        userActions: self._userActions,
        configModel: self._configModel,
        analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection,
        layerDefinitionsCollection: self._layerDefinitionsCollection,
        widgetDefinitionsCollection: self._widgetDefinitionsCollection
      });
    }, {
      breadcrumbsEnabled: true
    });
  },

  _addWidgetItem: function (model) {
    var view = new EditorWidgetView({
      model: model,
      layer: this._layerDefinitionsCollection.get(model.get('layer_id')),
      modals: this._modals,
      userActions: this._userActions,
      stackLayoutModel: this._stackLayoutModel
    });
    this.addView(view);
    this.$('.js-widgets').append(view.render().el);
  },

  clean: function () {
    this._destroySortable();
    CoreView.prototype.clean.apply(this);
  }
});
<|endoftext|>