<commit_before>'use strict';

var _, Q, TWEEN, d3;

_ = require('underscore');
Q = require('q');
TWEEN = require('tween');
d3 = require('d3');

var helper = require('./helper');
var tumblr_ = require('./tumblr.coffee');
var canvas_ = require('./canvas.coffee');

var d = global.document;

var CONSUMER_KEY = '';

var clock = helper.clock.create(10000);
var frame = helper.frame.create();

var tumblr, context;

function load () {
  var dfr, loader, loaderMask, loaderIcon, title, search;
  dfr = Q.defer();
  loader = d3.select('.loader');
  loaderMask = loader.select('.loader__mask');
  loaderIcon = loaderMask.select('.loader__icon');
  title = d3.select('header > .title');
  search = d3.select('nav > .search');
  loaderIcon.on(helper.transitionend(), function (d, i) {
    loader.remove();
    title.classed({ 'fade--out': false, 'fade--in': 'true' });
  });
  title.on(helper.transitionend(), function (d, i) {
    search.classed({ 'fade--out': false, 'fade--in': true });
    dfr.resolve();
  });
  loaderIcon.classed({ 'fade--in': false, 'fade--out': true });
  return dfr.promise;
}

function hash () {
  var dfr, query;
  dfr = Q.defer();
  query = global.decodeURIComponent(global.location.hash).replace(/#\//, '');
  if ('' === hash) {
    _.defer(dfr.resolve);
  } else {
    _.defer(function () { dfr.resolve(query); });
  }
  return dfr.promise;
}

function hashchange () {
  var dfr;
  dfr = Q.defer();
  d3.select(global).on('hashchange', function (d, i) {
    var query = global.decodeURIComponent(global.location.hash).replace(/#\//, '');
    d3.select(global).on('hashchange', null);
    dfr.resolve(query);
  });
  return dfr.promise;
}

function submit (query) {
  var dfr, form, input;
  dfr = Q.defer();
  form = d3.select('.search');
  input = form.select('.search__input');

  if (query) {
    _.defer(function () {
      input.property('value', query);
      form.classed({ 'position--in': false, 'position--out': true });
      dfr.resolve(query);
    });
  } else {
    form.on('submit', function (d, i) {
      var value = input.property('value');
      d3.event.preventDefault();
      form.on('submit', null);
      form.classed({ 'position--in': false, 'position--out': true });
      global.location.hash = '#/' + global.encodeURIComponent(value);
      dfr.resolve(value);
    });
  }

  return dfr.promise;
}

function api () {
  var keyword, target, offset, dfr;
  keyword = _.isString(arguments[0]) ? arguments[0] : undefined;
  target = _.isObject(arguments[0]) ? arguments[0] : tumblr_.create(keyword, CONSUMER_KEY);
  tumblr = target;
  offset = _.isNumber(arguments[1]) ? arguments[1] : 0;
  dfr = Q.defer();
  target.on('load', dfr.resolve);
  target.on('error', dfr.reject);
  target.request('photo', offset);
  return dfr.promise;
}

function cache (data) {
  var dfr, posts, photos, images, uris;
  dfr = Q.defer();
  posts = data.posts ? data.posts : data;
  photos = _.flatten(_.pluck(posts, 'photos'));
  images = _.pluck(_.without(photos, undefined), 'original_size');
  uris = _.filter(_.pluck(images, 'url'), function (url) {
    return -1 === url.indexOf('31.media.tumblr.com');
  });
  if (1 > uris.length) {
    _.defer(function () { dfr.reject(new Error('Empty')); });
  } else {
    helper.cache(uris, helper.img).then(dfr.resolve, dfr.reject);
  }
  return dfr.promise;
}

function next () {
  var dfr;
  dfr = Q.defer();
  d3.select(d).on('keydown', function (d, i) {
    if (32 === d3.event.keyCode) dfr.resolve();
  });
  return dfr.promise;
}

function fail (err) {
  submit().then(cache, fail).then(show, fail);
  console.error(err.message);
}

function show (images) {
  var inc = 0, len = images.length, offset = 1;

  context.set('img', images[inc]);
  context.set('x', 100);
  context.set('alpha', 0.0);
  context.setup();

  frame.stop();
  frame.remove();
  frame.add(auto);
  frame.add(context.update);
  frame.add(TWEEN.update);
  frame.start();

  var initialFadeIn = new TWEEN.Tween({ x: 100, alpha: 0.0 });
  initialFadeIn
  .to({ x: 0, alpha: 1.0 }, 500)
  .onUpdate(function () {
    context.set('x', this.x);
    context.set('alpha', this.alpha);
  })
  .onComplete(function () {
    TWEEN.remove(initialFadeIn);
  })
  .start();

  clock.tick();
  bind();
  hashchange().then(submit, fail).then(api, fail).then(cache, fail).then(show, fail);
  submit().then(api, fail).then(cache, fail).then(show, fail);

  function bind () {
    next().then(slide).then(bind);
  }

  function auto () {
    if (clock.ticked()) slide();
  }

  function slide () {
    var dfr, fadeIn, fadeOut;
    dfr = Q.defer();
    clock.tick();
    fadeIn = new TWEEN.Tween({ x: 0, alpha: 1.0 })
      .to({ x: 100, alpha: 0.0 }, 500)
      .onUpdate(function () {
        context.set('x', this.x);
        context.set('alpha', this.alpha);
      })
      .onComplete(function () {
        if (0 !== offset && inc === (len >> 1)) {
          api(tumblr, (20 * offset)).then(cache).then(function (images_) {
            images = _.union(images, images_);
            len = images.length;
          }, fail);
          offset = 20 * offset >= tumblr.get('total') ? 0 : offset + 1;
        }
        inc += 1;
        if (inc >= len) inc = 0;
        context.set('img', images[inc]);

        fadeOut = new TWEEN.Tween({ x: 100, alpha: 0.0 })
          .to({ x: 0, alpha: 1.0 }, 500)
          .onUpdate(function () {
            context.set('x', this.x);
            context.set('alpha', this.alpha);
          })
          .onComplete(function () {
            TWEEN.remove(fadeIn);
            TWEEN.remove(fadeOut);
            dfr.resolve();
          })
          .start();
      })
      .start();
    return dfr.promise;
  }
}

function animate (now) {
  global.requestAnimationFrame(animate);
  frame.run();
}

function init () {
  var main, canvas;
  canvas = d3.select('#main > .view');
  context = canvas_.createContext(canvas.node(), global.innerWidth, global.innerHeight);

  global.addEventListener('resize', context.resize, false);

  context.on('lost', frame.stop);
  context.on('restored', frame.start);

  Q.all([ helper.dom(), helper.sleep(1500) ])
    .then(load, fail)
    .then(hash, fail)
    .then(submit, fail)
    .then(api, fail)
    .then(cache, fail)
    .then(show, fail);

  animate(+(new Date()));
}

init();
<commit_msg>Add WebSocket support<commit_after>'use strict';

var _, Q, TWEEN, d3;

_ = require('underscore');
Q = require('q');
TWEEN = require('tween');
d3 = require('d3');

var helper = require('./helper');
var tumblr_ = require('./tumblr.coffee');
var canvas_ = require('./canvas.coffee');

var d = global.document;

var CONSUMER_KEY = '';

var clock = helper.clock.create(10000);
var frame = helper.frame.create();

var ws, tumblr, context;

function load (data) {
  var dfr, loader, loaderMask, loaderIcon, title, search;
  dfr = Q.defer();
  ws = data[1];
  loader = d3.select('.loader');
  loaderMask = loader.select('.loader__mask');
  loaderIcon = loaderMask.select('.loader__icon');
  title = d3.select('header > .title');
  search = d3.select('nav > .search');
  loaderIcon.on(helper.transitionend(), function (d, i) {
    loader.remove();
    title.classed({ 'fade--out': false, 'fade--in': 'true' });
  });
  title.on(helper.transitionend(), function (d, i) {
    search.classed({ 'fade--out': false, 'fade--in': true });
    dfr.resolve();
  });
  loaderIcon.classed({ 'fade--in': false, 'fade--out': true });
  return dfr.promise;
}

function message () {
  var dfr, sock;
  dfr = Q.defer();
  sock = d3.select(ws);
  sock.on('message', function (d, i) {
    var data = ('' === d3.event.data) ? {} : global.JSON.parse(d3.event.data);
    if (data.slidr) {
      sock.on('message', null);
      dfr.resolve(data.slidr);
    }
  });
  return dfr.promise;
}

function hash () {
  var dfr, query;
  dfr = Q.defer();
  query = global.decodeURIComponent(global.location.hash).replace(/#\//, '');
  if ('' === hash) {
    _.defer(dfr.resolve);
  } else {
    _.defer(function () { dfr.resolve(query); });
  }
  return dfr.promise;
}

function hashchange () {
  var dfr;
  dfr = Q.defer();
  d3.select(global).on('hashchange', function (d, i) {
    var query = global.decodeURIComponent(global.location.hash).replace(/#\//, '');
    d3.select(global).on('hashchange', null);
    dfr.resolve(query);
  });
  return dfr.promise;
}

function submit (query) {
  var dfr, form, input;
  dfr = Q.defer();
  form = d3.select('.search');
  input = form.select('.search__input');

  if (query) {
    _.defer(function () {
      input.property('value', query);
      form.classed({ 'position--in': false, 'position--out': true });
      global.location.hash = '#/' + global.encodeURIComponent(query);
      dfr.resolve(query);
    });
  } else {
    form.on('submit', function (d, i) {
      var value = input.property('value');
      d3.event.preventDefault();
      form.on('submit', null);
      form.classed({ 'position--in': false, 'position--out': true });
      global.location.hash = '#/' + global.encodeURIComponent(value);
      ws.send(global.JSON.stringify({ 'slidr': value }));
      dfr.resolve(value);
    });
  }

  return dfr.promise;
}

function api () {
  var keyword, target, offset, dfr;
  keyword = _.isString(arguments[0]) ? arguments[0] : undefined;
  target = _.isObject(arguments[0]) ? arguments[0] : tumblr_.create(keyword, CONSUMER_KEY);
  tumblr = target;
  offset = _.isNumber(arguments[1]) ? arguments[1] : 0;
  dfr = Q.defer();
  target.on('load', dfr.resolve);
  target.on('error', dfr.reject);
  target.request('photo', offset);
  return dfr.promise;
}

function cache (data) {
  var dfr, posts, photos, images, uris;
  dfr = Q.defer();
  posts = data.posts ? data.posts : data;
  photos = _.flatten(_.pluck(posts, 'photos'));
  images = _.pluck(_.without(photos, undefined), 'original_size');
  uris = _.filter(_.pluck(images, 'url'), function (url) {
    return -1 === url.indexOf('31.media.tumblr.com');
  });
  if (1 > uris.length) {
    _.defer(function () { dfr.reject(new Error('Empty')); });
  } else {
    helper.cache(uris, helper.img).then(dfr.resolve, dfr.reject);
  }
  return dfr.promise;
}

function next () {
  var dfr;
  dfr = Q.defer();
  d3.select(d).on('keydown', function (d, i) {
    if (32 === d3.event.keyCode) dfr.resolve();
  });
  return dfr.promise;
}

function fail (err) {
  submit()
    .then(api, fail)
    .then(cache, fail)
    .then(show, fail);

  console.error(err.message);
}

function show (images) {
  var inc = 0, len = images.length, offset = 1;

  context.set('img', images[inc]);
  context.set('x', 100);
  context.set('alpha', 0.0);
  context.setup();

  frame.stop();
  frame.remove();
  frame.add(auto);
  frame.add(context.update);
  frame.add(TWEEN.update);
  frame.start();

  var initialFadeIn = new TWEEN.Tween({ x: 100, alpha: 0.0 })
    .to({ x: 0, alpha: 1.0 }, 500)
    .onUpdate(function () {
      context.set('x', this.x);
      context.set('alpha', this.alpha);
    })
    .onComplete(function () {
      TWEEN.remove(initialFadeIn);
    })
    .start();

  clock.tick();
  bind();

  message()
    .then(submit, fail)
    .then(api, fail)
    .then(cache, fail)
    .then(show, fail);

  hashchange()
    .then(submit, fail)
    .then(api, fail)
    .then(cache, fail)
    .then(show, fail);

  submit()
    .then(api, fail)
    .then(cache, fail)
    .then(show, fail);

  function bind () {
    next().then(slide).then(bind);
  }

  function auto () {
    if (clock.ticked()) slide();
  }

  function slide () {
    var dfr, fadeIn, fadeOut;
    dfr = Q.defer();
    clock.tick();
    fadeIn = new TWEEN.Tween({ x: 0, alpha: 1.0 })
      .to({ x: 100, alpha: 0.0 }, 500)
      .onUpdate(function () {
        context.set('x', this.x);
        context.set('alpha', this.alpha);
      })
      .onComplete(function () {
        if (0 !== offset && inc === (len >> 1)) {
          api(tumblr, (20 * offset)).then(cache).then(function (images_) {
            images = _.union(images, images_);
            len = images.length;
          }, fail);
          offset = 20 * offset >= tumblr.get('total') ? 0 : offset + 1;
        }
        inc += 1;
        if (inc >= len) inc = 0;
        context.set('img', images[inc]);

        fadeOut = new TWEEN.Tween({ x: 100, alpha: 0.0 })
          .to({ x: 0, alpha: 1.0 }, 500)
          .onUpdate(function () {
            context.set('x', this.x);
            context.set('alpha', this.alpha);
          })
          .onComplete(function () {
            TWEEN.remove(fadeIn);
            TWEEN.remove(fadeOut);
            dfr.resolve();
          })
          .start();
      })
      .start();
    return dfr.promise;
  }
}

function animate (now) {
  global.requestAnimationFrame(animate);
  frame.run();
}

function init () {
  var main, canvas;
  canvas = d3.select('#main > .view');
  context = canvas_.createContext(canvas.node(), global.innerWidth, global.innerHeight);

  global.addEventListener('resize', context.resize, false);

  context.on('lost', frame.stop);
  context.on('restored', frame.start);

  Q.all([ helper.dom(), helper.ws('wss://wss.jit.su'), helper.sleep(1500) ])
    .then(load, fail)
    .then(hash, fail)
    .then(submit, fail)
    .then(api, fail)
    .then(cache, fail)
    .then(show, fail);

  animate(+(new Date()));
}

init();
<|endoftext|>


<commit_before>/**
 * guy
 * 单选框item
 * @type {*|void|Object}
 */
BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, {
    _defaultConfig: function () {
        return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this, arguments), {
            extraCls: "bi-single-select-radio-item",
            logic: {
                dynamic: false
            },
            height: 24,
            iconWrapperWidth: 26,
            hgap: 10,
            textHgap: 0,
            textLgap: 0,
            textRgap: 0
        });
    },
    _init: function () {
        BI.SingleSelectRadioItem.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.radio = BI.createWidget({
            type: "bi.radio"
        });
        this.text = BI.createWidget({
            type: "bi.label",
            cls: "list-item-text",
            textAlign: "left",
            whiteSpace: "nowrap",
            textHeight: o.height,
            height: o.height,
            hgap: o.hgap,
            rgap: o.textRgap,
            lgap: o.textLgap,
            text: o.text,
            keyword: o.keyword,
            value: o.value,
            py: o.py
        });

        BI.createWidget(BI.extend({
            element: this
        }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
            items: BI.LogicFactory.createLogicItemsByDirection("left", {
                type: "bi.center_adapt",
                items: [this.radio],
                width: o.iconWrapperWidth
            }, this.text)
        }))));
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doClick: function () {
        BI.SingleSelectRadioItem.superclass.doClick.apply(this, arguments);
        this.radio.setSelected(this.isSelected());
        if (this.isValid()) {
            this.fireEvent(BI.SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this);
        }
    },

    setSelected: function (v) {
        BI.SingleSelectRadioItem.superclass.setSelected.apply(this, arguments);
        this.radio.setSelected(v);

    }
});

