<commit_before>/*! ============================================================
 * bootstrapSwitch v1.7 by Larentis Mattia @SpiritualGuru
 * http://www.larentis.eu/
 *
 * Enhanced for radiobuttons by Stein, Peter @BdMdesigN
 * http://www.bdmdesign.org/
 *
 * Project site:
 * http://www.larentis.eu/switch/
 * ============================================================
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 * ============================================================ */

!function ($) {
  "use strict";

  $.fn['bootstrapSwitch'] = function (method) {
    var inputSelector = 'input[type!="hidden"]';
    var methods = {
      init: function () {
        return this.each(function () {
            var $element = $(this)
              , $div
              , $switchLeft
              , $switchRight
              , $label
              , $form = $element.closest('form')
              , myClasses = ""
              , classes = $element.attr('class')
              , color
              , moving
              , onLabel = "ON"
              , offLabel = "OFF"
              , icon = false;

            $.each(['switch-mini', 'switch-small', 'switch-large'], function (i, el) {
              if (classes.indexOf(el) >= 0)
                myClasses = el;
            });

            $element.addClass('has-switch');

            if ($element.data('on') !== undefined)
              color = "switch-" + $element.data('on');

            if ($element.data('on-label') !== undefined)
              onLabel = $element.data('on-label');

            if ($element.data('off-label') !== undefined)
              offLabel = $element.data('off-label');

            if ($element.data('icon') !== undefined)
              icon = $element.data('icon');

            $switchLeft = $('')
              .addClass("switch-left")
              .addClass(myClasses)
              .addClass(color)
              .html(onLabel);

            color = '';
            if ($element.data('off') !== undefined)
              color = "switch-" + $element.data('off');

            $switchRight = $('')
              .addClass("switch-right")
              .addClass(myClasses)
              .addClass(color)
              .html(offLabel);

            $label = $('')
              .html(" ")
              .addClass(myClasses)
              .attr('for', $element.find(inputSelector).attr('id'));

            if (icon) {
              $label.html('');
            }

            $div = $element.find(inputSelector).wrap($('
')).parent().data('animated', false);

            if ($element.data('animated') !== false)
              $div.addClass('switch-animate').data('animated', true);

            $div
              .append($switchLeft)
              .append($label)
              .append($switchRight);

            $element.find('>div').addClass(
              $element.find(inputSelector).is(':checked') ? 'switch-on' : 'switch-off'
            );

            if ($element.find(inputSelector).is(':disabled'))
              $(this).addClass('deactivate');

            var changeStatus = function ($this) {
              $this.siblings('label').trigger('mousedown').trigger('mouseup').trigger('click');
            };

            $element.on('keydown', function (e) {
              if (e.keyCode === 32) {
                e.stopImmediatePropagation();
                e.preventDefault();
                changeStatus($(e.target).find('span:first'));
              }
            });

            $switchLeft.on('click', function (e) {
              changeStatus($(this));
            });

            $switchRight.on('click', function (e) {
              changeStatus($(this));
            });

            $element.find(inputSelector).on('change', function (e, skipOnChange) {
              var $this = $(this)
                , $element = $this.parent()
                , thisState = $this.is(':checked')
                , state = $element.is('.switch-off');

              e.preventDefault();

              $element.css('left', '');

              if (state === thisState) {

                if (thisState)
                  $element.removeClass('switch-off').addClass('switch-on');
                else $element.removeClass('switch-on').addClass('switch-off');

                if ($element.data('animated') !== false)
                  $element.addClass("switch-animate");

                if (typeof skipOnChange === 'boolean' && skipOnChange)
                  return;

                $element.parent().trigger('switch-change', {'el': $this, 'value': thisState})
              }
            });

            $element.find('label').on('mousedown touchstart', function (e) {
              var $this = $(this);
              moving = false;

              e.preventDefault();
              e.stopImmediatePropagation();

              $this.closest('div').removeClass('switch-animate');

              if ($this.closest('.has-switch').is('.deactivate')) {
                $this.unbind('click');
              } else if ( $this.closest('.switch-on').parent().is('.radio-no-uncheck') ) {
                $this.unbind('click');
              } else {
                $this.on('mousemove touchmove', function (e) {
                  var $element = $(this).closest('.make-switch')
                    , relativeX = (e.pageX || e.originalEvent.targetTouches[0].pageX) - $element.offset().left
                    , percent = (relativeX / $element.width()) * 100
                    , left = 25
                    , right = 75;

                  moving = true;

                  if (percent < left)
                    percent = left;
                  else if (percent > right)
                    percent = right;

                  $element.find('>div').css('left', (percent - right) + "%")
                });

                $this.on('click touchend', function (e) {
                  var $this = $(this)
                    , $target = $(e.target)
                    , $myRadioCheckBox = $target.siblings('input');

                  e.stopImmediatePropagation();
                  e.preventDefault();

                  $this.unbind('mouseleave');

                  if (moving)
                    $myRadioCheckBox.prop('checked', !(parseInt($this.parent().css('left')) < -25));
                  else
                    $myRadioCheckBox.prop("checked", !$myRadioCheckBox.is(":checked"));

                  moving = false;
                  $myRadioCheckBox.trigger('change');
                });

                $this.on('mouseleave', function (e) {
                  var $this = $(this)
                    , $myInputBox = $this.siblings('input');

                  e.preventDefault();
                  e.stopImmediatePropagation();

                  $this.unbind('mouseleave');
                  $this.trigger('mouseup');

                  $myInputBox.prop('checked', !(parseInt($this.parent().css('left')) < -25)).trigger('change');
                });

                $this.on('mouseup', function (e) {
                  e.stopImmediatePropagation();
                  e.preventDefault();

                  $(this).unbind('mousemove');
                });
              }
            });

            if ($form.data('bootstrapSwitch') !== 'injected') {
              $form.bind('reset', function () {
                setTimeout(function () {
                  $form.find('.make-switch').each(function () {
                    var $input = $(this).find(inputSelector);

                    $input.prop('checked', $input.is(':checked')).trigger('change');
                  });
                }, 1);
              });
              $form.data('bootstrapSwitch', 'injected');
            }
          }
        );
      },
      toggleActivation: function () {
        var $this = $(this);

        $this.toggleClass('deactivate');
        $this.find(inputSelector).prop('disabled', $this.is('.deactivate'));
      },
      isActive: function () {
        return !$(this).hasClass('deactivate');
      },
      setActive: function (active) {
        var $this = $(this);

        if (active) {
          $this.removeClass('deactivate');
          $this.find(inputSelector).removeAttr('disabled');
        }
        else {
          $this.addClass('deactivate');
          $this.find(inputSelector).attr('disabled', 'disabled');
        }
      },
      toggleState: function (skipOnChange) {
        var $input = $(this).find(':checkbox');
        $input.prop('checked', !$input.is(':checked')).trigger('change', skipOnChange);
      },
      toggleRadioState: function (skipOnChange) {
        var $radioinput = $(this).find(':radio');
          $radioinput.not(':checked').prop('checked', !$radioinput.is(':checked')).trigger('change', skipOnChange);
      },
      toggleRadioStateAllowUncheck: function (uncheck, skipOnChange) {
        var $radioinput = $(this).find(':radio');
        if (uncheck) {
          $radioinput.not(':checked').trigger('change', skipOnChange);
        }
        else {
          $radioinput.not(':checked').prop('checked', !$radioinput.is(':checked')).trigger('change', skipOnChange);
        }
      },
      setState: function (value, skipOnChange) {
        $(this).find(inputSelector).prop('checked', value).trigger('change', skipOnChange);
      },
      setOnLabel: function(value) {
        var $switchLeft = $(this).find(".switch-left");
        $switchLeft.html(value);
      },
      setOffLabel: function(value) {
        var $switchRight = $(this).find(".switch-right");
        $switchRight.html(value);
      },
      setOnClass: function(value) {
        var $switchLeft = $(this).find(".switch-left");
        var color = '';
        if (value !== undefined) {
          if ($(this).attr('data-on') !== undefined) {
            color = "switch-" + $(this).attr('data-on')
          }
          $switchLeft.removeClass(color);
          color = "switch-" + value;
          $switchLeft.addClass(color);
        }
      },
      setOffClass: function(value) {
        var $switchRight = $(this).find(".switch-right");
        var color = '';
        if (value !== undefined) {
          if ($(this).attr('data-off') !== undefined) {
            color = "switch-" + $(this).attr('data-off')
          }
          $switchRight.removeClass(color);
          color = "switch-" + value;
          $switchRight.addClass(color);
        }
      },
      setAnimated: function(value) {
        var $element = $(this).find('inputSelector').parent();
        if (value === undefined) value = false;
        $element.data('animated', value);
        $element.attr('data-animated', value);

        if ($element.data('animated') !== false) {
          $element.addClass("switch-animate");
        } else {
          $element.removeClass("switch-animate");
        }
      },
      setSizeClass: function(value) {
        var $element = $(this);
        var $switchLeft = $element.find(".switch-left");
        var $switchRight = $element.find(".switch-right");
        var $label = $element.find("label");
        $.each(['switch-mini', 'switch-small', 'switch-large'], function (i, el) {
          if (el !== value) {
            $switchLeft.removeClass(el);
            $switchRight.removeClass(el);
            $label.removeClass(el);
          } else {
            $switchLeft.addClass(el);
            $switchRight.addClass(el);
            $label.addClass(el);
          }
        });
      },
      status: function () {
        return $(this).find(inputSelector).is(':checked');
      },
      destroy: function () {
        var $element = $(this)
          , $div = $element.find('div')
          , $form = $element.closest('form')
          , $inputbox;

        $div.find(':not(inputSelector)').remove();

        $inputbox = $div.children();
        $inputbox.unwrap().unwrap();

        $inputbox.unbind('change');

        if ($form) {
          $form.unbind('reset');
          $form.removeData('bootstrapSwitch');
        }

        return $inputbox;
      }
    };

    if (methods[method])
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    else if (typeof method === 'object' || !method)
      return methods.init.apply(this, arguments);
    else
      $.error('Method ' + method + ' does not exist!');
  };
}(jQuery);

(function($) {  // creates scope for $ sign assigned to jQuery
    $(function () { // on dom ready
        $('.make-switch')['bootstrapSwitch'](); // attach bootstrapswitch
    });
})(jQuery);
<commit_msg>fixed destroy method<commit_after>/*! ============================================================
 * bootstrapSwitch v1.7 by Larentis Mattia @SpiritualGuru
 * http://www.larentis.eu/
 *
 * Enhanced for radiobuttons by Stein, Peter @BdMdesigN
 * http://www.bdmdesign.org/
 *
 * Project site:
 * http://www.larentis.eu/switch/
 * ============================================================
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 * ============================================================ */

!function ($) {
  "use strict";

  $.fn['bootstrapSwitch'] = function (method) {
    var inputSelector = 'input[type!="hidden"]';
    var methods = {
      init: function () {
        return this.each(function () {
            var $element = $(this)
              , $div
              , $switchLeft
              , $switchRight
              , $label
              , $form = $element.closest('form')
              , myClasses = ""
              , classes = $element.attr('class')
              , color
              , moving
              , onLabel = "ON"
              , offLabel = "OFF"
              , icon = false;

            $.each(['switch-mini', 'switch-small', 'switch-large'], function (i, el) {
              if (classes.indexOf(el) >= 0)
                myClasses = el;
            });

            $element.addClass('has-switch');

            if ($element.data('on') !== undefined)
              color = "switch-" + $element.data('on');

            if ($element.data('on-label') !== undefined)
              onLabel = $element.data('on-label');

            if ($element.data('off-label') !== undefined)
              offLabel = $element.data('off-label');

            if ($element.data('icon') !== undefined)
              icon = $element.data('icon');

            $switchLeft = $('')
              .addClass("switch-left")
              .addClass(myClasses)
              .addClass(color)
              .html(onLabel);

            color = '';
            if ($element.data('off') !== undefined)
              color = "switch-" + $element.data('off');

            $switchRight = $('')
              .addClass("switch-right")
              .addClass(myClasses)
              .addClass(color)
              .html(offLabel);

            $label = $('')
              .html(" ")
              .addClass(myClasses)
              .attr('for', $element.find(inputSelector).attr('id'));

            if (icon) {
              $label.html('');
            }

            $div = $element.find(inputSelector).wrap($('
')).parent().data('animated', false);

            if ($element.data('animated') !== false)
              $div.addClass('switch-animate').data('animated', true);

            $div
              .append($switchLeft)
              .append($label)
              .append($switchRight);

            $element.find('>div').addClass(
              $element.find(inputSelector).is(':checked') ? 'switch-on' : 'switch-off'
            );

            if ($element.find(inputSelector).is(':disabled'))
              $(this).addClass('deactivate');

            var changeStatus = function ($this) {
              $this.siblings('label').trigger('mousedown').trigger('mouseup').trigger('click');
            };

            $element.on('keydown', function (e) {
              if (e.keyCode === 32) {
                e.stopImmediatePropagation();
                e.preventDefault();
                changeStatus($(e.target).find('span:first'));
              }
            });

            $switchLeft.on('click', function (e) {
              changeStatus($(this));
            });

            $switchRight.on('click', function (e) {
              changeStatus($(this));
            });

            $element.find(inputSelector).on('change', function (e, skipOnChange) {
              var $this = $(this)
                , $element = $this.parent()
                , thisState = $this.is(':checked')
                , state = $element.is('.switch-off');

              e.preventDefault();

              $element.css('left', '');

              if (state === thisState) {

                if (thisState)
                  $element.removeClass('switch-off').addClass('switch-on');
                else $element.removeClass('switch-on').addClass('switch-off');

                if ($element.data('animated') !== false)
                  $element.addClass("switch-animate");

                if (typeof skipOnChange === 'boolean' && skipOnChange)
                  return;

                $element.parent().trigger('switch-change', {'el': $this, 'value': thisState})
              }
            });

            $element.find('label').on('mousedown touchstart', function (e) {
              var $this = $(this);
              moving = false;

              e.preventDefault();
              e.stopImmediatePropagation();

              $this.closest('div').removeClass('switch-animate');

              if ($this.closest('.has-switch').is('.deactivate')) {
                $this.unbind('click');
              } else if ( $this.closest('.switch-on').parent().is('.radio-no-uncheck') ) {
                $this.unbind('click');
              } else {
                $this.on('mousemove touchmove', function (e) {
                  var $element = $(this).closest('.make-switch')
                    , relativeX = (e.pageX || e.originalEvent.targetTouches[0].pageX) - $element.offset().left
                    , percent = (relativeX / $element.width()) * 100
                    , left = 25
                    , right = 75;

                  moving = true;

                  if (percent < left)
                    percent = left;
                  else if (percent > right)
                    percent = right;

                  $element.find('>div').css('left', (percent - right) + "%")
                });

                $this.on('click touchend', function (e) {
                  var $this = $(this)
                    , $target = $(e.target)
                    , $myRadioCheckBox = $target.siblings('input');

                  e.stopImmediatePropagation();
                  e.preventDefault();

                  $this.unbind('mouseleave');

                  if (moving)
                    $myRadioCheckBox.prop('checked', !(parseInt($this.parent().css('left')) < -25));
                  else
                    $myRadioCheckBox.prop("checked", !$myRadioCheckBox.is(":checked"));

                  moving = false;
                  $myRadioCheckBox.trigger('change');
                });

                $this.on('mouseleave', function (e) {
                  var $this = $(this)
                    , $myInputBox = $this.siblings('input');

                  e.preventDefault();
                  e.stopImmediatePropagation();

                  $this.unbind('mouseleave');
                  $this.trigger('mouseup');

                  $myInputBox.prop('checked', !(parseInt($this.parent().css('left')) < -25)).trigger('change');
                });

                $this.on('mouseup', function (e) {
                  e.stopImmediatePropagation();
                  e.preventDefault();

                  $(this).unbind('mousemove');
                });
              }
            });

            if ($form.data('bootstrapSwitch') !== 'injected') {
              $form.bind('reset', function () {
                setTimeout(function () {
                  $form.find('.make-switch').each(function () {
                    var $input = $(this).find(inputSelector);

                    $input.prop('checked', $input.is(':checked')).trigger('change');
                  });
                }, 1);
              });
              $form.data('bootstrapSwitch', 'injected');
            }
          }
        );
      },
      toggleActivation: function () {
        var $this = $(this);

        $this.toggleClass('deactivate');
        $this.find(inputSelector).prop('disabled', $this.is('.deactivate'));
      },
      isActive: function () {
        return !$(this).hasClass('deactivate');
      },
      setActive: function (active) {
        var $this = $(this);

        if (active) {
          $this.removeClass('deactivate');
          $this.find(inputSelector).removeAttr('disabled');
        }
        else {
          $this.addClass('deactivate');
          $this.find(inputSelector).attr('disabled', 'disabled');
        }
      },
      toggleState: function (skipOnChange) {
        var $input = $(this).find(':checkbox');
        $input.prop('checked', !$input.is(':checked')).trigger('change', skipOnChange);
      },
      toggleRadioState: function (skipOnChange) {
        var $radioinput = $(this).find(':radio');
          $radioinput.not(':checked').prop('checked', !$radioinput.is(':checked')).trigger('change', skipOnChange);
      },
      toggleRadioStateAllowUncheck: function (uncheck, skipOnChange) {
        var $radioinput = $(this).find(':radio');
        if (uncheck) {
          $radioinput.not(':checked').trigger('change', skipOnChange);
        }
        else {
          $radioinput.not(':checked').prop('checked', !$radioinput.is(':checked')).trigger('change', skipOnChange);
        }
      },
      setState: function (value, skipOnChange) {
        $(this).find(inputSelector).prop('checked', value).trigger('change', skipOnChange);
      },
      setOnLabel: function(value) {
        var $switchLeft = $(this).find(".switch-left");
        $switchLeft.html(value);
      },
      setOffLabel: function(value) {
        var $switchRight = $(this).find(".switch-right");
        $switchRight.html(value);
      },
      setOnClass: function(value) {
        var $switchLeft = $(this).find(".switch-left");
        var color = '';
        if (value !== undefined) {
          if ($(this).attr('data-on') !== undefined) {
            color = "switch-" + $(this).attr('data-on')
          }
          $switchLeft.removeClass(color);
          color = "switch-" + value;
          $switchLeft.addClass(color);
        }
      },
      setOffClass: function(value) {
        var $switchRight = $(this).find(".switch-right");
        var color = '';
        if (value !== undefined) {
          if ($(this).attr('data-off') !== undefined) {
            color = "switch-" + $(this).attr('data-off')
          }
          $switchRight.removeClass(color);
          color = "switch-" + value;
          $switchRight.addClass(color);
        }
      },
      setAnimated: function(value) {
        var $element = $(this).find('inputSelector').parent();
        if (value === undefined) value = false;
        $element.data('animated', value);
        $element.attr('data-animated', value);

        if ($element.data('animated') !== false) {
          $element.addClass("switch-animate");
        } else {
          $element.removeClass("switch-animate");
        }
      },
      setSizeClass: function(value) {
        var $element = $(this);
        var $switchLeft = $element.find(".switch-left");
        var $switchRight = $element.find(".switch-right");
        var $label = $element.find("label");
        $.each(['switch-mini', 'switch-small', 'switch-large'], function (i, el) {
          if (el !== value) {
            $switchLeft.removeClass(el);
            $switchRight.removeClass(el);
            $label.removeClass(el);
          } else {
            $switchLeft.addClass(el);
            $switchRight.addClass(el);
            $label.addClass(el);
          }
        });
      },
      status: function () {
        return $(this).find(inputSelector).is(':checked');
      },
      destroy: function () {
        var $element = $(this)
          , $div = $element.find('div')
          , $form = $element.closest('form')
          , $inputbox;

        $div.find(':not(input)').remove();

        $inputbox = $div.children();
        $inputbox.unwrap().unwrap();

        $inputbox.unbind('change');

        if ($form) {
          $form.unbind('reset');
          $form.removeData('bootstrapSwitch');
        }

        return $inputbox;
      }
    };

    if (methods[method])
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    else if (typeof method === 'object' || !method)
      return methods.init.apply(this, arguments);
    else
      $.error('Method ' + method + ' does not exist!');
  };
}(jQuery);

(function($) {  // creates scope for $ sign assigned to jQuery
    $(function () { // on dom ready
        $('.make-switch')['bootstrapSwitch'](); // attach bootstrapswitch
    });
})(jQuery);
<|endoftext|>


<commit_before>/*
 * Spreed WebRTC.
 * Copyright (C) 2013-2014 struktur AG
 *
 * This file is part of Spreed WebRTC.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

"use strict";
define([
], function() {

	return ["$window", "$q", function($window, $q) {
		var pinCache = {};
		var roompin = {
			get: function(roomName) {
				var cachedPIN = pinCache[roomName];
				return cachedPIN ? cachedPIN : null;
			},
			clear: function(roomName) {
				delete pinCache[roomName];
				console.log("Cleared PIN for", roomName);
			},
			update: function(roomName, pin) {
				if (pin) {
					pinCache[roomName] = pin;
					$window.alert("PIN for room " + roomName + " is now '" + pin + "'");
				} else {
					roompin.clear(roomName);
					$window.alert("PIN lock has been removed from room " + roomName);
				}
			},
			requestInteractively: function(roomName) {
				var deferred = $q.defer();
				var pin = $window.prompt("Enter the PIN for " + roomName + " below");
				if (pin) {
					pinCache[roomName] = pin;
					deferred.resolve();
				} else {
					deferred.reject();
				}
				return deferred.promise;
			}
		};
		return roompin;
	}];
});
<commit_msg>Added comments to refactor service.<commit_after>/*
 * Spreed WebRTC.
 * Copyright (C) 2013-2014 struktur AG
 *
 * This file is part of Spreed WebRTC.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

"use strict";
define([
], function() {

	return ["$window", "$q", function($window, $q) {

		var pinCache = {};

		// XXX(longsleep): This service needs to get rid of all window.alert and prompt calls.
		var roompin = {
			get: function(roomName) {
				var cachedPIN = pinCache[roomName];
				return cachedPIN ? cachedPIN : null;
			},
			clear: function(roomName) {
				delete pinCache[roomName];
				console.log("Cleared PIN for", roomName);
			},
			update: function(roomName, pin) {
				if (pin) {
					pinCache[roomName] = pin;
					$window.alert("PIN for room " + roomName + " is now '" + pin + "'");
				} else {
					roompin.clear(roomName);
					$window.alert("PIN lock has been removed from room " + roomName);
				}
			},
			requestInteractively: function(roomName) {
				var deferred = $q.defer();
				var pin = $window.prompt("Enter the PIN for " + roomName + " below");
				if (pin) {
					pinCache[roomName] = pin;
					deferred.resolve();
				} else {
					deferred.reject();
				}
				return deferred.promise;
			}
		};

		return roompin;

	}];
});
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 *  Bootstrap.js
 *
 *  Created by Alexander Yuzhin on 5/27/14
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

function onDropDownKeyDown(e) {
    var $this       = $(this),
        $parent     = $this.parent(),
        beforeEvent = jQuery.Event('keydown.before.bs.dropdown', {keyCode: e.keyCode}),
        afterEvent  = jQuery.Event('keydown.after.bs.dropdown', {keyCode: e.keyCode});

    $parent.trigger(beforeEvent);

    if ($parent.hasClass('no-stop-propagate')) {
        if (arguments.length>1 && arguments[1] instanceof KeyboardEvent)
            e = arguments[1];
        if ( /^(38|40|27|13|9|37|39)$/.test(e.keyCode) && !e.ctrlKey && !e.altKey) {
            patchDropDownKeyDownAdditional.call(this, e);
            if (!/(37|39)/.test(e.keyCode)) {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    } else {
        patchDropDownKeyDown.call(this, e);
        e.preventDefault();
        e.stopPropagation();
    }

    $parent.trigger(afterEvent);
}

function patchDropDownKeyDown(e) {
    if (!/(38|40|27|37|39)/.test(e.keyCode)) return;

    var $this = $(this);

    e.preventDefault();
    e.stopPropagation();

    if ($this.is('.disabled, :disabled')) return;

    var $parent  = getParent($this);
    var isActive = $parent.hasClass('open') || $parent.hasClass('over');

    if (!isActive || (isActive && e.keyCode == 27)) {
        if (e.which == 27) {
            $items = $('[role=menu] li.dropdown-submenu.over:visible', $parent);
            if ($items.length) {
                $items.eq($items.length-1).removeClass('over');
                return false;
            } else if ($parent.hasClass('dropdown-submenu') && $parent.hasClass('over')) {
                $parent.removeClass('over');
                $parent.find('> a').focus();
            } else {
                $parent.find('[data-toggle=dropdown]').focus();
            }
        }
        return (isActive) ? $this.click() : undefined;
    }

//    var $items = $('[role=menu] li:not(.divider):visible a', $parent)   - original search function
    var $items = $('> [role=menu] > li:not(.divider):not(.disabled):visible', $parent).find('> a');

    if (!$items.length) return;

    var index = $items.index($items.filter(':focus'));
    if (e.keyCode == 39) {     // right
        if (index<0) return;

        var li = $items.eq(index).parent();
        if (li.hasClass('dropdown-submenu') && !li.hasClass('over')) {// open submenu and select first <li> item
            li.mouseenter();
            li.addClass('focused-submenu');
             _.delay(function() {
                 var mnu = $('> [role=menu]', li),
                    $subitems = mnu.find('> li:not(.divider):not(.disabled):visible > a'),
                    $dataviews = mnu.find('> li:not(.divider):not(.disabled):visible .dataview'),
                    $internal_menu = mnu.find('> li:not(.divider):not(.disabled):visible ul.internal-menu');
                if ($subitems.length>0 && $dataviews.length<1 && $internal_menu.length<1)
                    ($subitems.index($subitems.filter(':focus'))<0) && $subitems.eq(0).focus();
            }, 250);
        }
    } else if (e.keyCode == 37) {     // left
        if ($parent.hasClass('dropdown-submenu') && $parent.hasClass('over')) { // close submenu
            $parent.removeClass('over');
            $parent.find('> a').focus();
        }
    } else {
        if (e.keyCode == 38) { index > 0 ? index-- : ($this.hasClass('no-cyclic') ? (index = 0) : (index = $items.length - 1));} else         // up
        if (e.keyCode == 40) { index < $items.length - 1 ? index++ : ($this.hasClass('no-cyclic') ? (index = $items.length - 1) : (index = 0));}              // down
        if (!~index) index=0;
        if ($parent.hasClass('dropdown-submenu') && $parent.hasClass('over'))
            $parent.addClass('focused-submenu'); // for Safari. When focus go from parent menuItem to it's submenu don't hide this submenu

        $items.eq(index).focus();
    }
}

function patchDropDownKeyDownAdditional(e) { // only for formula menu when typing in cell editor
    if (!/(38|40|27|37|39)/.test(e.keyCode)) return;

    var $this = $(this);

    if (!/(37|39)/.test(e.keyCode)) {
        e.preventDefault();
        e.stopPropagation();
    }

    if ($this.is('.disabled, :disabled')) return;

    var $parent  = getParent($this);
    var isActive = $parent.hasClass('open') || $parent.hasClass('over');

    if (!isActive || (isActive && (e.keyCode == 27 || e.keyCode == 37 || e.keyCode == 39))) {
//        if (e.which == 27)
//            $parent.find('[data-toggle=dropdown]').focus();
        return (isActive) ? $this.click() : undefined;
    }

    var $items = $('> [role=menu] > li:not(.divider):not(.disabled):visible', $parent).find('> a');

    if (!$items.length) return;

    var index = $items.index($items.filter('.focus')),
        previndex = index;
    if (e.keyCode == 38) { index > 0 ? index-- : ($this.hasClass('no-cyclic') ? (index = 0) : (index = $items.length - 1));} else         // up
    if (e.keyCode == 40) { index < $items.length - 1 ? index++ : ($this.hasClass('no-cyclic') ? (index = $items.length - 1) : (index = 0));}              // down
    if (!~index) index=0;

    $items.removeClass('focus');
    $items.eq(index).addClass('focus');

    if (previndex !== index) {
        var tip = $items.eq(previndex).parent().data('bs.tooltip');
        if (tip) {
            tip.hide();
        }
        tip = $items.eq(index).parent().data('bs.tooltip');
        if (tip) {
            tip.show();
        }
    }
}

function getParent($this) {
    var selector = $this.attr('data-target');

    if (!selector) {
        selector = $this.attr('href');
        selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
    }

    var $parent = selector && $(selector);

    return $parent && $parent.length ? $parent : $this.parent();
}

function clearMenus(isFromInputControl) {
    $('.dropdown-toggle').each(function (e) {
        var $parent = ($(this)).parent();
        if (!$parent.hasClass('open')) return;
        if ($parent.attr('data-value') == 'prevent-canvas-click') {
            $parent.attr('data-value','');
            return;
        }
        $parent.trigger(e = $.Event('hide.bs.dropdown'));
        if (e.isDefaultPrevented()) return;
        $parent.removeClass('open').trigger('hidden.bs.dropdown', isFromInputControl);
    })
}

$(document)
    .off('keydown.bs.dropdown.data-api')
    .on('keydown.bs.dropdown.data-api', '[data-toggle=dropdown], [role=menu]' , onDropDownKeyDown);

/*
*      workaround closing menu by right click
* */
(function () {
    var eventsObj = $._data($(document).get(0), "events"), clickDefHandler;
    if (eventsObj && eventsObj.click) {
        eventsObj.click.every(function(e, i, a){
            if (/click/.test(e.type) && !e.selector && /bs\..+\.dropdown/.test(e.namespace)) {
                clickDefHandler = e.handler;
            }

            return !clickDefHandler;
        });
    }

    function onDropDownClick(e) {
        if (e.which == 1 || e.which == undefined)
            clearMenus(/form-control/.test(e.target.className));
    }

    if (!!clickDefHandler) {
        $(document)
            .off('click.bs.dropdown.data-api', clickDefHandler)
            .on('click.bs.dropdown.data-api', onDropDownClick);
    }
})();
/*
* */<commit_msg>Fix Bug 43332 (#258)<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 *  Bootstrap.js
 *
 *  Created by Alexander Yuzhin on 5/27/14
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

function onDropDownKeyDown(e) {
    var $this       = $(this),
        $parent     = $this.parent(),
        beforeEvent = jQuery.Event('keydown.before.bs.dropdown', {keyCode: e.keyCode}),
        afterEvent  = jQuery.Event('keydown.after.bs.dropdown', {keyCode: e.keyCode});

    $parent.trigger(beforeEvent);

    if ($parent.hasClass('no-stop-propagate')) {
        if (arguments.length>1 && arguments[1] instanceof KeyboardEvent)
            e = arguments[1];
        if ( /^(38|40|27|13|9|37|39)$/.test(e.keyCode) && !e.ctrlKey && !e.altKey) {
            patchDropDownKeyDownAdditional.call(this, e);
            if (!/(37|39)/.test(e.keyCode)) {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    } else {
        patchDropDownKeyDown.call(this, e);
        e.preventDefault();
        e.stopPropagation();
    }

    $parent.trigger(afterEvent);
}

function patchDropDownKeyDown(e) {
    if (!/(38|40|27|37|39)/.test(e.keyCode)) return;

    var $this = $(this);

    e.preventDefault();
    e.stopPropagation();

    if ($this.is('.disabled, :disabled')) return;

    var $parent  = getParent($this);
    var isActive = $parent.hasClass('open') || $parent.hasClass('over');

    if (!isActive || (isActive && e.keyCode == 27)) {
        if (e.which == 27) {
            $items = $('[role=menu] li.dropdown-submenu.over:visible', $parent);
            if ($items.length) {
                $items.eq($items.length-1).removeClass('over');
                return false;
            } else if ($parent.hasClass('dropdown-submenu') && $parent.hasClass('over')) {
                $parent.removeClass('over');
                $parent.find('> a').focus();
            } else {
                $parent.find('[data-toggle=dropdown]').focus();
            }
        }
        return (isActive) ? $this.click() : undefined;
    }

//    var $items = $('[role=menu] li:not(.divider):visible a', $parent)   - original search function
    var $items = $('> [role=menu] > li:not(.divider):not(.disabled):visible', $parent).find('> a');

    if (!$items.length) return;

    var index = $items.index($items.filter(':focus'));
    if (e.keyCode == 39) {     // right
        if (index<0) return;

        var li = $items.eq(index).parent();
        if (li.hasClass('dropdown-submenu') && !li.hasClass('over')) {// open submenu and select first <li> item
            li.mouseenter();
            li.addClass('focused-submenu');
             _.delay(function() {
                 var mnu = $('> [role=menu]', li),
                    $subitems = mnu.find('> li:not(.divider):not(.disabled):visible > a'),
                    $dataviews = mnu.find('> li:not(.divider):not(.disabled):visible .dataview'),
                    $internal_menu = mnu.find('> li:not(.divider):not(.disabled):visible ul.internal-menu');
                if ($subitems.length>0 && $dataviews.length<1 && $internal_menu.length<1)
                    ($subitems.index($subitems.filter(':focus'))<0) && $subitems.eq(0).focus();
            }, 250);
        }
    } else if (e.keyCode == 37) {     // left
        if ($parent.hasClass('dropdown-submenu') && $parent.hasClass('over')) { // close submenu
            $parent.removeClass('over');
            $parent.find('> a').focus();
        }
    } else {
        if (e.keyCode == 38) { index > 0 ? index-- : ($this.hasClass('no-cyclic') ? (index = 0) : (index = $items.length - 1));} else         // up
        if (e.keyCode == 40) { index < $items.length - 1 ? index++ : ($this.hasClass('no-cyclic') ? (index = $items.length - 1) : (index = 0));}              // down
        if (!~index) index=0;
        if ($parent.hasClass('dropdown-submenu') && $parent.hasClass('over'))
            $parent.addClass('focused-submenu'); // for Safari. When focus go from parent menuItem to it's submenu don't hide this submenu

        $items.eq(index).focus();
    }
}

function patchDropDownKeyDownAdditional(e) { // only for formula menu when typing in cell editor
    if (!/(38|40|27|37|39)/.test(e.keyCode)) return;

    var $this = $(this);

    if (!/(37|39)/.test(e.keyCode)) {
        e.preventDefault();
        e.stopPropagation();
    }

    if ($this.is('.disabled, :disabled')) return;

    var $parent  = getParent($this);
    var isActive = $parent.hasClass('open') || $parent.hasClass('over');

    if (!isActive || (isActive && (e.keyCode == 27 || e.keyCode == 37 || e.keyCode == 39))) {
//        if (e.which == 27)
//            $parent.find('[data-toggle=dropdown]').focus();
        return (isActive) ? $this.click() : undefined;
    }

    var $items = $('> [role=menu] > li:not(.divider):not(.disabled):visible', $parent).find('> a');

    if (!$items.length) return;

    var index = $items.index($items.filter('.focus')),
        previndex = index;
    if (e.keyCode == 38) { index > 0 ? index-- : ($this.hasClass('no-cyclic') ? (index = 0) : (index = $items.length - 1));} else         // up
    if (e.keyCode == 40) { index < $items.length - 1 ? index++ : ($this.hasClass('no-cyclic') ? (index = $items.length - 1) : (index = 0));}              // down
    if (!~index) index=0;

    $items.removeClass('focus');
    $items.eq(index).addClass('focus');

    if (previndex !== index) {
        var tip = $items.eq(previndex).parent().data('bs.tooltip');
        if (tip) {
            tip.hide();
        }
        tip = $items.eq(index).parent().data('bs.tooltip');
        if (tip) {
            tip.show();
        }
    }
}

function getParent($this) {
    var selector = $this.attr('data-target');

    if (!selector) {
        selector = $this.attr('href');
        selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
    }

    var $parent = selector && $(selector);

    return $parent && $parent.length ? $parent : $this.parent();
}

function clearMenus(isFromInputControl) {
    $('.dropdown-toggle').each(function (e) {
        var $parent = ($(this)).parent();
        if (!$parent.hasClass('open')) return;
        if ($parent.attr('data-value') == 'prevent-canvas-click') {
            $parent.attr('data-value','');
            return;
        }
        $parent.trigger(e = $.Event('hide.bs.dropdown'));
        if (e.isDefaultPrevented()) return;
        $parent.removeClass('open').trigger('hidden.bs.dropdown', isFromInputControl);
    })
}

function toggle() {
    $('.dropdown-backdrop').remove();
}

$(document)
    .off('keydown.bs.dropdown.data-api')
    .on('keydown.bs.dropdown.data-api', '[data-toggle=dropdown], [role=menu]' , onDropDownKeyDown);

('ontouchstart' in document.documentElement) && $(document).on('click.bs.dropdown.data-api', '[data-toggle=dropdown]', toggle);
/*
*      workaround closing menu by right click
* */
(function () {
    var eventsObj = $._data($(document).get(0), "events"), clickDefHandler;
    if (eventsObj && eventsObj.click) {
        eventsObj.click.every(function(e, i, a){
            if (/click/.test(e.type) && !e.selector && /bs\..+\.dropdown/.test(e.namespace)) {
                clickDefHandler = e.handler;
            }

            return !clickDefHandler;
        });
    }

    function onDropDownClick(e) {
        if (e.which == 1 || e.which == undefined)
            clearMenus(/form-control/.test(e.target.className));
    }

    if (!!clickDefHandler) {
        $(document)
            .off('click.bs.dropdown.data-api', clickDefHandler)
            .on('click.bs.dropdown.data-api', onDropDownClick);
    }
})();
/*
* */<|endoftext|>


<commit_before>(function (window) {
    var View = window.Sparrow.View,
        Api = window.Sparrow.Api,
        Metrics = window.Sparrow.Metrics,
        Actions = {},
        Data = {
            compareRequests: [],
            testResultsError: false,
            testResults: []
        };

    Actions.init = function () {
        Api.CompareRequest.list().allAtOnce(function (l) {
            Data.compareRequests = l;
            Actions.render();
        })
    };

    Actions.selectCompareRequest = function (id) {
        var compareRequest = false, i;
        for (i = 0; i < Data.compareRequests.length && Data.compareRequests[i].id != id; i++) {
        }
        if (i >= Data.compareRequests.length) {
            return;
        }
        compareRequest = Data.compareRequests[i];

        if (compareRequest) {
            $.when(compareRequest.base_test_run(), compareRequest.head_test_run())
                .done(function (base_test_run, head_test_run) {
                    var q = [base_test_run, head_test_run],
                        testRuns;
                    q = q.filter(function (e) {
                        return e.results.length > 0;
                    });
                    testRuns = [].concat(q);
                    q = q.map(function (e) {
                        return e.results[0]();
                    });
                    if (q.length == 0) {
                        Data.testResultsError = 'No results available for the selected comparison';
                        Actions.render();
                        return;
                    }
                    $.when.apply($, q)
                        .done(function () {
                            var results = Array.prototype.slice.call(arguments, 0);
                            Data.testResultsError = false;
                            Data.testResults = new Metrics.CollectionComparison(
                                results.map(function(result,i){
                                    return new Metrics.Collection(result, testRuns[i]);
                                })
                            );
                            Actions.render();
                        });
                });
        }
    };

    Actions.render = function () {
        View.render(Data);
    };

    $.extend(window.Sparrow.Actions, {
        Data: Data
    }, Actions);
})(window);<commit_msg>Small error message improvement when tests are still running<commit_after>(function (window) {
    var View = window.Sparrow.View,
        Api = window.Sparrow.Api,
        Metrics = window.Sparrow.Metrics,
        Actions = {},
        Data = {
            compareRequests: [],
            testResultsError: false,
            testResults: []
        };

    Actions.init = function () {
        Actions.render();
        setTimeout(Actions.loadCompareRequests, 0);
    };

    Actions.loadCompareRequests = function () {
        startLoading();
        Api.CompareRequest.list(100).allAtOnce(function (l) {
            Data.compareRequests = l;
            Actions.render();
        })
    };

    Actions.selectCompareRequest = function (id) {
        var compareRequest = false, i;
        for (i = 0; i < Data.compareRequests.length && Data.compareRequests[i].id != id; i++) {
        }
        if (i >= Data.compareRequests.length) {
            return;
        }
        compareRequest = Data.compareRequests[i];

        if (compareRequest) {
            $.when(compareRequest.base_test_run(), compareRequest.head_test_run())
                .done(function (base_test_run, head_test_run) {
                    var q = [base_test_run, head_test_run],
                        testRuns;
                    if (q[0].status < 2 || q[1].status < 2) {
                        var errorText = 'Ooops! Something went wrong!';
                        if (q[0].status == -1 || q[1].status == -1) {
                            errorText = 'One or more tests have failed.';
                        } else if (q[0].status != 2 || q[1].statis != -2) {
                            errorText = 'One or more tests have not yet finished.';
                        }
                        Data.testResultsError = errorText;
                        stopLoading();
                        Actions.render();
                        return;
                    }

                    q = q.filter(function (e) {
                        return e.results.length > 0;
                    });
                    testRuns = [].concat(q);
                    q = q.map(function (e) {
                        return e.results[0]();
                    });

                    if (q.length == 0) {
                        Data.testResultsError = 'No results available for the selected comparison';
                        Actions.render();
                        return;
                    }
                    $.when.apply($, q)
                        .done(function () {
                            var results = Array.prototype.slice.call(arguments, 0);
                            Data.testResultsError = false;
                            Data.testResults = new Metrics.CollectionComparison(
                                results.map(function(result,i){
                                    return new Metrics.Collection(result, testRuns[i]);
                                })
                            );
                            Actions.render();
                        });
                });
        }
    };

    Actions.setServerName = function (server) {
        if (Data.serverName == server) {
            return;
        }
        Data.serverName = server;
        Api.setServer(server);
        storage.setItem(STORAGE_KEY_SERVER, server);
        Actions.loadCompareRequests();
    };

    Actions.render = function () {
        View.render(Data);
    };

    $.extend(window.Sparrow.Actions, {
        Data: Data
    }, Actions);
})(window);<|endoftext|>


<commit_before>module.exports = (guild, user) => {
    guild.defaultChannel.sendMessage(`${user.username} was banned!`);
    guild.defaultChannel.sendMessage("Glory to the hammer!");
};
<commit_msg>Update guildBanAdd.js<commit_after>module.exports = (guild, user => {
    guild.defaultChannel.sendMessage(`${user.username} was banned!`);
    guild.defaultChannel.sendMessage("Glory to the hammer!");
};
<|endoftext|>


<commit_before>var App = Ember.Application.create();

App.Boards = ['common', 'intermediate', 'advanced'];

// Models

App.Store = DS.Store.extend({
  revision: 13,
  adapter: EmberCouchDBKit.DocumentAdapter.create({db: 'boards'})
});

App.Store.registerAdapter('App.Attachment', EmberCouchDBKit.AttachmentAdapter.extend({db: 'boards'}));

App.Issue = DS.Model.extend({
  text: DS.attr('string'),
  type: DS.attr('string', {defaultValue: 'issue'}),
  board: DS.belongsTo('App.Position'),
  attachments: DS.hasMany('App.Attachment', {embedded: true})
});

App.Attachment = DS.Model.extend({
  content_type: DS.attr('string'),
  length: DS.attr('number'),
  file_name: DS.attr('string'),
  db: DS.attr('string')
});

App.Position = DS.Model.extend({
  issues: DS.hasMany('App.Issue'),
  type: DS.attr('string', {defaultValue: 'position'})
});

// Routes

App.IndexRoute = Ember.Route.extend({

  setupController: function(controller, model) {
    this._setupPositionHolders();

    this._position();
    this._issue();
  },

  renderTemplate: function() {
    this.render();
    // link particular controller with its outlet
    self = this;
    App.Boards.forEach(function(label) {
       self.render('board',{outlet: label, into: 'index', controller: label});
    });
  },

  _setupPositionHolders: function() {
    self = this;
    App.Boards.forEach(function(type) {
      // set issues into appropriate controller through position model
      position = App.Position.find(type);
      position.one('didLoad', function() {
        self.controllerFor(type).set('position', this);
      });
      // create position documents (as a part of first time initialization)
      if (position.get('store.adapter').is(404, {for: type})) {
        App.Position.createRecord({ id: type }).get('store').commit();
      }
    });
  },

  _position: function(){
    // create a CouchDB `/_change` listener which serves an position documents
    params = { include_docs: true, timeout: 100, filter: 'issues/only_positions'}
    position = EmberCouchDBKit.ChangesFeed.create({ db: 'boards', content: params });

    // all upcoming changes are passed to `_handlePositionChanges` callback through `longpoll` strategy
    position.longpoll(this._handlePositionChanges, this);
  },

  _handlePositionChanges: function(data) {
    self = this;
    data.forEach(function(obj){
      position = self.controllerFor(obj.doc._id).get('position');
      // we should reload particular postion model in case of update is received from another user
      if (position.get('_data.raw._rev') != obj.doc._rev)
        position.reload();
    });
  },

  _issue: function() {
    // create a CouchDB `/_change` issue listener which serves an issues
    params = { include_docs: true, timeout: 100, filter: 'issues/issue'}
    issue = EmberCouchDBKit.ChangesFeed.create({ db: 'boards', content: params });

    // all upcoming changes are passed to `_handleIssueChanges` callback through `fromTail` strategy
    self = this;
    issue.fromTail(function(){
      issue.longpoll(self._handleIssueChanges, self);
    });
  },

  _handleIssueChanges: function(data) {
    self = this;
    // apply received updates
    data.forEach(function(obj){
      issue = App.Issue.find(obj.doc._id);
      if(issue.get('isLoaded')) issue.reload();
    });
  }
});

// Controllers

App.IndexController = Ember.Controller.extend({

  content: Ember.computed.alias('position.issues'),

  createIssue: function(fields) {
    fields.board = App.Position.find(this.get('name'));
    issue = App.Issue.createRecord(fields);
    //issue.set('board', App.Position.find(this.get('name')));
    issue.get('store').commit();

    //issue.on('didCreate', function() {
    //issue.addObserver('id', function(sender, key, value, context, rev) {
    //  this.get('board.issues').pushObject(this);
    //});
  },
  saveMessage: function(model) {
    model.save();
  },
  deleteMessage: function(message) {
    message.deleteRecord();
    message.get('store').commit();

    this.get('content').removeObject(message);
  },
  browseFile: function(view) {
    viewId = view.get('elementId');
    document.getElementById(viewId).click();
  },
  needs: App.Boards
});

App.CommonController       = App.IndexController.extend({ name: 'common' });
App.IntermediateController = App.IndexController.extend({ name: 'intermediate' });
App.AdvancedController     = App.IndexController.extend({ name: 'advanced' });

//  Views

App.NewIssueView = Ember.View.extend({
  tagName: "form",

  create: false,

  attributeBindings: ["style"],

  style: "display:inline",

  _save:  function(event) {
    event.preventDefault();
    if (this.get('create')){
      this.get('controller').send("createIssue", {text: this.get("TextArea.value")});
    }
    this.toggleProperty('create');
  },

  submit: function(event){
    this._save(event);
  },

  keyDown: function(event){
    if(event.keyCode == 13){
      this._save(event);
    }
  }
});

App.FocusedTextArea = Ember.TextArea.extend({
  attributeBindings: ['autofocus'],

  autofocus: 'autofocus'
});

App.CancelView = Ember.View.extend({
  tagName: "span",

  click: function(event){
    event.preventDefault();
    this.set('parentView.create',false);
  }
});

App.DeleteView = Ember.View.extend({
  tagName: "span",

  click: function(event){
    event.preventDefault();
    this.get('controller').send('deleteMessage', this.get('context'));
  }
});

App.AttachmentView = Ember.TextField.extend({
  type: 'file',
  attributeBindings: ["style"],
  style: "display:none",
  change: function(event) {
    id = this.get('elementId')
    console.log(event.target.files);
    var files = event.target.files;

    for (var i = 0, f; f = files[i]; i++) {
      if (!f.type.match('image.*')) {
        continue;
      }
      console.log( f.name, f.type, f.size || 'n/a', f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a');
    }

  }
});

App.IssueView = Ember.View.extend({
  tagName: "form",

  edit: false,

  submit: function(event){
    event.preventDefault();
    if (this.get('edit')){
      this.get('controller').send('saveMessage', this.get("context"));
    }
    this.toggleProperty('edit');
  },

  attributeBindings: ['draggable'],

  draggable: 'true',

  dragStart: function(event) {
    event.dataTransfer.setData('id', this.get('elementId'));
  },

  dragEnter: function(event) {
    event.preventDefault();
    event.target.style.opacity = '0.4';
  },

  dragOver: function(event) {
    event.preventDefault();
  },
  dragLeave: function(event) {
    event.preventDefault();
    event.target.style.opacity = '1';
  },

  drop: function(event) {
    var viewId = event.dataTransfer.getData('id');
    var view = Ember.View.views[viewId];
    var newModel = view.get('context');
    var oldModel = this.get('context');
    var position = this.get('controller.content').toArray().indexOf(oldModel)
    view.get('controller.content').removeObject(newModel);
    thisArray = this.get('controller.content').toArray().insertAt(position, newModel);
    this.set('controller.content.content', thisArray.getEach('_reference'));
    this.set('controller.position.issues.content', thisArray.getEach('_reference'));
    this.get('controller.position').save();

    if(view.get('controller.name') !== this.get('controller.name')){
      newModel.set('board', this.get('controller.name'));
      newModel.get('store').commit();
      viewArray = view.get('controller.content').toArray();
      view.set('controller.content.content', viewArray.getEach('_reference'));
      view.set('controller.position.issues.content', viewArray.getEach('_reference'));
      view.get('controller.position').save();
    }
    event.preventDefault();
    event.target.style.opacity = '1';
  }
});
<commit_msg>Organized entities more carefully<commit_after>var App = Ember.Application.create();

App.Boards = ['common', 'intermediate', 'advanced'];

// Models

App.Store = DS.Store.extend({
  revision: 13,
  adapter: EmberCouchDBKit.DocumentAdapter.create({db: 'boards'})
});

App.Store.registerAdapter('App.Attachment', EmberCouchDBKit.AttachmentAdapter.extend({db: 'boards'}));

App.Issue = DS.Model.extend({
  text: DS.attr('string'),
  type: DS.attr('string', {defaultValue: 'issue'}),
  board: DS.belongsTo('App.Position'),
  attachments: DS.hasMany('App.Attachment', {embedded: true})
});

App.Attachment = DS.Model.extend({
  content_type: DS.attr('string'),
  length: DS.attr('number'),
  file_name: DS.attr('string'),
  db: DS.attr('string')
});

App.Position = DS.Model.extend({
  issues: DS.hasMany('App.Issue'),
  type: DS.attr('string', {defaultValue: 'position'})
});

// Routes

App.IndexRoute = Ember.Route.extend({

  setupController: function(controller, model) {
    this._setupPositionHolders();

    this._position();
    this._issue();
  },

  renderTemplate: function() {
    this.render();
    // link particular controller with its outlet
    self = this;
    App.Boards.forEach(function(label) {
       self.render('board',{outlet: label, into: 'index', controller: label});
    });
  },

  _setupPositionHolders: function() {
    self = this;
    App.Boards.forEach(function(type) {
      // set issues into appropriate controller through position model
      position = App.Position.find(type);
      position.one('didLoad', function() {
        self.controllerFor(type).set('position', this);
      });
      // create position documents (as a part of first time initialization)
      if (position.get('store.adapter').is(404, {for: type})) {
        App.Position.createRecord({ id: type }).get('store').commit();
      }
    });
  },

  _position: function(){
    // create a CouchDB `/_change` listener which serves an position documents
    params = { include_docs: true, timeout: 100, filter: 'issues/only_positions'}
    position = EmberCouchDBKit.ChangesFeed.create({ db: 'boards', content: params });

    // all upcoming changes are passed to `_handlePositionChanges` callback through `longpoll` strategy
    position.longpoll(this._handlePositionChanges, this);
  },

  _handlePositionChanges: function(data) {
    self = this;
    data.forEach(function(obj){
      position = self.controllerFor(obj.doc._id).get('position');
      // we should reload particular postion model in case of update is received from another user
      if (position.get('_data.raw._rev') != obj.doc._rev)
        position.reload();
    });
  },

  _issue: function() {
    // create a CouchDB `/_change` issue listener which serves an issues
    params = { include_docs: true, timeout: 100, filter: 'issues/issue'}
    issue = EmberCouchDBKit.ChangesFeed.create({ db: 'boards', content: params });

    // all upcoming changes are passed to `_handleIssueChanges` callback through `fromTail` strategy
    self = this;
    issue.fromTail(function(){
      issue.longpoll(self._handleIssueChanges, self);
    });
  },

  _handleIssueChanges: function(data) {
    self = this;
    // apply received updates
    data.forEach(function(obj){
      issue = App.Issue.find(obj.doc._id);
      if(issue.get('isLoaded')) issue.reload();
    });
  }
});

// Controllers

App.IndexController = Ember.Controller.extend({

  content: Ember.computed.alias('position.issues'),

  createIssue: function(fields) {
    fields.board = App.Position.find(this.get('name'));
    issue = App.Issue.createRecord(fields);
    //issue.set('board', App.Position.find(this.get('name')));
    issue.get('store').commit();

    //issue.on('didCreate', function() {
    //issue.addObserver('id', function(sender, key, value, context, rev) {
    //  this.get('board.issues').pushObject(this);
    //});
  },
  saveMessage: function(model) {
    model.save();
  },
  deleteMessage: function(message) {
    message.deleteRecord();
    message.get('store').commit();

    this.get('content').removeObject(message);
  },
  browseFile: function(view) {
    viewId = view.get('elementId');
    document.getElementById(viewId).click();
  },
  needs: App.Boards
});

App.CommonController       = App.IndexController.extend({ name: 'common' });
App.IntermediateController = App.IndexController.extend({ name: 'intermediate' });
App.AdvancedController     = App.IndexController.extend({ name: 'advanced' });

//  Views

App.IssueView = Ember.View.extend({
  tagName: "form",
  edit: false,
  attributeBindings: ['draggable'],
  draggable: 'true',

  submit: function(event){
    event.preventDefault();
    if (this.get('edit')){
      this.get('controller').send('saveMessage', this.get("context"));
    }
    this.toggleProperty('edit');
  },

  dragStart: function(event) {
    event.dataTransfer.setData('id', this.get('elementId'));
  },

  dragEnter: function(event) {
    event.preventDefault();
    event.target.style.opacity = '0.4';
  },

  dragOver: function(event) {
    event.preventDefault();
  },
  dragLeave: function(event) {
    event.preventDefault();
    event.target.style.opacity = '1';
  },

  drop: function(event) {
    var viewId = event.dataTransfer.getData('id');
    var view = Ember.View.views[viewId];
    var newModel = view.get('context');
    var oldModel = this.get('context');
    var position = this.get('controller.content').toArray().indexOf(oldModel)
    view.get('controller.content').removeObject(newModel);
    thisArray = this.get('controller.content').toArray().insertAt(position, newModel);
    this.set('controller.content.content', thisArray.getEach('_reference'));
    this.set('controller.position.issues.content', thisArray.getEach('_reference'));
    this.get('controller.position').save();

    if(view.get('controller.name') !== this.get('controller.name')){
      newModel.set('board', this.get('controller.name'));
      newModel.get('store').commit();
      viewArray = view.get('controller.content').toArray();
      view.set('controller.content.content', viewArray.getEach('_reference'));
      view.set('controller.position.issues.content', viewArray.getEach('_reference'));
      view.get('controller.position').save();
    }
    event.preventDefault();
    event.target.style.opacity = '1';
  }
});

App.NewIssueView = Ember.View.extend({

  tagName: "form",
  create: false,
  attributeBindings: ["style"],
  style: "display:inline",

  submit: function(event){
    this._save(event);
  },

  keyDown: function(event){
    if(event.keyCode == 13){
      this._save(event);
    }
  },

  _save: function(event) {
    event.preventDefault();
    if (this.get('create')){
      this.get('controller').send("createIssue", {text: this.get("TextArea.value")});
    }
    this.toggleProperty('create');
  }
});

App.FocusedTextArea = Ember.TextArea.extend({
  attributeBindings: ['autofocus'],
  autofocus: 'autofocus'
});

App.CancelView = Ember.View.extend({
  tagName: "span",

  click: function(event){
    event.preventDefault();
    this.set('parentView.create',false);
  }
});

App.DeleteView = Ember.View.extend({
  tagName: "span",

  click: function(event){
    event.preventDefault();
    this.get('controller').send('deleteMessage', this.get('context'));
  }
});

App.AttachmentView = Ember.TextField.extend({
  type: 'file',
  attributeBindings: ["style"],
  style: "display:none",
  change: function(event) {
    id = this.get('elementId')
    console.log(event.target.files);
    var files = event.target.files;

    for (var i = 0, f; f = files[i]; i++) {
      if (!f.type.match('image.*')) {
        continue;
      }
      console.log( f.name, f.type, f.size || 'n/a', f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a');
    }

  }
});
<|endoftext|>


<commit_before>// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes } from 'react';
import { modules } from 'stripes-loader'; // eslint-disable-line

const Pluggable = (props, context) => {
  const plugins = modules.plugin || [];
  let best;

  for (name of Object.keys(plugins)) {
    const m = plugins[name];
    if (m.pluginType === props.type) {
      best = m;
      if (m.module === context.stripes.plugins[props.type]) break;
    }
  }

  if (best) {
    const Child = context.stripes.connect(best.getModule());
    return <Child {...props} />
  }

  return props.children;
};

Pluggable.contextTypes = {
  stripes: PropTypes.shape({
    hasPerm: PropTypes.func.isRequired,
  }).isRequired,
};

Pluggable.propTypes = {
  type: PropTypes.string.isRequired,
};

export default Pluggable;
<commit_msg>Get rid of obsolete eslint-disable-next-line import/no-unresolved comments. Part of STRIPES-429<commit_after>import React, { PropTypes } from 'react';
import { modules } from 'stripes-loader'; // eslint-disable-line

const Pluggable = (props, context) => {
  const plugins = modules.plugin || [];
  let best;

  for (name of Object.keys(plugins)) {
    const m = plugins[name];
    if (m.pluginType === props.type) {
      best = m;
      if (m.module === context.stripes.plugins[props.type]) break;
    }
  }

  if (best) {
    const Child = context.stripes.connect(best.getModule());
    return <Child {...props} />
  }

  return props.children;
};

Pluggable.contextTypes = {
  stripes: PropTypes.shape({
    hasPerm: PropTypes.func.isRequired,
  }).isRequired,
};

Pluggable.propTypes = {
  type: PropTypes.string.isRequired,
};

export default Pluggable;
<|endoftext|>


<commit_before>// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes } from 'react';
import { modules } from 'stripes-loader'; // eslint-disable-line

const Pluggable = props => {
  const plugins = modules.plugin || [];
  for (name of Object.keys(plugins)) {
    const m = plugins[name];
    if (m.pluginType === props.type) {
      const Child = props.stripes.connect(m.getModule());
      return <Child {...props} />
    }
  }

  return props.children;
};

Pluggable.propTypes = {
  type: PropTypes.string.isRequired,
};

export default Pluggable;
<commit_msg><Pluggable> respects preferred plugin of its type if defined<commit_after>// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes } from 'react';
import { modules } from 'stripes-loader'; // eslint-disable-line

const Pluggable = props => {
  const plugins = modules.plugin || [];
  let best;

  for (name of Object.keys(plugins)) {
    const m = plugins[name];
    if (m.pluginType === props.type) {
      best = m;
      if (m.module === props.stripes.plugins[props.type]) break;
    }
  }

  if (best) {
    const Child = props.stripes.connect(best.getModule());
    return <Child {...props} />
  }

  return props.children;
};

Pluggable.propTypes = {
  type: PropTypes.string.isRequired,
};

export default Pluggable;
<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular.module('vimeoPluginWidget', ['ngRoute', 'infinite-scroll'])
    .config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {

      /**
       * To make href urls safe on mobile
       */
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|cdvfile):/);

      $routeProvider
        .when('/', {
          resolve: {
            videoData: ['DataStore', '$q', 'TAG_NAMES', 'CONTENT_TYPE', 'Location', function (DataStore, $q, TAG_NAMES, CONTENT_TYPE, Location) {
              var deferred = $q.defer();
              var success = function (result) {
                  if (result.data && result.data.content) {
                    if (result.data.content.type && result.data.content.type === CONTENT_TYPE.SINGLE_VIDEO && result.data.content.videoID) {
                      Location.goTo("#/video/" + result.data.content.videoID);
                      deferred.resolve();
                    }
                    else if (result.data.content.type && ((result.data.content.type === CONTENT_TYPE.CHANNEL_FEED) || (result.data.content.type === CONTENT_TYPE.USER_FEED)) && result.data.content.feedID) {
                      Location.goTo("#/feed/" + result.data.content.feedID);
                      deferred.resolve();
                    }
                    else {
                      Location.goTo("#/feed/1");
                      deferred.resolve();
                    }
                  } else {
                    Location.goTo("#/feed/1");
                    deferred.resolve();
                  }
                }
                , error = function (err) {
                  Location.goTo("#/feed/1");
                  deferred.reject();
                };
              DataStore.get(TAG_NAMES.VIMEO_INFO).then(success, error);
            }]
          }
        })
        .when('/feed/:feedId', {
          templateUrl: 'templates/home.html',
          controllerAs: 'WidgetFeed',
          controller: 'WidgetFeedCtrl'
        })
        .when('/video/:videoId', {
          templateUrl: 'templates/Item_Details.html',
          controller: 'WidgetSingleCtrl',
          controllerAs: 'WidgetSingle'

        })
        .otherwise('/');
    }])
    .filter('getImageUrl', ['Buildfire', function (Buildfire) {
      return function (url, width, height, type) {
        if (type == 'resize')
          return Buildfire.imageLib.resizeImage(url, {
            width: width,
            height: height
          });
        else
          return Buildfire.imageLib.cropImage(url, {
            width: width,
            height: height
          });
      }
    }])
    .directive("backgroundImage", ['$filter', function ($filter) {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          var getImageUrlFilter = $filter("getImageUrl");
          var setBackgroundImage = function (backgroundImage) {
            if (backgroundImage) {
              element.css(
                'background', '#010101 url('
                + getImageUrlFilter(backgroundImage, 342, 770, 'resize')
                + ') repeat fixed top center');
            } else {
              element.css('background', 'none');
            }
          };
          attrs.$observe('backgroundImage', function (newValue) {
            setBackgroundImage(newValue);
          });
        }
      };
    }])
    .directive("buildFireCarousel", ["$rootScope", function ($rootScope) {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          $rootScope.$broadcast("Carousel:LOADED");
        }
      };
    }])
    .filter('returnVimeoUrl', ['$sce', function ($sce) {
      return function (uri) {
        var id = uri.split("/").pop();
        return $sce.trustAsResourceUrl("//player.vimeo.com/video/" + id);
      }
    }])
    .filter('returnVideoUrl', [function () {
      return function (uri) {
        var videoId = uri.split("/").pop();
        return "#/video/" + videoId;
      }
    }])
    .directive("triggerNgRepeatRender", [function () {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          var a = $(elem).width();
        }
      };
    }])
    .run(['Location', '$location', function (Location, $location) {
      buildfire.navigation.onBackButtonClick = function () {
        var reg = /^\/feed/;
        if (!($location.path().match(reg))) {
          Location.goTo('#/');
        }
      };

    }]);
})(window.angular, window.buildfire);
<commit_msg>Appended "http" in front of vimeo video url<commit_after>'use strict';

