<commit_before>var XenAuction = {};

XenAuction.Config = {
	currentTime: 0,
	phrases: {
		'secondsLeft': 	'Seconds Left',
		'minutesLeft': 	'Minutes Left',
		'hoursLeft': 	'Hours Left',
		'daysLeft': 	'Days Left',

		'errorInvalidQuantity': 	'You are trying to buy a higher quantity than there is available'
	}
};

XenAuction.List = function() { this.__construct(); };
XenAuction.List.prototype = {
	__construct: function()
	{

		this.parseTimeleft();

		$(document).ready(function()
		{

			if ($(".chzn-select").length > 0)
			{
				$(".chzn-select").chosen();
			}

		});

	},

	parseTimeleft: function()
	{

		$(".auctionItem .timeLeft").each(function() {

			if ($(this).parents('.status_active').length == 0 || $(this).data('processed'))
			{
				return;
			}

			var time = $(this).text();
			var left = time - XenAuction.Config.currentTime;

			if (left < 0)
			{
				$(this).parents(".auctionItem").hide();
				return;
			}
			else if (left < 60)
			{
				var p = [left, XenAuction.Config.phrases.secondsLeft];
			}
			else if (left < 3600)
			{
				var p = [left / 60, XenAuction.Config.phrases.minutesLeft];
			}
			else if (left < 86400)
			{
				var p = [left / 3600, XenAuction.Config.phrases.hoursLeft];
			}
			else
			{
				var p = [left / 86400, XenAuction.Config.phrases.daysLeft];
			}

			$(this).html("");

			$(this).append($("
").text(Math.ceil(p[0])));
			$(this).append($("
").text(p[1]));

			$(this).data('processed', true);

		});

	}
};

XenAuction.Widget = function() { this.__construct(); };
XenAuction.Widget.prototype = {
	__construct: function()
	{
		this.renderWidget();
		//var checkCsrf = setInterval($.context(function() {
		//	if (XenForo._csrfToken != '')
		//	{
		//		clearInterval(checkCsrf);
		//		this.loadWidget();
		//	}
		//}, this));
	},

	loadWidget: function()
	{
		XenForo.ajax($("base").attr("href") + 'auctions/random', [{name: '_xfToken', value: XenForo._csrfToken}], $.context(this.renderWidget, this));
	},

	renderWidget: function(data)
	{
		//$("#auctionWidgetPlaceholder").replaceWith($(data.templateHtml));
		$(window).resize(this.resizer);
		this.resizer();
	},

	resizer: function()
	{
		var liWidth = $("#auctionWidget > li:first-child").outerWidth(true);

		$("#auctionWidget > li").hide();

		var total = 0;

		for (var i=10;i>0;i--)
		{
			$("#auctionWidget > li:nth-child("+i+")").show();
			total += $("#auctionWidget > li:nth-child("+i+")").outerWidth(true);

			if (total > $("#auctionWidget").innerWidth())
			{
				$("#auctionWidget > li:nth-child("+i+")").hide();
				break;
			}
		}
	}
};

XenAuction.Bid = function() { this.__construct(); };
XenAuction.Bid.prototype = {
	__construct: function()
	{

		$("input[name=quantity]").keyup(this.onChangeQuantity);
		$("input[name=bid]").keyup(this.onChangeBid);

	},

	onChangeBid: function()
	{
		$(this).next('.formValidationInlineError').remove();

		var form = $(this).parents('form.auctionBid');

		var bid 	= parseInt($(this).val());
		var minBid 	= parseInt(form.find("input.min_bid").val());

		if (isNaN(bid) || bid < minBid)
		{
			XenAuction.Helpers.showInputError(this, XenAuction.Config.phrases.errorBidTooLow);
		}
	},

	onChangeQuantity: function()
	{
		$(this).next('.formValidationInlineError').remove();

		var form = $(this).parents('form.auctionBid');

		var quantity 		= $(this).val();
		var cost 			= form.find("input.cost").val();
		var availability 	= form.find("input.availability").val();

		if (isNaN(quantity) || quantity > availability)
		{
			XenAuction.Helpers.showInputError(this, XenAuction.Config.phrases.errorInvalidQuantity);
		}

		var totalCost = parseInt(quantity) * parseFloat(cost);

		form.find('dd.paying').text(number_format(totalCost));
	}

};

XenAuction.Create = function() { this.__construct(); };
XenAuction.Create.prototype = {
	__construct: function()
	{

		$("input[name=bid_enable]").click(this.toggleEnable);
		$("input[name=buyout_enable]").click(this.toggleEnable);
		$(".chzn-select").chosen({allow_option_creation: true});

	},

	toggleEnable: function()
	{

		if ($(this).is(":checked"))
		{
			$(this).prev('input').removeAttr('disabled');
		}
		else
		{
			$(this).prev('input').attr('disabled', 'disabled');
		}

		if ($("#bid_enable").is(":checked"))
		{
			$("#availability_wrap").hide();
			$("#availability_wrap").find("input[name=availability]").val(1);
		}
		else if ($("#buyout_enable").is(":checked"))
		{
			$("#availability_wrap").show();
		}

	},

}

XenAuction.HistoryPanes = function() { this.__construct(); };
XenAuction.HistoryPanes.prototype = {
	__construct: function()
	{
		this.overrideTabConstructor();
		this.$tabs = new XenForo.Tabs($('#HistoryTabs'));
		this.removeParamsFromUrls();

		$(".historySearch form").submit( this.searchSubmit );
	},

	searchSubmit: function()
	{
		var href = window.location.pathname + window.location.search;
		var regex = new RegExp(/(?:\?|\&|\%3F|\&amp\;)page\=\d*/);
		href = href.replace(regex, '');

		$(".historySearch form").attr("action", href + '#' + $("#HistoryPanes li:visible").attr("id"));
	},

	overrideTabConstructor: function()
	{
		XenForo.Tabs.prototype.__construct = function($tabContainer)
		{
			this.$tabContainer = $tabContainer;
			this.$panes = $($tabContainer.data('panes'));

			var index = 0;

			$tabContainer.find('a[href]').each(function()
			{
				var $this = $(this), hrefParts = $this.attr('href').split('#');
				if (location.hash.substr(1) == hrefParts[1])
				{
					$tabContainer.find(".active").removeClass("active");
					$this.addClass("active");
					$this.parent().addClass("active");
					index = $this.parent().index();
				}
			});

			$tabContainer.tabs(this.$panes, {
				current: 'active',
				history: false,
				onBeforeClick: $.context(this, 'onBeforeClick'),
				initialIndex: index
			});
			this.api = $tabContainer.data('tabs');
		}
	},

	removeParamsFromUrls: function()
	{
		var regex = new RegExp(/(?:\?|\&|\%3F|\&amp\;)(?:page|search)\=[A-Za-z0-9 ]*/);

		this.$tabs.$panes.each(function()
		{
			var url = $(this).data('loadUrl');
			url = url.replace(regex, '');
			$(this).data('loadUrl', url);
		});

		$("#HistoryTabs > li > a").each(function()
		{
			var url = $(this).attr("href");
			url = url.replace(regex, '');
			$(this).attr("href", url);
		});
	}
}

XenAuction.Helpers = {

	showInputError: function(input, message)
	{
		var error 	= $(''+message+'').insertAfter(input);
		var coords 	= $(input).coords('outer', 'position');
		error.css({
			top: coords.top,
			left: coords.left + coords.width + 10
		}).show();
	},

	fixOverlay: function()
	{
		var originalOverlay 	= XenForo.createOverlay;
		XenForo.createOverlay 	= function($trigger, templateHtml, extraOptions)
		{
			var overlay = originalOverlay.call(this, $trigger, templateHtml, extraOptions);
			var elem 	= overlay.getOverlay();

			overlay.onLoad = function()
			{
				var position= elem.position();
				elem.css('position', 'absolute');
				elem.position(position);
				elem.find(".button[type=reset]").removeAttr('disabled').removeClass('disabled');

				elem.find(".Disabler").click(function() {
					setTimeout(function() {
						elem.find(".button[type=reset]").removeAttr('disabled').removeClass('disabled');
					}, 100);
				});
			};

			overlay.onClose = function()
			{
				elem.find('form').trigger('reset');
			};

			return overlay;
		};
	}

}

$(document).ready(XenAuction.Helpers.fixOverlay);

// helpers

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
<commit_msg>Fix overlay position<commit_after>var XenAuction = {};

XenAuction.Config = {
	currentTime: 0,
	phrases: {
		'secondsLeft': 	'Seconds Left',
		'minutesLeft': 	'Minutes Left',
		'hoursLeft': 	'Hours Left',
		'daysLeft': 	'Days Left',

		'errorInvalidQuantity': 	'You are trying to buy a higher quantity than there is available'
	}
};

XenAuction.List = function() { this.__construct(); };
XenAuction.List.prototype = {
	__construct: function()
	{

		this.parseTimeleft();

		$(document).ready(function()
		{

			if ($(".chzn-select").length > 0)
			{
				$(".chzn-select").chosen();
			}

		});

	},

	parseTimeleft: function()
	{

		$(".auctionItem .timeLeft").each(function() {

			if ($(this).parents('.status_active').length == 0 || $(this).data('processed'))
			{
				return;
			}

			var time = $(this).text();
			var left = time - XenAuction.Config.currentTime;

			if (left < 0)
			{
				$(this).parents(".auctionItem").hide();
				return;
			}
			else if (left < 60)
			{
				var p = [left, XenAuction.Config.phrases.secondsLeft];
			}
			else if (left < 3600)
			{
				var p = [left / 60, XenAuction.Config.phrases.minutesLeft];
			}
			else if (left < 86400)
			{
				var p = [left / 3600, XenAuction.Config.phrases.hoursLeft];
			}
			else
			{
				var p = [left / 86400, XenAuction.Config.phrases.daysLeft];
			}

			$(this).html("");

			$(this).append($("
").text(Math.ceil(p[0])));
			$(this).append($("
").text(p[1]));

			$(this).data('processed', true);

		});

	}
};

XenAuction.Widget = function() { this.__construct(); };
XenAuction.Widget.prototype = {
	__construct: function()
	{
		this.renderWidget();
		//var checkCsrf = setInterval($.context(function() {
		//	if (XenForo._csrfToken != '')
		//	{
		//		clearInterval(checkCsrf);
		//		this.loadWidget();
		//	}
		//}, this));
	},

	loadWidget: function()
	{
		XenForo.ajax($("base").attr("href") + 'auctions/random', [{name: '_xfToken', value: XenForo._csrfToken}], $.context(this.renderWidget, this));
	},

	renderWidget: function(data)
	{
		//$("#auctionWidgetPlaceholder").replaceWith($(data.templateHtml));
		$(window).resize(this.resizer);
		this.resizer();
	},

	resizer: function()
	{
		var liWidth = $("#auctionWidget > li:first-child").outerWidth(true);

		$("#auctionWidget > li").hide();

		var total = 0;

		for (var i=10;i>0;i--)
		{
			$("#auctionWidget > li:nth-child("+i+")").show();
			total += $("#auctionWidget > li:nth-child("+i+")").outerWidth(true);

			if (total > $("#auctionWidget").innerWidth())
			{
				$("#auctionWidget > li:nth-child("+i+")").hide();
				break;
			}
		}
	}
};

XenAuction.Bid = function() { this.__construct(); };
XenAuction.Bid.prototype = {
	__construct: function()
	{

		$("input[name=quantity]").keyup(this.onChangeQuantity);
		$("input[name=bid]").keyup(this.onChangeBid);

	},

	onChangeBid: function()
	{
		$(this).next('.formValidationInlineError').remove();

		var form = $(this).parents('form.auctionBid');

		var bid 	= parseInt($(this).val());
		var minBid 	= parseInt(form.find("input.min_bid").val());

		if (isNaN(bid) || bid < minBid)
		{
			XenAuction.Helpers.showInputError(this, XenAuction.Config.phrases.errorBidTooLow);
		}
	},

	onChangeQuantity: function()
	{
		$(this).next('.formValidationInlineError').remove();

		var form = $(this).parents('form.auctionBid');

		var quantity 		= $(this).val();
		var cost 			= form.find("input.cost").val();
		var availability 	= form.find("input.availability").val();

		if (isNaN(quantity) || quantity > availability)
		{
			XenAuction.Helpers.showInputError(this, XenAuction.Config.phrases.errorInvalidQuantity);
		}

		var totalCost = parseInt(quantity) * parseFloat(cost);

		form.find('dd.paying').text(number_format(totalCost));
	}

};

XenAuction.Create = function() { this.__construct(); };
XenAuction.Create.prototype = {
	__construct: function()
	{

		$("input[name=bid_enable]").click(this.toggleEnable);
		$("input[name=buyout_enable]").click(this.toggleEnable);
		$(".chzn-select").chosen({allow_option_creation: true});

	},

	toggleEnable: function()
	{

		if ($(this).is(":checked"))
		{
			$(this).prev('input').removeAttr('disabled');
		}
		else
		{
			$(this).prev('input').attr('disabled', 'disabled');
		}

		if ($("#bid_enable").is(":checked"))
		{
			$("#availability_wrap").hide();
			$("#availability_wrap").find("input[name=availability]").val(1);
		}
		else if ($("#buyout_enable").is(":checked"))
		{
			$("#availability_wrap").show();
		}

	},

}

XenAuction.HistoryPanes = function() { this.__construct(); };
XenAuction.HistoryPanes.prototype = {
	__construct: function()
	{
		this.overrideTabConstructor();
		this.$tabs = new XenForo.Tabs($('#HistoryTabs'));
		this.removeParamsFromUrls();

		$(".historySearch form").submit( this.searchSubmit );
	},

	searchSubmit: function()
	{
		var href = window.location.pathname + window.location.search;
		var regex = new RegExp(/(?:\?|\&|\%3F|\&amp\;)page\=\d*/);
		href = href.replace(regex, '');

		$(".historySearch form").attr("action", href + '#' + $("#HistoryPanes li:visible").attr("id"));
	},

	overrideTabConstructor: function()
	{
		XenForo.Tabs.prototype.__construct = function($tabContainer)
		{
			this.$tabContainer = $tabContainer;
			this.$panes = $($tabContainer.data('panes'));

			var index = 0;

			$tabContainer.find('a[href]').each(function()
			{
				var $this = $(this), hrefParts = $this.attr('href').split('#');
				if (location.hash.substr(1) == hrefParts[1])
				{
					$tabContainer.find(".active").removeClass("active");
					$this.addClass("active");
					$this.parent().addClass("active");
					index = $this.parent().index();
				}
			});

			$tabContainer.tabs(this.$panes, {
				current: 'active',
				history: false,
				onBeforeClick: $.context(this, 'onBeforeClick'),
				initialIndex: index
			});
			this.api = $tabContainer.data('tabs');
		}
	},

	removeParamsFromUrls: function()
	{
		var regex = new RegExp(/(?:\?|\&|\%3F|\&amp\;)(?:page|search)\=[A-Za-z0-9 ]*/);

		this.$tabs.$panes.each(function()
		{
			var url = $(this).data('loadUrl');
			url = url.replace(regex, '');
			$(this).data('loadUrl', url);
		});

		$("#HistoryTabs > li > a").each(function()
		{
			var url = $(this).attr("href");
			url = url.replace(regex, '');
			$(this).attr("href", url);
		});
	}
}

XenAuction.Helpers = {

	showInputError: function(input, message)
	{
		var error 	= $(''+message+'').insertAfter(input);
		var coords 	= $(input).coords('outer', 'position');
		error.css({
			top: coords.top,
			left: coords.left + coords.width + 10
		}).show();
	},

	fixOverlay: function()
	{
		var originalOverlay 	= XenForo.createOverlay;
		XenForo.createOverlay 	= function($trigger, templateHtml, extraOptions)
		{
			var overlay = originalOverlay.call(this, $trigger, templateHtml, extraOptions);
			var elem 	= overlay.getOverlay();

			overlay.onLoad = function()
			{
				var position = elem.offset();
				elem.css('position', 'absolute');
				elem.offset(position);
				elem.find(".button[type=reset]").removeAttr('disabled').removeClass('disabled');

				elem.find(".Disabler").click(function() {
					setTimeout(function() {
						elem.find(".button[type=reset]").removeAttr('disabled').removeClass('disabled');
					}, 100);
				});
			};

			overlay.onClose = function()
			{
				elem.find('form').trigger('reset');
			};

			return overlay;
		};
	}

}

$(document).ready(XenAuction.Helpers.fixOverlay);

// helpers

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
<|endoftext|>


<commit_before>import Tweenable from 'shifty'

/**
 * Gets the absolute position in pixels of a given element,
 * taking into account its CSS transformed position.
 *
 * @param {Node} element
 * @returns {Array} [x, y] where x is number of pixels from the
 *    left side of the viewport and y is the number of pixels
 *    from the top of the viewport.
 */
export function getElAbsolutePos (el) {
  let pos = [0, 0]

  do {
    pos[0] += el.offsetLeft + (el.cssTransformLeft || 0)
    pos[1] += el.offsetTop + (el.cssTransformTop || 0)

    el = el.offsetParent
  } while (el)

  return pos
}

/**
 * Converts a street name to a readable and URL-friendly slug name
 *
 * @param {string} slug
 * @returns {string}
 */
export function normalizeSlug (slug) {
  slug = slug.toLowerCase()
  slug = slug.replace(/ /g, '-')
  slug = slug.replace(/-{2,}/, '-')
  slug = slug.replace(/[^a-zA-Z0-9-]/g, '')
  slug = slug.replace(/^[-]+|[-]+$/g, '')

  return slug
}

/**
 * Tweens the given numeric properties on an element over time.
 *
 * @param {Element} el
 * @param {Object<string, number>} props
 * @param {number} duration
 */
export function animate (el, props, duration) {
  const initialProps = {}

  Object.keys(props).forEach(function (prop) {
    initialProps[prop] = el[prop] || 0
  })

  if (el.tweenable) {
    el.tweenable.stop()
  }

  el.tweenable = new Tweenable()
  el.tweenable.tween({
    from: initialProps,
    to: props,
    duration: duration,
    step: (state) => Object.assign(el, state)
  })
}

/**
 * Adapted from Crockford's "Remedial Javascript"
 * http://javascript.crockford.com/remedial.html
 * Crockford's implementation recommended extending the String prototype object,
 * but much has been said about not doing that, e.g.:
 * https://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/
 * Since it is only used for this module's purpose, it is now merely a function
 * that returns a supplanted string, rather than extending the String prototype.
 */
export function supplant (string, data) {
  return string.replace(/\{\{([^{}]*)\}\}/g,
    function (a, b) {
      var r = data[b]
      return typeof r === 'string' || typeof r === 'number' ? r : a
    }
  )
}
<commit_msg>Update tween() syntax<commit_after>import { tween } from 'shifty'

/**
 * Gets the absolute position in pixels of a given element,
 * taking into account its CSS transformed position.
 *
 * @param {Node} element
 * @returns {Array} [x, y] where x is number of pixels from the
 *    left side of the viewport and y is the number of pixels
 *    from the top of the viewport.
 */
export function getElAbsolutePos (el) {
  let pos = [0, 0]

  do {
    pos[0] += el.offsetLeft + (el.cssTransformLeft || 0)
    pos[1] += el.offsetTop + (el.cssTransformTop || 0)

    el = el.offsetParent
  } while (el)

  return pos
}

/**
 * Converts a street name to a readable and URL-friendly slug name
 *
 * @param {string} slug
 * @returns {string}
 */
export function normalizeSlug (slug) {
  slug = slug.toLowerCase()
  slug = slug.replace(/ /g, '-')
  slug = slug.replace(/-{2,}/, '-')
  slug = slug.replace(/[^a-zA-Z0-9-]/g, '')
  slug = slug.replace(/^[-]+|[-]+$/g, '')

  return slug
}

/**
 * Tweens the given numeric properties on an element over time.
 *
 * @param {Element} el
 * @param {Object<string, number>} props
 * @param {number} duration
 */
export function animate (el, props, duration) {
  const initialProps = {}

  Object.keys(props).forEach(function (prop) {
    initialProps[prop] = el[prop] || 0
  })

  tween({
    from: initialProps,
    to: props,
    duration: duration,
    step: (state) => Object.assign(el, state)
  })
}

/**
 * Adapted from Crockford's "Remedial Javascript"
 * http://javascript.crockford.com/remedial.html
 * Crockford's implementation recommended extending the String prototype object,
 * but much has been said about not doing that, e.g.:
 * https://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/
 * Since it is only used for this module's purpose, it is now merely a function
 * that returns a supplanted string, rather than extending the String prototype.
 */
export function supplant (string, data) {
  return string.replace(/\{\{([^{}]*)\}\}/g,
    function (a, b) {
      var r = data[b]
      return typeof r === 'string' || typeof r === 'number' ? r : a
    }
  )
}
<|endoftext|>


<commit_before>'use strict';

describe('components', function () {
  it('can register a component', function() {
    fw.components.register('ComponentA', {
      template: '
a template
',
      viewModel: function() {
        this.variable = fw.observable().broadcastAs('variable');
      }
    });

    expect(fw.components.isRegistered('ComponentA')).to.eql(true);
  });

  it('can instantiate a registered component via a <declarative> statement', function(done) {
    var componentInitialized = false;
    var container = document.getElementById('declarativeComponent');

    expect(componentInitialized).to.be(false);

    fw.components.register('declarative-component', {
      template: '
a template
',
      viewModel: fw.viewModel({
        initialize: function() {
          componentInitialized = true;
        }
      })
    });

    fw.start(container);

    setTimeout(function() {
      expect(componentInitialized).to.be(true);
      done();
    }, 0);
  });

  it('can specify and load via the default location', function(done) {
    var container = document.getElementById('defaultComponentLocation');
    window.defaultComponentLocationLoaded = false;

    fw.components.defaultLocation({
      viewModel: 'scripts/testAssets/defaultComponentLocation/',
      template: 'testAssets/defaultComponentLocation/'
    });

    expect(window.defaultComponentLocationLoaded).to.be(false);

    fw.start(container);

    setTimeout(function() {
      expect(window.defaultComponentLocationLoaded).to.be(true);
      done();
    }, 30);
  });

  it('can specify and load via a registered location', function(done) {
    var container = document.getElementById('registeredComponentLocation');
    window.registeredComponentLocationLoaded = false;

    fw.components.registerLocation('registered-component-location', {
      viewModel: 'scripts/testAssets/registeredComponentLocation/',
      template: 'testAssets/registeredComponentLocation/'
    });

    expect(window.registeredComponentLocationLoaded).to.be(false);

    fw.start(container);

    setTimeout(function() {
      expect(window.registeredComponentLocationLoaded).to.be(true);
      done();
    }, 30);
  });

  it('can specify and load via a registered location for a combined component', function(done) {
    var container = document.getElementById('registeredCombinedComponentLocation');
    window.registeredComponentLocationLoaded = false;

    fw.components.registerLocation('registered-combined-component-location', 'scripts/testAssets/registeredComponentLocation/');

    expect(window.registeredComponentLocationLoaded).to.be(false);

    fw.start(container);

    setTimeout(function() {
      expect(window.registeredComponentLocationLoaded).to.be(true);
      done();
    }, 30);
  });
});
<commit_msg>test tuning<commit_after>'use strict';

describe('components', function () {
  it('can register a component', function() {
    fw.components.register('ComponentA', {
      template: '
a template
',
      viewModel: function() {
        this.variable = fw.observable().broadcastAs('variable');
      }
    });

    expect(fw.components.isRegistered('ComponentA')).to.eql(true);
  });

  it('can instantiate a registered component via a <declarative> statement', function(done) {
    var componentInitialized = false;
    var container = document.getElementById('declarativeComponent');

    expect(componentInitialized).to.be(false);

    fw.components.register('declarative-component', {
      template: '
a template
',
      viewModel: fw.viewModel({
        initialize: function() {
          componentInitialized = true;
        }
      })
    });

    fw.start(container);

    setTimeout(function() {
      expect(componentInitialized).to.be(true);
      done();
    }, 0);
  });

  it('can specify and load via the default location', function(done) {
    var container = document.getElementById('defaultComponentLocation');
    window.defaultComponentLocationLoaded = false;

    fw.components.defaultLocation({
      viewModel: 'scripts/testAssets/defaultComponentLocation/',
      template: 'testAssets/defaultComponentLocation/'
    });

    expect(window.defaultComponentLocationLoaded).to.be(false);

    fw.start(container);

    setTimeout(function() {
      expect(window.defaultComponentLocationLoaded).to.be(true);
      done();
    }, 300);
  });

  it('can specify and load via a registered location', function(done) {
    var container = document.getElementById('registeredComponentLocation');
    window.registeredComponentLocationLoaded = false;

    fw.components.registerLocation('registered-component-location', {
      viewModel: 'scripts/testAssets/registeredComponentLocation/',
      template: 'testAssets/registeredComponentLocation/'
    });

    expect(window.registeredComponentLocationLoaded).to.be(false);

    fw.start(container);

    setTimeout(function() {
      expect(window.registeredComponentLocationLoaded).to.be(true);
      done();
    }, 300);
  });

  it('can specify and load via a registered location for a combined component', function(done) {
    var container = document.getElementById('registeredCombinedComponentLocation');
    window.registeredComponentLocationLoaded = false;

    fw.components.registerLocation('registered-combined-component-location', 'scripts/testAssets/registeredComponentLocation/');

    expect(window.registeredComponentLocationLoaded).to.be(false);

    fw.start(container);

    setTimeout(function() {
      expect(window.registeredComponentLocationLoaded).to.be(true);
      done();
    }, 300);
  });
});
<|endoftext|>


<commit_before>var http = require ('http');            // For serving a basic web page.
var mongoose = require ("mongoose");  // The reason for this demo.
var querystring = require('querystring');
var utils = require('utils');

// Here we find an appropriate database to connect to, defaulting to
// localhost if we don't find one.
var uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/HelloMongoose';

// The http server will listen to an appropriate port, or default to
// port 5000.
var theport = process.env.PORT || 5000;

// Makes connection asynchronously.  Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(uristring, function (err, res) {
  if (err) {
  console.log ('ERROR connecting to: ' + uristring + '. ' + err);
  } else {
    console.log ('Succeeded connected to: ' + uristring);
  }
});

var UserSchema = new mongoose.Schema({
  slack_id: { type: String },
  name: { type: String }
});

var User = mongoose.model('User', UserSchema);

http.createServer(function (req, res) {
    var fullBody = '';

    req.on('data', function(chunk) {
      // append the current chunk of data to the fullBody variable
      fullBody += chunk.toString();
    });

    req.on('end', function() {

      // request ended -> do something with the data
      res.writeHead(200, "OK", {'Content-Type': 'text/html'});

      console.log(fullBody);
      // parse the received body data
      var decodedBody = JSON.parse(fullBody);
      console.log(decodedBody);

      var user = getOrCreateUser(decodedBody.user_id, decodedBody.name, function(user){

        var responseBody;
        if(user.justCreated){
          responseBody = { text : 'Bienvenue ' + user.name };
        }else{
          var target = findTarget(req.text);
          var amount = findAmount(req.text);
          responseBody = { text : 'Donné ' + amount + ' à ' +target.name };
        }

        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end( JSON.stringify(responseBody) );

      });

    });

}).listen(theport, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8080/');

var findTarget = function(text){
  var target_id = str.match(/\<@(.*)\>/).pop();
  User.find({ slack_id: target_id}, function(err, users){
    console.log(users);
    return users[0];
  });

}

var findAmount = function(text){
  var numbers = text.match(/\\d+\\.?\\d*/g);
  console.log(numbers);
  return numbers[0];
}

var getOrCreateUser = function(user_id, name, callback){

  console.log(user_id);

  User.find({ slack_id: user_id}, function(err, users){
  console.log(user_id);

    if (err) return console.error(err);

    var user;
    if (users.length == 0)
    {
      user = new User({ slack_id: user_id, name: name });
      user.save();
      user.justCreated = true;
    }

    else
    {
      user = users[0];
      user.justCreated = false;
    }
    console.log(user);

    callback(user);

  });

}<commit_msg>Parse mention + amount ok<commit_after>var http = require ('http');            // For serving a basic web page.
var mongoose = require ("mongoose");  // The reason for this demo.
var querystring = require('querystring');

// Here we find an appropriate database to connect to, defaulting to
// localhost if we don't find one.
var uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/HelloMongoose';

// The http server will listen to an appropriate port, or default to
// port 5000.
var theport = process.env.PORT || 5000;

// Makes connection asynchronously.  Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(uristring, function (err, res) {
  if (err) {
  console.log ('ERROR connecting to: ' + uristring + '. ' + err);
  } else {
    console.log ('Succeeded connected to: ' + uristring);
  }
});

var UserSchema = new mongoose.Schema({
  slack_id: { type: String },
  name: { type: String }
});

var User = mongoose.model('User', UserSchema);

http.createServer(function (req, res) {
    var fullBody = '';

    req.on('data', function(chunk) {
      // append the current chunk of data to the fullBody variable
      fullBody += chunk.toString();
    });

    req.on('end', function() {

      // request ended -> do something with the data
      res.writeHead(200, "OK", {'Content-Type': 'text/html'});

      // parse the received body data
      var decodedBody = querystring.parse(fullBody);

      var user = getOrCreateUser(decodedBody.user_id, decodedBody.user_name, function(user){

        var responseBody;
        if(user.justCreated){
          responseBody = { text : 'Bienvenue ' + user.name };

          res.writeHead(200, {'Content-Type': 'application/json'});
          res.end( JSON.stringify(responseBody) );

        }else{
          findTarget(decodedBody.text, function(user){
            var amount = findAmount(decodedBody.text);
            responseBody = { text : 'Donné ' + amount + ' à ' +user.name };

            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end( JSON.stringify(responseBody) );

          });
        }

      });

    });

    new User({ slack_id: 'U02BFK30A', name: 'bertran' }).save();

}).listen(theport, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8080/');

var findTarget = function(text, callback){
  var target_id = text.match(/\<@(.*)\>/).pop();

    User.find({ slack_id: target_id}, function(err, users){
    callback(users[0]);
  });

}

var findAmount = function(text){
  var numbers = text.match(/\d+/);
  return numbers[0];
}

var getOrCreateUser = function(user_id, name, callback){

  User.find({ slack_id: user_id}, function(err, users){

    if (err) return console.error(err);

    var user;
    if (users.length == 0)
    {
      user = new User({ slack_id: user_id, name: name });
      user.save();
      user.justCreated = true;
    }

    else
    {
      user = users[0];
      user.justCreated = false;
    }

    callback(user);

  });

}<|endoftext|>


<commit_before>
'use strict';

var unknown = require('./unknown-service-plugin');

function Parser(plugins) {
    function filterPluginsForServices(serviceNames, unknownServices) {
        return plugins.concat(unknownServices).filter(function (plugin) {
            return serviceNames.findIndex(function (serviceName) {
                    return plugin.name === serviceName;
                }) !== -1;
        });
    }

    function filterPluginsForService(serviceNames, unknownServices) {
        return plugins.concat(unknownServices).filter(function (plugin) {
            return plugin.name === serviceNames;
        });
    }

    function selectPlugins(serviceNames, unknownServices) {
        if (typeof serviceNames === 'string') {
            return filterPluginsForService(serviceNames, unknownServices);
        }
        else if (typeof serviceNames && serviceNames instanceof Array) {
            return filterPluginsForServices(serviceNames, unknownServices);
        }
        return plugins.concat(unknownServices);
    }

    function availableServices(services) {
        var available = [];
        for (var property in services) {
            if (services.hasOwnProperty(property)) {
                available.push(property);
            }
        }
        return available;
    }

    function createPluginsForUnknownServices(services) {
        var unknownServicePlugins = [];
        availableServices(services).forEach(function(service) {
            if (plugins.findIndex(function (plugin) {
                return plugin.selector === service;
            }) === -1) {
                unknownServicePlugins.push(new unknown.Parser(service));
            }
        });

        return unknownServicePlugins;
    }

    this.parse = function parse(services, serviceNames) {
        // Ensure the services are an object
        if (typeof services === 'string') {
            services = JSON.parse(services);
        }

        // Select the plugins to parse with
        var unknownServices = createPluginsForUnknownServices(services);
        var selectedPlugins = selectPlugins(serviceNames, unknownServices);

        // Use the selected plugins to parse the service
        var result = {};
        selectedPlugins.forEach(function(plugin) {
            result[plugin.name] = plugin.parse(services);
        });

        return result;
    };

    this.resolveAll = function resolveAll() {
        return this.parse(process.env.VCAP_SERVICES, null);
    };

    this.resolve = function resolve(serviceNames) {
        return this.parse(process.env.VCAP_SERVICES, serviceNames);
    };
}

module.exports = {
    Parser : Parser
};
<commit_msg>Refactor the VCAP Parser to clarify the selection of plugins to use.<commit_after>
'use strict';

var unknown = require('./unknown-service-plugin');

function Parser(plugins) {
    function filterPluginsForServices(availablePlugins, serviceNames) {
        return availablePlugins.filter(function (plugin) {
            return serviceNames.findIndex(function (serviceName) {
                    return plugin.name === serviceName;
                }) !== -1;
        });
    }

    function selectPlugins(serviceNames, unknownServices) {
        var availablePlugins = plugins.concat(unknownServices);

        if (typeof serviceNames === 'string') {
            return filterPluginsForServices(availablePlugins, [serviceNames]);
        }
        else if (typeof serviceNames && serviceNames instanceof Array) {
            return filterPluginsForServices(availablePlugins, serviceNames);
        }
        return availablePlugins;
    }

    function availableServices(services) {
        var available = [];
        for (var property in services) {
            if (services.hasOwnProperty(property)) {
                available.push(property);
            }
        }
        return available;
    }

    function isKnownService(serviceName) {
        return plugins.findIndex(function (plugin) {
            return plugin.selector === serviceName;
        }) === -1;
    }

    function createPluginsForUnknownServices(services) {
        var unknownServicePlugins = [];
        availableServices(services).forEach(function(service) {
            if (isKnownService(service)) {
                unknownServicePlugins.push(new unknown.Parser(service));
            }
        });

        return unknownServicePlugins;
    }

    this.parse = function parse(services, serviceNames) {
        // Ensure the services are an object
        if (typeof services === 'string') {
            services = JSON.parse(services);
        }

        // Select the plugins to parse with
        var unknownServices = createPluginsForUnknownServices(services);
        var selectedPlugins = selectPlugins(serviceNames, unknownServices);

        // Use the selected plugins to parse the service
        var result = {};
        selectedPlugins.forEach(function(plugin) {
            result[plugin.name] = plugin.parse(services);
        });

        return result;
    };

    this.resolveAll = function resolveAll() {
        return this.parse(process.env.VCAP_SERVICES, null);
    };

    this.resolve = function resolve(serviceNames) {
        return this.parse(process.env.VCAP_SERVICES, serviceNames);
    };
}

module.exports = {
    Parser : Parser
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var _ = require('lodash');
var Model = require('./lib/model');
var defaultMethods = require('./lib/defaultMethods');
var internalMethods = require('./lib/internalMethods');

/**
 * Build Extended Model Prototype
 *
 * @param {Object} context
 * @param {Object} mixins
 * @return {Object}
 * @api public
 */

module.exports = function(context, mixins) {

  /**
   * Extend the model prototype with default instance methods
   */

  var prototype = _.extend({

    toObject: function() {
      return new defaultMethods.toObject(context, this);
    },

    save: function(cb) {
      return new defaultMethods.save(context, this, cb);
    },

    destroy: function(cb) {
      return new defaultMethods.destroy(context, this, cb);
    },

    _defineAssociations: function() {
      new internalMethods.defineAssociations(context, this);
    },

    _normalizeAssociations: function() {
      new internalMethods.normalizeAssociations(context, this);
    },

    /**
     * Model.validate()
     *
     * Takes the currently set attributes and validates the model
     * Shorthand for Model.validate({ attributes }, cb)
     *
     * @param {Function} callback
     * @return callback - (err)
     */

    validate: function(cb) {
      var self = this;

      // Collect current values
      var values = this.toObject();

      context.validate( values, function(err) {
        if(err) return cb(err);
        cb();
      });
    }

  }, mixins);

  // If any of the attributes are protected, the default toJSON method should
  // remove them.
  var protectedAttributes = _.compact(_.map(context._attributes, function(attr, key) {return attr.protected ? key : undefined;}));
  if (protectedAttributes.length) {
    prototype.toJSON = function() {
      var obj = this.toObject();
      _.each(protectedAttributes, function(key) {
        delete obj[key];
      });
      return obj;
    };
  }
  // Otherwise just return the raw object
  else {
    prototype.toJSON = function() {
      return this.toObject();
    };
  }

  var model = Model.extend(prototype);

  // Return the extended model for use in Waterline
  return model;
};
<commit_msg>Fixed issue where toJSON was no longer overrideable, then flagellated myself for checking in code without running tests first.<commit_after>
/**
 * Module dependencies
 */

var _ = require('lodash');
var Model = require('./lib/model');
var defaultMethods = require('./lib/defaultMethods');
var internalMethods = require('./lib/internalMethods');

/**
 * Build Extended Model Prototype
 *
 * @param {Object} context
 * @param {Object} mixins
 * @return {Object}
 * @api public
 */

module.exports = function(context, mixins) {

  /**
   * Extend the model prototype with default instance methods
   */

  var prototypeFns = {

    toObject: function() {
      return new defaultMethods.toObject(context, this);
    },

    save: function(cb) {
      return new defaultMethods.save(context, this, cb);
    },

    destroy: function(cb) {
      return new defaultMethods.destroy(context, this, cb);
    },

    _defineAssociations: function() {
      new internalMethods.defineAssociations(context, this);
    },

    _normalizeAssociations: function() {
      new internalMethods.normalizeAssociations(context, this);
    },

    /**
     * Model.validate()
     *
     * Takes the currently set attributes and validates the model
     * Shorthand for Model.validate({ attributes }, cb)
     *
     * @param {Function} callback
     * @return callback - (err)
     */

    validate: function(cb) {
      var self = this;

      // Collect current values
      var values = this.toObject();

      context.validate( values, function(err) {
        if(err) return cb(err);
        cb();
      });
    }

  };

  // If any of the attributes are protected, the default toJSON method should
  // remove them.
  var protectedAttributes = _.compact(_.map(context._attributes, function(attr, key) {return attr.protected ? key : undefined;}));
  if (protectedAttributes.length) {
    prototypeFns.toJSON = function() {
      var obj = this.toObject();
      _.each(protectedAttributes, function(key) {
        delete obj[key];
      });
      return obj;
    };
  }
  // Otherwise just return the raw object
  else {
    prototypeFns.toJSON = function() {
      return this.toObject();
    };
  }

  var prototype = _.extend(prototypeFns, mixins);

  var model = Model.extend(prototype);

  // Return the extended model for use in Waterline
  return model;
};
<|endoftext|>


<commit_before>/* Original version taken form https://github.com/tadruj/s3upload-coffee-javascript
 * Modified by Dale Karp <dale@dale.io> */
(function() {

  window.S3Upload = (function() {

    S3Upload.prototype.s3_object_name = 'default_name';

    S3Upload.prototype.s3_sign_put_url = '/signS3put';

    S3Upload.prototype.file_dom_selector = 'file_upload';

    S3Upload.prototype.onFinishS3Put = function(public_url) {
      return console.log('base.onFinishS3Put()', public_url);
    };

    S3Upload.prototype.onProgress = function(percent, status) {
      return console.log('base.onProgress()', percent, status);
    };

    S3Upload.prototype.onError = function(status) {
      return console.log('base.onError()', status);
    };

    function S3Upload(options) {
      if (options == null) options = {};
      for (option in options) {
        this[option] = options[option];
      }
      if (options.blobMode) {
        this.handleBlob(options.blob);
      }
      else {
        this.handleFileSelect(document.getElementById(this.file_dom_selector));
      }
    }

    S3Upload.prototype.handleBlob = function(blob) {
      var f, files, output, _i, _len, _results;
      this.onProgress(0, 'Upload started.');
      output = [];
      _results = [];
      console.log(blob);
      _results.push(this.uploadFile(blob));
      return _results;
    };

    S3Upload.prototype.handleFileSelect = function(file_element) {
      var f, files, output, _i, _len, _results;
      this.onProgress(0, 'Upload started.');
      files = file_element.files;
      output = [];
      _results = [];
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        f = files[_i];
        _results.push(this.uploadFile(f));
      }
      return _results;
    };

    S3Upload.prototype.createCORSRequest = function(method, url) {
      var xhr;
      xhr = new XMLHttpRequest();
      if (xhr.withCredentials != null) {
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest !== "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        xhr = null;
      }
      return xhr;
    };

    S3Upload.prototype.executeOnSignedUrl = function(file, callback) {
      var this_s3upload, xhr;
      this_s3upload = this;
      xhr = new XMLHttpRequest();
      xhr.open('GET', this.s3_sign_put_url + '?s3_object_type=' + file.type + '&s3_object_name=' + file.name, true);
      xhr.overrideMimeType('text/plain; charset=x-user-defined');
      xhr.onreadystatechange = function(e) {
        var result;
        if (this.readyState === 4 && this.status === 200) {
          try {
            result = JSON.parse(this.responseText);
          } catch (error) {
            this_s3upload.onError('Signing server returned some ugly/empty JSON: "' + this.responseText + '"');
            return false;
          }
          return callback(decodeURIComponent(result.signed_request), result.url, result.name);
        } else if (this.readyState === 4 && this.status !== 200) {
          return this_s3upload.onError('Could not contact request signing server. Status = ' + this.status);
        }
      };
      return xhr.send();
    };

    S3Upload.prototype.uploadToS3 = function(file, url, public_url, name) {
      var this_s3upload, xhr;
      this_s3upload = this;
      xhr = this.createCORSRequest('PUT', url);
      if (!xhr) {
        this.onError('CORS not supported');
      } else {
        xhr.onload = function() {
          if (xhr.status === 200) {
            this_s3upload.onProgress(100, 'Upload completed.');
            return this_s3upload.onFinishS3Put(public_url, name);
          } else {
            return this_s3upload.onError('Upload error: ' + xhr.status);
          }
        };
        xhr.onerror = function() {
          return this_s3upload.onError('XHR error.');
        };
        xhr.upload.onprogress = function(e) {
          var percentLoaded;
          if (e.lengthComputable) {
            percentLoaded = Math.round((e.loaded / e.total) * 100);
            return this_s3upload.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing.' : 'Uploading.');
          }
        };
      }
      xhr.setRequestHeader('Content-Type', file.type);
      xhr.setRequestHeader('x-amz-acl', 'public-read');
      return xhr.send(file);
    };

    S3Upload.prototype.uploadFile = function(file) {
      var this_s3upload;
      this_s3upload = this;
      return this.executeOnSignedUrl(file, function(signedURL, publicURL, name) {
        return this_s3upload.uploadToS3(file, signedURL, publicURL, name);
      });
    };

    return S3Upload;

  })();

}).call(this);
<commit_msg>added license to s3upload.js<commit_after>/* Original version taken form https://github.com/tadruj/s3upload-coffee-javascript
 * License
 * Copyright 2013 tadruj
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * Modified by Dale Karp <dale@dale.io> */
(function() {

  window.S3Upload = (function() {

    S3Upload.prototype.s3_object_name = 'default_name';

    S3Upload.prototype.s3_sign_put_url = '/signS3put';

    S3Upload.prototype.file_dom_selector = 'file_upload';

    S3Upload.prototype.onFinishS3Put = function(public_url) {
      return console.log('base.onFinishS3Put()', public_url);
    };

    S3Upload.prototype.onProgress = function(percent, status) {
      return console.log('base.onProgress()', percent, status);
    };

    S3Upload.prototype.onError = function(status) {
      return console.log('base.onError()', status);
    };

    function S3Upload(options) {
      if (options == null) options = {};
      for (option in options) {
        this[option] = options[option];
      }
      if (options.blobMode) {
        this.handleBlob(options.blob);
      }
      else {
        this.handleFileSelect(document.getElementById(this.file_dom_selector));
      }
    }

    S3Upload.prototype.handleBlob = function(blob) {
      var f, files, output, _i, _len, _results;
      this.onProgress(0, 'Upload started.');
      output = [];
      _results = [];
      console.log(blob);
      _results.push(this.uploadFile(blob));
      return _results;
    };

    S3Upload.prototype.handleFileSelect = function(file_element) {
      var f, files, output, _i, _len, _results;
      this.onProgress(0, 'Upload started.');
      files = file_element.files;
      output = [];
      _results = [];
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        f = files[_i];
        _results.push(this.uploadFile(f));
      }
      return _results;
    };

    S3Upload.prototype.createCORSRequest = function(method, url) {
      var xhr;
      xhr = new XMLHttpRequest();
      if (xhr.withCredentials != null) {
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest !== "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        xhr = null;
      }
      return xhr;
    };

    S3Upload.prototype.executeOnSignedUrl = function(file, callback) {
      var this_s3upload, xhr;
      this_s3upload = this;
      xhr = new XMLHttpRequest();
      xhr.open('GET', this.s3_sign_put_url + '?s3_object_type=' + file.type + '&s3_object_name=' + file.name, true);
      xhr.overrideMimeType('text/plain; charset=x-user-defined');
      xhr.onreadystatechange = function(e) {
        var result;
        if (this.readyState === 4 && this.status === 200) {
          try {
            result = JSON.parse(this.responseText);
          } catch (error) {
            this_s3upload.onError('Signing server returned some ugly/empty JSON: "' + this.responseText + '"');
            return false;
          }
          return callback(decodeURIComponent(result.signed_request), result.url, result.name);
        } else if (this.readyState === 4 && this.status !== 200) {
          return this_s3upload.onError('Could not contact request signing server. Status = ' + this.status);
        }
      };
      return xhr.send();
    };

    S3Upload.prototype.uploadToS3 = function(file, url, public_url, name) {
      var this_s3upload, xhr;
      this_s3upload = this;
      xhr = this.createCORSRequest('PUT', url);
      if (!xhr) {
        this.onError('CORS not supported');
      } else {
        xhr.onload = function() {
          if (xhr.status === 200) {
            this_s3upload.onProgress(100, 'Upload completed.');
            return this_s3upload.onFinishS3Put(public_url, name);
          } else {
            return this_s3upload.onError('Upload error: ' + xhr.status);
          }
        };
        xhr.onerror = function() {
          return this_s3upload.onError('XHR error.');
        };
        xhr.upload.onprogress = function(e) {
          var percentLoaded;
          if (e.lengthComputable) {
            percentLoaded = Math.round((e.loaded / e.total) * 100);
            return this_s3upload.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing.' : 'Uploading.');
          }
        };
      }
      xhr.setRequestHeader('Content-Type', file.type);
      xhr.setRequestHeader('x-amz-acl', 'public-read');
      return xhr.send(file);
    };

    S3Upload.prototype.uploadFile = function(file) {
      var this_s3upload;
      this_s3upload = this;
      return this.executeOnSignedUrl(file, function(signedURL, publicURL, name) {
        return this_s3upload.uploadToS3(file, signedURL, publicURL, name);
      });
    };

    return S3Upload;

  })();

}).call(this);
<|endoftext|>


<commit_before>exports = module.exports = function(store) {
  var qs = require('querystring');

  // TODO: If no state, and there's a returnTo option, store that
  //       as initial state.

  function redirect(req, res, next) {
    console.log('#### REDIRECT TO LOGIN');
    console.log(req.locals);
    //return;

    //return res.redirect('/login/oob');

    var options = req.locals || {}
      , state, q;

    if (options.methods && options.methods.indexOf('otp') != -1) {
      //return res.redirect('/login/otp');
      return res.redirect('/login/oob');
    }

    //if (Object.keys(options).length == 0) {
    if (true) {
      q = req.state ? '?' + qs.stringify({ state: req.state.handle }) : '';
      return res.redirect('/login' + q);
    }

    state = { name: 'login' };
    state.maxAttempts = options.maxAttempts || 3;
    if (req.state) { state.prev = req.state.handle; }

    store.save(req, state, function(err, h) {
      return res.redirect('/login' + '?' + qs.stringify({ state: h }));
    });
  }

  return [
    redirect
  ];

};

exports['@require'] = [
  'http://i.bixbyjs.org/http/state/Store'
];
<commit_msg>Do not add state param to redirect.<commit_after>exports = module.exports = function(store) {
  var qs = require('querystring');

  // TODO: If no state, and there's a returnTo option, store that
  //       as initial state.

  function redirect(req, res, next) {
    console.log('#### REDIRECT TO LOGIN');
    console.log(req.locals);
    //return;

    //return res.redirect('/login/oob');

    var options = req.locals || {}
      , state, q;

    if (options.methods && options.methods.indexOf('otp') != -1) {
      //return res.redirect('/login/otp');
      return res.redirect('/login/oob');
    }

    //if (Object.keys(options).length == 0) {
    if (true) {
      //q = req.state ? '?' + qs.stringify({ state: req.state.handle }) : '';
      //return res.redirect('/login' + q);
      return res.redirect('/login');
    }

    state = { name: 'login' };
    state.maxAttempts = options.maxAttempts || 3;
    if (req.state) { state.prev = req.state.handle; }

    store.save(req, state, function(err, h) {
      return res.redirect('/login' + '?' + qs.stringify({ state: h }));
    });
  }

  return [
    redirect
  ];

};

exports['@require'] = [
  'http://i.bixbyjs.org/http/state/Store'
];
<|endoftext|>


<commit_before>import React from 'react';
import settings from 'settings';
import getPetitionOwner from 'selectors/petitionOwner';
import getPetitionCity from 'selectors/petitionCity';
import getPetitionPath from 'helpers/getPetitionPath';
import { Link } from 'react-router';
import styles from 'components/EditPetition/edit-petition.scss';
import Container from 'components/Container';
import FormWrapper from 'components/FormWrapper';
import Header from 'components/Header';
import PageTitle from 'components/PageTitle';
import RespondToPetitionForm from 'components/RespondToPetitionForm';
import RespondToPetitionHints from 'components/RespondToPetitionHints';
import Paragraph from 'components/Paragraph';

const RespondToPetition = ({ petition, petitionResponse, router }) => (
  <Container>
    <FormWrapper>

        <PageTitle
          title={settings.respondToPetitionPage.title}
          intro={settings.respondToPetitionPage.intro}
        />

      <Paragraph noMargin>
        {`${settings.respondToPetitionPage.details.for} `}
        <Link to={getPetitionPath(petition.id)}>{petition.title}</Link>
      </Paragraph>
      <Paragraph noMargin>
        {`${settings.respondToPetitionPage.details.by} ${getPetitionOwner(petition)}`}
      </Paragraph>
      <Paragraph noMargin>
        {`${settings.respondToPetitionPage.details.in} ${getPetitionCity(petition).name}`}
      </Paragraph>
      <Paragraph>
        {`${settings.respondToPetitionPage.details.collected} ${petition.supporters.amount} ${settings.respondToPetitionPage.details.votes}`}
      </Paragraph>
      <RespondToPetitionHints petition={petition} />

        <RespondToPetitionForm
          initialValues={petitionResponse}
          petition={petition}
          petitionResponse={petitionResponse}
        />

    </FormWrapper>
  </Container>
);

export default RespondToPetition;
<commit_msg>Use custom Link component in response intro<commit_after>import React from 'react';
import settings from 'settings';
import getPetitionOwner from 'selectors/petitionOwner';
import getPetitionCity from 'selectors/petitionCity';
import getPetitionPath from 'helpers/getPetitionPath';
import Link from 'components/Link';
import styles from 'components/EditPetition/edit-petition.scss';
import Container from 'components/Container';
import FormWrapper from 'components/FormWrapper';
import Header from 'components/Header';
import PageTitle from 'components/PageTitle';
import RespondToPetitionForm from 'components/RespondToPetitionForm';
import RespondToPetitionHints from 'components/RespondToPetitionHints';
import Paragraph from 'components/Paragraph';

const RespondToPetition = ({ petition, petitionResponse, router }) => (
  <Container>
    <FormWrapper>

        <PageTitle
          title={settings.respondToPetitionPage.title}
          intro={settings.respondToPetitionPage.intro}
        />

      <Paragraph noMargin>
        {`${settings.respondToPetitionPage.details.for} `}
        <Link href={getPetitionPath(petition.id)}>{petition.title}</Link>
      </Paragraph>
      <Paragraph noMargin>
        {`${settings.respondToPetitionPage.details.by} ${getPetitionOwner(petition)}`}
      </Paragraph>
      <Paragraph noMargin>
        {`${settings.respondToPetitionPage.details.in} ${getPetitionCity(petition).name}`}
      </Paragraph>
      <Paragraph>
        {`${settings.respondToPetitionPage.details.collected} ${petition.supporters.amount} ${settings.respondToPetitionPage.details.votes}`}
      </Paragraph>
      <RespondToPetitionHints petition={petition} />

        <RespondToPetitionForm
          initialValues={petitionResponse}
          petition={petition}
          petitionResponse={petitionResponse}
        />

    </FormWrapper>
  </Container>
);

export default RespondToPetition;
<|endoftext|>


<commit_before>
$('.button').click(function(){

var nameVal = $('.name').val();
var hours = $('.hour').val();
var html = 'Name: ' + nameVal + ', Hours: ' + hours + '\n';

$('.name').val('');
$('.hour').val('');

qwest.get(('https://testmessenger5.herokuapp.com/read'), {
  'text' : html
}).then(function (response) {
  console.log('yes baby');
})

})
<commit_msg>welcome screen<commit_after>
$('.button').click(function(){

var nameVal = $('.name').val();
var hours = $('.hour').val();
var html = 'Name: ' + nameVal + ', Hours: ' + hours + '\n';

$('.name').val('');
$('.hour').val('');

qwest.post(('https://testmessenger5.herokuapp.com/read'), {
  'text' : html
}).then(function () {
  console.log('yes baby');
})

})
<|endoftext|>


<commit_before>import Orbit from 'orbit/main';
import Schema from 'orbit-common/schema';
import MemorySource from 'orbit-common/memory-source';
import Transaction from 'orbit-common/transaction';
import { uuid } from 'orbit/lib/uuid';
import { Promise, all } from 'rsvp';
import { equalOps } from 'tests/test-helper';

///////////////////////////////////////////////////////////////////////////////

var source;
var schema;
var transaction;

module("OC - Transaction", {
  setup: function() {
    Orbit.Promise = Promise;

    schema = new Schema({
      models: {
        planet: {
          attributes: {
            name: {type: 'string'},
            classification: {type: 'string'}
          },
          links: {
            moons: {type: 'hasMany', model: 'moon', inverse: 'planet'}
          },
          keys: {
            id: { primaryKey: true, defaultValue: uuid }
          }
        },
        moon: {
          attributes: {
            name: {type: 'string'}
          },
          links: {
            planet: {type: 'hasOne', model: 'planet', inverse: 'moons'}
          }
        }
      }
    });

    source = new MemorySource(schema);
  },

  teardown: function() {
    schema = null;
    source = null;
    Orbit.Promise = null;
  }
});

test("it exists", function(assert) {
  var transaction = new Transaction(schema, {baseSource: source});
  assert.ok(transaction);
});

test("requires the `baseSource` option", function(assert) {
  assert.throws(function() {
      var transaction = new Transaction(schema);
    },
    new Error("Assertion failed: `baseSource` must be supplied as an option when constructing a Transaction.")
  );
});

test("automatically begins by default", function(assert) {
  var transaction = new Transaction(schema, {baseSource: source});
  assert.equal(transaction.active, true);
});

test("does not auto-begin if the `active` option = false", function(assert) {
  var transaction = new Transaction(schema, {baseSource: source, active: false});
  assert.equal(transaction.active, false);
});

test("once begun, tracks operations performed and inverse operations", function(assert) {
  assert.expect(4);

  var transaction = new Transaction(schema, {baseSource: source});

  assert.equal(transaction.operations.length, 0, 'transaction has no operations');
  assert.equal(transaction.inverseOperations.length, 0, 'transaction has no inverse operations');

  return transaction.add('planet', {name: 'Jupiter', classification: 'gas giant'}).then(function(planet) {
    equalOps(transaction.operations,
      [{op: 'add', path: 'planet/' + planet.id, value: planet}],
      'transaction tracked `add` operation');

    equalOps(transaction.inverseOperations,
      [{op: 'remove', path: 'planet/' + planet.id}],
      'transaction tracked inverse operations');
  });
});

test("`commit` applies operations to `baseSource`", function(assert) {
  assert.expect(3);

  var transaction = new Transaction(schema, {baseSource: source});

  assert.equal(source.length('planet'), 0, 'base source has no planets');

  return transaction.add('planet', {name: 'Jupiter', classification: 'gas giant'}).then(function(planet) {
    return transaction.commit().then(function() {
      assert.equal(source.length('planet'), 1, 'base source has a planet');
      assert.deepEqual(source.retrieve(['planet', planet.id]), planet, 'planet matches');
    });
  });
});

test("an unisolated transaction will retrieve missing data from its `baseSource`", function(assert) {
  assert.expect(3);

  var transaction = new Transaction(schema, {baseSource: source});

  assert.equal(transaction.isolated, false, 'transactions are not isolated by default');

  return source.add('planet', {name: 'Jupiter', classification: 'gas giant'}).then(function(planet) {
    assert.equal(transaction.length('planet'), 1, 'transaction can retrieve planet from base source');
    assert.deepEqual(transaction.retrieve(['planet', planet.id]), planet, 'planet matches');
  });
});

test("an isolated transaction won't retrieve any data from its `baseSource`", function(assert) {
  assert.expect(2);

  var transaction = new Transaction(schema, {baseSource: source, isolated: true});

  assert.equal(transaction.isolated, true, 'transaction is isolated');

  return source.add('planet', {name: 'Jupiter', classification: 'gas giant'}).then(function(planet) {
    assert.equal(transaction.length('planet'), 0, 'transaction has no planets defined');
  });
});
<commit_msg>Reformat promise chains.<commit_after>import Orbit from 'orbit/main';
import Schema from 'orbit-common/schema';
import MemorySource from 'orbit-common/memory-source';
import Transaction from 'orbit-common/transaction';
import { uuid } from 'orbit/lib/uuid';
import { Promise, all } from 'rsvp';
import { equalOps } from 'tests/test-helper';

///////////////////////////////////////////////////////////////////////////////

var source;
var schema;
var transaction;

module("OC - Transaction", {
  setup: function() {
    Orbit.Promise = Promise;

    schema = new Schema({
      models: {
        planet: {
          attributes: {
            name: {type: 'string'},
            classification: {type: 'string'}
          },
          links: {
            moons: {type: 'hasMany', model: 'moon', inverse: 'planet'}
          },
          keys: {
            id: { primaryKey: true, defaultValue: uuid }
          }
        },
        moon: {
          attributes: {
            name: {type: 'string'}
          },
          links: {
            planet: {type: 'hasOne', model: 'planet', inverse: 'moons'}
          }
        }
      }
    });

    source = new MemorySource(schema);
  },

  teardown: function() {
    schema = null;
    source = null;
    Orbit.Promise = null;
  }
});

test("it exists", function(assert) {
  var transaction = new Transaction(schema, {baseSource: source});
  assert.ok(transaction);
});

test("requires the `baseSource` option", function(assert) {
  assert.throws(function() {
      var transaction = new Transaction(schema);
    },
    new Error("Assertion failed: `baseSource` must be supplied as an option when constructing a Transaction.")
  );
});

test("automatically begins by default", function(assert) {
  var transaction = new Transaction(schema, {baseSource: source});
  assert.equal(transaction.active, true);
});

test("does not auto-begin if the `active` option = false", function(assert) {
  var transaction = new Transaction(schema, {baseSource: source, active: false});
  assert.equal(transaction.active, false);
});

test("once begun, tracks operations performed and inverse operations", function(assert) {
  assert.expect(4);

  var transaction = new Transaction(schema, {baseSource: source});

  assert.equal(transaction.operations.length, 0, 'transaction has no operations');
  assert.equal(transaction.inverseOperations.length, 0, 'transaction has no inverse operations');

  return transaction.add('planet', {name: 'Jupiter', classification: 'gas giant'})
    .then(function(planet) {
      equalOps(transaction.operations,
        [{op: 'add', path: 'planet/' + planet.id, value: planet}],
        'transaction tracked `add` operation');

      equalOps(transaction.inverseOperations,
        [{op: 'remove', path: 'planet/' + planet.id}],
        'transaction tracked inverse operations');
    });
});

test("`commit` applies operations to `baseSource`", function(assert) {
  assert.expect(3);

  var transaction = new Transaction(schema, {baseSource: source});

  assert.equal(source.length('planet'), 0, 'base source has no planets');

  var jupiter;

  return transaction.add('planet', {name: 'Jupiter', classification: 'gas giant'})
    .then(function(planet) {
      jupiter = planet;

      return transaction.commit();
    })
    .then(function() {
      assert.equal(source.length('planet'), 1, 'base source has a planet');
      assert.deepEqual(source.retrieve(['planet', jupiter.id]), jupiter, 'planet matches');
    });
});

test("an unisolated transaction will retrieve missing data from its `baseSource`", function(assert) {
  assert.expect(3);

  var transaction = new Transaction(schema, {baseSource: source});

  assert.equal(transaction.isolated, false, 'transactions are not isolated by default');

  return source.add('planet', {name: 'Jupiter', classification: 'gas giant'})
    .then(function(planet) {
      assert.equal(transaction.length('planet'), 1, 'transaction can retrieve planet from base source');
      assert.deepEqual(transaction.retrieve(['planet', planet.id]), planet, 'planet matches');
    });
});

test("an isolated transaction won't retrieve any data from its `baseSource`", function(assert) {
  assert.expect(2);

  var transaction = new Transaction(schema, {baseSource: source, isolated: true});

  assert.equal(transaction.isolated, true, 'transaction is isolated');

  return source.add('planet', {name: 'Jupiter', classification: 'gas giant'})
    .then(function(planet) {
      assert.equal(transaction.length('planet'), 0, 'transaction has no planets defined');
    });
});
<|endoftext|>


<commit_before>function showTaskOverview(groupNum){

	var task_id = getEventJSONIndex(groupNum);
	var eventObj = flashTeamsJSON["events"][task_id];
	var title = eventObj["title"];

	//uniq_u is null for author, we use this to decide whether to show the edit link next to project overview
	var uniq_u=getParameterByName('uniq');

	//modal label
	var label = title;
	$('#task_modal_Label').html(label);

	//modal content
	//var taskOverviewContent = '

' + description + '

';
	var taskOverviewContent = getTaskOverviewContent(groupNum);
	//$('#taskOverview').html(taskOverviewContent);
	$('#task-text').html(taskOverviewContent);

	if(in_progress == true){
        if(eventObj.status == "started"){
            $("#start-end-task").css('display', '');
            $("#start-end-task").attr('onclick', 'confirmCompleteTask('+groupNum+')');
            $("#start-end-task").html('Complete');
        }
        else if(eventObj.status == "completed"){
             $("#start-end-task").css('display', '');
              $("#start-end-task").html('Complete');
              $("#start-end-task").prop('disabled', true)
        }
        else{
           $("#start-end-task").css('display', '');
            $("#start-end-task").attr('onclick', 'startTask('+groupNum+')');
            $("#start-end-task").html('Start');
        }
    }
    else{
            $("#start-end-task").css('display', 'none');
    }

	if(in_progress != true && (uniq_u == "" || memberType == "pc" || memberType == "client") ) {
		$("#edit-save-task").css('display', '');
		$("#edit-save-task").attr('onclick', 'editTaskOverview(true,'+groupNum+')');
		$("#edit-save-task").html('Edit');
	}
	else{
		$("#edit-save-task").css('display', 'none');
		$("#delete").css('display','none');
	}
}

function editTaskOverview(popover,groupNum){

	var task_id = getEventJSONIndex(groupNum);
	var eventObj = flashTeamsJSON["events"][task_id];
	var title = eventObj["title"];

	if(popover==true){
		$('#task-edit-link').hide();

		//label
		label = '<input type ="text" name="eventName" id="eventName' + '" placeholder="'+title+'" >'
		$('#task_modal_Label').html(label);

        //content
        var taskOverviewForm = getTaskOverviewForm(groupNum);
		/*var taskOverviewForm = '<form name="taskOverviewForm" id="taskOverviewForm" style="margin-bottom: 5px;">'
					+'<textarea type="text"" id="descriptionInput" rows="6" placeholder="Task description ...">'+description+'</textarea>'
					+ 'Cancel'
					+'</form>';*/
		$('#task-text').html(taskOverviewForm);

		$("#edit-save-task").attr('onclick', 'saveTaskOverview('+groupNum+')');
		$("#edit-save-task").html('Save');

        $("#inputs").tagsinput();
        $("#outputs").tagsinput();
	}

}

function getTaskOverviewForm(groupNum){

var task_id = getEventJSONIndex(groupNum);
	var eventObj = flashTeamsJSON["events"][task_id];

	 var totalMinutes = eventObj["duration"];
    var groupNum = eventObj["id"];
    var title = eventObj["title"];
    var startHr = eventObj["startHr"];
    var startMin = eventObj["startMin"];
    var notes = eventObj["notes"];
    var inputs = eventObj["inputs"];
    if(!inputs) inputs = "";
    var outputs = eventObj["outputs"];
    if(!outputs) outputs = "";
    var numHours = Math.floor(totalMinutes/60);
    var minutesLeft = totalMinutes%60;
    var dri_id = eventObj.dri;
    var PC_id = eventObj.pc;
/*'<form name="taskOverviewForm" id="taskOverviewForm" style="margin-bottom: 5px;">'
					+'<textarea type="text"" id="descriptionInput" rows="6" placeholder="Task description ...">'+description+'</textarea>'
					+ 'Cancel'
					+'</form>';*/

var form ='<form name="taskOverviewForm" id="taskOverviewForm" style="margin-bottom: 5px;">'
        + '
'
        + 'Event Start:
'
        + 'Hours: <input type="number" id="startHr" placeholder="' + startHr
            + '" min="0" style="width:35px">         '
        + 'Minutes: <input type="number" id="startMin" placeholder="' + startMin
            + '" min="0" step="15" max="45" style="width:35px">
'
        + 'Total Runtime:
'
        + 'Hours: <input type = "number" id="hours" placeholder="'
            +numHours+'" min="0" style="width:35px"/>         '
        + 'Minutes: <input type = "number" id = "minutes" placeholder="'+minutesLeft
            +'" style="width:35px" min="0" step="15" max="45"/>
'
        + 'Members

'
            + writeEventMembers(eventObj)  +'
'

        + '
Project Coordinator
<select class="pcInput"'
            +' name="pcName" id="pcEvent"'
			+ 'onchange="getPC('+groupNum + ')">'+ writePCMembers(groupNum,PC_id) +'</select>'

        + '
Directly-Responsible Individual
<select class="driInput"'
            +' name="driName" id="driEvent"'
			+ 'onchange="getDRI('+groupNum + ')">'+ writeDRIMembers(groupNum,dri_id) +'</select>'

        + '
Notes:
<textarea rows="3" id="notes">' + notes + '</textarea>'
        + '
<input type="text" value="' + inputs + '" placeholder="Add input" id="inputs" />
'
        + '
<input type="text" value="' + outputs + '" placeholder="Add output" id="outputs" />

'
        + 'Cancel'
        + '</form>';

        return form;

}

function getTaskOverviewContent(groupNum){
	var task_id = getEventJSONIndex(groupNum);
	var ev = flashTeamsJSON["events"][task_id];

    var hrs = Math.floor(ev.duration/60);
    var mins = ev.duration % 60;

    var content = 'Event Start:
'
        + ev.startHr + ':'
        + ev.startMin.toFixed(0) + '
'
        +'Total Runtime:
'
        + hrs + ' hrs ' + mins + ' mins
';

    if(ev.inputs) {
        content += 'Inputs:
';
        var inputs = ev.inputs.split(",");
        for(var i=0;i<inputs.length;i++){
            content += inputs[i];
            content += "
";
        }
    }

    if(ev.outputs) {
        content += 'Outputs:
';
        var outputs = ev.outputs.split(",");
        for(var i=0;i<outputs.length;i++){
            content += outputs[i];
            content += "
";
        }
    }

    var num_members = ev.members.length;
    if(num_members > 0){
        content += 'Members:
';
        for (var j=0;j<num_members;j++){
            var member = getMemberById(ev.members[j]);
            content += member.role;
            content += '
';
        }
    }

    if (ev.pc != "" && ev.pc != undefined){
        var pc_id = parseInt (ev.pc);
        var mem = null;

        for (var i = 0; i<flashTeamsJSON["members"].length; i++){

            if(flashTeamsJSON["members"][i].id == pc_id){
                mem = flashTeamsJSON["members"][i].role;
                break;
            }
        }
          if(mem && mem != undefined){
            content += 'Project Coordinator:
';
            content += mem;
            content += '
';
        }
    }

     if (ev.dri != "" && ev.dri != undefined){
        var dri_id = parseInt (ev.dri);
        var mem = null;

        for (var i = 0; i<flashTeamsJSON["members"].length; i++){

            if(flashTeamsJSON["members"][i].id == dri_id){
                mem = flashTeamsJSON["members"][i].role;
                break;
            }
        }

        if(mem && mem != undefined){
            content += 'Directly-Responsible Individual:
';
            content += mem;
            content += '
';
        }
    }

    if (ev.content != ""){
        content += 'Notes:
';
        content += ev.notes;
        content += '
';
    }

    return content;
}

function saveTaskOverview(groupNum){
	var task_id = getEventJSONIndex(groupNum);
	var ev = flashTeamsJSON["events"][task_id];

    if($("#eventName").val() !="")
        ev.title = $("#eventName").val();

    //Get Start Time
    var startHour = $("#startHr").val();
    if (startHour == "") startHour = parseInt($("#startHr").attr("placeholder"));
    var startMin = $("#startMin").val();

    if (startMin == "") startMin = parseInt($("#startMin").attr("placeholder"));
    //newX
    startHour = parseInt(startHour);
    startMin = parseInt(startMin);
    var newX = (startHour * 100) + (startMin/15*25);
    newX = newX - (newX%(STEP_WIDTH)) - DRAGBAR_WIDTH/2;

    var eventNotes = $("#notes").val();
    var driId = getDRI(groupNum);
    var pcId = getPC(groupNum);

    var indexOfJSON = getEventJSONIndex(groupNum);
    var ev = flashTeamsJSON["events"][indexOfJSON];

    removeAllMemberCircles(ev);

    //Update members of event
    flashTeamsJSON["events"][indexOfJSON].members = [];
    for (var i = 0; i<flashTeamsJSON["members"].length; i++) {
        var member = flashTeamsJSON["members"][i];
        var memberId = member.id;
        var checkbox = $("#event" + groupNum + "member" + i + "checkbox")[0];
        if (checkbox == undefined) continue;
        if (checkbox.checked == true) {
            ev.members.push(memberId); //Update JSON
        }
    }

    //Update width
    var newHours = $("#hours").val();
    var newMin = $("#minutes").val();
    if (newHours == "") newHours = parseInt($("#hours")[0].placeholder);
    if (newMin == "") newMin = parseInt($("#minutes" )[0].placeholder);
    newMin = Math.round(parseInt(newMin)/15) * 15;

    //cannot have events shorter than 30 minutes
    if (newHours == 0 && newMin == 15){
        newMin = 30;
    }
    var newWidth = (newHours * 100) + (newMin/15*25);

    //Update JSON
    var indexOfJSON = getEventJSONIndex(groupNum);

    ev.notes = eventNotes;
    ev.dri = driId;
    ev.pc = pcId;
    ev.startHr = parseInt(startHour);
    ev.startMin = Math.round(parseInt(startMin)/15) * 15;
    ev.startTime = ev.startHr*60 + ev.startMin;
    ev.duration = durationForWidth(newWidth);
    ev.x = newX;
    ev.inputs = $('#inputs').val();
    ev.outputs = $('#outputs' ).val();

    drawEvent(ev, 0);

    updateStatus();
    //showTaskOverview(groupNum);
      $('#task_modal').modal('hide');
}<commit_msg>reformatted content of the modal in author and user views.<commit_after>function showTaskOverview(groupNum){

	var task_id = getEventJSONIndex(groupNum);
	var eventObj = flashTeamsJSON["events"][task_id];
	var title = eventObj["title"];

	//uniq_u is null for author, we use this to decide whether to show the edit link next to project overview
	var uniq_u=getParameterByName('uniq');

	//modal label
	var label = title;
	$('#task_modal_Label').html(label);

	//modal content
	//var taskOverviewContent = '

' + description + '

';
	var taskOverviewContent = getTaskOverviewContent(groupNum);
	//$('#taskOverview').html(taskOverviewContent);
	$('#task-text').html(taskOverviewContent);

	if(in_progress == true){
        if(eventObj.status == "started"){
            $("#start-end-task").css('display', '');
            $("#start-end-task").attr('onclick', 'confirmCompleteTask('+groupNum+')');
            $("#start-end-task").html('Complete');
        }
        else if(eventObj.status == "completed"){
             $("#start-end-task").css('display', '');
              $("#start-end-task").html('Complete');
              $("#start-end-task").prop('disabled', true)
        }
        else{
           $("#start-end-task").css('display', '');
            $("#start-end-task").attr('onclick', 'startTask('+groupNum+')');
            $("#start-end-task").html('Start');
        }
    }
    else{
            $("#start-end-task").css('display', 'none');
    }

    if(uniq_u == "" || memberType == "pc" || memberType == "client"){
        $("#hire-task").css('display','');
    }
    else{
        $("#hire-task").css('display','none');
    }

	if(in_progress != true && (uniq_u == "" || memberType == "pc" || memberType == "client") ) {
		$("#edit-save-task").css('display', '');

        $("#edit-save-task").attr('onclick', 'editTaskOverview(true,'+groupNum+')');
		$("#edit-save-task").html('Edit');
	}
	else{
		$("#edit-save-task").css('display', 'none');
		$("#delete").css('display','none');

	}
}

function editTaskOverview(popover,groupNum){

	var task_id = getEventJSONIndex(groupNum);
	var eventObj = flashTeamsJSON["events"][task_id];
	var title = eventObj["title"];

	if(popover==true){
		$('#task-edit-link').hide();

		//label
		label = '<input type ="text" name="eventName" id="eventName' + '" placeholder="'+title+'" >'
		$('#task_modal_Label').html(label);

        //content
        var taskOverviewForm = getTaskOverviewForm(groupNum);
		/*var taskOverviewForm = '<form name="taskOverviewForm" id="taskOverviewForm" style="margin-bottom: 5px;">'
					+'<textarea type="text"" id="descriptionInput" rows="6" placeholder="Task description ...">'+description+'</textarea>'
					+ 'Cancel'
					+'</form>';*/
		$('#task-text').html(taskOverviewForm);

		$("#edit-save-task").attr('onclick', 'saveTaskOverview('+groupNum+')');
		$("#edit-save-task").html('Save');

        $("#inputs").tagsinput();
        $("#outputs").tagsinput();
	}

}

function getTaskOverviewForm(groupNum){

var task_id = getEventJSONIndex(groupNum);
	var eventObj = flashTeamsJSON["events"][task_id];

	 var totalMinutes = eventObj["duration"];
    var groupNum = eventObj["id"];
    var title = eventObj["title"];
    var startHr = eventObj["startHr"];
    var startMin = eventObj["startMin"];
    var notes = eventObj["notes"];
    var inputs = eventObj["inputs"];
    if(!inputs) inputs = "";
    var outputs = eventObj["outputs"];
    if(!outputs) outputs = "";
    var numHours = Math.floor(totalMinutes/60);
    var minutesLeft = totalMinutes%60;
    var dri_id = eventObj.dri;
    var PC_id = eventObj.pc;
/*'<form name="taskOverviewForm" id="taskOverviewForm" style="margin-bottom: 5px;">'
					+'<textarea type="text"" id="descriptionInput" rows="6" placeholder="Task description ...">'+description+'</textarea>'
					+ 'Cancel'
					+'</form>';*/

var form ='<form name="taskOverviewForm" id="taskOverviewForm" style="margin-bottom: 5px;">'
        + '
'
        + '
'
        + '
'
        + 'Event Start
'
        + 'Hours : <input type="number" id="startHr" placeholder="' + startHr
            + '" min="0" style="width:36px">         '
        + 'Minutes : <input type="number" id="startMin" placeholder="' + startMin
            + '" min="0" step="15" max="45" style="width:36px">
'

        + 'Project Coordinator
<select class="pcInput"'
            +' name="pcName" id="pcEvent"'
            + 'onchange="getPC('+groupNum + ')">'+ writePCMembers(groupNum,PC_id) +'</select>'

        + '

'
        + 'Total Runtime
'
        + 'Hours : <input type = "number" id="hours" placeholder="'
            +numHours+'" min="0" style="width:36px"/>         '
        + 'Minutes : <input type = "number" id = "minutes" placeholder="'+minutesLeft
            +'" style="width:36px" min="0" step="15" max="45"/>
'
        + 'Directly-Responsible Individual
<select class="driInput"'
            +' name="driName" id="driEvent"'
			+ 'onchange="getDRI('+groupNum + ')">'+ writeDRIMembers(groupNum,dri_id) +'</select>'
        + '
'
        + '
'

        + '
'
        + '
'
        + 'Members

'
        + writeEventMembers(eventObj)  +'
'

        + '
Description
<textarea class="span12" style="width:475px" rows="5" placeholder="Description of the task..." id="notes">' + notes + '</textarea>'
        + 'Inputs

<input type="text" value="' + inputs + '" placeholder="Add input" id="inputs" />
'
        + 'Deliverables
<input type="text" value="' + outputs + '" placeholder="Add deliverable" id="outputs" />
'

        + '
Cancel'

        + '
'
        + '
'
        + '
'

        + '</form>';

        return form;

}

function getTaskOverviewContent(groupNum){
	var task_id = getEventJSONIndex(groupNum);
	var ev = flashTeamsJSON["events"][task_id];

    var hrs = Math.floor(ev.duration/60);
    var mins = ev.duration % 60;

    var content = '
'
        + '
'
        + 'Event Start:  '
        + ev.startHr + ':'
        + ev.startMin.toFixed(0) + '
'
        + '
'
        + '
'
        +'Total Runtime:  '
        + hrs+':'+mins
        + '
';
        + '
';

            if (ev.pc != "" && ev.pc != undefined){
        var pc_id = parseInt (ev.pc);
        var mem = null;

        for (var i = 0; i<flashTeamsJSON["members"].length; i++){

            if(flashTeamsJSON["members"][i].id == pc_id){
                mem = flashTeamsJSON["members"][i].role;
                break;
            }
        }
          if(mem && mem != undefined){
            content += '

'
            content += 'Project Coordinator:
';
            content += mem;
            content += "
"

        }
    }
    else{

    }

     if (ev.dri != "" && ev.dri != undefined){
        var dri_id = parseInt (ev.dri);
        var mem = null;

        for (var i = 0; i<flashTeamsJSON["members"].length; i++){

            if(flashTeamsJSON["members"][i].id == dri_id){
                mem = flashTeamsJSON["members"][i].role;
                break;
            }
        }

        if(mem && mem != undefined){
            content += '
';
            content += 'Directly-Responsible Individual:
';
            content += mem;
            content += '

'
        }
    }
    else{

    }

    if(ev.inputs) {
        content += 'Inputs:
';
        var inputs = ev.inputs.split(",");
        for(var i=0;i<inputs.length;i++){
            content += inputs[i];
            content += "
";
        }
    }

    if(ev.outputs) {
        content += 'Deliverables:
';
        var outputs = ev.outputs.split(",");
        for(var i=0;i<outputs.length;i++){
            content += outputs[i];
            content += "
";
        }
    }

    var num_members = ev.members.length;
    if(num_members > 0){
        content += 'Members:
';
        for (var j=0;j<num_members-1;j++){
            var member = getMemberById(ev.members[j]);
            content += member.role;
            content += ', ';
        }
        var member = getMemberById(ev.members[num_members-1]);
        content += member.role;
        content += '
';
    }

    if (ev.notes != ""){
        content += 'Description:
';
        content += ev.notes;
        content += '
';
    }

    return content;
}

function saveTaskOverview(groupNum){
	var task_id = getEventJSONIndex(groupNum);
	var ev = flashTeamsJSON["events"][task_id];

    if($("#eventName").val() !="")
        ev.title = $("#eventName").val();

    //Get Start Time
    var startHour = $("#startHr").val();
    if (startHour == "") startHour = parseInt($("#startHr").attr("placeholder"));
    var startMin = $("#startMin").val();

    if (startMin == "") startMin = parseInt($("#startMin").attr("placeholder"));
    //newX
    startHour = parseInt(startHour);
    startMin = parseInt(startMin);
    var newX = (startHour * 100) + (startMin/15*25);
    newX = newX - (newX%(STEP_WIDTH)) - DRAGBAR_WIDTH/2;

    var eventNotes = $("#notes").val();
    var driId = getDRI(groupNum);
    var pcId = getPC(groupNum);

    var indexOfJSON = getEventJSONIndex(groupNum);
    var ev = flashTeamsJSON["events"][indexOfJSON];

    removeAllMemberCircles(ev);

    //Update members of event
    flashTeamsJSON["events"][indexOfJSON].members = [];
    for (var i = 0; i<flashTeamsJSON["members"].length; i++) {
        var member = flashTeamsJSON["members"][i];
        var memberId = member.id;
        var checkbox = $("#event" + groupNum + "member" + i + "checkbox")[0];
        if (checkbox == undefined) continue;
        if (checkbox.checked == true) {
            ev.members.push(memberId); //Update JSON
        }
    }

    //Update width
    var newHours = $("#hours").val();
    var newMin = $("#minutes").val();
    if (newHours == "") newHours = parseInt($("#hours")[0].placeholder);
    if (newMin == "") newMin = parseInt($("#minutes" )[0].placeholder);
    newMin = Math.round(parseInt(newMin)/15) * 15;

    //cannot have events shorter than 30 minutes
    if (newHours == 0 && newMin == 15){
        newMin = 30;
    }
    var newWidth = (newHours * 100) + (newMin/15*25);

    //Update JSON
    var indexOfJSON = getEventJSONIndex(groupNum);

    ev.notes = eventNotes;
    ev.dri = driId;
    ev.pc = pcId;
    ev.startHr = parseInt(startHour);
    ev.startMin = Math.round(parseInt(startMin)/15) * 15;
    ev.startTime = ev.startHr*60 + ev.startMin;
    ev.duration = durationForWidth(newWidth);
    ev.x = newX;
    ev.inputs = $('#inputs').val();
    ev.outputs = $('#outputs' ).val();

    drawEvent(ev, 0);

    updateStatus();
    //showTaskOverview(groupNum);
      $('#task_modal').modal('hide');
}<|endoftext|>


<commit_before>const getRandomValues = (buf) => {
  if (typeof process !== 'undefined') {
    const nodeCrypto = require('crypto');
    const bytes = nodeCrypto.randomBytes(buf.length);
    buf.set(bytes);
    return buf;
  }

  if (window.crypto && window.crypto.getRandomValues) {
    return window.crypto.getRandomValues(buf);
  }

  if (window.msCrypto && window.msCrypto.getRandomValues) {
    return window.msCrypto.getRandomValues(buf);
  }

  throw new Error('No secure random number generator available.');
};

module.exports = getRandomValues;
<commit_msg>Support generating random values in web worker without window<commit_after>const getRandomValues = (buf) => {
  if (typeof process !== 'undefined') {
    const nodeCrypto = require('crypto');
    const bytes = nodeCrypto.randomBytes(buf.length);
    buf.set(bytes);
    return buf;
  }

  if (typeof crypto !== 'undefined') {
    return crypto.getRandomValues(buf);
  }

  if (window.crypto && window.crypto.getRandomValues) {
    return window.crypto.getRandomValues(buf);
  }

  if (window.msCrypto && window.msCrypto.getRandomValues) {
    return window.msCrypto.getRandomValues(buf);
  }

  throw new Error('No secure random number generator available.');
};

module.exports = getRandomValues;
<|endoftext|>


<commit_before>/*!
 * jQuery JavaScript Line Editor plugin
 *
 * Copyright 2010, Philip Schalm
 * Licensed under the MIT licence.
 *
 * Date: 2010-08-15
 */

(function($) {
  jQuery.fn.lineeditor = function () {
    if ( $(this).data('lineeditor') ) { return $(this).data('lineeditor') }
    return this.each(function () {
      this.lineeditor = function() {
        if (this.nodeName.toLowerCase() != 'textarea') { return; }

        var el = {};
        $el = $(this);

        el.addLine = function(value) {
          value = (value && value.target ? value.preventDefault() && '' : value);
          var input = $('<input type="text">').val(value?value.toString():'').change(el.processValues).keyup(el.processValues).keypress(el.processValues);
          var input_container = $('');
          el.container.find('a:last').before(input_container.append(input).append(el.buttons.clone(true)));
          el.processValues();
          el.calculatePositioning();
          return input;
        }

        el.removeLine = function(ev) {
          ev.preventDefault();
          $(this).closest('.input').remove();
          el.processValues();
        }

        el.move = function(direction) {
          return (function(ev) {
            ev.preventDefault();
            var target = $(this).closest('.input');
            if (direction == 'down') {
              target.insertAfter(target.next('.input'));
            } else if ( direction == 'up' ) {
              target.insertBefore(target.prev('.input'));
            }
            el.calculatePositioning();
          })
        }

        el.processValues = function(e) {
          if (e && e.keyCode == 9) {
            e.preventDefault();
            target = $(e.target).closest('.input');
            if (!e.shiftKey) {
              target.nextAll('.input:first').find('input[type=text]:first').focus().size() || el.addLine().focus();
            } else {
              target.prevAll('.input:first').find('input[type=text]').focus();
            }
            return;
          }
          el.hidden.val(
            el.container.find('input[type=text]').map(function(){
              return $(this).val();
            }).toArray().join("\n").trim()
          );
        }

        el.calculatePositioning = function() {
          el.container.find('.input').each(function(){
            if ( $(this).prev('.input').size() ) {
              $(this).find('.moveup').size() || $(this).find('.buttons').append(el.buttons.find('.moveup').clone(true));
            } else {
              $(this).find('.moveup').remove();
            }

            if ( $(this).next('.input').size() ) {
               $(this).find('.movedown').size() || $(this).find('.buttons').append(el.buttons.find('.movedown').clone(true));
            } else {
              $(this).find('.movedown').remove();
            }

            $(this).width($(this).find('input[type=text]').outerWidth());
          })
        }

        el.$el = $el;

        el.hidden = $('<input type="hidden">').attr('id', this.id).attr('name',this.name).val($el.val());
        el.container = $('

');
        el.val = $el.val();

        el.buttons = $('');
        $.each({
          'delete': el.removeLine,
          'moveup': el.move('up'),
          'movedown': el.move('down')
        },function(k,v){
          var node = $('' + k + '').click(v);
          el.buttons.append(node);
        });

        el.hidden.val(el.val);
        el.container.append(el.hidden);

        el.container.append($('Add Line').click(el.addLine));
        $.each(el.val.split("\n"),function(){
          el.addLine(this);
        });

        $el.replaceWith(el.container);
        el.calculatePositioning();

        el.hidden.data('lineeditor', el);
        return this;
      }
      return this.lineeditor();
    })
  }
})(jQuery);<commit_msg>Tab works correctly again in the lineeditor.<commit_after>/*!
 * jQuery JavaScript Line Editor plugin
 *
 * Copyright 2010, Philip Schalm
 * Licensed under the MIT licence.
 *
 * Date: 2010-08-15
 */

(function($) {
  jQuery.fn.lineeditor = function () {
    if ( $(this).data('lineeditor') ) { return $(this).data('lineeditor') }
    return this.each(function () {
      this.lineeditor = function() {
        if (this.nodeName.toLowerCase() != 'textarea') { return; }

        var el = {};
        $el = $(this);

        el.addLine = function(value) {
          value = (value && value.target ? value.preventDefault() && '' : value);
          var input = $('<input type="text">').val(value?value.toString():'').
            bind('change keyup keypress', el.processValues).
            keydown(el.handleTab);
          var input_container = $('');
          el.container.find('a:last').before(input_container.append(input).append(el.buttons.clone(true)));
          el.processValues();
          el.calculatePositioning();
          return input;
        }

        el.removeLine = function(ev) {
          ev.preventDefault();
          $(this).closest('.input').remove();
          el.processValues();
        }

        el.move = function(direction) {
          return (function(ev) {
            ev.preventDefault();
            var target = $(this).closest('.input');
            if (direction == 'down') {
              target.insertAfter(target.next('.input'));
            } else if ( direction == 'up' ) {
              target.insertBefore(target.prev('.input'));
            }
            el.calculatePositioning();
          })
        }

        el.handleTab = function(e) {
          if (e && e.keyCode == 9) {
            e.preventDefault();
            target = $(e.target).closest('.input');
            if (!e.shiftKey) {
              target.nextAll('.input:first').find('input[type=text]:first').focus().size() || el.addLine().focus();
            } else {
              target.prevAll('.input:first').find('input[type=text]').focus();
            }
            return;
          }
        }

        el.processValues = function(e) {
          el.hidden.val(
            el.container.find('input[type=text]').map(function(){
              return $(this).val();
            }).toArray().join("\n").trim()
          );
        }

        el.calculatePositioning = function() {
          el.container.find('.input').each(function(){
            if ( $(this).prev('.input').size() ) {
              $(this).find('.moveup').size() || $(this).find('.buttons').append(el.buttons.find('.moveup').clone(true));
            } else {
              $(this).find('.moveup').remove();
            }

            if ( $(this).next('.input').size() ) {
               $(this).find('.movedown').size() || $(this).find('.buttons').append(el.buttons.find('.movedown').clone(true));
            } else {
              $(this).find('.movedown').remove();
            }

            $(this).width($(this).find('input[type=text]').outerWidth());
          })
        }

        el.$el = $el;

        el.hidden = $('<input type="hidden">').attr('id', this.id).attr('name',this.name).val($el.val());
        el.container = $('

');
        el.val = $el.val();

        el.buttons = $('');
        $.each({
          'delete': el.removeLine,
          'moveup': el.move('up'),
          'movedown': el.move('down')
        },function(k,v){
          var node = $('' + k + '').click(v);
          el.buttons.append(node);
        });

        el.hidden.val(el.val);
        el.container.append(el.hidden);

        el.container.append($('Add Line').click(el.addLine));
        $.each(el.val.split("\n"),function(){
          el.addLine(this);
        });

        $el.replaceWith(el.container);
        el.calculatePositioning();

        el.hidden.data('lineeditor', el);
        return this;
      }
      return this.lineeditor();
    })
  }
})(jQuery);<|endoftext|>


<commit_before>'use strict';

var angular = require('camunda-commons-ui/vendor/angular'),
    camLayoutCtrl = require('./controllers/cam-layout-ctrl'),
    camHeaderViewsCtrl = require('./controllers/cam-header-views-ctrl');

require('camunda-commons-ui/lib/util/index');

var navigationModule = angular.module('cam.tasklist.navigation', [
  require('camunda-commons-ui/lib/util/index').name,
  'ui.bootstrap',
  'cam.tasklist.user'
]);

navigationModule.controller('camHeaderViewsCtrl', camHeaderViewsCtrl);
navigationModule.controller('camLayoutCtrl', camLayoutCtrl);

module.exports = navigationModule;
<commit_msg>fix(tasklist): remove user module dependencies<commit_after>'use strict';

var angular = require('camunda-commons-ui/vendor/angular'),
    camLayoutCtrl = require('./controllers/cam-layout-ctrl'),
    camHeaderViewsCtrl = require('./controllers/cam-header-views-ctrl');

require('camunda-commons-ui/lib/util/index');

var navigationModule = angular.module('cam.tasklist.navigation', [
  require('camunda-commons-ui/lib/util/index').name,
  'ui.bootstrap'
]);

navigationModule.controller('camHeaderViewsCtrl', camHeaderViewsCtrl);
navigationModule.controller('camLayoutCtrl', camLayoutCtrl);

module.exports = navigationModule;
<|endoftext|>