BI.SingleSelectRadioItem.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.single_select_radio_item", BI.SingleSelectRadioItem);
<commit_msg>无JIRA任务 radio item 图标宽度默认16<commit_after>/**
 * guy
 * 单选框item
 * @type {*|void|Object}
 */
BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, {
    _defaultConfig: function () {
        return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this, arguments), {
            extraCls: "bi-single-select-radio-item",
            logic: {
                dynamic: false
            },
            height: 24,
            iconWrapperWidth: 16,
            hgap: 10,
            textHgap: 0,
            textLgap: 0,
            textRgap: 0
        });
    },
    _init: function () {
        BI.SingleSelectRadioItem.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.radio = BI.createWidget({
            type: "bi.radio"
        });
        this.text = BI.createWidget({
            type: "bi.label",
            cls: "list-item-text",
            textAlign: "left",
            whiteSpace: "nowrap",
            textHeight: o.height,
            height: o.height,
            hgap: o.hgap,
            rgap: o.textRgap,
            lgap: o.textLgap,
            text: o.text,
            keyword: o.keyword,
            value: o.value,
            py: o.py
        });

        BI.createWidget(BI.extend({
            element: this
        }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
            items: BI.LogicFactory.createLogicItemsByDirection("left", {
                type: "bi.center_adapt",
                items: [this.radio],
                width: o.iconWrapperWidth
            }, this.text)
        }))));
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doClick: function () {
        BI.SingleSelectRadioItem.superclass.doClick.apply(this, arguments);
        this.radio.setSelected(this.isSelected());
        if (this.isValid()) {
            this.fireEvent(BI.SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this);
        }
    },

    setSelected: function (v) {
        BI.SingleSelectRadioItem.superclass.setSelected.apply(this, arguments);
        this.radio.setSelected(v);

    }
});

BI.SingleSelectRadioItem.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.single_select_radio_item", BI.SingleSelectRadioItem);
<|endoftext|>


<commit_before>'use strict';

angular.module('users').controller('userManagement', ['$scope', '$state', '$stateParams','$location', 'ManagementService',
	function($scope, $state, $stateParams, $location, ManagementService)
	{

		$scope.mId = 0;
		$scope.roles = ['user', 'teacher', 'admin'];

		$scope.findOne = function()
		{
			$scope.mUser = ManagementService.mUser;
		};

		$scope.viewUser = function(mUser){
			ManagementService.mUser = mUser;
			$location.path('/users/:' + mUser._id);
		};

		$scope.find = function()
		{
			$scope.users = ManagementService.query();
		};

		$scope.$on('$locationChangeStart', function( event ) {
			for (var mUser in $scope.users){
				$scope.users[mUser].$update(function(response) {
					console.log('Saved user' + $scope.users[mUser].displayName);
					$scope.success = true;
				}, function(response) {
					$scope.error = response.data.message;
				});
			}
		});

		$scope.remove = function(mUser)
		{
			if (mUser){
				mUser.$remove(function()
				{
					for (var i in $scope.users) {
		                if ($scope.users[i] === mUser) {
		                    $scope.users.splice(i, 1); // remove item from scope
		                }
		            }
				});
            }
		};

		$scope.changeRole = function(mUser, role)
		{
			mUser.roles = [role];
			mUser.$update(function()
			{
				$state.reload();
			});
		}
	}
]);<commit_msg>Changing roles seems to affect something with login. Commented out for now.<commit_after>'use strict';

angular.module('users').controller('userManagement', ['$scope', '$state', '$stateParams','$location', 'ManagementService',
	function($scope, $state, $stateParams, $location, ManagementService)
	{

		$scope.mId = 0;
		$scope.roles = ['user', 'teacher', 'admin'];

		$scope.findOne = function()
		{
			$scope.mUser = ManagementService.mUser;
		};

		$scope.viewUser = function(mUser){
			ManagementService.mUser = mUser;
			$location.path('/users/:' + mUser._id);
		};

		$scope.find = function()
		{
			$scope.users = ManagementService.query();
		};

		$scope.$on('$locationChangeStart', function( event ) {
			for (var mUser in $scope.users){
				$scope.users[mUser].$update(function(response) {
					console.log('Saved user' + $scope.users[mUser].displayName);
					$scope.success = true;
				}, function(response) {
					$scope.error = response.data.message;
				});
			}
		});

		$scope.remove = function(mUser)
		{
			if (mUser){
				mUser.$remove(function()
				{
					for (var i in $scope.users) {
		                if ($scope.users[i] === mUser) {
		                    $scope.users.splice(i, 1); // remove item from scope
		                }
		            }
				});
            }
		};

		$scope.changeRole = function(mUser, role)
		{
			/*
			mUser.roles = [role];
			console.log(mUser);
			mUser.$update(function()
			{
				$state.reload();
			});
			*/
		}
	}
]);<|endoftext|>