(function (angular, buildfire) {
  angular.module('vimeoPluginWidget', ['ngRoute', 'infinite-scroll'])
    .config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {

      /**
       * To make href urls safe on mobile
       */
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|cdvfile):/);

      $routeProvider
        .when('/', {
          resolve: {
            videoData: ['DataStore', '$q', 'TAG_NAMES', 'CONTENT_TYPE', 'Location', function (DataStore, $q, TAG_NAMES, CONTENT_TYPE, Location) {
              var deferred = $q.defer();
              var success = function (result) {
                  if (result.data && result.data.content) {
                    if (result.data.content.type && result.data.content.type === CONTENT_TYPE.SINGLE_VIDEO && result.data.content.videoID) {
                      Location.goTo("#/video/" + result.data.content.videoID);
                      deferred.resolve();
                    }
                    else if (result.data.content.type && ((result.data.content.type === CONTENT_TYPE.CHANNEL_FEED) || (result.data.content.type === CONTENT_TYPE.USER_FEED)) && result.data.content.feedID) {
                      Location.goTo("#/feed/" + result.data.content.feedID);
                      deferred.resolve();
                    }
                    else {
                      Location.goTo("#/feed/1");
                      deferred.resolve();
                    }
                  } else {
                    Location.goTo("#/feed/1");
                    deferred.resolve();
                  }
                }
                , error = function (err) {
                  Location.goTo("#/feed/1");
                  deferred.reject();
                };
              DataStore.get(TAG_NAMES.VIMEO_INFO).then(success, error);
            }]
          }
        })
        .when('/feed/:feedId', {
          templateUrl: 'templates/home.html',
          controllerAs: 'WidgetFeed',
          controller: 'WidgetFeedCtrl'
        })
        .when('/video/:videoId', {
          templateUrl: 'templates/Item_Details.html',
          controller: 'WidgetSingleCtrl',
          controllerAs: 'WidgetSingle'

        })
        .otherwise('/');
    }])
    .filter('getImageUrl', ['Buildfire', function (Buildfire) {
      return function (url, width, height, type) {
        if (type == 'resize')
          return Buildfire.imageLib.resizeImage(url, {
            width: width,
            height: height
          });
        else
          return Buildfire.imageLib.cropImage(url, {
            width: width,
            height: height
          });
      }
    }])
    .directive("backgroundImage", ['$filter', function ($filter) {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          var getImageUrlFilter = $filter("getImageUrl");
          var setBackgroundImage = function (backgroundImage) {
            if (backgroundImage) {
              element.css(
                'background', '#010101 url('
                + getImageUrlFilter(backgroundImage, 342, 770, 'resize')
                + ') repeat fixed top center');
            } else {
              element.css('background', 'none');
            }
          };
          attrs.$observe('backgroundImage', function (newValue) {
            setBackgroundImage(newValue);
          });
        }
      };
    }])
    .directive("buildFireCarousel", ["$rootScope", function ($rootScope) {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          $rootScope.$broadcast("Carousel:LOADED");
        }
      };
    }])
    .filter('returnVimeoUrl', ['$sce', function ($sce) {
      return function (uri) {
        var id = uri.split("/").pop();
        return $sce.trustAsResourceUrl("http://player.vimeo.com/video/" + id);
      }
    }])
    .filter('returnVideoUrl', [function () {
      return function (uri) {
        var videoId = uri.split("/").pop();
        return "#/video/" + videoId;
      }
    }])
    .directive("triggerNgRepeatRender", [function () {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          var a = $(elem).width();
        }
      };
    }])
    .run(['Location', '$location', function (Location, $location) {
      buildfire.navigation.onBackButtonClick = function () {
        var reg = /^\/feed/;
        if (!($location.path().match(reg))) {
          Location.goTo('#/');
        }
      };

    }]);
})(window.angular, window.buildfire);
<|endoftext|>