<commit_before>(function($) {
  $.extend(true, $.summernote.lang, {
    'sv-SE': {
      font: {
        bold: 'Fet',
        italic: 'Kursiv',
        underline: 'Understruken',
        clear: 'Radera formatering',
        height: 'Radavstånd',
        name: 'Teckensnitt',
        strikethrough: 'Genomstruken',
        subscript: 'Subscript',
        superscript: 'Superscript',
        size: 'Teckenstorlek',
      },
      image: {
        image: 'Bild',
        insert: 'Infoga bild',
        resizeFull: 'Full storlek',
        resizeHalf: 'Halv storlek',
        resizeQuarter: 'En fjärdedel i storlek',
        floatLeft: 'Vänsterjusterad',
        floatRight: 'Högerjusterad',
        floatNone: 'Ingen justering',
        shapeRounded: 'Shape: Rounded',
        shapeCircle: 'Shape: Circle',
        shapeThumbnail: 'Shape: Thumbnail',
        shapeNone: 'Shape: None',
        dragImageHere: 'Dra en bild hit',
        dropImage: 'Drop image or Text',
        selectFromFiles: 'Välj från filer',
        maximumFileSize: 'Maximum file size',
        maximumFileSizeError: 'Maximum file size exceeded.',
        url: 'Länk till bild',
        remove: 'Ta bort bild',
        original: 'Original',
      },
      video: {
        video: 'Filmklipp',
        videoLink: 'Länk till filmklipp',
        insert: 'Infoga filmklipp',
        url: 'Länk till filmklipp',
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion eller Youku)',
      },
      link: {
        link: 'Länk',
        insert: 'Infoga länk',
        unlink: 'Ta bort länk',
        edit: 'Redigera',
        textToDisplay: 'Visningstext',
        url: 'Till vilken URL ska denna länk peka?',
        openInNewWindow: 'Öppna i ett nytt fönster',
        useProtocol: 'Använd standardprotokoll',
      },
      table: {
        table: 'Tabell',
        addRowAbove: 'Add row above',
        addRowBelow: 'Add row below',
        addColLeft: 'Add column left',
        addColRight: 'Add column right',
        delRow: 'Delete row',
        delCol: 'Delete column',
        delTable: 'Delete table',
      },
      hr: {
        insert: 'Infoga horisontell linje',
      },
      style: {
        style: 'Stil',
        p: 'p',
        blockquote: 'Citat',
        pre: 'Kod',
        h1: 'Rubrik 1',
        h2: 'Rubrik 2',
        h3: 'Rubrik 3',
        h4: 'Rubrik 4',
        h5: 'Rubrik 5',
        h6: 'Rubrik 6',
      },
      lists: {
        unordered: 'Punktlista',
        ordered: 'Numrerad lista',
      },
      options: {
        help: 'Hjälp',
        fullscreen: 'Fullskärm',
        codeview: 'HTML-visning',
      },
      paragraph: {
        paragraph: 'Justera text',
        outdent: 'Minska indrag',
        indent: 'Öka indrag',
        left: 'Vänsterjusterad',
        center: 'Centrerad',
        right: 'Högerjusterad',
        justify: 'Justera text',
      },
      color: {
        recent: 'Senast använda färg',
        more: 'Fler färger',
        background: 'Bakgrundsfärg',
        foreground: 'Teckenfärg',
        transparent: 'Genomskinlig',
        setTransparent: 'Gör genomskinlig',
        reset: 'Nollställ',
        resetToDefault: 'Återställ till standard',
      },
      shortcut: {
        shortcuts: 'Kortkommandon',
        close: 'Stäng',
        textFormatting: 'Textformatering',
        action: 'Funktion',
        paragraphFormatting: 'Avsnittsformatering',
        documentStyle: 'Dokumentstil',
        extraKeys: 'Extra keys',
      },
      help: {
        'insertParagraph': 'Insert Paragraph',
        'undo': 'Undoes the last command',
        'redo': 'Redoes the last command',
        'tab': 'Tab',
        'untab': 'Untab',
        'bold': 'Set a bold style',
        'italic': 'Set a italic style',
        'underline': 'Set a underline style',
        'strikethrough': 'Set a strikethrough style',
        'removeFormat': 'Clean a style',
        'justifyLeft': 'Set left align',
        'justifyCenter': 'Set center align',
        'justifyRight': 'Set right align',
        'justifyFull': 'Set full align',
        'insertUnorderedList': 'Toggle unordered list',
        'insertOrderedList': 'Toggle ordered list',
        'outdent': 'Outdent on current paragraph',
        'indent': 'Indent on current paragraph',
        'formatPara': 'Change current block\'s format as a paragraph(P tag)',
        'formatH1': 'Change current block\'s format as H1',
        'formatH2': 'Change current block\'s format as H2',
        'formatH3': 'Change current block\'s format as H3',
        'formatH4': 'Change current block\'s format as H4',
        'formatH5': 'Change current block\'s format as H5',
        'formatH6': 'Change current block\'s format as H6',
        'insertHorizontalRule': 'Insert horizontal rule',
        'linkDialog.show': 'Show Link Dialog',
      },
      history: {
        undo: 'Ångra',
        redo: 'Gör om',
      },
      specialChar: {
        specialChar: 'SPECIAL CHARACTERS',
        select: 'Select Special characters',
      },
    },
  });
})(jQuery);
<commit_msg>Update summernote-sv-SE.js<commit_after>(function($) {
  $.extend(true, $.summernote.lang, {
    'sv-SE': {
      font: {
        bold: 'Fet',
        italic: 'Kursiv',
        underline: 'Understruken',
        clear: 'Radera formatering',
        height: 'Radavstånd',
        name: 'Teckensnitt',
        strikethrough: 'Genomstruken',
        subscript: 'Nedsänkt',
        superscript: 'Upphöjd',
        size: 'Teckenstorlek',
      },
      image: {
        image: 'Bild',
        insert: 'Infoga bild',
        resizeFull: 'Full storlek',
        resizeHalf: 'Halv storlek',
        resizeQuarter: 'En fjärdedel i storlek',
        floatLeft: 'Vänsterjusterad',
        floatRight: 'Högerjusterad',
        floatNone: 'Ingen justering',
        shapeRounded: 'Form: Avrundad',
        shapeCircle: 'Form: Cirkel',
        shapeThumbnail: 'Form: Miniatyr',
        shapeNone: 'Form: Ingen',
        dragImageHere: 'Dra en bild hit',
        dropImage: 'Släpp bild eller text',
        selectFromFiles: 'Välj från filer',
        maximumFileSize: 'Maximal filstorlek',
        maximumFileSizeError: 'Maximal filstorlek har överskridits.',
        url: 'Länk till bild',
        remove: 'Ta bort bild',
        original: 'Original',
      },
      video: {
        video: 'Filmklipp',
        videoLink: 'Länk till filmklipp',
        insert: 'Infoga filmklipp',
        url: 'Länk till filmklipp',
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion eller Youku)',
      },
      link: {
        link: 'Länk',
        insert: 'Infoga länk',
        unlink: 'Ta bort länk',
        edit: 'Redigera',
        textToDisplay: 'Visningstext',
        url: 'Till vilken URL ska denna länk peka?',
        openInNewWindow: 'Öppna i ett nytt fönster',
        useProtocol: 'Använd standardprotokoll',
      },
      table: {
        table: 'Tabell',
        addRowAbove: 'Lägg till rad ovanför',
        addRowBelow: 'Lägg till rad under',
        addColLeft: 'Lägg till kolumn åt vänster',
        addColRight: 'Lägg till kolumn åt höger',
        delRow: 'Radera rad',
        delCol: 'Radera kolumn',
        delTable: 'Radera tabell',
      },
      hr: {
        insert: 'Infoga horisontell linje',
      },
      style: {
        style: 'Stil',
        p: 'p',
        blockquote: 'Citat',
        pre: 'Kod',
        h1: 'Rubrik 1',
        h2: 'Rubrik 2',
        h3: 'Rubrik 3',
        h4: 'Rubrik 4',
        h5: 'Rubrik 5',
        h6: 'Rubrik 6',
      },
      lists: {
        unordered: 'Punktlista',
        ordered: 'Numrerad lista',
      },
      options: {
        help: 'Hjälp',
        fullscreen: 'Fullskärm',
        codeview: 'HTML-visning',
      },
      paragraph: {
        paragraph: 'Justera text',
        outdent: 'Minska indrag',
        indent: 'Öka indrag',
        left: 'Vänsterjusterad',
        center: 'Centrerad',
        right: 'Högerjusterad',
        justify: 'Justera text',
      },
      color: {
        recent: 'Senast använda färg',
        more: 'Fler färger',
        background: 'Bakgrundsfärg',
        foreground: 'Teckenfärg',
        transparent: 'Genomskinlig',
        setTransparent: 'Gör genomskinlig',
        reset: 'Nollställ',
        resetToDefault: 'Återställ till standard',
      },
      shortcut: {
        shortcuts: 'Kortkommandon',
        close: 'Stäng',
        textFormatting: 'Textformatering',
        action: 'Funktion',
        paragraphFormatting: 'Avsnittsformatering',
        documentStyle: 'Dokumentstil',
        extraKeys: 'Extra tangenter',
      },
      help: {
        'insertParagraph': 'Infoga paragraf',
        'undo': 'Ångra senaste kommandot',
        'redo': 'Gör om senaste kommandot',
        'tab': 'Lägg till indrag',
        'untab': 'Ta bort indrag',
        'bold': 'Tillämpa fet stil',
        'italic': 'Tillämpa kursiv stil',
        'underline': 'Tillämpa understruken stil',
        'strikethrough': 'Tillämpa genomstruken stil',
        'removeFormat': 'Rensa formatering',
        'justifyLeft': 'Tillämpa vänsterjustering',
        'justifyCenter': 'Tillämpa centrering',
        'justifyRight': 'Tillämpa högerjustering',
        'justifyFull': 'Tillämpa justerad text',
        'insertUnorderedList': 'Tillämpa punktlista',
        'insertOrderedList': 'Tillämpa numrerad lista',
        'outdent': 'Minska indrag för aktuell paragraf',
        'indent': 'Öka indrag för aktuell paragraf',
        'formatPara': 'Ändra formatet för aktuellt block till en paragraf (P-tagg)',
        'formatH1': 'Ändra formatet för aktuellt block till rubrik 1',
        'formatH2': 'Ändra formatet för aktuellt block till rubrik 2',
        'formatH3': 'Ändra formatet för aktuellt block till rubrik 3',
        'formatH4': 'Ändra formatet för aktuellt block till rubrik 4',
        'formatH5': 'Ändra formatet för aktuellt block till rubrik 5',
        'formatH6': 'Ändra formatet för aktuellt block till rubrik 6',
        'insertHorizontalRule': 'Infoga horisontell linje',
        'linkDialog.show': 'Visa dialogruta för länk',
      },
      history: {
        undo: 'Ångra',
        redo: 'Gör om',
      },
      specialChar: {
        specialChar: 'SPECIALTECKEN',
        select: 'Välj specialtecken',
      },
    },
  });
})(jQuery);
<|endoftext|>


<commit_before>/**
 * guy
 * 单选框item
 * @type {*|void|Object}
 */
BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, {
    _defaultConfig: function () {
        return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this, arguments), {
            extraCls: "bi-single-select-radio-item",
            logic: {
                dynamic: false
            },
            height: 24
        });
    },
    _init: function () {
        BI.SingleSelectRadioItem.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.radio = BI.createWidget({
            type: "bi.radio"
        });
        this.text = BI.createWidget({
            type: "bi.label",
            cls: "list-item-text",
            textAlign: "left",
            whiteSpace: "nowrap",
            textHeight: o.height,
            height: o.height,
            hgap: o.hgap,
            text: o.text,
            keyword: o.keyword,
            value: o.value,
            py: o.py
        });

        BI.createWidget(BI.extend({
            element: this
        }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
            items: BI.LogicFactory.createLogicItemsByDirection("left", {
                type: "bi.center_adapt",
                items: [this.radio],
                width: 26
            }, this.text)
        }))));
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doClick: function () {
        BI.SingleSelectRadioItem.superclass.doClick.apply(this, arguments);
        this.radio.setSelected(this.isSelected());
        if (this.isValid()) {
            this.fireEvent(BI.SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this);
        }
    },

    setSelected: function (v) {
        BI.SingleSelectRadioItem.superclass.setSelected.apply(this, arguments);
        this.radio.setSelected(v);

    }
});

BI.SingleSelectRadioItem.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.single_select_radio_item", BI.SingleSelectRadioItem);
<commit_msg>Pull request #1793: BI-81833 fix: 单选按钮宽度变化导致的错位问题<commit_after>/**
 * guy
 * 单选框item
 * @type {*|void|Object}
 */
BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, {
    _defaultConfig: function () {
        return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this, arguments), {
            extraCls: "bi-single-select-radio-item",
            logic: {
                dynamic: false
            },
            height: 24
        });
    },
    _init: function () {
        BI.SingleSelectRadioItem.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.radio = BI.createWidget({
            type: "bi.radio"
        });
        this.text = BI.createWidget({
            type: "bi.label",
            cls: "list-item-text",
            textAlign: "left",
            whiteSpace: "nowrap",
            textHeight: o.height,
            height: o.height,
            hgap: o.hgap,
            text: o.text,
            keyword: o.keyword,
            value: o.value,
            py: o.py
        });

        BI.createWidget(BI.extend({
            element: this
        }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
            items: BI.LogicFactory.createLogicItemsByDirection("left", {
                type: "bi.center_adapt",
                items: [this.radio],
                width: 16
            }, this.text)
        }))));
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doClick: function () {
        BI.SingleSelectRadioItem.superclass.doClick.apply(this, arguments);
        this.radio.setSelected(this.isSelected());
        if (this.isValid()) {
            this.fireEvent(BI.SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this);
        }
    },

    setSelected: function (v) {
        BI.SingleSelectRadioItem.superclass.setSelected.apply(this, arguments);
        this.radio.setSelected(v);

    }
});

BI.SingleSelectRadioItem.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.single_select_radio_item", BI.SingleSelectRadioItem);
<|endoftext|>


<commit_before>// 'use strict'

var table = document.getElementById('postBoard');
var nameData;

var jobNumber = 1;
var trElement;

// assigning localstorage array to the new variable to use in rendering rows

var clientArray = JSON.parse(localStorage.getItem('lsClientArray'));
//console.log(clientArray);

function renderHeader(){

  trElement = document.createElement('thead');
  table.appendChild(trElement);

  nameData = document.createElement('td');
  nameData.textContent = " Job #";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Name";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "E-mail";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Job Description";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Location";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Time Frame";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Accept job";
  trElement.appendChild(nameData);

};

renderHeader();

//rendering table rows function:
function renderAsRow(client){
  for (var i = 0; i<clientArray.length; i++){

    trElement = document.createElement('tr');

    trElement = document.createElement('tr');
    trElement.setAttribute('class', 'available');
    nameData = document.createElement('td');
    nameData.textContent = jobNumber;
    trElement.appendChild(nameData);

    jobNumber++;

    nameData = document.createElement('td');
    nameData.textContent = client[i].name;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].email;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].descript;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].loc;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].time;
    trElement.appendChild(nameData);

    var checkbox = document.createElement('INPUT');
    checkbox.type = "checkbox";

    trElement.appendChild(checkbox);

    // dimming checjbox on click
    checkbox.addEventListener('click', function() {

      if (this.checked){
        this.parentElement.setAttribute('class', 'unavailable');
      } else {
        this.parentElement.setAttribute('class', 'available');
      }
    })

    table.appendChild(trElement);

  }
}

renderAsRow(clientArray);

function initMap() {

  var citiesCoordinates = [
    {name:'Seattle', lat:47.6062, lng:-122.3321},
    {name:'redmond', lat:47.6740, lng:-122.1215},
    {name:'Bellevue', lat:47.6101, lng:-122.2015}
  ];
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat:47.6062, lng:-122.3321}
  });
  for (i=0; i<citiesCoordinates.length;i++){
    var marker = new google.maps.Marker({
      position: {lat: citiesCoordinates[i].lat, lng: citiesCoordinates[i].lng},
      map: map
    });
  }
}
<commit_msg>a few cities markers on map<commit_after>// 'use strict'

var table = document.getElementById('postBoard');
var nameData;

var jobNumber = 1;
var trElement;

// assigning localstorage array to the new variable to use in rendering rows

var clientArray = JSON.parse(localStorage.getItem('lsClientArray'));
//console.log(clientArray);

function renderHeader(){

  trElement = document.createElement('thead');
  table.appendChild(trElement);

  nameData = document.createElement('td');
  nameData.textContent = " Job #";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Name";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "E-mail";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Job Description";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "City";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Time Frame";
  trElement.appendChild(nameData);

  nameData = document.createElement('td');
  nameData.textContent = "Accept job";
  trElement.appendChild(nameData);

};

renderHeader();

//rendering table rows function:
function renderAsRow(client){
  for (var i = 0; i<clientArray.length; i++){

    trElement = document.createElement('tr');

    trElement = document.createElement('tr');
    trElement.setAttribute('class', 'available');
    nameData = document.createElement('td');
    nameData.textContent = jobNumber;
    trElement.appendChild(nameData);

    jobNumber++;

    nameData = document.createElement('td');
    nameData.textContent = client[i].name;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].email;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].descript;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].loc;
    trElement.appendChild(nameData);

    nameData = document.createElement('td');
    nameData.textContent = client[i].time;
    trElement.appendChild(nameData);

    var checkbox = document.createElement('INPUT');
    checkbox.type = "checkbox";

    trElement.appendChild(checkbox);

    // dimming checjbox on click
    checkbox.addEventListener('click', function() {

      if (this.checked){
        this.parentElement.setAttribute('class', 'unavailable');
      } else {
        this.parentElement.setAttribute('class', 'available');
      }
    })

    table.appendChild(trElement);

  }
}

renderAsRow(clientArray);

function initMap() {

  var citiesCoordinates = [
    {name:'seattle', lat:47.6062, lng:-122.3321},
    {name:'redmond', lat:47.6740, lng:-122.1215},
    {name:'bellevue', lat:47.6101, lng:-122.2015},
    {name:'sammamish', lat:47.6163, lng:-122.0356},
    {name:'kirkland', lat: 47.6769,  lng:-122.2060},
    {name:'mercer island', lat: 7.5707, lng:-122.2221},
    {name: 'bothel', lat: 7.7610, lng:-122.2056},
    {name: 'new castle', lat: 47.5390, lng:-122.1557},
    {name:'renton', lat: 47.4829, lng:-122.2171},
    {name: 'issaquah', lat: 47.5301, lng: -122.0326}
  ];
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat:47.6062, lng:-122.3321}
  });
  for (i=0; i<citiesCoordinates.length;i++){
    var marker = new google.maps.Marker({
      position: {lat: citiesCoordinates[i].lat, lng: citiesCoordinates[i].lng},
      map: map
    });
  }
}
<|endoftext|>


<commit_before>L.Path.SVG_NS = 'http://www.w3.org/2000/svg';

L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);

L.Path = L.Path.extend({
	statics: {
		SVG: L.Browser.svg
	},

	getPathString: function () {
		// form path string here
	},

	_createElement: function (name) {
		return document.createElementNS(L.Path.SVG_NS, name);
	},

	_initElements: function () {
		this._map._initPathRoot();
		this._initPath();
		this._initStyle();
	},

	_initPath: function () {
		this._container = this._createElement('g');

		this._path = this._createElement('path');
		this._container.appendChild(this._path);

		this._map._pathRoot.appendChild(this._container);
	},

	_initStyle: function () {
		if (this.options.stroke) {
			this._path.setAttribute('stroke-linejoin', 'round');
			this._path.setAttribute('stroke-linecap', 'round');
		}
		if (this.options.fill) {
			this._path.setAttribute('fill-rule', 'evenodd');
		}
		this._updateStyle();
	},

	_updateStyle: function () {
		if (this.options.stroke) {
			this._path.setAttribute('stroke', this.options.color);
			this._path.setAttribute('stroke-opacity', this.options.opacity);
			this._path.setAttribute('stroke-width', this.options.weight);
		} else {
			this._path.setAttribute('stroke', 'none');
		}
		if (this.options.fill) {
			this._path.setAttribute('fill', this.options.fillColor || this.options.color);
			this._path.setAttribute('fill-opacity', this.options.fillOpacity);
		} else {
			this._path.setAttribute('fill', 'none');
		}
	},

	_updatePath: function () {
		var str = this.getPathString();
		if (!str) {
			// fix webkit empty string parsing bug
			str = 'M0 0';
		}
		this._path.setAttribute('d', str);
	},

	// TODO remove duplication with L.Map
	_initEvents: function () {
		if (this.options.clickable) {
			if (L.Browser.svg || !L.Browser.vml) {
				this._path.setAttribute('class', 'leaflet-clickable');
			}

			L.DomEvent.addListener(this._container, 'click', this._onMouseClick, this);

			var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu'];
			for (var i = 0; i < events.length; i++) {
				L.DomEvent.addListener(this._container, events[i], this._fireMouseEvent, this);
			}
		}
	},

	_onMouseClick: function (e) {
		if (this._map.dragging && this._map.dragging.moved()) {
			return;
		}

		if (e.type === 'contextmenu') {
			L.DomEvent.preventDefault(e);
		}

		this._fireMouseEvent(e);
	},

	_fireMouseEvent: function (e) {
		if (!this.hasEventListeners(e.type)) {
			return;
		}
		var map = this._map,
			containerPoint = map.mouseEventToContainerPoint(e),
			layerPoint = map.containerPointToLayerPoint(containerPoint),
			latlng = map.layerPointToLatLng(layerPoint);

		this.fire(e.type, {
			latlng: latlng,
			layerPoint: layerPoint,
			containerPoint: containerPoint,
			originalEvent: e
		});

		L.DomEvent.stopPropagation(e);
	}
});

L.Map.include({
	_initPathRoot: function () {
		if (!this._pathRoot) {
			this._pathRoot = L.Path.prototype._createElement('svg');
			this._panes.overlayPane.appendChild(this._pathRoot);

			this.on('moveend', this._updateSvgViewport);
			this._updateSvgViewport();
		}
	},

	_updateSvgViewport: function () {
		this._updatePathViewport();

		var vp = this._pathViewport,
			min = vp.min,
			max = vp.max,
			width = max.x - min.x,
			height = max.y - min.y,
			root = this._pathRoot,
			pane = this._panes.overlayPane;

		// Hack to make flicker on drag end on mobile webkit less irritating
		// Unfortunately I haven't found a good workaround for this yet
		if (L.Browser.webkit) {
			pane.removeChild(root);
		}

		L.DomUtil.setPosition(root, min);
		root.setAttribute('width', width);
		root.setAttribute('height', height);
		root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));

		if (L.Browser.webkit) {
			pane.appendChild(root);
		}
	}
});
<commit_msg>Only apply Path.SVG mobile Webkit hack for mobileWebkit<commit_after>L.Path.SVG_NS = 'http://www.w3.org/2000/svg';

L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);

L.Path = L.Path.extend({
	statics: {
		SVG: L.Browser.svg
	},

	getPathString: function () {
		// form path string here
	},

	_createElement: function (name) {
		return document.createElementNS(L.Path.SVG_NS, name);
	},

	_initElements: function () {
		this._map._initPathRoot();
		this._initPath();
		this._initStyle();
	},

	_initPath: function () {
		this._container = this._createElement('g');

		this._path = this._createElement('path');
		this._container.appendChild(this._path);

		this._map._pathRoot.appendChild(this._container);
	},

	_initStyle: function () {
		if (this.options.stroke) {
			this._path.setAttribute('stroke-linejoin', 'round');
			this._path.setAttribute('stroke-linecap', 'round');
		}
		if (this.options.fill) {
			this._path.setAttribute('fill-rule', 'evenodd');
		}
		this._updateStyle();
	},

	_updateStyle: function () {
		if (this.options.stroke) {
			this._path.setAttribute('stroke', this.options.color);
			this._path.setAttribute('stroke-opacity', this.options.opacity);
			this._path.setAttribute('stroke-width', this.options.weight);
		} else {
			this._path.setAttribute('stroke', 'none');
		}
		if (this.options.fill) {
			this._path.setAttribute('fill', this.options.fillColor || this.options.color);
			this._path.setAttribute('fill-opacity', this.options.fillOpacity);
		} else {
			this._path.setAttribute('fill', 'none');
		}
	},

	_updatePath: function () {
		var str = this.getPathString();
		if (!str) {
			// fix webkit empty string parsing bug
			str = 'M0 0';
		}
		this._path.setAttribute('d', str);
	},

	// TODO remove duplication with L.Map
	_initEvents: function () {
		if (this.options.clickable) {
			if (L.Browser.svg || !L.Browser.vml) {
				this._path.setAttribute('class', 'leaflet-clickable');
			}

			L.DomEvent.addListener(this._container, 'click', this._onMouseClick, this);

			var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu'];
			for (var i = 0; i < events.length; i++) {
				L.DomEvent.addListener(this._container, events[i], this._fireMouseEvent, this);
			}
		}
	},

	_onMouseClick: function (e) {
		if (this._map.dragging && this._map.dragging.moved()) {
			return;
		}

		if (e.type === 'contextmenu') {
			L.DomEvent.preventDefault(e);
		}

		this._fireMouseEvent(e);
	},

	_fireMouseEvent: function (e) {
		if (!this.hasEventListeners(e.type)) {
			return;
		}
		var map = this._map,
			containerPoint = map.mouseEventToContainerPoint(e),
			layerPoint = map.containerPointToLayerPoint(containerPoint),
			latlng = map.layerPointToLatLng(layerPoint);

		this.fire(e.type, {
			latlng: latlng,
			layerPoint: layerPoint,
			containerPoint: containerPoint,
			originalEvent: e
		});

		L.DomEvent.stopPropagation(e);
	}
});

L.Map.include({
	_initPathRoot: function () {
		if (!this._pathRoot) {
			this._pathRoot = L.Path.prototype._createElement('svg');
			this._panes.overlayPane.appendChild(this._pathRoot);

			this.on('moveend', this._updateSvgViewport);
			this._updateSvgViewport();
		}
	},

	_updateSvgViewport: function () {
		this._updatePathViewport();

		var vp = this._pathViewport,
			min = vp.min,
			max = vp.max,
			width = max.x - min.x,
			height = max.y - min.y,
			root = this._pathRoot,
			pane = this._panes.overlayPane;

		// Hack to make flicker on drag end on mobile webkit less irritating
		// Unfortunately I haven't found a good workaround for this yet
		if (L.Browser.mobileWebkit) {
			pane.removeChild(root);
		}

		L.DomUtil.setPosition(root, min);
		root.setAttribute('width', width);
		root.setAttribute('height', height);
		root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));

		if (L.Browser.mobileWebkit) {
			pane.appendChild(root);
		}
	}
});
<|endoftext|>


<commit_before>import bAlert from './alert'
import bBreadcrumb from './breadcrumb'
import bButtonCheckbox from './button-checkbox'
import bButtonGroup from './button-group'
import bButtonRadio from './button-radio'
import bButton from './button'
import bCard from './card'
import bCarousel from './carousel'
import bCarouselSlide from './carousel-slide'
import bCollapse from './collapse'
import bCollapseToggle from './collapse-toggle'
import bDropdown from './dropdown'
import bDropdownSelect from './dropdown-select'
import bFormCheckbox from './form-checkbox'
import bFormRadio from './form-radio'
import bFormInput from './form-input'
import bFormSelect from './form-select'
import bFormTextarea from './form-textarea'
import bJumbotron from './jumbotron'
import bTags from './tags'
import bListGroup from './list-group'
import bListGroupItem from './list-group-item'
import bMedia from './media'
import bModal from './modal'
import bNav from './nav'
import bNavItem from './nav-item'
import bNavItemDropdown from './nav-item-dropdown'
import bNavbar from './navbar'
import bPagination from './pagination'
import bPopover from './popover'
import bProgress from './progress'
import bTables from './tables'
import bTabs from './tabs'
import bTab from './tab'
import bTooltip from './tooltip'

export {
  bAlert,
  bBreadcrumb,
  bButtonCheckbox,
  bButtonGroup,
  bButtonRadio,
  bButton as bButton,
  bButton as bBtn,
  bCard,
  bDropdown,
  bDropdownSelect,
  bFormCheckbox,
  bFormRadio,
  bFormInput,
  bFormSelect,
  bFormTextarea,
  bJumbotron,
  bTags,
  bMedia,
  bModal,
  bNavbar,
  bPagination,
  bPopover,
  bProgress,
  bTables,
  bTooltip,
  bTab,
  bTabs,
  bNav,
  bNavItem,
  bNavItemDropdown,
  bListGroupItem,
  bListGroup,
  bCarouselSlide as bSlide,
  bCarousel,
  bCollapse,
  bCollapseToggle
}
<commit_msg>add .vue prefix to all imports<commit_after>import bAlert from './alert.vue'
import bBreadcrumb from './breadcrumb.vue'
import bButtonCheckbox from './button-checkbox.vue'
import bButtonGroup from './button-group.vue'
import bButtonRadio from './button-radio.vue'
import bButton from './button.vue'
import bCard from './card.vue'
import bCarousel from './carousel.vue'
import bCarouselSlide from './carousel-slide.vue'
import bCollapse from './collapse.vue'
import bCollapseToggle from './collapse-toggle.vue'
import bDropdown from './dropdown.vue'
import bDropdownSelect from './dropdown-select.vue'
import bFormCheckbox from './form-checkbox.vue'
import bFormRadio from './form-radio.vue'
import bFormInput from './form-input.vue'
import bFormSelect from './form-select.vue'
import bFormTextarea from './form-textarea.vue'
import bJumbotron from './jumbotron.vue'
import bTags from './tags.vue'
import bListGroup from './list-group.vue'
import bListGroupItem from './list-group-item.vue'
import bMedia from './media.vue'
import bModal from './modal.vue'
import bNav from './nav.vue'
import bNavItem from './nav-item.vue'
import bNavItemDropdown from './nav-item-dropdown.vue'
import bNavbar from './navbar.vue'
import bPagination from './pagination.vue'
import bPopover from './popover.vue'
import bProgress from './progress.vue'
import bTables from './tables.vue'
import bTabs from './tabs.vue'
import bTab from './tab.vue'
import bTooltip from './tooltip.vue'

export {
  bAlert,
  bBreadcrumb,
  bButtonCheckbox,
  bButtonGroup,
  bButtonRadio,
  bButton as bButton,
  bButton as bBtn,
  bCard,
  bDropdown,
  bDropdownSelect,
  bFormCheckbox,
  bFormRadio,
  bFormInput,
  bFormSelect,
  bFormTextarea,
  bJumbotron,
  bTags,
  bMedia,
  bModal,
  bNavbar,
  bPagination,
  bPopover,
  bProgress,
  bTables,
  bTooltip,
  bTab,
  bTabs,
  bNav,
  bNavItem,
  bNavItemDropdown,
  bListGroupItem,
  bListGroup,
  bCarouselSlide as bSlide,
  bCarousel,
  bCollapse,
  bCollapseToggle
}
<|endoftext|>


<commit_before>'use strict';
require('dotenv').config();
var Slack = require('slack-node');
var mongoose = require('mongoose');
var async = require("async");
var appleLohData = require('./appleLohFetch').appleLohData;
var appleLohDetailedInfo = require('./appleLohFetch').appleLohDetailedInfo;
var async = require("async");
var eachLimit = async.eachLimit;

var findArticleAppleLohTask = require('./AppleLohTasks').findArticleAppleLohTask;
var notifySlackAppleLohTask = require('./AppleLohTasks').notifySlackAppleLohTask;
var saveArticleAppleLohTask = require('./AppleLohTasks').saveArticleAppleLohTask;

const CONCURRENCY = 4;

function getArticleHits(slack) {
  appleLohData().then(function(data) {
    // connect to smg mongodb
    mongoose.connect(process.env.MONGODB_URI);

    eachLimit(data, CONCURRENCY, processArticle,function(error){
      if (error) {
        console.log("error: ", error);
      } else {
        console.log("Article run success!");
      }
    });

  }).catch(function(err){
    console.log("error from appleLohData: ", err);
  });

  function processArticle(data, done) {
    appleLohDetailedInfo(data.url).then(function(data){
      var tasks = [];
      var context = {
        link: data[0].link,
        title: data[0].title,
        hits: data[0]._hits,
        thumb_url_medium: data[0].thumb_url_medium,
        author: data[0].author,
        slack: slack
      };

      tasks.push(function(done) {
        findArticleAppleLohTask(context, done);
      });

      tasks.push(function(done) {
        notifySlackAppleLohTask(context, done);
      });

      tasks.push(function(done) {
        saveArticleAppleLohTask(context, done);
      });

      async.series(tasks, done);
    });
  }
}

function postData() {
  // set up slack incoming webhook
  let webhookUri = process.env.WEBHOOK_URI;
  let slack = new Slack();
  slack.setWebhook(webhookUri);
  getArticleHits(slack);
}

module.exports = postData;
<commit_msg>trying to fix bug<commit_after>require('dotenv').config();
var Slack = require('slack-node');
var mongoose = require('mongoose');
var async = require("async");
var appleLohData = require('./appleLohFetch').appleLohData;
var appleLohDetailedInfo = require('./appleLohFetch').appleLohDetailedInfo;
var async = require("async");
var eachLimit = async.eachLimit;

var findArticleAppleLohTask = require('./AppleLohTasks').findArticleAppleLohTask;
var notifySlackAppleLohTask = require('./AppleLohTasks').notifySlackAppleLohTask;
var saveArticleAppleLohTask = require('./AppleLohTasks').saveArticleAppleLohTask;

const CONCURRENCY = 4;

function getArticleHits(slack) {
  appleLohData().then(function(data) {
    // connect to smg mongodb
    mongoose.connect(process.env.MONGODB_URI);

    eachLimit(data, CONCURRENCY, processArticle,function(error){
      if (error) {
        console.log("error: ", error);
      } else {
        console.log("Article run success!");
      }
    });

  }).catch(function(err){
    console.log("error from appleLohData: ", err);
  });

  function processArticle(data, done) {
    appleLohDetailedInfo(data.url).then(function(data){
      var tasks = [];
      var context = {
        link: data[0].link,
        title: data[0].title,
        hits: data[0]._hits,
        thumb_url_medium: data[0].thumb_url_medium,
        author: data[0].author,
        slack: slack
      };

      tasks.push(function(done) {
        findArticleAppleLohTask(context, done);
      });

      tasks.push(function(done) {
        notifySlackAppleLohTask(context, done);
      });

      tasks.push(function(done) {
        saveArticleAppleLohTask(context, done);
      });

      async.series(tasks, done);
    });
  }
}

function postData() {
  // set up slack incoming webhook
  let webhookUri = process.env.WEBHOOK_URI;
  let slack = new Slack();
  slack.setWebhook(webhookUri);
  getArticleHits(slack);
}

module.exports = postData;
<|endoftext|>


<commit_before>var old_session = -1;
var old_layout = -1;

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

function check_warning(w, sessions) {
    if (w.type == 'req') {
        var firstFound = true;
        var secondFound = true;
        var ss = [];
        w.sessions1.forEach(function(s1) { ss.push(s1); });
        w.sessions2.forEach(function(s2) { ss.push(s2); });

        for (var i=0; i<w.sessions1.length; i++) {
            if (sessions.indexOf(w.sessions1[i]) < 0) {
                firstFound = false;
            }
        }
        for (var i=0; i<w.sessions2.length; i++) {
            if (sessions.indexOf(w.sessions2[i]) < 0) {
                secondFound = false;
            }
        }

        if (firstFound && !secondFound) {
            return true;
        }

        return false;
    }
}

function seat_droped(session, layout, seat) {
    var selector = '#' + session + '_' + layout + '_' + seat;
    $(selector).addClass("seat-L");
    $(selector).removeClass("seat-H");
    $(selector).unbind("click").click(function() {
        SeatMap.clickSeat($(this));
    });
}

function seat_holded(session, layout, seat) {
    var selector = '#' + session + '_' + layout + '_' + seat;

    if ($(selector).hasClass("seat-selected")) {
        return;
    }

    $(selector).addClass("seat-H");
    $(selector).removeClass("seat-L");
    $(selector).unbind("click");
}

function seat_reserved(session, layout, seat) {
    var selector = '#' + session + '_' + layout + '_' + seat;
    $(selector).addClass("seat-R");
    $(selector).removeClass("seat-L");
    $(selector).removeClass("seat-H");
    $(selector).unbind("click");
}

function websocketCB(ev, data) {
    if (ev == 'hold') {
        var seat = data.row + '_' + data.col;
        seat_holded(data.session, data.layout, seat);
    } else if (ev == 'drop') {
        var seat = data.row + '_' + data.col;
        seat_droped(data.session, data.layout, seat);
    } else if (ev == 'confirm') {
        var seat = data.row + '_' + data.col;
        seat_reserved(data.session, data.layout, seat);
    }
}

function seatCB(ev, seat) {
    var row = seat.data("row");
    var col = seat.data("col");
    var session = seat.data("session");
    var layout = seat.data("layout");

    var current = [];
    var currentval = $("#seats-"+session).val();
    if (currentval) {
        current = currentval.split(",");
    }

    var str = layout + '_' + row + '_' + col;

    args = session;
    args += ' ' + layout;
    args += ' ' + row;
    args += ' ' + col;
    args += ' ' + client;

    if (ev == 'select') {
        current.push(str);
        ws.send('hold_seat ' + args);
    } else if (ev == 'unselect') {
        var idx = current.indexOf(str);
        if (idx >= 0) {
            current.splice(idx, 1);
        }
        ws.send('drop_seat ' + args);
    }

    $("#seats-"+session).val(current.join(","));
    $("#"+session).val(current.length);

    updateBadges(session, layout);

    $("#"+session).keyup();
}

function updateBadges(session, layout) {
    //updating the label with the number of selected seats
    var currentval = $("#seats-"+session).val();
    var current = currentval.split(",");
    var n = 0;
    current.forEach(function(element) {
        if (element.startsWith(layout + '_')) {
            n++;
        }
    });
    badge = $("#badge-"+session+"-"+layout);
    badge.text(n);
    if (n) {
        badge.addClass("label-success");
        badge.removeClass("label-default");
    } else {
        badge.removeClass("label-success");
        badge.addClass("label-default");
    }
    // Remove old badges. recursive function
    if (old_session != -1 && (old_session != session || old_layout != layout)) {
        updateBadges(old_session, old_layout);
    }
    old_session = session;
    old_layout = layout;
}

function recalcSums(obj) {
    var session = obj.attr("id");
    var val = parseInt(obj.val(), 10);

    var max = parseInt(obj.attr('max') || 500, 10);
    if (val > max) {
        val = max;
        obj.val(max);
    }

    var price = parseFloat(obj.data("price"));
    $("#"+session+"-subtotal-price").html(val * price);
}

function recalcTotal() {
    var sum = 0;
    $(".sessioninput").each(function() {
        var n = parseInt($(this).val(), 10);
        var price = parseFloat($(this).data("price"));
        sum += price * n;
    });
    $("#total").html(sum);
}

function fillSelectedSeats(obj) {
    // obj should be a .seats-input
    var session = obj.data('session');
    var v = obj.val();
    if (v) {
        var current = [];
        current = v.split(",");
        $("#"+session).val(current.length);
        $("#"+session).keyup();

        function recursiveSelection(arr, finish) {
            var c = arr.pop();
            var selector = '#' + session + '_' + c;
            var layout = c.split('_')[0];
            var l = $('.layout-'+session+'-'+layout);
            var obj = $('.display-'+session+'-'+layout);

            SeatMap.preloadLayout(l, obj, function() {
                $(selector).addClass("seat-selected");
                if (arr.length) {
                    recursiveSelection(arr, finish);
                } else {
                    finish();
                }
            });
        }

        recursiveSelection(current.slice(0), function() {
            current.forEach(function(c) {
                var layout = c.split('_')[0];
                updateBadges(session, layout);
            });
        });
    }
}

function autoSelectSeat(s, n) {
    autoSeats(s, n).then(function(autoseats) {
        var value = [];
        autoseats.forEach(function(obj) {
            value.push(obj.layout+"_"+obj.row+"_"+obj.col);

            args = s;
            args += ' ' + obj.layout;
            args += ' ' + obj.row;
            args += ' ' + obj.col;
            args += ' ' + client;
            ws.send('hold_seat ' + args);
        });
        $("#seats-"+s).val(value.join(","));
        fillSelectedSeats($("#seats-"+s));
    }).fail(function(error) {
        $("#"+s).val(0);
        alert(error);
    });
}

function seatsChange(obj) {
    // obj should be a .sessioninput
    if (!obj) {
        obj = $(this);
    }
    recalcSums(obj);
    recalcTotal();

    // if no name in the input, it's a numbered session
    // we do here the seat auto selection
    if (!obj.attr("name")) {
        var val = obj.val();
        var s = obj.data('session');
        var v = $("#seats-"+s).val();
        if (!v) {
            autoSelectSeat(s, val);
        } else {
            var current = [];
            current = v.split(",");
            if (current.length != val) {
                // unselecting all selected
                current.forEach(function(c) {
                    selector = '#' + s + '_' + c;
                    $(selector).removeClass('seat-selected');

                    a = c.split('_');
                    args = s;
                    args += ' ' + a[0];
                    args += ' ' + a[1];
                    args += ' ' + a[2];
                    args += ' ' + client;
                    ws.send('drop_seat ' + args);
                });
                $("#seats-"+s).val("");

                autoSelectSeat(s, val);
            }
        }
    }
}

$(document).ready(function() {
    $("form").submit(function() {
        var warnings = [];
        var sessions = [];

        $('.sessioninput').each(function() {
            val = parseInt($(this).val(), 10);
            id = $(this).attr("id");
            if (val) {
                sessions.push(id);
            }
        });

        $('.warning').each(function() {
            var warning = {};
            warning.name = $(this).data('name');
            warning.sessions1 = String($(this).data('sessions1')).split(',');
            warning.sessions2 = String($(this).data('sessions2')).split(',');
            warning.type = $(this).data('type');
            warning.message = $(this).data('message');
            warnings.push(warning);
        });

        for(var i=0; i<warnings.length; i++) {
            var w = warnings[i];
            if (check_warning(w, sessions)) {
                return confirm(w.message);
            }
        }

        return true;
    });

    $('.withtooltip').tooltip();

    $(".seatmap").each(function() {
        var session = $(this).data('session');
        var obj = $("#modal-" + session);
        SeatMap.bindLayout(obj);
    });

    SeatMap.cbs.add(seatCB);
    ws.cbs.add(websocketCB);

    if (session_expired) {
        $(".sessioninput").val("0");
        $(".seats-input").val("");
    }

    $(".seats-input").each(function() {
        fillSelectedSeats($(this));
    });

    // calculating sums
    $('.sessioninput').keyup(function() {
        var obj = $(this);
        delay(function() { seatsChange(obj) }, 500);
    });
    recalcTotal();

    $('.sessioninput').each(function() {
        recalcSums($(this));
        $(this).click(function() { $(this).select(); });
    });

    $(".plus").click(function() {
        btn = $(this);
        btn.prop("disabled", true); // Disable button
        var id = '#' + $(this).data("id");
        var max = parseInt($(id).attr('max') || 500, 10);
        var current = parseInt($(id).val(), 10);

        var next = current + 1;
        if (next > max) {
            next = max;
        }
        $(id).val(next);
        $(id).keyup();

        setTimeout(function() {
            btn.prop("disabled", false); // Enable button
        }, 600);
    });
    $(".minus").click(function() {
        var id = '#' + $(this).data("id");
        var min = parseInt($(id).attr('min') || 0, 10);
        var current = parseInt($(id).val(), 10);

        var next = current - 1;
        if (next < min) {
            next = min;
        }
        $(id).val(next);
        $(id).keyup();
    });
});
<commit_msg>Updating badges when autoselect fails<commit_after>var old_session = -1;
var old_layout = -1;

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

function check_warning(w, sessions) {
    if (w.type == 'req') {
        var firstFound = true;
        var secondFound = true;
        var ss = [];
        w.sessions1.forEach(function(s1) { ss.push(s1); });
        w.sessions2.forEach(function(s2) { ss.push(s2); });

        for (var i=0; i<w.sessions1.length; i++) {
            if (sessions.indexOf(w.sessions1[i]) < 0) {
                firstFound = false;
            }
        }
        for (var i=0; i<w.sessions2.length; i++) {
            if (sessions.indexOf(w.sessions2[i]) < 0) {
                secondFound = false;
            }
        }

        if (firstFound && !secondFound) {
            return true;
        }

        return false;
    }
}

function seat_droped(session, layout, seat) {
    var selector = '#' + session + '_' + layout + '_' + seat;
    $(selector).addClass("seat-L");
    $(selector).removeClass("seat-H");
    $(selector).unbind("click").click(function() {
        SeatMap.clickSeat($(this));
    });
}

function seat_holded(session, layout, seat) {
    var selector = '#' + session + '_' + layout + '_' + seat;

    if ($(selector).hasClass("seat-selected")) {
        return;
    }

    $(selector).addClass("seat-H");
    $(selector).removeClass("seat-L");
    $(selector).unbind("click");
}

function seat_reserved(session, layout, seat) {
    var selector = '#' + session + '_' + layout + '_' + seat;
    $(selector).addClass("seat-R");
    $(selector).removeClass("seat-L");
    $(selector).removeClass("seat-H");
    $(selector).unbind("click");
}

function websocketCB(ev, data) {
    if (ev == 'hold') {
        var seat = data.row + '_' + data.col;
        seat_holded(data.session, data.layout, seat);
    } else if (ev == 'drop') {
        var seat = data.row + '_' + data.col;
        seat_droped(data.session, data.layout, seat);
    } else if (ev == 'confirm') {
        var seat = data.row + '_' + data.col;
        seat_reserved(data.session, data.layout, seat);
    }
}

function seatCB(ev, seat) {
    var row = seat.data("row");
    var col = seat.data("col");
    var session = seat.data("session");
    var layout = seat.data("layout");

    var current = [];
    var currentval = $("#seats-"+session).val();
    if (currentval) {
        current = currentval.split(",");
    }

    var str = layout + '_' + row + '_' + col;

    args = session;
    args += ' ' + layout;
    args += ' ' + row;
    args += ' ' + col;
    args += ' ' + client;

    if (ev == 'select') {
        current.push(str);
        ws.send('hold_seat ' + args);
    } else if (ev == 'unselect') {
        var idx = current.indexOf(str);
        if (idx >= 0) {
            current.splice(idx, 1);
        }
        ws.send('drop_seat ' + args);
    }

    $("#seats-"+session).val(current.join(","));
    $("#"+session).val(current.length);

    updateBadges(session, layout);

    $("#"+session).keyup();
}

function updateBadges(session, layout) {
    //updating the label with the number of selected seats
    var currentval = $("#seats-"+session).val();
    var current = currentval.split(",");
    var n = 0;
    current.forEach(function(element) {
        if (element.startsWith(layout + '_')) {
            n++;
        }
    });
    badge = $("#badge-"+session+"-"+layout);
    badge.text(n);
    if (n) {
        badge.addClass("label-success");
        badge.removeClass("label-default");
    } else {
        badge.removeClass("label-success");
        badge.addClass("label-default");
    }
    // Remove old badges. recursive function
    if (old_session != -1 && (old_session != session || old_layout != layout)) {
        updateBadges(old_session, old_layout);
    }
    old_session = session;
    old_layout = layout;
}

function recalcSums(obj) {
    var session = obj.attr("id");
    var val = parseInt(obj.val(), 10);

    var max = parseInt(obj.attr('max') || 500, 10);
    if (val > max) {
        val = max;
        obj.val(max);
    }

    var price = parseFloat(obj.data("price"));
    $("#"+session+"-subtotal-price").html(val * price);
}

function recalcTotal() {
    var sum = 0;
    $(".sessioninput").each(function() {
        var n = parseInt($(this).val(), 10);
        var price = parseFloat($(this).data("price"));
        sum += price * n;
    });
    $("#total").html(sum);
}

function fillSelectedSeats(obj) {
    // obj should be a .seats-input
    var session = obj.data('session');
    var v = obj.val();
    if (v) {
        var current = [];
        current = v.split(",");
        $("#"+session).val(current.length);
        $("#"+session).keyup();

        function recursiveSelection(arr, finish) {
            var c = arr.pop();
            var selector = '#' + session + '_' + c;
            var layout = c.split('_')[0];
            var l = $('.layout-'+session+'-'+layout);
            var obj = $('.display-'+session+'-'+layout);

            SeatMap.preloadLayout(l, obj, function() {
                $(selector).addClass("seat-selected");
                if (arr.length) {
                    recursiveSelection(arr, finish);
                } else {
                    finish();
                }
            });
        }

        recursiveSelection(current.slice(0), function() {
            current.forEach(function(c) {
                var layout = c.split('_')[0];
                updateBadges(session, layout);
            });
        });
    }
}

function autoSelectSeat(s, n) {
    autoSeats(s, n).then(function(autoseats) {
        var value = [];
        autoseats.forEach(function(obj) {
            value.push(obj.layout+"_"+obj.row+"_"+obj.col);

            args = s;
            args += ' ' + obj.layout;
            args += ' ' + obj.row;
            args += ' ' + obj.col;
            args += ' ' + client;
            ws.send('hold_seat ' + args);
        });
        $("#seats-"+s).val(value.join(","));
        fillSelectedSeats($("#seats-"+s));
    }).fail(function(error) {
        $("#"+s).val(0);
        var layouts = $('#modal-'+s+' .layout');
        layouts.each(function() {
            var id = $(this).data('id');
            updateBadges(s, id);
        });
        alert(error);
    });
}

function seatsChange(obj) {
    // obj should be a .sessioninput
    if (!obj) {
        obj = $(this);
    }
    recalcSums(obj);
    recalcTotal();

    // if no name in the input, it's a numbered session
    // we do here the seat auto selection
    if (!obj.attr("name")) {
        var val = obj.val();
        var s = obj.data('session');
        var v = $("#seats-"+s).val();
        if (!v) {
            autoSelectSeat(s, val);
        } else {
            var current = [];
            current = v.split(",");
            if (current.length != val) {
                // unselecting all selected
                current.forEach(function(c) {
                    selector = '#' + s + '_' + c;
                    $(selector).removeClass('seat-selected');

                    a = c.split('_');
                    args = s;
                    args += ' ' + a[0];
                    args += ' ' + a[1];
                    args += ' ' + a[2];
                    args += ' ' + client;
                    ws.send('drop_seat ' + args);
                });
                $("#seats-"+s).val("");

                autoSelectSeat(s, val);
            }
        }
    }
}

$(document).ready(function() {
    $("form").submit(function() {
        var warnings = [];
        var sessions = [];

        $('.sessioninput').each(function() {
            val = parseInt($(this).val(), 10);
            id = $(this).attr("id");
            if (val) {
                sessions.push(id);
            }
        });

        $('.warning').each(function() {
            var warning = {};
            warning.name = $(this).data('name');
            warning.sessions1 = String($(this).data('sessions1')).split(',');
            warning.sessions2 = String($(this).data('sessions2')).split(',');
            warning.type = $(this).data('type');
            warning.message = $(this).data('message');
            warnings.push(warning);
        });

        for(var i=0; i<warnings.length; i++) {
            var w = warnings[i];
            if (check_warning(w, sessions)) {
                return confirm(w.message);
            }
        }

        return true;
    });

    $('.withtooltip').tooltip();

    $(".seatmap").each(function() {
        var session = $(this).data('session');
        var obj = $("#modal-" + session);
        SeatMap.bindLayout(obj);
    });

    SeatMap.cbs.add(seatCB);
    ws.cbs.add(websocketCB);

    if (session_expired) {
        $(".sessioninput").val("0");
        $(".seats-input").val("");
    }

    $(".seats-input").each(function() {
        fillSelectedSeats($(this));
    });

    // calculating sums
    $('.sessioninput').keyup(function() {
        var obj = $(this);
        delay(function() { seatsChange(obj) }, 500);
    });
    recalcTotal();

    $('.sessioninput').each(function() {
        recalcSums($(this));
        $(this).click(function() { $(this).select(); });
    });

    $(".plus").click(function() {
        btn = $(this);
        btn.prop("disabled", true); // Disable button
        var id = '#' + $(this).data("id");
        var max = parseInt($(id).attr('max') || 500, 10);
        var current = parseInt($(id).val(), 10);

        var next = current + 1;
        if (next > max) {
            next = max;
        }
        $(id).val(next);
        $(id).keyup();

        setTimeout(function() {
            btn.prop("disabled", false); // Enable button
        }, 600);
    });
    $(".minus").click(function() {
        var id = '#' + $(this).data("id");
        var min = parseInt($(id).attr('min') || 0, 10);
        var current = parseInt($(id).val(), 10);

        var next = current - 1;
        if (next < min) {
            next = min;
        }
        $(id).val(next);
        $(id).keyup();
    });
});
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';

var getMediaButton = document.querySelector('button#getMedia');
var createPeerConnectionButton =
    document.querySelector('button#createPeerConnection');
var createOfferButton = document.querySelector('button#createOffer');
var setOfferButton = document.querySelector('button#setOffer');
var createAnswerButton = document.querySelector('button#createAnswer');
var setAnswerButton = document.querySelector('button#setAnswer');
var hangupButton = document.querySelector('button#hangup');
var dataChannelDataReceived;

getMediaButton.onclick = getMedia;
createPeerConnectionButton.onclick = createPeerConnection;
createOfferButton.onclick = createOffer;
setOfferButton.onclick = setOffer;
createAnswerButton.onclick = createAnswer;
setAnswerButton.onclick = setAnswer;
hangupButton.onclick = hangup;

var offer;
var offerSdpTextarea = document.querySelector('div#local textarea');
var answer;
var answerSdpTextarea = document.querySelector('div#remote textarea');

var audioSelect = document.querySelector('select#audioSrc');
var videoSelect = document.querySelector('select#videoSrc');

audioSelect.onchange = videoSelect.onchange = getMedia;

var localVideo = document.querySelector('div#local video');
var remoteVideo = document.querySelector('div#remote video');

var selectSourceDiv = document.querySelector('div#selectSource');

var localPeerConnection;
var remotePeerConnection;
var localStream;
var sendChannel;
var receiveChannel;
var dataChannelOptions = {
  ordered: true
};
var dataChannelCounter = 0;
var sendDataLoop;
var offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 1
};

getSources();

function getSources() {
  if (typeof MediaStreamTrack === 'undefined') {
    alert(
      'This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
  } else {
    navigator.mediaDevices.enumerateDevices().then(gotSources);
  }
}

function gotSources(sourceInfos) {
  selectSourceDiv.classList.remove('hidden');
  var audioCount = 0;
  var videoCount = 0;
  for (var i = 0; i < sourceInfos.length; i++) {
    var option = document.createElement('option');
    option.value = sourceInfos[i].deviceId;
    option.text = sourceInfos[i].label;
    if (sourceInfos[i].kind === 'audioinput') {
      audioCount++;
      if (option.text === '') {
        option.text = 'Audio ' + audioCount;
      }
      audioSelect.appendChild(option);
    } else if (sourceInfos[i].kind === 'videoinput') {
      videoCount++;
      if (option.text === '') {
        option.text = 'Video ' + videoCount;
      }
      videoSelect.appendChild(option);
    } else {
      console.log('unknown', JSON.stringify(sourceInfos[i]));
    }
  }
}

function getMedia() {
  getMediaButton.disabled = true;
  createPeerConnectionButton.disabled = false;

  if (localStream) {
    localVideo.src = null;
    localStream.getTracks().forEach(function(track) {
      track.stop();
    });
  }
  var audioSource = audioSelect.value;
  trace('Selected audio source: ' + audioSource);
  var videoSource = videoSelect.value;
  trace('Selected video source: ' + videoSource);

  var constraints = {
    audio: {
      optional: [{
        sourceId: audioSource
      }]
    },
    video: {
      optional: [{
        sourceId: videoSource
      }]
    }
  };
  trace('Requested local stream');
  navigator.mediaDevices.getUserMedia(constraints)
  .then(gotStream)
  .catch(function(e) {
    console.log('navigator.getUserMedia error: ', e);
  });
}

function gotStream(stream) {
  trace('Received local stream');
  localVideo.srcObject = stream;
  localStream = stream;
}

function createPeerConnection() {
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = false;
  createAnswerButton.disabled = false;
  setOfferButton.disabled = false;
  setAnswerButton.disabled = false;
  hangupButton.disabled = false;
  trace('Starting call');
  var videoTracks = localStream.getVideoTracks();
  var audioTracks = localStream.getAudioTracks();
  if (videoTracks.length > 0) {
    trace('Using video device: ' + videoTracks[0].label);
  }
  if (audioTracks.length > 0) {
    trace('Using audio device: ' + audioTracks[0].label);
  }
  var servers = null;

  localPeerConnection = new RTCPeerConnection(servers);
  trace('Created local peer connection object localPeerConnection');
  if (RTCPeerConnection.prototype.createDataChannel) {
    sendChannel = localPeerConnection.createDataChannel('sendDataChannel',
        dataChannelOptions);
    localPeerConnection.onicecandidate = iceCallback1;
    sendChannel.onopen = onSendChannelStateChange;
    sendChannel.onclose = onSendChannelStateChange;
    sendChannel.onerror = onSendChannelStateChange;
  }

  remotePeerConnection = new RTCPeerConnection(servers);
  trace('Created remote peer connection object remotePeerConnection');
  remotePeerConnection.onicecandidate = iceCallback2;
  remotePeerConnection.onaddstream = gotRemoteStream;
  remotePeerConnection.ondatachannel = receiveChannelCallback;

  localPeerConnection.addStream(localStream);
  trace('Adding Local Stream to peer connection');
}

function onSetSessionDescriptionSuccess() {
  trace('Set session description success.');
}

function onSetSessionDescriptionError(error) {
  trace('Failed to set session description: ' + error.toString());
}

// Workaround for crbug/322756.
function maybeAddLineBreakToEnd(sdp) {
  var endWithLineBreak = new RegExp(/\n$/);
  if (!endWithLineBreak.test(sdp)) {
    return sdp + '\n';
  }
  return sdp;
}

function createOffer() {
  localPeerConnection.createOffer(
    offerOptions
  ).then(
    gotDescription1,
    onCreateSessionDescriptionError
  );
}

function onCreateSessionDescriptionError(error) {
  trace('Failed to create session description: ' + error.toString());
}

function setOffer() {
  var sdp = offerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  offer.sdp = sdp;
  localPeerConnection.setLocalDescription(offer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
  trace('Modified Offer from localPeerConnection \n' + sdp);
  remotePeerConnection.setRemoteDescription(offer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
}

function gotDescription1(description) {
  offer = description;
  offerSdpTextarea.disabled = false;
  offerSdpTextarea.value = description.sdp;
}

function createAnswer() {
  // Since the 'remote' side has no media stream we need
  // to pass in the right constraints in order for it to
  // accept the incoming offer of audio and video.
  remotePeerConnection.createAnswer().then(
    gotDescription2,
    onCreateSessionDescriptionError
  );
}

function setAnswer() {
  var sdp = answerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  answer.sdp = sdp;
  remotePeerConnection.setLocalDescription(answer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
  trace('Modified Answer from remotePeerConnection \n' + sdp);
  localPeerConnection.setRemoteDescription(answer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
}

function gotDescription2(description) {
  answer = description;
  answerSdpTextarea.disabled = false;
  answerSdpTextarea.value = description.sdp;
}

function sendData() {
  sendChannel.send(dataChannelCounter);
  trace('DataChannel send counter: ' + dataChannelCounter);
  dataChannelCounter++;
}

function hangup() {
  remoteVideo.src = '';
  trace('Ending call');
  localStream.getTracks().forEach(function(track) {
    track.stop();
  });
  sendChannel.close();
  if (receiveChannel) {
    receiveChannel.close();
  }
  localPeerConnection.close();
  remotePeerConnection.close();
  localPeerConnection = null;
  remotePeerConnection = null;
  offerSdpTextarea.disabled = true;
  answerSdpTextarea.disabled = true;
  getMediaButton.disabled = false;
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = true;
  setOfferButton.disabled = true;
  createAnswerButton.disabled = true;
  setAnswerButton.disabled = true;
  hangupButton.disabled = true;
}

function gotRemoteStream(e) {
  remoteVideo.srcObject = e.stream;
  trace('Received remote stream');
}

function iceCallback1(event) {
  if (event.candidate) {
    remotePeerConnection.addIceCandidate(
      new RTCIceCandidate(event.candidate)
    ).then(
      onAddIceCandidateSuccess,
      onAddIceCandidateError
    );
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  if (event.candidate) {
    localPeerConnection.addIceCandidate(
      new RTCIceCandidate(event.candidate)
    ).then(
      onAddIceCandidateSuccess,
      onAddIceCandidateError
    );
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function receiveChannelCallback(event) {
  trace('Receive Channel Callback');
  receiveChannel = event.channel;
  receiveChannel.onmessage = onReceiveMessageCallback;
  receiveChannel.onopen = onReceiveChannelStateChange;
  receiveChannel.onclose = onReceiveChannelStateChange;
}

function onReceiveMessageCallback(event) {
  dataChannelDataReceived = event.data;
  trace('DataChannel receive counter: ' + dataChannelDataReceived);
}

function onSendChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Send channel state is: ' + readyState);
  if (readyState === 'open') {
    sendDataLoop = setInterval(sendData, 1000);
  } else {
    clearInterval(sendDataLoop);
  }
}

function onReceiveChannelStateChange() {
  var readyState = receiveChannel.readyState;
  trace('Receive channel state is: ' + readyState);
}
<commit_msg>munge-sdp: fix onicecandidate handler for Edge (#831)<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';

var getMediaButton = document.querySelector('button#getMedia');
var createPeerConnectionButton =
    document.querySelector('button#createPeerConnection');
var createOfferButton = document.querySelector('button#createOffer');
var setOfferButton = document.querySelector('button#setOffer');
var createAnswerButton = document.querySelector('button#createAnswer');
var setAnswerButton = document.querySelector('button#setAnswer');
var hangupButton = document.querySelector('button#hangup');
var dataChannelDataReceived;

getMediaButton.onclick = getMedia;
createPeerConnectionButton.onclick = createPeerConnection;
createOfferButton.onclick = createOffer;
setOfferButton.onclick = setOffer;
createAnswerButton.onclick = createAnswer;
setAnswerButton.onclick = setAnswer;
hangupButton.onclick = hangup;

var offer;
var offerSdpTextarea = document.querySelector('div#local textarea');
var answer;
var answerSdpTextarea = document.querySelector('div#remote textarea');

var audioSelect = document.querySelector('select#audioSrc');
var videoSelect = document.querySelector('select#videoSrc');

audioSelect.onchange = videoSelect.onchange = getMedia;

var localVideo = document.querySelector('div#local video');
var remoteVideo = document.querySelector('div#remote video');

var selectSourceDiv = document.querySelector('div#selectSource');

var localPeerConnection;
var remotePeerConnection;
var localStream;
var sendChannel;
var receiveChannel;
var dataChannelOptions = {
  ordered: true
};
var dataChannelCounter = 0;
var sendDataLoop;
var offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 1
};

getSources();

function getSources() {
  if (typeof MediaStreamTrack === 'undefined') {
    alert(
      'This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
  } else {
    navigator.mediaDevices.enumerateDevices().then(gotSources);
  }
}

function gotSources(sourceInfos) {
  selectSourceDiv.classList.remove('hidden');
  var audioCount = 0;
  var videoCount = 0;
  for (var i = 0; i < sourceInfos.length; i++) {
    var option = document.createElement('option');
    option.value = sourceInfos[i].deviceId;
    option.text = sourceInfos[i].label;
    if (sourceInfos[i].kind === 'audioinput') {
      audioCount++;
      if (option.text === '') {
        option.text = 'Audio ' + audioCount;
      }
      audioSelect.appendChild(option);
    } else if (sourceInfos[i].kind === 'videoinput') {
      videoCount++;
      if (option.text === '') {
        option.text = 'Video ' + videoCount;
      }
      videoSelect.appendChild(option);
    } else {
      console.log('unknown', JSON.stringify(sourceInfos[i]));
    }
  }
}

function getMedia() {
  getMediaButton.disabled = true;
  createPeerConnectionButton.disabled = false;

  if (localStream) {
    localVideo.src = null;
    localStream.getTracks().forEach(function(track) {
      track.stop();
    });
  }
  var audioSource = audioSelect.value;
  trace('Selected audio source: ' + audioSource);
  var videoSource = videoSelect.value;
  trace('Selected video source: ' + videoSource);

  var constraints = {
    audio: {
      optional: [{
        sourceId: audioSource
      }]
    },
    video: {
      optional: [{
        sourceId: videoSource
      }]
    }
  };
  trace('Requested local stream');
  navigator.mediaDevices.getUserMedia(constraints)
  .then(gotStream)
  .catch(function(e) {
    console.log('navigator.getUserMedia error: ', e);
  });
}

function gotStream(stream) {
  trace('Received local stream');
  localVideo.srcObject = stream;
  localStream = stream;
}

function createPeerConnection() {
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = false;
  createAnswerButton.disabled = false;
  setOfferButton.disabled = false;
  setAnswerButton.disabled = false;
  hangupButton.disabled = false;
  trace('Starting call');
  var videoTracks = localStream.getVideoTracks();
  var audioTracks = localStream.getAudioTracks();
  if (videoTracks.length > 0) {
    trace('Using video device: ' + videoTracks[0].label);
  }
  if (audioTracks.length > 0) {
    trace('Using audio device: ' + audioTracks[0].label);
  }
  var servers = null;

  localPeerConnection = new RTCPeerConnection(servers);
  trace('Created local peer connection object localPeerConnection');
  localPeerConnection.onicecandidate = iceCallback1;
  if (RTCPeerConnection.prototype.createDataChannel) {
    sendChannel = localPeerConnection.createDataChannel('sendDataChannel',
        dataChannelOptions);
    sendChannel.onopen = onSendChannelStateChange;
    sendChannel.onclose = onSendChannelStateChange;
    sendChannel.onerror = onSendChannelStateChange;
  }

  remotePeerConnection = new RTCPeerConnection(servers);
  trace('Created remote peer connection object remotePeerConnection');
  remotePeerConnection.onicecandidate = iceCallback2;
  remotePeerConnection.onaddstream = gotRemoteStream;
  remotePeerConnection.ondatachannel = receiveChannelCallback;

  localPeerConnection.addStream(localStream);
  trace('Adding Local Stream to peer connection');
}

function onSetSessionDescriptionSuccess() {
  trace('Set session description success.');
}

function onSetSessionDescriptionError(error) {
  trace('Failed to set session description: ' + error.toString());
}

// Workaround for crbug/322756.
function maybeAddLineBreakToEnd(sdp) {
  var endWithLineBreak = new RegExp(/\n$/);
  if (!endWithLineBreak.test(sdp)) {
    return sdp + '\n';
  }
  return sdp;
}

function createOffer() {
  localPeerConnection.createOffer(
    offerOptions
  ).then(
    gotDescription1,
    onCreateSessionDescriptionError
  );
}

function onCreateSessionDescriptionError(error) {
  trace('Failed to create session description: ' + error.toString());
}

function setOffer() {
  var sdp = offerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  offer.sdp = sdp;
  localPeerConnection.setLocalDescription(offer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
  trace('Modified Offer from localPeerConnection \n' + sdp);
  remotePeerConnection.setRemoteDescription(offer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
}

function gotDescription1(description) {
  offer = description;
  offerSdpTextarea.disabled = false;
  offerSdpTextarea.value = description.sdp;
}

function createAnswer() {
  // Since the 'remote' side has no media stream we need
  // to pass in the right constraints in order for it to
  // accept the incoming offer of audio and video.
  remotePeerConnection.createAnswer().then(
    gotDescription2,
    onCreateSessionDescriptionError
  );
}

function setAnswer() {
  var sdp = answerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  answer.sdp = sdp;
  remotePeerConnection.setLocalDescription(answer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
  trace('Modified Answer from remotePeerConnection \n' + sdp);
  localPeerConnection.setRemoteDescription(answer).then(
    onSetSessionDescriptionSuccess,
    onSetSessionDescriptionError
  );
}

function gotDescription2(description) {
  answer = description;
  answerSdpTextarea.disabled = false;
  answerSdpTextarea.value = description.sdp;
}

function sendData() {
  sendChannel.send(dataChannelCounter);
  trace('DataChannel send counter: ' + dataChannelCounter);
  dataChannelCounter++;
}

function hangup() {
  remoteVideo.src = '';
  trace('Ending call');
  localStream.getTracks().forEach(function(track) {
    track.stop();
  });
  sendChannel.close();
  if (receiveChannel) {
    receiveChannel.close();
  }
  localPeerConnection.close();
  remotePeerConnection.close();
  localPeerConnection = null;
  remotePeerConnection = null;
  offerSdpTextarea.disabled = true;
  answerSdpTextarea.disabled = true;
  getMediaButton.disabled = false;
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = true;
  setOfferButton.disabled = true;
  createAnswerButton.disabled = true;
  setAnswerButton.disabled = true;
  hangupButton.disabled = true;
}

function gotRemoteStream(e) {
  remoteVideo.srcObject = e.stream;
  trace('Received remote stream');
}

function iceCallback1(event) {
  if (event.candidate) {
    remotePeerConnection.addIceCandidate(
      new RTCIceCandidate(event.candidate)
    ).then(
      onAddIceCandidateSuccess,
      onAddIceCandidateError
    );
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  if (event.candidate) {
    localPeerConnection.addIceCandidate(
      new RTCIceCandidate(event.candidate)
    ).then(
      onAddIceCandidateSuccess,
      onAddIceCandidateError
    );
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function receiveChannelCallback(event) {
  trace('Receive Channel Callback');
  receiveChannel = event.channel;
  receiveChannel.onmessage = onReceiveMessageCallback;
  receiveChannel.onopen = onReceiveChannelStateChange;
  receiveChannel.onclose = onReceiveChannelStateChange;
}

function onReceiveMessageCallback(event) {
  dataChannelDataReceived = event.data;
  trace('DataChannel receive counter: ' + dataChannelDataReceived);
}

function onSendChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Send channel state is: ' + readyState);
  if (readyState === 'open') {
    sendDataLoop = setInterval(sendData, 1000);
  } else {
    clearInterval(sendDataLoop);
  }
}

function onReceiveChannelStateChange() {
  var readyState = receiveChannel.readyState;
  trace('Receive channel state is: ' + readyState);
}
<|endoftext|>