<commit_before>'use strict';

const dbDsl = require('dumonda-me-server-test-util').dbDSL;
const db = require('dumonda-me-server-test-util').db;
const eMail = require('dumonda-me-server-lib').eMail;
const sinon = require('sinon');
const testee = requireSrc('invitations');
const fs = require('fs');
const tmp = require('tmp');

describe('Send invitations emails', function () {

    let stubSendEMail, sandbox;

    beforeEach(async function () {
        let stubFileSync;
        await dbDsl.init(6);
        sandbox = sinon.sandbox.create();
        stubSendEMail = sandbox.stub(eMail, 'sendEMail');
        stubSendEMail.resolves({});
        stubFileSync = sandbox.stub(tmp, 'fileSync');
        stubFileSync.returns({name: 'test', Body: 'test'});
        sandbox.stub(fs, 'writeFileSync');

    });

    afterEach(function () {
        sandbox.restore();
    });

    it('Send invitation', async function () {
        dbDsl.invitationSentBeforeRegistration('3',
            [{emailOfUserToInvite: 'info@dumonda.me', sendingEmailPending: true}]);
        await dbDsl.sendToDb();

        await testee.sendInvitations();

        stubSendEMail.calledWith("invitePerson", {
            name: `user Meier3`, userImage: sinon.match.any,
            unsubscribeLink: `${process.env.DUMONDA_ME_DOMAIN}unsubscribe/invitedUser/info@dumonda.me`
        }, 'de', 'info@dumonda.me').should.be.true;

        let notification = await db.cypher()
            .match(`(invitedUser:InvitedUser)<-[:SENDING_EMAIL_PENDING]-(:User {userId: '3'})`)
            .return(`invitedUser`).end().send();
        notification.length.should.equals(0);
    });
});
<commit_msg>Test sending multiple invitations for a user.<commit_after>'use strict';

const dbDsl = require('dumonda-me-server-test-util').dbDSL;
const db = require('dumonda-me-server-test-util').db;
const eMail = require('dumonda-me-server-lib').eMail;
const sinon = require('sinon');
const testee = requireSrc('invitations');
const fs = require('fs');
const tmp = require('tmp');

describe('Send invitations emails', function () {

    let stubSendEMail, sandbox;

    beforeEach(async function () {
        let stubFileSync;
        await dbDsl.init(6);
        sandbox = sinon.sandbox.create();
        stubSendEMail = sandbox.stub(eMail, 'sendEMail');
        stubSendEMail.resolves({});
        stubFileSync = sandbox.stub(tmp, 'fileSync');
        stubFileSync.returns({name: 'test', Body: 'test'});
        sandbox.stub(fs, 'writeFileSync');

    });

    afterEach(function () {
        sandbox.restore();
    });

    it('Sending invitation', async function () {
        dbDsl.invitationSentBeforeRegistration('3',
            [{emailOfUserToInvite: 'info@dumonda.me', sendingEmailPending: true}]);
        await dbDsl.sendToDb();

        await testee.sendInvitations();

        stubSendEMail.calledWith("invitePerson", {
            name: `user Meier3`, userImage: sinon.match.any,
            unsubscribeLink: `${process.env.DUMONDA_ME_DOMAIN}unsubscribe/invitedUser/info@dumonda.me`
        }, 'de', 'info@dumonda.me').should.be.true;

        let notification = await db.cypher()
            .match(`(invitedUser:InvitedUser)<-[:SENDING_EMAIL_PENDING]-(:User {userId: '3'})`)
            .return(`invitedUser`).end().send();
        notification.length.should.equals(0);
    });

    it('Sending multiple invitations from same user', async function () {
        dbDsl.invitationSentBeforeRegistration('3',
            [{emailOfUserToInvite: 'info@dumonda.me', sendingEmailPending: true}]);
        dbDsl.invitationSentBeforeRegistration('3',
            [{emailOfUserToInvite: 'info2@dumonda.me', sendingEmailPending: true}]);
        dbDsl.invitationSentBeforeRegistration('3',
            [{emailOfUserToInvite: 'info3@dumonda.me', sendingEmailPending: true}]);
        await dbDsl.sendToDb();

        await testee.sendInvitations();

        stubSendEMail.calledWith("invitePerson", {
            name: `user Meier3`, userImage: sinon.match.any,
            unsubscribeLink: `${process.env.DUMONDA_ME_DOMAIN}unsubscribe/invitedUser/info@dumonda.me`
        }, 'de', 'info@dumonda.me').should.be.true;

        stubSendEMail.calledWith("invitePerson", {
            name: `user Meier3`, userImage: sinon.match.any,
            unsubscribeLink: `${process.env.DUMONDA_ME_DOMAIN}unsubscribe/invitedUser/info2@dumonda.me`
        }, 'de', 'info2@dumonda.me').should.be.true;

        stubSendEMail.calledWith("invitePerson", {
            name: `user Meier3`, userImage: sinon.match.any,
            unsubscribeLink: `${process.env.DUMONDA_ME_DOMAIN}unsubscribe/invitedUser/info3@dumonda.me`
        }, 'de', 'info3@dumonda.me').should.be.true;

        let notification = await db.cypher()
            .match(`(invitedUser:InvitedUser)<-[:SENDING_EMAIL_PENDING]-(:User {userId: '3'})`)
            .return(`invitedUser`).end().send();
        notification.length.should.equals(0);
    });
});
<|endoftext|>


<commit_before>"use strict";

var moment = require('moment');
var midNight = moment().startOf('day').format('YYYY-MM-DD HH:mm:ss');
var midYear = moment().startOf('year').format('YYYY-MM-DD HH:mm:ss');

var template = {
  weibo: [
    {
      limit: '10',
      rightString: '10秒前'
    },
    {
      above: '10',
      limit: '60',
      unit: 'second',
      rightString: '秒前'
    },
    {
      above: '60',
      limit: '3600',
      unit: 'minute',
      rightString: '分钟前'
    },
    {
      above: '3600',
      limit: moment().unix() - moment(midNight).unix(),
      unit: 'HH:mm',
      leftString: '今天'
    },
    {
      limit: moment().unix() - moment(midYear).unix(),
      above: moment().unix() - moment(midNight).unix(),
      unit: 'MMM Do HH:mm'
    },
    {
      above: moment().unix() - moment(midYear).unix(),
      unit: 'YYYY-MM-DD HH:mm'
    }
  ],
  weiboMobile: [
    {
      limit: '10',
      rightString: '10秒前'
    },
    {
      above: '10',
      limit: '60',
      unit: 'second',
      rightString: '秒前'
    },
    {
      above: '60',
      limit: '3600',
      unit: 'minute',
      rightString: '分钟前'
    },
    {
      above: '3600',
      limit: moment().unix() - moment(midNight).unix(),
      unit: 'HH:mm',
      leftString: '今天'
    },
    {
      above: moment().unix() - moment(midNight).unix(),
      limit: moment().unix() - moment(midNight).unix() + 86400,
      unit: 'HH:mm',
      leftString: '昨天'
    },
    {
      limit: moment().unix() - moment(midYear).unix(),
      above: moment().unix() - moment(midNight).unix() + 86400,
      unit: 'M-D'
    },
    {
      above: moment().unix() - moment(midYear).unix(),
      unit: 'YY-MM-DD'
    }
  ],
  wechat: [{
    limit: '60',
    rightString: '1分钟前'
    },
    {
      above: '60',
      limit: '3600',
      unit: 'minute',
      rightString: '分钟前'
    },
    {
      above: '3600',
      limit: moment().unix() - moment(midNight).unix(),
      unit: 'hour',
      rightString: '小时前'
    },
    {
      above: moment().unix() - moment(midNight).unix(),
      unit: 'date',
      rightString: '天前'
    }
  ]
};
module.exports = template;<commit_msg>fix bug<commit_after>"use strict";

var moment = require('moment');
var midNight = moment().startOf('day').unix();
var midYear = moment().startOf('year').unix();

var template = {
  weibo: [
    {
      limit: '10',
      rightString: '10秒前'
    },
    {
      above: '10',
      limit: '60',
      unit: 'second',
      rightString: '秒前'
    },
    {
      above: '60',
      limit: '3600',
      unit: 'minute',
      rightString: '分钟前'
    },
    {
      above: '3600',
      limit: moment().unix() - midNight,
      unit: 'HH:mm',
      leftString: '今天'
    },
    {
      limit: moment().unix() - midYear,
      above: moment().unix() - midNight,
      unit: 'MMM Do HH:mm'
    },
    {
      above: moment().unix() - midYear,
      unit: 'YYYY-MM-DD HH:mm'
    }
  ],
  weiboMobile: [
    {
      limit: '10',
      rightString: '10秒前'
    },
    {
      above: '10',
      limit: '60',
      unit: 'second',
      rightString: '秒前'
    },
    {
      above: '60',
      limit: '3600',
      unit: 'minute',
      rightString: '分钟前'
    },
    {
      above: '3600',
      limit: moment().unix() - midNight,
      unit: 'HH:mm',
      leftString: '今天'
    },
    {
      above: moment().unix() - midNight,
      limit: moment().unix() - midNight + 86400,
      unit: 'HH:mm',
      leftString: '昨天'
    },
    {
      limit: moment().unix() - midYear,
      above: moment().unix() - midNight + 86400,
      unit: 'M-D'
    },
    {
      above: moment().unix() - midYear,
      unit: 'YY-MM-DD'
    }
  ],
  wechat: [{
    limit: '60',
    rightString: '1分钟前'
    },
    {
      above: '60',
      limit: '3600',
      unit: 'minute',
      rightString: '分钟前'
    },
    {
      above: '3600',
      limit: moment().unix() - midNight,
      unit: 'hour',
      rightString: '小时前'
    },
    {
      above: moment().unix() - midNight,
      unit: 'date',
      rightString: '天前'
    }
  ]
};
module.exports = template;<|endoftext|>


<commit_before>/*!
 * jQuery Destaque - a simple slideshow plugin with built-in parallax effect
 * https://github.com/globocom/destaque
 * version: 0.1.0
 */

;(function ($, window, document, undefined) {

  $.fn.destaque = function(params) {
    var params = $.extend({}, $.fn.destaque.options, params);
    return new Destaque(this, params);
  };

  $.fn.destaque.options = {
    currentSlide: 0,
    slideSpeed: 1000,
    slideMovement: 150,
    slideDirection: "toLeft",
    elementSpeed: 1000,
    autoSlideDelay: 3000,
    resumeSlideDelay: 250,
    stopOnMouseOver: true,
    easingType: "easeInOutExpo",
    itemDefaultZIndex: 10,
    itemSelector: "div.item",
    itemLoadedClass: "loaded",
    activeItemClass: "active",
    itemForegroundElementSelector: ".foreground img",

    // Callbacks
    onInit: function (slideshow) {},
    onResize: function (slideshow) {},
    onPause: function(slideshow) {},
    onResume: function(slideshow) {},
    onSlideLoad: function(slideshow, item, idx) {},
    beforePageUpdate: function(slideshow, pageData) {},
    onPageUpdate: function(slideshow, pageData) {}
  };

  var Destaque = function (element, params) {
    this.element = $(element);
    this.params = params;

    this.params.initialized = false;
    this.params.mouseOver = false;
    this.params.animating = false;

    this.params.autoId = 0;
    this.params.autoTimeStamp = 0;

    this._initElements();
    this._initListeners();

    this.params.onInit(this);
  };

  Destaque.prototype = {
    pause: function() {
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = true;
        window.clearTimeout(params.autoId);
        params.onPause(this);
      }
    },

    resume: function() {
      var self = this;
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = false;

        var timeout = 0;

        if (params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp) < 0) {
          timeout = params.resumeSlideDelay;
        } else {
          timeout = params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp);
        }

        params.autoId = window.setTimeout(function() {
          self._slideElementsOut();
        }, timeout);

        params.onResume(this);
      }
    },

    restart: function() {
      this.goTo(0);
    },

    slideSetAndMove: function(direction, targetToClear) {
      var params = this.params;

      if (!params.animating) {
        if (direction === "toLeft") {
          params.slideDirection = "toLeft";
          params.elementDirection = "fromLeft";
          this.element.removeClass("right").addClass("left");
        } else {
          params.slideDirection = "toRight";
          params.elementDirection = "fromRight";
          this.element.removeClass("left").addClass("right");
        }

        this._setElementPositions(true);
        this._slideElementsOut(targetToClear);
      }
    },

    goTo: function(slideNumber) {
      var params = this.params;
      var current = params.currentSlide;
      var currentSlide = this._currentSlide();

      if (slideNumber < 0 || slideNumber > params.slideSum) {
        return;
      }

      if (slideNumber > current || (current == params.slideSum && slideNumber == 0)) {
        params.currentSlide = slideNumber - 1;
        this.slideSetAndMove('toLeft', currentSlide);

      } else if (slideNumber < current) {
        params.currentSlide = slideNumber + 1;
        this.slideSetAndMove('toRight', currentSlide);
      }
    },

    refresh: function(newParams) {
      this.pause();
      this.params = $.extend({}, this.params, (newParams || {}));

      this.element.find(this.params.itemSelector + "." + this.params.activeItemClass).removeClass(this.params.activeItemClass);
      this.element.find(this.params.itemSelector).removeAttr("style").removeClass(this.params.itemLoadedClass).hide();
      this.element.find(this.params.itemSelector + " " + this.params.itemForegroundElementSelector).removeAttr("style");

      this.params.initialized = false;
      this._initElements();
      this.resume();
    },

    _initListeners: function() {
      this._initPaginationListeners();
      this._initMouseListeners();
      this._initKeyboardListeners();
      this._initMobileListeners();
      this._initWindowListeners();
    },

    _initPaginationListeners: function () {
      var self = this;

      if (!this.params.controlsSelector) {
        return;
      }
      $(this.params.controlsSelector).each(function() {
        $(this).bind("click.destaque", function(e) {
          e.preventDefault();

          var direction = $(this).attr("rel") === "prev" ? "toRight" : "toLeft";
          self.slideSetAndMove(direction);
        });
      });
    },

    _initMobileListeners: function() {
      var self = this;

      this.element.bind("swipeleft.destaque", function(e) {
        self.slideSetAndMove("toLeft");
       });

      this.element.bind("swiperight.destaque", function (e) {
        self.slideSetAndMove("toRight");
      });
    },

    _initMouseListeners: function () {
      var params = this.params;
      var self = this;

      if (params.slideSum > 1) {
        if (params.stopOnMouseOver) {
          this.element.mouseover(function() {
            self.pause();
          });

          this.element.mouseleave(function() {
            self.resume();
          });
        }
      }
    },

    _initKeyboardListeners: function() {
      var self = this;
      $("body").bind("keydown.destaque", function(e) {
        if (e.keyCode === 37) {
          self.slideSetAndMove("toRight");
        } else {
          if (e.keyCode === 39) {
            self.slideSetAndMove("toLeft");
          }
        }
      });
    },

    _initWindowListeners: function() {
      var self = this;

      $(window).bind("resize.destaque", function() {
        self.params.onResize(self);
      });
    },

    _initElements: function () {
      var element = this.element;
      var params = this.params;

      if (!params.initialized) {
        params.baseSize = element.width();
        params.slideSum = element.find(this.params.itemSelector).length;
        params.elementDirection = params.slideDirection === "toLeft" ? "fromLeft" : "toLeft";
        if (params.currentSlide < 0 || params.currentSlide >= params.slideSum) {
          params.currentSlide = 0;
        }

        this._initSlide();

        params.initialized = true;
      }
    },

    _initSlide: function() {
      var self = this;
      var params = this.params;

      this.element.find(params.itemSelector).each(function() {
        $(this).data("zIndex", params.itemDefaultZIndex).css({zIndex: params.itemDefaultZIndex});
      });

      this.element.find(params.itemForegroundElementSelector).each(function (idx, e) {
        var e = $(this);

        var initialX = parseInt(e.css("left"), 10) + (self.element.width() - params.baseSize) / 2;
        var initialY = parseInt(e.css("top"), 10);

        e.css({top: initialY, left: params.baseSize});
        e.data("xPos", initialX).data("yPos", initialY).data("slidePos", 9999);
      });

      this._loadSlide();
      this._currentSlide().addClass(params.activeItemClass).show();
      this._slideElementsIn();

      params.autoTimeStamp = new Date().getTime();
    },

    _setElementPositions: function(justCalculate) {
      var params = this.params;
      var element, pos = 0;

      this._currentSlide().find(params.itemForegroundElementSelector).each(function(i) {
        element = $(this);

        if (params.elementDirection === "fromLeft") {
          pos = params.baseSize + (i * params.baseSize) - (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        } else {
          pos = -params.baseSize - (i * params.baseSize) + (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        }

        element.data("slidePos", pos);

        if (!justCalculate) {
          element.css({left: pos});
        }
      });
    },

    _moveSlide: function(targetToClear) {
      var self = this;
      var params = this.params;

      var initialPosition = 0;
      var outPosition = 0;
      var current = this._currentSlide();
      var next = this._nextSlide();
      params.animating = true;

      if (params.slideDirection === "toLeft") {
        outPosition = -params.slideMovement;
        next.css({left: params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      } else {
        outPosition = params.slideMovement;
        next.css({left: -params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      }

      next.stop().animate({left: initialPosition}, params.slideSpeed, params.easingType, function() {
        next.addClass(params.activeItemClass);
      });

      this._clearTarget(current, outPosition);
      if (targetToClear) {
        this._clearTarget(targetToClear, outPosition);
      }

      this._updateCurrentSlide();
    },

    _clearTarget: function(target, outPosition) {
      var params = this.params;
      target.css({zIndex: params.itemDefaultZIndex}).stop().animate({left: outPosition}, params.slideSpeed, params.easingType, function() {
        $(this).removeClass(params.activeItemClass).hide();
      });
    },

    _updatePagers: function(callback) {
      var params = this.params;
      var data = {
        currentSlide: params.currentSlide,
        totalSlides:  params.slideSum
      };

      return params[callback](this, data);
    },

    _currentSlide: function() {
      var params = this.params;
      return this.element.find(params.itemSelector).eq(params.currentSlide);
    },

    _previousPage: function() {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      } else {
        if (params.currentSlide < params.slideSum - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      }
    },

    _nextPage: function(idx) {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide < this.element.find(params.itemSelector).length - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      } else {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      }
    },

    _nextSlide: function() {
      return this.element.find(this.params.itemSelector).eq(this._nextPage());
    },

    _updateCurrentSlide: function() {
      this.params.currentSlide = this._nextPage();

      this._loadSlide();
      this._slideElementsIn();
    },

    _loadSlide: function() {
      var self = this;
      var params = this.params;

      var slidesIdx = [
        params.currentSlide,
        this._previousPage(),
        this._nextPage()
      ];

      var i, idx;
      for (i = 0; i < slidesIdx.length; i++) {
        idx = slidesIdx[i];

        this.element.find(params.itemSelector).eq(idx).each(function() {
          if (!$(this).hasClass(params.itemLoadedClass)) {
            $(this).addClass(params.itemLoadedClass);
            params.onSlideLoad(self, this, idx);
          }
        });
      }
    },

    _slideElementsIn: function() {
      var self = this;
      var params = this.params;

      var current = this._currentSlide();
      var elementNum = current.find(params.itemForegroundElementSelector).length;

      this._setElementPositions();

      current.each(function() {
        $(this).find(params.itemForegroundElementSelector).each(function(i) {
          if (!params.initialized) {
            $(this).css({left: $(this).data("xPos"), top: $(this).data("yPos")});

            if (elementNum - 1 === i && !params.mouseOver && params.slideSum > 1) {
              params.autoId = window.setTimeout(function() {
                self._slideElementsOut();
              }, params.autoSlideDelay);

              params.animating = false;
            }
          } else {
            params.animating = true;

            $(this).stop().css({left: $(this).data("slidePos"), top: $(this).data("yPos")});
            $(this).animate({left: $(this).data("xPos")}, params.elementSpeed, params.easingType, function() {
              if (elementNum - 1 === i && params.slideSum > 1) {
                if (!params.mouseOver) {
                  params.autoId = window.setTimeout(function() {
                    self._slideElementsOut();
                  }, params.autoSlideDelay);
                }

                params.autoTimeStamp = new Date().getTime();
                params.animating = false;
              }
            });
          }
        });
      });
    },

    _slideElementsOut: function(targetToClear) {
      var params = this.params;

      if (params.slideSum < 2) {
        return;
      }

      if (this._updatePagers("beforePageUpdate") === false) {
        return;
      };

      params.animating = true;
      window.clearTimeout(params.autoId);

      this.element.find(params.itemSelector + " " + params.itemForegroundElementSelector).removeAttr("style");
      this.element.find(params.itemSelector + "." + params.activeItemClass + " " + params.itemForegroundElementSelector).each(function() {
        var pos = params.elementDirection === "fromLeft" ? $(this).data("slidePos") * -1 + params.baseSize - $(this).width() : $(this).data("slidePos") * -1;
        $(this).stop().animate({left: pos}, params.elementSpeed, params.easingType);
      });

      this._moveSlide(targetToClear);
      this._updatePagers("onPageUpdate");
    }
  };

})(jQuery, window, document, undefined);<commit_msg>Fixed initialization code to make multiple instances work on the same document on IE/Firefox 3.x.<commit_after>/*!
 * jQuery Destaque - a simple slideshow plugin with built-in parallax effect
 * https://github.com/globocom/destaque
 * version: 0.1.0
 */

;(function ($, window, document, undefined) {

  $.fn.destaque = function(params) {
    var params = $.extend({}, $.fn.destaque.options, params);
    return new Destaque(this, params);
  };

  $.fn.destaque.options = {
    currentSlide: 0,
    slideSpeed: 1000,
    slideMovement: 150,
    slideDirection: "toLeft",
    elementSpeed: 1000,
    autoSlideDelay: 3000,
    resumeSlideDelay: 250,
    stopOnMouseOver: true,
    easingType: "easeInOutExpo",
    itemDefaultZIndex: 10,
    itemSelector: "div.item",
    itemLoadedClass: "loaded",
    activeItemClass: "active",
    itemForegroundElementSelector: ".foreground img",

    // Callbacks
    onInit: function (slideshow) {},
    onResize: function (slideshow) {},
    onPause: function(slideshow) {},
    onResume: function(slideshow) {},
    onSlideLoad: function(slideshow, item, idx) {},
    beforePageUpdate: function(slideshow, pageData) {},
    onPageUpdate: function(slideshow, pageData) {}
  };

  var Destaque = function (element, params) {
    this.element = $(element);
    this.params = params;

    this.params.initialized = false;
    this.params.mouseOver = false;
    this.params.animating = false;

    this.params.autoId = 0;
    this.params.autoTimeStamp = 0;

    this._initElements();
    this._initListeners();

    this.params.onInit(this);
  };

  Destaque.prototype = {
    pause: function() {
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = true;
        window.clearTimeout(params.autoId);
        params.onPause(this);
      }
    },

    resume: function() {
      var self = this;
      var params = this.params;

      if (!params.animating) {
        params.mouseOver = false;

        var timeout = 0;

        if (params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp) < 0) {
          timeout = params.resumeSlideDelay;
        } else {
          timeout = params.autoSlideDelay - (new Date().getTime() - params.autoTimeStamp);
        }

        params.autoId = window.setTimeout(function() {
          self._slideElementsOut();
        }, timeout);

        params.onResume(this);
      }
    },

    restart: function() {
      this.goTo(0);
    },

    slideSetAndMove: function(direction, targetToClear) {
      var params = this.params;

      if (!params.animating) {
        if (direction === "toLeft") {
          params.slideDirection = "toLeft";
          params.elementDirection = "fromLeft";
          this.element.removeClass("right").addClass("left");
        } else {
          params.slideDirection = "toRight";
          params.elementDirection = "fromRight";
          this.element.removeClass("left").addClass("right");
        }

        this._setElementPositions(true);
        this._slideElementsOut(targetToClear);
      }
    },

    goTo: function(slideNumber) {
      var params = this.params;
      var current = params.currentSlide;
      var currentSlide = this._currentSlide();

      if (slideNumber < 0 || slideNumber > params.slideSum) {
        return;
      }

      if (slideNumber > current || (current == params.slideSum && slideNumber == 0)) {
        params.currentSlide = slideNumber - 1;
        this.slideSetAndMove('toLeft', currentSlide);

      } else if (slideNumber < current) {
        params.currentSlide = slideNumber + 1;
        this.slideSetAndMove('toRight', currentSlide);
      }
    },

    refresh: function(newParams) {
      this.pause();
      this.params = $.extend({}, this.params, (newParams || {}));

      this.element.find(this.params.itemSelector + "." + this.params.activeItemClass).removeClass(this.params.activeItemClass);
      this.element.find(this.params.itemSelector).removeAttr("style").removeClass(this.params.itemLoadedClass).hide();
      this.element.find(this.params.itemSelector + " " + this.params.itemForegroundElementSelector).removeAttr("style");

      this.params.initialized = false;
      this._initElements();
      this.resume();
    },

    _initListeners: function() {
      this._initPaginationListeners();
      this._initMouseListeners();
      this._initKeyboardListeners();
      this._initMobileListeners();
      this._initWindowListeners();
    },

    _initPaginationListeners: function () {
      var self = this;

      if (!this.params.controlsSelector) {
        return;
      }
      $(this.params.controlsSelector).each(function() {
        $(this).bind("click.destaque", function(e) {
          e.preventDefault();

          var direction = $(this).attr("rel") === "prev" ? "toRight" : "toLeft";
          self.slideSetAndMove(direction);
        });
      });
    },

    _initMobileListeners: function() {
      var self = this;

      this.element.bind("swipeleft.destaque", function(e) {
        self.slideSetAndMove("toLeft");
       });

      this.element.bind("swiperight.destaque", function (e) {
        self.slideSetAndMove("toRight");
      });
    },

    _initMouseListeners: function () {
      var params = this.params;
      var self = this;

      if (params.slideSum > 1) {
        if (params.stopOnMouseOver) {
          this.element.mouseover(function() {
            self.pause();
          });

          this.element.mouseleave(function() {
            self.resume();
          });
        }
      }
    },

    _initKeyboardListeners: function() {
      var self = this;
      $("body").bind("keydown.destaque", function(e) {
        if (e.keyCode === 37) {
          self.slideSetAndMove("toRight");
        } else {
          if (e.keyCode === 39) {
            self.slideSetAndMove("toLeft");
          }
        }
      });
    },

    _initWindowListeners: function() {
      var self = this;

      $(window).bind("resize.destaque", function() {
        self.params.onResize(self);
      });
    },

    _initElements: function () {
      var element = this.element;
      var params = this.params;

      if (!params.initialized) {
        params.baseSize = element.width();
        params.slideSum = element.find(this.params.itemSelector).length;
        params.elementDirection = params.slideDirection === "toLeft" ? "fromLeft" : "toLeft";
        if (params.currentSlide < 0 || params.currentSlide >= params.slideSum) {
          params.currentSlide = 0;
        }

        this._initSlide();

        params.initialized = true;
      }
    },

    _initSlide: function() {
      var self = this;
      var params = this.params;

      this.element.find(params.itemSelector).each(function() {
        $(this).data("zIndex", params.itemDefaultZIndex).css({zIndex: params.itemDefaultZIndex});
      });

      this.element.find(params.itemForegroundElementSelector).each(function (idx, e) {
        var e = $(this);

        var initialX = parseInt(e.css("left"), 10) || 0;

        e.css({left: initialX});
        e.data("xPos", initialX).data("slidePos", 9999);
      });

      this._loadSlide();
      this._currentSlide().addClass(params.activeItemClass).show();
      this._slideElementsIn();

      params.autoTimeStamp = new Date().getTime();
    },

    _setElementPositions: function(justCalculate) {
      var params = this.params;
      var element, pos = 0;

      this._currentSlide().find(params.itemForegroundElementSelector).each(function(i) {
        element = $(this);

        if (params.elementDirection === "fromLeft") {
          pos = params.baseSize + (i * params.baseSize) - (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        } else {
          pos = -params.baseSize - (i * params.baseSize) + (i > 0 ? parseInt(element.data("xPos"), 10) : 0);
        }

        element.data("slidePos", pos);

        if (!justCalculate) {
          element.css({left: pos});
        }
      });
    },

    _moveSlide: function(targetToClear) {
      var self = this;
      var params = this.params;

      var initialPosition = 0;
      var outPosition = 0;
      var current = this._currentSlide();
      var next = this._nextSlide();
      params.animating = true;

      if (params.slideDirection === "toLeft") {
        outPosition = -params.slideMovement;
        next.css({left: params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      } else {
        outPosition = params.slideMovement;
        next.css({left: -params.baseSize, zIndex: params.itemDefaultZIndex + 1}).show();
      }

      next.stop().animate({left: initialPosition}, params.slideSpeed, params.easingType, function() {
        next.addClass(params.activeItemClass);
      });

      this._clearTarget(current, outPosition);
      if (targetToClear) {
        this._clearTarget(targetToClear, outPosition);
      }

      this._updateCurrentSlide();
    },

    _clearTarget: function(target, outPosition) {
      var params = this.params;
      target.css({zIndex: params.itemDefaultZIndex}).stop().animate({left: outPosition}, params.slideSpeed, params.easingType, function() {
        $(this).removeClass(params.activeItemClass).hide();
      });
    },

    _updatePagers: function(callback) {
      var params = this.params;
      var data = {
        currentSlide: params.currentSlide,
        totalSlides:  params.slideSum
      };

      return params[callback](this, data);
    },

    _currentSlide: function() {
      var params = this.params;
      return this.element.find(params.itemSelector).eq(params.currentSlide);
    },

    _previousPage: function() {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      } else {
        if (params.currentSlide < params.slideSum - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      }
    },

    _nextPage: function(idx) {
      var params = this.params;

      if (params.slideDirection === "toLeft") {
        if (params.currentSlide < this.element.find(params.itemSelector).length - 1) {
          return params.currentSlide + 1;
        } else {
          return 0;
        }
      } else {
        if (params.currentSlide > 0) {
          return params.currentSlide - 1;
        } else {
          return this.element.find(params.itemSelector).length - 1;
        }
      }
    },

    _nextSlide: function() {
      return this.element.find(this.params.itemSelector).eq(this._nextPage());
    },

    _updateCurrentSlide: function() {
      this.params.currentSlide = this._nextPage();

      this._loadSlide();
      this._slideElementsIn();
    },

    _loadSlide: function() {
      var self = this;
      var params = this.params;

      var slidesIdx = [
        params.currentSlide,
        this._previousPage(),
        this._nextPage()
      ];

      var i, idx;
      for (i = 0; i < slidesIdx.length; i++) {
        idx = slidesIdx[i];

        this.element.find(params.itemSelector).eq(idx).each(function() {
          if (!$(this).hasClass(params.itemLoadedClass)) {
            $(this).addClass(params.itemLoadedClass);
            params.onSlideLoad(self, this, idx);
          }
        });
      }
    },

    _slideElementsIn: function() {
      var self = this;
      var params = this.params;

      var current = this._currentSlide();
      var elementNum = current.find(params.itemForegroundElementSelector).length;

      this._setElementPositions();

      current.each(function() {
        $(this).find(params.itemForegroundElementSelector).each(function(i) {
          if (!params.initialized) {
            $(this).css({left: $(this).data("xPos")});

            if (elementNum - 1 === i && !params.mouseOver && params.slideSum > 1) {
              params.autoId = window.setTimeout(function() {
                self._slideElementsOut();
              }, params.autoSlideDelay);

              params.animating = false;
            }
          } else {
            params.animating = true;

            $(this).stop().css({left: $(this).data("slidePos")});
            $(this).animate({left: $(this).data("xPos")}, params.elementSpeed, params.easingType, function() {
              if (elementNum - 1 === i && params.slideSum > 1) {
                if (!params.mouseOver) {
                  params.autoId = window.setTimeout(function() {
                    self._slideElementsOut();
                  }, params.autoSlideDelay);
                }

                params.autoTimeStamp = new Date().getTime();
                params.animating = false;
              }
            });
          }
        });
      });
    },

    _slideElementsOut: function(targetToClear) {
      var params = this.params;

      if (params.slideSum < 2) {
        return;
      }

      if (this._updatePagers("beforePageUpdate") === false) {
        return;
      };

      params.animating = true;
      window.clearTimeout(params.autoId);

      this.element.find(params.itemSelector + " " + params.itemForegroundElementSelector).removeAttr("style");
      this.element.find(params.itemSelector + "." + params.activeItemClass + " " + params.itemForegroundElementSelector).each(function() {
        var pos = params.elementDirection === "fromLeft" ? $(this).data("slidePos") * -1 + params.baseSize - $(this).width() : $(this).data("slidePos") * -1;
        $(this).stop().animate({left: pos}, params.elementSpeed, params.easingType);
      });

      this._moveSlide(targetToClear);
      this._updatePagers("onPageUpdate");
    }
  };

})(jQuery, window, document, undefined);
<|endoftext|>


<commit_before>
/*global jQuery, ref_copy_self $ */

/** HTTP REST client plugin for jQuery */
(function ( $, Q ) {

	// Simply do nothing if Q is not available
	if( Q === undefined ) {
		Q = function noop(x) { return x; };
	}

	/** Copy object */
	function copy(o) {
		return JSON.parse(JSON.stringify(o));
	}

	/** Resource constructor
	 * @param obj {object} The resource object
	 */
	function Resource(obj) {
		//console.log( 'at new Resource(): obj = ' + JSON.stringify(obj) );
		var self = this;
		obj = copy(obj);
		ref_copy_self(self, obj);
	}

	/**
	 * Returns a copy of variable `from` with any child objects with a property `$ref`
	 * recursively converted as `function(opts)` which will call `Resource.get($ref, opts)`.
	 */
	function ref_copy(from) {
		//console.log( 'at ref_copy(): from = ' + JSON.stringify(from) );
		//console.log( 'typeof from = ' + (typeof from) );

		var to;

		// Handle arrays
		if( from && (typeof from === 'object') && (from instanceof Array) ) {
			//console.log( '^ from is Array: ' + JSON.stringify(from) );

			to = from.map(ref_copy);

		// Convert objects with a property `$ref` as a function shortcut to `Resource.get(url, opts)`;
		} else if( from && (typeof from === 'object') && (from.$ref !== undefined) ) {
			//console.log( '^ from is $ref-object: ' + JSON.stringify(from) );

			var url = from.$ref;
			function To() { }
			to = new To();

			To.prototype.get = function(opts) {
				return Resource.get(url, opts);
			};

			To.prototype.post = function(opts) {
				return Resource.post(url, opts);
			};
			To.prototype.update = to.post;

			To.prototype.del = function(opts) {
				return Resource.del(url, opts);
			};

			ref_copy_self(to, from);

		// Convert normal objects
		} else if( from && (typeof from === 'object') ) {

			to = {};
			//console.log( '^ from is plain object: ' + JSON.stringify(from) );
			ref_copy_self(to, from);

		// Anything else is passed directly back
		} else {
			//console.log( '^ from is other type: ' + JSON.stringify(from) );
			to = from;
		}

		//console.log('..returning ' + JSON.stringify(to) + ' of type ' + (typeof to));
		return to;
	}

	/** Copies recursively any child objects with property a `$ref` as a function calling `Resource.get()`
	 * @param self {object|function} The object where the properties should be copied
	 * @param obj {object} The object from the properties should be copied
	 */
	function ref_copy_self(self, obj) {
		//console.log( 'at ref_copy_self(): self = ' + JSON.stringify(self) + ', obj = ' + JSON.stringify(obj) );
		Object.keys(obj).forEach(function(key) {
			self[key] = ref_copy(obj[key]);
		});
	}

	/** Get JSON REST resource at `url` and returns promise of an interface */
	Resource.get = function(url, params) {
		//console.log(' at Resource.get(' + JSON.stringify(url) + ')' );

		var jqxhr = Q($.ajax({
		  dataType: "json",
		  url: url,
		  data: params,
		  cache: false
		}));

		var res = jqxhr.then(function success_handler(data) {
			//console.log( 'at jqxhr.then(): data = ' + JSON.stringify( data ) );
			if(data.$ref === undefined) {
				//console.log('Warning! Resource from ' + url + ' did not have $ref property. Using ' + url + ' instead.' );
				data.$ref = url;
			}

			var res = new Resource(data);
			//console.log('res.session is type of ' + typeof res.session);
			return res;
		}, function fail_handler(err) {
			//console.log( 'at jqxhr.fail(): err = ' + JSON.stringify( err ) );
			throw err;
		});
		return res;
	};

	/** POST to the JSON REST resource at `url`. Returns a promise of an interface. */
	Resource.post = function(url, params) {
		//console.log(' at Resource.get(' + JSON.stringify(url) + ')' );

		var jqxhr = Q($.ajax({
		  type: 'POST',
		  dataType: "json",
		  url: url,
		  data: params
		}));

		var res = jqxhr.then(function success_handler(data) {
			//console.log( 'at jqxhr.then(): data = ' + JSON.stringify( data ) );
			if(data.$ref === undefined) {
				//console.log('Warning! Resource from ' + url + ' did not have $ref property. Using ' + url + ' instead.' );
				data.$ref = url;
			}

			var res = new Resource(data);
			//console.log('res.session is type of ' + typeof res.session);
			return res;
		}, function fail_handler(err) {
			//console.log( 'at jqxhr.fail(): err = ' + JSON.stringify( err ) );
			return err;
		});
		return res;
	};

	/** DELETE to the JSON REST resource at `url`. Returns a promise of an interface. */
	Resource.del = function(url, params) {
		//console.log(' at Resource.get(' + JSON.stringify(url) + ')' );

		params = params || {};
		params._method = 'DELETE';

		var jqxhr = Q($.ajax({
		  type: 'POST',
		  dataType: "json",
		  url: url,
		  data: params
		}));

		var res = jqxhr.then(function success_handler(data) {
			//console.log( 'at jqxhr.then(): data = ' + JSON.stringify( data ) );
			if(data.$ref === undefined) {
				//console.log('Warning! Resource from ' + url + ' did not have $ref property. Using ' + url + ' instead.' );
				data.$ref = url;
			}

			var res = new Resource(data);
			//console.log('res.session is type of ' + typeof res.session);
			return res;
		}, function fail_handler(err) {
			//console.log( 'at jqxhr.fail(): err = ' + JSON.stringify( err ) );
			throw err;
		});
		return res;
	};

	// Export as `$.nor.rest`
	if( $.nor === undefined ) { $.nor = {}; }

	$.nor.rest = Resource;

	if(typeof module !== 'undefined') {
		module.exports = Resource;
	}

}( (typeof require !== 'undefined') ? require('jquery') : window.jQuery, (typeof require !== 'undefined') ? require('q') : window.Q ));

/* EOF */
<commit_msg>Added commented debug.log<commit_after>
/*global jQuery, ref_copy_self $ */

/** HTTP REST client plugin for jQuery */
(function ( $, Q ) {

	// Simply do nothing if Q is not available
	if( Q === undefined ) {
		Q = function noop(x) { return x; };
	}

	/** Copy object */
	function copy(o) {
		return JSON.parse(JSON.stringify(o));
	}

	/** Resource constructor
	 * @param obj {object} The resource object
	 */
	function Resource(obj) {
		//console.log( 'at new Resource(): obj = ' + JSON.stringify(obj) );
		var self = this;
		obj = copy(obj);
		ref_copy_self(self, obj);
	}

	/**
	 * Returns a copy of variable `from` with any child objects with a property `$ref`
	 * recursively converted as `function(opts)` which will call `Resource.get($ref, opts)`.
	 */
	function ref_copy(from) {
		//console.log( 'at ref_copy(): from = ' + JSON.stringify(from) );
		//console.log( 'typeof from = ' + (typeof from) );

		var to;

		// Handle arrays
		if( from && (typeof from === 'object') && (from instanceof Array) ) {
			//console.log( '^ from is Array: ' + JSON.stringify(from) );

			to = from.map(ref_copy);

		// Convert objects with a property `$ref` as a function shortcut to `Resource.get(url, opts)`;
		} else if( from && (typeof from === 'object') && (from.$ref !== undefined) ) {
			//console.log( '^ from is $ref-object: ' + JSON.stringify(from) );

			var url = from.$ref;
			function To() { }
			to = new To();

			To.prototype.get = function(opts) {
				return Resource.get(url, opts);
			};

			To.prototype.post = function(opts) {
				return Resource.post(url, opts);
			};
			To.prototype.update = to.post;

			To.prototype.del = function(opts) {
				return Resource.del(url, opts);
			};

			ref_copy_self(to, from);

		// Convert normal objects
		} else if( from && (typeof from === 'object') ) {

			to = {};
			//console.log( '^ from is plain object: ' + JSON.stringify(from) );
			ref_copy_self(to, from);

		// Anything else is passed directly back
		} else {
			//console.log( '^ from is other type: ' + JSON.stringify(from) );
			to = from;
		}

		//console.log('..returning ' + JSON.stringify(to) + ' of type ' + (typeof to));
		return to;
	}

	/** Copies recursively any child objects with property a `$ref` as a function calling `Resource.get()`
	 * @param self {object|function} The object where the properties should be copied
	 * @param obj {object} The object from the properties should be copied
	 */
	function ref_copy_self(self, obj) {
		//console.log( 'at ref_copy_self(): self = ' + JSON.stringify(self) + ', obj = ' + JSON.stringify(obj) );
		Object.keys(obj).forEach(function(key) {
			self[key] = ref_copy(obj[key]);
		});
	}

	/** Get JSON REST resource at `url` and returns promise of an interface */
	Resource.get = function(url, params) {
		//console.log(' at Resource.get(' + JSON.stringify(url) + ')' );

		var jqxhr = Q($.ajax({
		  dataType: "json",
		  url: url,
		  data: params,
		  cache: false
		}));

		var res = jqxhr.then(function success_handler(data) {
			//console.log( 'at jqxhr.then(): data = ' + JSON.stringify( data ) );
			if(data.$ref === undefined) {
				//console.log('Warning! Resource from ' + url + ' did not have $ref property. Using ' + url + ' instead.' );
				data.$ref = url;
			}

			var res = new Resource(data);
			//console.log('res.session is type of ' + typeof res.session);
			return res;
		}, function fail_handler(err) {
			//console.log( 'at jqxhr.fail(): err = ' + JSON.stringify( err ) );
			throw err;
		});
		return res;
	};

	/** POST to the JSON REST resource at `url`. Returns a promise of an interface. */
	Resource.post = function(url, params) {
		//console.log(' at Resource.get(' + JSON.stringify(url) + ')' );

		var jqxhr = Q($.ajax({
		  type: 'POST',
		  dataType: "json",
		  url: url,
		  data: params
		}));

		var res = jqxhr.then(function success_handler(data) {
			//console.log( 'at jqxhr.then(): data = ' + JSON.stringify( data ) );
			if(data.$ref === undefined) {
				//console.log('Warning! Resource from ' + url + ' did not have $ref property. Using ' + url + ' instead.' );
				data.$ref = url;
			}

			var res = new Resource(data);
			//console.log('res.session is type of ' + typeof res.session);
			return res;
		}, function fail_handler(err) {
			//console.log( 'at jqxhr.fail(): err = ' + JSON.stringify( err ) );
			return err;
		});
		return res;
	};

	/** DELETE to the JSON REST resource at `url`. Returns a promise of an interface. */
	Resource.del = function(url, params) {
		//console.log(' at Resource.get(' + JSON.stringify(url) + ')' );

		params = params || {};
		params._method = 'DELETE';

		//debug.log('url = ', url);
		//debug.log('params = ', params);

		var jqxhr = Q($.ajax({
		  type: 'POST',
		  dataType: "json",
		  url: url,
		  data: params
		}));

		var res = jqxhr.then(function success_handler(data) {
			//console.log( 'at jqxhr.then(): data = ' + JSON.stringify( data ) );
			if(data.$ref === undefined) {
				//console.log('Warning! Resource from ' + url + ' did not have $ref property. Using ' + url + ' instead.' );
				data.$ref = url;
			}

			var res = new Resource(data);
			//console.log('res.session is type of ' + typeof res.session);
			return res;
		}, function fail_handler(err) {
			//console.log( 'at jqxhr.fail(): err = ' + JSON.stringify( err ) );
			throw err;
		});
		return res;
	};

	// Export as `$.nor.rest`
	if( $.nor === undefined ) { $.nor = {}; }

	$.nor.rest = Resource;

	if(typeof module !== 'undefined') {
		module.exports = Resource;
	}

}( (typeof require !== 'undefined') ? require('jquery') : window.jQuery, (typeof require !== 'undefined') ? require('q') : window.Q ));

/* EOF */
<|endoftext|>


<commit_before>(function ( $ ) {

    $.fn.richText = function( options ) {

        var $inputElement = $(this);
        var $editor,
            $toolbarList = $('<ul />'),
            $toolbarElement = $('<li />'),
            $btnBold = $('<a />', {class: "richText-btn fa fa-bold", text: "Bold"}),
            $btnItalic = $('<a />', {class: "richText-btn fa fa-italic", text: "Italic"}),
            $btnUnderline = $('<a />', {class: "richText-btn fa fa-underline", text: "Underline"}),
            $btnLeftAlign = $('<a />', {class: "richText-btn fa fa-align-left", text: "Align left"}),
            $btnCenterAlign = $('<a />', {class: "richText-btn fa fa-align-left", text: "Align center"}),
            $btnRightAlign = $('<a />', {class: "richText-btn fa fa-align-left", text: "Align right"}),
            $btnOL = $('<a />', {class: "richText-btn fa fa-list-ol", text: "OL"}),
            $btnUL = $('<a />', {class: "richText-btn fa fa-list", text: "UL"});

        // set default options
        // and merge them with the parameter options
        var settings = $.extend({

            // text formatting
            bold: true,
            italic: true,
            underline: true,

            // text alignment
            leftAlign: true,
            centerAlign: true,
            rightAlign: true,

            // lists
            ol: true,
            ul: true,

            // title
            heading: true,

            // colors
            fontColor: true,
            backgroundColor: true,

            // uploads
            imageUpload: true,
            fileUpload: true,

            // link
            urls: true,

            // tables
            table: true,

            // code
            removeStyles: true,
            code: true

        }, options );

        // initizalize editor
        var init = function() {
            $editor = $('<div />', {class: "richText"});
            var $toolbar = $('<div />', {class: "richText-toolbar"});
            var $editorView = $('<div />', {class: "richText-editor", contenteditable: true});
            $toolbar.append($toolbarList);

            /* text formatting */
            if(settings.bold === true) {
                $toolbarList.append($toolbarElement.clone().append($btnBold));
            }
            if(settings.italic === true) {
                $toolbarList.append($toolbarElement.clone().append($btnItalic));
            }
            if(settings.underline === true) {
                $toolbarList.append($toolbarElement.clone().append($btnUnderline));
            }

            /* align */
            if(settings.leftAlign === true) {
                $toolbarList.append($toolbarElement.clone().append($btnLeftAlign));
            }
            if(settings.centerAlign === true) {
                $toolbarList.append($toolbarElement.clone().append($btnCenterAlign));
            }
            if(settings.rightAlign === true) {
                $toolbarList.append($toolbarElement.clone().append($btnRightAlign));
            }

            /* lists */
            if(settings.ol === true) {
                $toolbarList.append($toolbarElement.clone().append($btnOL));
            }
            if(settings.ul === true) {
                $toolbarList.append($toolbarElement.clone().append($btnUL));
            }

            $editor.append($toolbar);
            $editor.append($editorView);
            $editor.append($inputElement.clone().hide());
            $inputElement.replaceWith($editor);
        };

        init();

        return $(this);
    };

}( jQuery ));<commit_msg>Add missing buttons<commit_after>(function ( $ ) {

    $.fn.richText = function( options ) {

        var $inputElement = $(this);
        var $editor,
            $toolbarList = $('<ul />'),
            $toolbarElement = $('<li />'),
            $btnBold = $('<a />', {class: "richText-btn fa fa-bold"}), // bold
            $btnItalic = $('<a />', {class: "richText-btn fa fa-italic"}), // italic
            $btnUnderline = $('<a />', {class: "richText-btn fa fa-underline"}), // underline
            $btnLeftAlign = $('<a />', {class: "richText-btn fa fa-align-left"}), // left align
            $btnCenterAlign = $('<a />', {class: "richText-btn fa fa-align-center"}), // centered
            $btnRightAlign = $('<a />', {class: "richText-btn fa fa-align-right"}), // right align
            $btnOL = $('<a />', {class: "richText-btn fa fa-list-ol"}), // ordered list
            $btnUL = $('<a />', {class: "richText-btn fa fa-list"}), // unordered list
            $btnHeading = $('<a />', {class: "richText-btn fa fa-header"}), // title/header
            $btnFontColor = $('<a />', {class: "richText-btn fa fa-paint-brush"}), // font color
            $btnImageUpload = $('<a />', {class: "richText-btn fa fa-image"}), // image
            $btnFileUpload = $('<a />', {class: "richText-btn fa fa-file-text-o"}), // file
            $btnURLs = $('<a />', {class: "richText-btn fa fa-link"}), // urls/links
            $btnTable = $('<a />', {class: "richText-btn fa fa-table"}), // table
            $btnRemoveStyles = $('<a />', {class: "richText-btn fa fa-recycle"}), // clean up styles
            $btnCode = $('<a />', {class: "richText-btn fa fa-code"}); // code

        // set default options
        // and merge them with the parameter options
        var settings = $.extend({

            // text formatting
            bold: true,
            italic: true,
            underline: true,

            // text alignment
            leftAlign: true,
            centerAlign: true,
            rightAlign: true,

            // lists
            ol: true,
            ul: true,

            // title
            heading: true,

            // colors
            fontColor: true,

            // uploads
            imageUpload: true,
            fileUpload: true,

            // link
            urls: true,

            // tables
            table: true,

            // code
            removeStyles: true,
            code: true

        }, options );

        // initizalize editor
        var init = function() {
            $editor = $('<div />', {class: "richText"});
            var $toolbar = $('<div />', {class: "richText-toolbar"});
            var $editorView = $('<div />', {class: "richText-editor", contenteditable: true});
            $toolbar.append($toolbarList);

            /* text formatting */
            if(settings.bold === true) {
                $toolbarList.append($toolbarElement.clone().append($btnBold));
            }
            if(settings.italic === true) {
                $toolbarList.append($toolbarElement.clone().append($btnItalic));
            }
            if(settings.underline === true) {
                $toolbarList.append($toolbarElement.clone().append($btnUnderline));
            }

            /* align */
            if(settings.leftAlign === true) {
                $toolbarList.append($toolbarElement.clone().append($btnLeftAlign));
            }
            if(settings.centerAlign === true) {
                $toolbarList.append($toolbarElement.clone().append($btnCenterAlign));
            }
            if(settings.rightAlign === true) {
                $toolbarList.append($toolbarElement.clone().append($btnRightAlign));
            }

            /* lists */
            if(settings.ol === true) {
                $toolbarList.append($toolbarElement.clone().append($btnOL));
            }
            if(settings.ul === true) {
                $toolbarList.append($toolbarElement.clone().append($btnUL));
            }

            /* heading */
            if(settings.heading === true) {
                $toolbarList.append($toolbarElement.clone().append($btnHeading));
            }

            /* colors */
            if(settings.fontColor === true) {
                $toolbarList.append($toolbarElement.clone().append($btnFontColor));
            }

            /* uploads */
            if(settings.imageUpload === true) {
                $toolbarList.append($toolbarElement.clone().append($btnImageUpload));
            }
            if(settings.fileUpload === true) {
                $toolbarList.append($toolbarElement.clone().append($btnFileUpload));
            }

            /* urls */
            if(settings.urls === true) {
                $toolbarList.append($toolbarElement.clone().append($btnURLs));
            }

            /* code */
            if(settings.removeStyles === true) {
                $toolbarList.append($toolbarElement.clone().append($btnRemoveStyles));
            }
            if(settings.code === true) {
                $toolbarList.append($toolbarElement.clone().append($btnCode));
            }

            $editor.append($toolbar);
            $editor.append($editorView);
            $editor.append($inputElement.clone().hide());
            $inputElement.replaceWith($editor);
        };

        init();

        return $(this);
    };

}( jQuery ));<|endoftext|>


<commit_before>this.mmooc=this.mmooc||{};

//https://webapps.stackexchange.com/questions/85517/how-can-i-download-subtitles-for-a-vimeo-video
this.mmooc.vimeo = function() {
	var hrefPrefix = "$KPASAPIURL/vimeo/";
	var transcriptIdPrefix = "vimeoTranscript";
	var transcriptArr = [];
	var initialized = false;
    var noOfVimeoVideos = $(".mmoocVimeoVideoTranscript").length;
    var noOfInits = 0;
	function transcript(transcriptId, language, name)
	{
		var playbackRate = 1.0;
		var transcriptId = transcriptId;
		var videoId = transcriptId.split(transcriptIdPrefix)[1];
        var iframeId = "vimeo" + videoId;
		var transcriptButtonId = "vimeoTranscriptButtonId" + videoId;
		var transcriptContentId = "vimeoTranscriptContentId" + videoId;
		var player = null;

		var href = hrefPrefix + videoId;
        //Array of captions in video
		var captionsLoaded = false;

		//Timeout for next caption
		var captionTimeout = null;

		var captions = null;

		//Keep track of which captions we are showing
		var currentCaptionIndex = 0;
		var nextCaptionIndex = 0;

		this.initializePlayer = function() {
			var transcript = this;
			var iframe = document.getElementById(iframeId);
			player = new Vimeo.Player(iframe);
			player.on('play', function() {
				console.log('Played the video');
				transcript.playerPlaying();
			});
			player.on('pause', function() {
				console.log("Paused the video.");
				transcript.playerNotPlaying();
			});
	/*        player.ready().then(function () {
				console.log('player is ready!');
			});
	*/
			player.getVideoTitle().then(function(title) {
				console.log('title:', title);
			});
			player.on('cuechange', function(d) {
				//console.log(d);
				//transcript.playerPlaying();
			});
			player.on('cuepoint', function(d) {
				console.log(d);
			})
			player.on('texttrackchange', function(d) {
				console.log(d);
			})
			player.on('playbackratechange', function(d) {
				transcript.setPlaybackRate(d.playbackRate);
				console.log(d);
			})
		}
		var findCaptionIndexFromTimestamp = function(timeStamp) {
			var start = 0;
			var duration = 0;
			for (var i = 0, il = captions.length; i < il; i++) {
			  start = Number(getStartTimeFromCaption(i));
			  duration = Number(getDurationFromCaption(i));

			  //Return the first caption if the timeStamp is smaller than the first caption start time.
			  if (timeStamp < start) {
				break;
			  }

			  //Check if the timestamp is in the interval of this caption.
			  if (timeStamp >= start && timeStamp < start + duration) {
				break;
			  }
			}
			return i;
		  };

		var clearCurrentHighlighting = function()
		{
			console.log("Clear caption index ") + currentCaptionIndex;
			var timeStampId = getTimeIdFromTimestampIndex(currentCaptionIndex);
			$("#"+timeStampId).css('background-color', '');
		}

		var highlightNextCaption = function ()
		{
			var timestampId = getTimeIdFromTimestampIndex(nextCaptionIndex);
			$("#"+timestampId).css('background-color', 'yellow');
			console.log("Timestamp id:" + timestampId);
			var target = document.getElementById(timestampId);
			var targetParent = document.getElementById(transcriptContentId);
			console.log("target offsetTop:" + target.offsetTop);
			console.log("targetParent offsetTop:" + targetParent.offsetTop);

			targetParent.scrollTop = target.offsetTop - (targetParent.offsetTop + targetParent.offsetHeight / 2);

		}
		//Calculate timeout for when next subtitle should be displayed
		var calculateTimeout = function(currentTime) {
			var startTimeCurrentCaption = Number(getStartTimeFromCaption(currentCaptionIndex));
			var startTimeNextCaption = Number(getStartTimeFromCaption(nextCaptionIndex));
			var durationCurrentCaption = Number(getDurationFromCaption(currentCaptionIndex));
			var timeoutValue = 0;

			console.log("calculateTimeout. CurrentTime:" + currentTime + " startTimeNextCaption:" + startTimeNextCaption);
			//The normal case
			if(startTimeNextCaption >= currentTime) {
				timeoutValue = startTimeNextCaption - currentTime;
			}
			return timeoutValue;
		  };

		  this.setCaptionTimeout = function(timeoutValue) {
			console.log("setCaptionTimeout:" + timeoutValue);
			if (timeoutValue < 0) {
			  return;
			}

			clearTimeout(captionTimeout);

			var transcript = this;
			var adjustedTimeoutValue = timeoutValue / transcript.getPlaybackRate();
			console.log("adjusted timeout:" + adjustedTimeoutValue);

			captionTimeout = setTimeout(function() {
			  transcript.highlightCaptionAndPrepareForNext();
			}, adjustedTimeoutValue * 1000);
		  };

		var getStartTimeFromCaption = function(i)
		{
			if(i >= captions.length)
			{
				return -1;
			}
			return captions[i].getAttribute('start');
		}
		var getDurationFromCaption = function(i)
		{
			if(i >= captions.length)
			{
				return -1;
			}
			return captions[i].getAttribute('dur');
		}
		var getTimeIdFromTimestampIndex = function(i)
		{
			var strTimestamp = "" + i;
			return "t" + videoId + strTimestamp;
		}

		//////////////////
		//Public functions
		/////////////////
		//This function highlights the next caption in the list and
		//sets a timeout for the next one after that.
		//It must be public as it is called from a timer.
		this.highlightCaptionAndPrepareForNext = function() {
			clearCurrentHighlighting();
			highlightNextCaption();
			console.log("Previous caption index: " + currentCaptionIndex);
			currentCaptionIndex = nextCaptionIndex;
			console.log("New caption index:" + currentCaptionIndex);
			nextCaptionIndex++;

			var transcript = this;

			player.getCurrentTime().then(function(currentTime) {
				var timeoutValue = calculateTimeout(currentTime);
				if (nextCaptionIndex < captions.length) {
					transcript.setCaptionTimeout(timeoutValue);
				} else {
					console.log("No more captions.");
				}
			}).catch(function(error) {
                console.log("highlightCaptionAndPrepareForNext:Could not get current time from vimeo in player playing:" + error);
            });;
		};
		this.setCurrentTime = function (seekToTime)
		{
            player.setCurrentTime(seekToTime).then(function(seconds) {
                console.log("Jumped to " + seconds);
            }).catch(function(error) {
                switch (error.name) {
                case 'RangeError':
                    console.log("The time is less than 0 or greater than the video's duration.");
                    break;

                default:
                    console.log("Some other error occurred.");
                    break;
                }
            });
        }

        this.play = function() {
			var transcript = this;
			player.getPaused().then(function(paused) {
				if(!paused) {
					transcript.playerPlaying();
				} else {
					player.play().then(function() {
						console.log("The video is playing");
					}).catch(function(error) {
						switch (error.name) {
							case 'PasswordError':
								console.log("The video is password protected.")
								break;

							case 'PrivacyError':
								// The video is private
								console.log("The video is private.")
								break;

							default:
								console.log("Some error occured.")

								break;
						}
					});
				}
			});
        }

		this.highlightCaptionFromTimestamp = function(timeStamp) {
			clearCurrentHighlighting();
			nextCaptionIndex = findCaptionIndexFromTimestamp(timeStamp);
			currentCaptionIndex = nextCaptionIndex;

			var startTime = Number(getStartTimeFromCaption(currentCaptionIndex));

			var timeoutValue = -1;
			if (timeStamp < startTime) {
			  timeoutValue = startTime - timeStamp;
			} else {
			  highlightNextCaption();
			  timeoutValue = calculateTimeout(timeStamp);
			}
			this.setCaptionTimeout(timeoutValue);
		  };
		this.transcriptLoaded = function(transcript) {
			console.log("Transcript loaded.");
			var start = 0;
			captions = transcript.getElementsByTagName('text');

			var srt_output = '
';
			srt_output += '';
			srt_output += 'Transcript';
			srt_output += '
';

			srt_output += '
';

			srt_output += "
";
			var noOfSentencesInParagraph = 0;
			var captionText = "";
			for (var i = 0, il = captions.length; i < il; i++) {
				start =+ getStartTimeFromCaption(i);

				captionText = captions[i].textContent.replace(/</g, '<').replace(/>/g, '>');
				var timestampId = getTimeIdFromTimestampIndex(i);
				srt_output += "" + captionText + " ";
				noOfSentencesInParagraph++;
				if((noOfSentencesInParagraph > 10) && captionText.includes(".")) {
					srt_output += "

";
					noOfSentencesInParagraph = 0;
				}
			};
			srt_output += "
";
			srt_output += "
";

			$("#vimeoTranscript" + videoId).append(srt_output);

			$('#' + transcriptButtonId).click(function(event) {
				mmooc.vimeo.toggleReveal(transcriptContentId);
				return false;
			});

			captionsLoaded = true;

			var transcript = this;

			transcript.initializePlayer();

			console.log("Get player state.");
			console.log(player);
			player.getPaused().then(function(paused) {
				console.log("Player state paused:" + paused);
				if(!paused) {
					transcript.playerPlaying();
				}
			});
		}

		this.getTranscriptId = function()
		{
			return transcriptId;
		}
		this.getTranscriptContentId = function()
		{
			return transcriptContentId;
		}
		this.getIframeId = function()
		{
			return iframeId;
		}
		this.getVideoId = function()
		{
			return videoId;
		}
		this.getPlaybackRate = function() {
			return playbackRate;
		}
		this.setPlaybackRate = function(newPlaybackRate) {
			playbackRate = newPlaybackRate;
		}
		this.getPlayer = function()
		{
			return player;
		}

        this.getTranscript = function()
		{
			var oTranscript = this;
			$.ajax({
				url: href,
				type: 'GET',
                data: {},
				success: function(response) {
					oTranscript.transcriptLoaded(response);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					console.log("Error during GET");
				}
			});
		}

		this.playerPlaying = function()
		{
			console.log("Player playing.");
			if(!captionsLoaded)
			{
				console.log("Captions not loaded.");
				return;
			}

            var player = this.getPlayer();
            var transcript = this;
            player.getCurrentTime().then(function(currentTime) {
    		    transcript.highlightCaptionFromTimestamp(currentTime);
            }).catch(function(error) {
                console.log("Could not get current time from vimeo in player playing:" + error);
            });
		}
		this.playerNotPlaying = function (transcript)
		{
			if(!captionsLoaded)
			{
				return;
			}
			clearTimeout(captionTimeout);
		}
	}

	//Called when user clicks somewhere in the transcript.
	$(function() {
		$(document).on('click', '.btnVimeoSeek', function() {
			var seekToTime = $(this).data('seek');
			var transcript = mmooc.vimeo.getTranscriptFromTranscriptId($(this).parent().parent().attr("id"));
//            var iframe = document.getElementById("vimeo" + transcript.videoId);
//            var player = new Vimeo.Player(iframe);
            try {
                transcript.setCurrentTime(seekToTime);
                transcript.play();
            }
            catch(e) {
                console.log("Vimeo exception:" + e);
            }
		});
	});

	return {
		toggleReveal(id) {
			var body = "#"+id;
			if ($(body).css('display') != 'none') {
				$(body).slideUp(400);
			} else {
				$(body).slideDown(400);
			}
		},
		getTranscriptFromTranscriptId(transcriptId)
		{
			for (index = 0; index < transcriptArr.length; ++index) {
				var transcriptCandidateId = transcriptArr[index].getTranscriptContentId();
				if(transcriptCandidateId == transcriptId)
				{
					return transcriptArr[index];
				}
			}
			return null;
		},
	    getTranscriptFromIframeId(iframeId)
	    {
			for (index = 0; index < transcriptArr.length; ++index) {
				if(transcriptArr[index].getIframeId() == iframeId)
				{
					return transcriptArr[index];
				}
			}
			return null;
	    },
	    getNoOfVimeoVideos() {
            return noOfVimeoVideos;
        },
	    getTranscriptFromVideoId(videoId)
	    {
			for (index = 0; index < transcriptArr.length; ++index) {
				if(transcriptArr[index].getVideoId() == videoId)
				{
					return transcriptArr[index];
				}
			}
			return null;
	    },

		init : function ()
		{
            noOfInits++;
            if(noOfInits < noOfVimeoVideos)
            {
                console.log("" + noOfInits + " of " + noOfVimeoVideos + " initialized.");
                return;
            }
            console.log("Vimeo initializing");

			if(!initialized)
			{
				initialized = true;
				$(".mmoocVimeoVideoTranscript" ).each(function( i ) {
					var language = $(this).data('language');
					var name = $(this).data('name');
					var oTranscript = new transcript(this.id, language, name);
					transcriptArr.push(oTranscript);
                    oTranscript.getTranscript();
				});
			} else {
				console.log("Vimeo already initialized. Reinitialize player.");
				for(var i = 0; i < transcriptArr.length; i++) {
					transcriptArr[i].initializePlayer();
				}
			}
		}
	}
}();

<commit_msg>Automatically display transcript for all vimeo videos.<commit_after>this.mmooc=this.mmooc||{};

//https://webapps.stackexchange.com/questions/85517/how-can-i-download-subtitles-for-a-vimeo-video
this.mmooc.vimeo = function() {
	var hrefPrefix = "$KPASAPIURL/vimeo/";
	var transcriptIdPrefix = "vimeoTranscript";
	var transcriptArr = [];
	var initialized = false;
    var noOfVimeoVideos = 0;

    var noOfInits = 0;
	function transcript(vimeoVideoId, iframe)
	{
		var playbackRate = 1.0;
		var transcriptId = "transcript" + vimeoVideoId;
		var videoId = vimeoVideoId;
		var transcriptButtonId = "vimeoTranscriptButtonId" + videoId;
		var transcriptContentId = "vimeoTranscriptContentId" + videoId;
		var player = null;

		var href = hrefPrefix + videoId;
        //Array of captions in video
		var captionsLoaded = false;

		//Timeout for next caption
		var captionTimeout = null;

		var captions = null;

		//Keep track of which captions we are showing
		var currentCaptionIndex = 0;
		var nextCaptionIndex = 0;

		this.initializePlayer = function() {
			var transcript = this;
			var iframe = transcript.getIframeElement();
			player = new Vimeo.Player(iframe);
			player.on('play', function() {
				console.log('Played the video');
				transcript.playerPlaying();
			});
			player.on('pause', function() {
				console.log("Paused the video.");
				transcript.playerNotPlaying();
			});
			player.getVideoTitle().then(function(title) {
				console.log('title:', title);
			});
			player.on('cuechange', function(d) {
				//console.log(d);
				//transcript.playerPlaying();
			});
			player.on('cuepoint', function(d) {
				console.log(d);
			})
			player.on('texttrackchange', function(d) {
				console.log(d);
			})
			player.on('playbackratechange', function(d) {
				transcript.setPlaybackRate(d.playbackRate);
				console.log(d);
			})
		}
		var findCaptionIndexFromTimestamp = function(timeStamp) {
			var start = 0;
			var duration = 0;
			for (var i = 0, il = captions.length; i < il; i++) {
			  start = Number(getStartTimeFromCaption(i));
			  duration = Number(getDurationFromCaption(i));

			  //Return the first caption if the timeStamp is smaller than the first caption start time.
			  if (timeStamp < start) {
				break;
			  }

			  //Check if the timestamp is in the interval of this caption.
			  if (timeStamp >= start && timeStamp < start + duration) {
				break;
			  }
			}
			return i;
		  };

		var clearCurrentHighlighting = function()
		{
			console.log("Clear caption index ") + currentCaptionIndex;
			var timeStampId = getTimeIdFromTimestampIndex(currentCaptionIndex);
			$("#"+timeStampId).css('background-color', '');
		}

		var highlightNextCaption = function ()
		{
			var timestampId = getTimeIdFromTimestampIndex(nextCaptionIndex);
			$("#"+timestampId).css('background-color', 'yellow');
			console.log("Timestamp id:" + timestampId);
			var target = document.getElementById(timestampId);
			var targetParent = document.getElementById(transcriptContentId);
			console.log("target offsetTop:" + target.offsetTop);
			console.log("targetParent offsetTop:" + targetParent.offsetTop);

			targetParent.scrollTop = target.offsetTop - (targetParent.offsetTop + targetParent.offsetHeight / 2);

		}
		//Calculate timeout for when next subtitle should be displayed
		var calculateTimeout = function(currentTime) {
			var startTimeCurrentCaption = Number(getStartTimeFromCaption(currentCaptionIndex));
			var startTimeNextCaption = Number(getStartTimeFromCaption(nextCaptionIndex));
			var durationCurrentCaption = Number(getDurationFromCaption(currentCaptionIndex));
			var timeoutValue = 0;

			console.log("calculateTimeout. CurrentTime:" + currentTime + " startTimeNextCaption:" + startTimeNextCaption);
			//The normal case
			if(startTimeNextCaption >= currentTime) {
				timeoutValue = startTimeNextCaption - currentTime;
			}
			return timeoutValue;
		  };

		  this.setCaptionTimeout = function(timeoutValue) {
			console.log("setCaptionTimeout:" + timeoutValue);
			if (timeoutValue < 0) {
			  return;
			}

			clearTimeout(captionTimeout);

			var transcript = this;
			var adjustedTimeoutValue = timeoutValue / transcript.getPlaybackRate();
			console.log("adjusted timeout:" + adjustedTimeoutValue);

			captionTimeout = setTimeout(function() {
			  transcript.highlightCaptionAndPrepareForNext();
			}, adjustedTimeoutValue * 1000);
		  };

		var getStartTimeFromCaption = function(i)
		{
			if(i >= captions.length)
			{
				return -1;
			}
			return captions[i].getAttribute('start');
		}
		var getDurationFromCaption = function(i)
		{
			if(i >= captions.length)
			{
				return -1;
			}
			return captions[i].getAttribute('dur');
		}
		var getTimeIdFromTimestampIndex = function(i)
		{
			var strTimestamp = "" + i;
			return "t" + videoId + strTimestamp;
		}

		//////////////////
		//Public functions
		/////////////////
		//This function highlights the next caption in the list and
		//sets a timeout for the next one after that.
		//It must be public as it is called from a timer.
		this.highlightCaptionAndPrepareForNext = function() {
			clearCurrentHighlighting();
			highlightNextCaption();
			console.log("Previous caption index: " + currentCaptionIndex);
			currentCaptionIndex = nextCaptionIndex;
			console.log("New caption index:" + currentCaptionIndex);
			nextCaptionIndex++;

			var transcript = this;

			player.getCurrentTime().then(function(currentTime) {
				var timeoutValue = calculateTimeout(currentTime);
				if (nextCaptionIndex < captions.length) {
					transcript.setCaptionTimeout(timeoutValue);
				} else {
					console.log("No more captions.");
				}
			}).catch(function(error) {
                console.log("highlightCaptionAndPrepareForNext:Could not get current time from vimeo in player playing:" + error);
            });;
		};
		this.setCurrentTime = function (seekToTime)
		{
            player.setCurrentTime(seekToTime).then(function(seconds) {
                console.log("Jumped to " + seconds);
            }).catch(function(error) {
                switch (error.name) {
                case 'RangeError':
                    console.log("The time is less than 0 or greater than the video's duration.");
                    break;

                default:
                    console.log("Some other error occurred.");
                    break;
                }
            });
        }

        this.play = function() {
			var transcript = this;
			player.getPaused().then(function(paused) {
				if(!paused) {
					transcript.playerPlaying();
				} else {
					player.play().then(function() {
						console.log("The video is playing");
					}).catch(function(error) {
						switch (error.name) {
							case 'PasswordError':
								console.log("The video is password protected.")
								break;

							case 'PrivacyError':
								// The video is private
								console.log("The video is private.")
								break;

							default:
								console.log("Some error occured.")

								break;
						}
					});
				}
			});
        }

		this.highlightCaptionFromTimestamp = function(timeStamp) {
			clearCurrentHighlighting();
			nextCaptionIndex = findCaptionIndexFromTimestamp(timeStamp);
			currentCaptionIndex = nextCaptionIndex;

			var startTime = Number(getStartTimeFromCaption(currentCaptionIndex));

			var timeoutValue = -1;
			if (timeStamp < startTime) {
			  timeoutValue = startTime - timeStamp;
			} else {
			  highlightNextCaption();
			  timeoutValue = calculateTimeout(timeStamp);
			}
			this.setCaptionTimeout(timeoutValue);
		  };
		this.transcriptLoaded = function(transcript, iframe) {
			console.log("Transcript loaded.");
			var start = 0;
			captions = transcript.getElementsByTagName('text');

			var srt_output = '
';
			srt_output += '';
			srt_output += 'Transcript';
			srt_output += '
';

			srt_output += '
';

			srt_output += "
";
			var noOfSentencesInParagraph = 0;
			var captionText = "";
			for (var i = 0, il = captions.length; i < il; i++) {
				start =+ getStartTimeFromCaption(i);

				captionText = captions[i].textContent.replace(/</g, '<').replace(/>/g, '>');
				var timestampId = getTimeIdFromTimestampIndex(i);
				srt_output += "" + captionText + " ";
				noOfSentencesInParagraph++;
				if((noOfSentencesInParagraph > 10) && captionText.includes(".")) {
					srt_output += "

";
					noOfSentencesInParagraph = 0;
				}
			};
			srt_output += "
";
			srt_output += "
";

			var e = document.createElement('div');
			e.innerHTML = srt_output;

			iframe.parentNode.insertBefore(e, iframe.nextSibling);

			$('#' + transcriptButtonId).click(function(event) {
				mmooc.vimeo.toggleReveal(transcriptContentId);
				return false;
			});

			captionsLoaded = true;

			var transcript = this;

			transcript.initializePlayer();

			console.log("Get player state.");
			console.log(player);
			player.getPaused().then(function(paused) {
				console.log("Player state paused:" + paused);
				if(!paused) {
					transcript.playerPlaying();
				}
			});
		}

		this.getTranscriptId = function()
		{
			return transcriptId;
		}
		this.getTranscriptContentId = function()
		{
			return transcriptContentId;
		}
		this.getVideoId = function()
		{
			return videoId;
		}
		this.getIframeElement = function() {
			return iframe;
		}
		this.getPlaybackRate = function() {
			return playbackRate;
		}
		this.setPlaybackRate = function(newPlaybackRate) {
			playbackRate = newPlaybackRate;
		}
		this.getPlayer = function()
		{
			return player;
		}

        this.getTranscript = function()
		{
			var oTranscript = this;
			$.ajax({
				url: href,
				type: 'GET',
                data: {},
				success: function(response) {
					oTranscript.transcriptLoaded(response, oTranscript.getIframeElement());
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					console.log("Error during GET");
				}
			});
		}

		this.playerPlaying = function()
		{
			console.log("Player playing.");
			if(!captionsLoaded)
			{
				console.log("Captions not loaded.");
				return;
			}

            var player = this.getPlayer();
            var transcript = this;
            player.getCurrentTime().then(function(currentTime) {
    		    transcript.highlightCaptionFromTimestamp(currentTime);
            }).catch(function(error) {
                console.log("Could not get current time from vimeo in player playing:" + error);
            });
		}
		this.playerNotPlaying = function (transcript)
		{
			if(!captionsLoaded)
			{
				return;
			}
			clearTimeout(captionTimeout);
		}
	}

	//Called when user clicks somewhere in the transcript.
	$(function() {
		$(document).on('click', '.btnVimeoSeek', function() {
			var seekToTime = $(this).data('seek');
			var transcript = mmooc.vimeo.getTranscriptFromTranscriptId($(this).parent().parent().attr("id"));
//            var iframe = document.getElementById("vimeo" + transcript.videoId);
//            var player = new Vimeo.Player(iframe);
            try {
                transcript.setCurrentTime(seekToTime);
                transcript.play();
            }
            catch(e) {
                console.log("Vimeo exception:" + e);
            }
		});
	});

	return {
		toggleReveal(id) {
			var body = "#"+id;
			if ($(body).css('display') != 'none') {
				$(body).slideUp(400);
			} else {
				$(body).slideDown(400);
			}
		},
		getTranscriptFromTranscriptId(transcriptId)
		{
			for (index = 0; index < transcriptArr.length; ++index) {
				var transcriptCandidateId = transcriptArr[index].getTranscriptContentId();
				if(transcriptCandidateId == transcriptId)
				{
					return transcriptArr[index];
				}
			}
			return null;
		},
	    getNoOfVimeoVideos() {
            return noOfVimeoVideos;
        },
	    getTranscriptFromVideoId(videoId)
	    {
			for (index = 0; index < transcriptArr.length; ++index) {
				if(transcriptArr[index].getVideoId() == videoId)
				{
					return transcriptArr[index];
				}
			}
			return null;
	    },
	    getVimeoVideoIdFromUrl(url) {
			var id = "";
			var result = url.match(/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|video\/|)(\d+)(?:[a-zA-Z0-9_\-]+)?/i);

			if (result){
				id = result[1];
			}
			return id;
		},
		init : function ()
		{
            noOfInits++;
            if(noOfInits < noOfVimeoVideos)
            {
                console.log("" + noOfInits + " of " + noOfVimeoVideos + " initialized.");
                return;
            }
            console.log("Vimeo initializing");

			if(!initialized)
			{
				initialized = true;
				var iframes = document.getElementsByTagName('iframe');
				for (var i = 0; i < iframes.length; i++) {
					var iframe = iframes[i];
					var vimeoId = mmooc.vimeo.getVimeoVideoIdFromUrl(iframe.src);
					if(vimeoId != "") {
						noOfVimeoVideos++;
						var oTranscript = new transcript(vimeoId, iframe);
						transcriptArr.push(oTranscript);
						oTranscript.getTranscript();
					}
				}
			} else {
				console.log("Vimeo already initialized. Reinitialize player.");
				for(var i = 0; i < transcriptArr.length; i++) {
					var oTranscript = transcriptArr[i];
					oTranscript.initializePlayer();
				}
			}
		}
	}
}();

<|endoftext|>


<commit_before>window.$$ = window.$$ || {};
window.$$.draw = window.$$.draw || {};

(function (DRAW) {
    "use strict";

    var FreeDraw = function (container, para) {
        DRAW.Basic.call(this, container, para);
        this._setupBinding();
    };
    FreeDraw.prototype = Object.create(DRAW.Basic.prototype);
    FreeDraw.prototype.constructor = FreeDraw;

    FreeDraw.prototype.startDrawing = function (para) {
        // draw element
        var para = para || {};
        //var style = para.color || '#000000';
        //var thickness = para.thickness || 1;
        //var join = para.join || 'round';

        //this._ctx.lineWidth = thickness;
        //this._ctx.strokeStyle = style;
        //this._ctx.lineJoin = join;

        for (var i in para) {
            this._ctx[i] = para[i];
        }

        this._ctx.beginPath();
        this._lastPos = null;
        this.container.addEventListener("mousemove", this._fn_draw, false);
    };

    FreeDraw.prototype.stopDrawing = function () {
        this._lastPos = null;
        this.container.removeEventListener(evt, this._fn_draw, false);
    };

    FreeDraw.prototype._setupBinding = function () {
        var that = this;

        var _getMousePos = function (e) {
            var pos;
            if (e.pageX == undefined) {
                pos = [e.originalEvent.touches[0].pageX, e.originalEvent.touches[0].pageY];
            } else {
                pos = [e.pageX, e.pageY];
            }
            var viewportOffset = that._canvas.getBoundingClientRect();
            pos[1] -= viewportOffset.top;
            pos[0] -= viewportOffset.left
            return pos;
        };

        this._lastPos = null;
        this._fn_draw = function (e) {
            var mousePos = _getMousePos(e);
            if (that._lastPos === null) {
                that._lastPos = mousePos;
                that._ctx.moveTo(mousePos[0], mousePos[1]);
                return false;
            }

            that._ctx.lineTo(mousePos[0], mousePos[1]);
            that._ctx.stroke();
            that._lastPos = mousePos;
        };
    };

    DRAW.freeDraw = FreeDraw;
})(window.$$.draw);
<commit_msg>test for offset<commit_after>window.$$ = window.$$ || {};
window.$$.draw = window.$$.draw || {};

(function (DRAW) {
    "use strict";

    var FreeDraw = function (container, para) {
        DRAW.Basic.call(this, container, para);
        this._setupBinding();
    };
    FreeDraw.prototype = Object.create(DRAW.Basic.prototype);
    FreeDraw.prototype.constructor = FreeDraw;

    FreeDraw.prototype.startDrawing = function (para) {
        // draw element
        var para = para || {};
        //var style = para.color || '#000000';
        //var thickness = para.thickness || 1;
        //var join = para.join || 'round';

        //this._ctx.lineWidth = thickness;
        //this._ctx.strokeStyle = style;
        //this._ctx.lineJoin = join;

        for (var i in para) {
            this._ctx[i] = para[i];
        }

        this._ctx.beginPath();
        this._lastPos = null;
        this.container.addEventListener("mousemove", this._fn_draw, false);
    };

    FreeDraw.prototype.stopDrawing = function () {
        this._lastPos = null;
        this.container.removeEventListener(evt, this._fn_draw, false);
    };

    FreeDraw.prototype._setupBinding = function () {
        var that = this;

        var getOffset = function (dom) {

        };

        var _getMousePos = function (e) {
            var pos;
            if (e.pageX == undefined) {
                pos = [e.originalEvent.touches[0].pageX, e.originalEvent.touches[0].pageY];
            } else {
                pos = [e.pageX, e.pageY];
            }
            var viewportOffset = that._canvas.getBoundingClientRect();
            pos[1] -= viewportOffset.top;
            pos[0] -= viewportOffset.left

            //http://www.cnblogs.com/zhiyishou/p/4214285.html
            e.currentTarget
            return pos;
        };

        this._lastPos = null;
        this._fn_draw = function (e) {
            var mousePos = _getMousePos(e);
            if (that._lastPos === null) {
                that._lastPos = mousePos;
                that._ctx.moveTo(mousePos[0], mousePos[1]);
                return false;
            }

            that._ctx.lineTo(mousePos[0], mousePos[1]);
            that._ctx.stroke();
            that._lastPos = mousePos;
        };
    };

    DRAW.freeDraw = FreeDraw;
})(window.$$.draw);
<|endoftext|>


<commit_before>/**
 * @author Joppe Aarts <joppe@apestaartje.info>
 * @copyright Apestaartje <http://apestaartje.info>
 */

import {Container} from 'lib/dependencyinjection/Container';

/**
 * @class Kernel
 */
export class Kernel {
    /**
     * Constructor
     *
     * @param {string} environment
     * @param {boolean} debug
     */
    constructor(environment, debug = false) {
        this.environment = environment;
        this.debug = debug;

        this.container = new Container();
        this.bundles = this.registerBundles();
    }

    /**
     * @returns {void}
     */
    boot() {
        this.bundles.forEach(bundle => {
            bundle.setContainer(this.container);
            bundle.boot();
        });
    }

    /**
     * @returns {Container}
     */
    getContainer() {
        return this.container;
    }

    /**
     * @returns {Array}
     */
    getBundles() {
        return this.bundles;
    }

    /**
     * @returns {Array}
     */
    registerBundles() {
        return [];
    }

    /**
     * @returns {string}
     */
    getEnvironment() {
        return this.environment;
    }

    /**
     * @returns {boolean}
     */
    isDebug() {
        return this.debug;
    }
}<commit_msg>on boot loop over all bundles and call their init method, after that loop another time and call the boot method<commit_after>/**
 * @author Joppe Aarts <joppe@apestaartje.info>
 * @copyright Apestaartje <http://apestaartje.info>
 */

import {Container} from 'lib/dependencyinjection/Container';

/**
 * @class Kernel
 */
export class Kernel {
    /**
     * Constructor
     *
     * @param {string} environment
     * @param {boolean} debug
     */
    constructor(environment, debug = false) {
        this.environment = environment;
        this.debug = debug;

        this.container = new Container();
        this.bundles = this.registerBundles();
    }

    /**
     * @returns {void}
     */
    boot() {
        this.bundles.forEach(bundle => {
            bundle.setContainer(this.container);
            bundle.init();
        });

        this.bundles.forEach(bundle => {
            bundle.boot();
        });
    }

    /**
     * @returns {Container}
     */
    getContainer() {
        return this.container;
    }

    /**
     * @returns {Array}
     */
    getBundles() {
        return this.bundles;
    }

    /**
     * @returns {Array}
     */
    registerBundles() {
        return [];
    }

    /**
     * @returns {string}
     */
    getEnvironment() {
        return this.environment;
    }

    /**
     * @returns {boolean}
     */
    isDebug() {
        return this.debug;
    }
}<|endoftext|>


<commit_before>System.config({
	transpiler: 'typescript',
	typescriptOptions: {
		emitDecoratorMetadata: true,
        experimentalDecorators: true
	},
	map: {
		'app': '/app',

		'@angular/common': '@angular/common/bundles/common.umd.min.js',
		'@angular/compiler': '@angular/compiler/bundles/compiler.umd.min.js',
		'@angular/core': '@angular/core/bundles/core.umd.min.js',
		'@angular/forms': '@angular/forms/bundles/forms.umd.min.js',
		'@angular/http': '@angular/http/bundles/http.umd.min.js',
		'@angular/platform-browser': '@angular/platform-browser/bundles/platform-browser.umd.min.js',
		'@angular/platform-browser-dynamic': '@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.min.js',
		'@angular/router': '@angular/router/bundles/router.umd.min.js',

		'rxjs': 'rxjs/bundles/Rx.min.js',
		'typescript': 'typescript/lib/typescript.js'
	},
	packages: {
		app: {
			main: './main.ts',
			defaultExtension: 'ts'
		},
		rxjs: {
			defaultExtension: 'js'
		}
	}
});

System.import('app').catch(console.error.bind(console));
<commit_msg>Systemjs Typescript target added<commit_after>System.config({
	transpiler: 'typescript',
	typescriptOptions: {
		target: "es5",
		module: "commonjs",
		emitDecoratorMetadata: true,
        experimentalDecorators: true
	},
	map: {
		'app': '/app',

		'@angular/common': '@angular/common/bundles/common.umd.min.js',
		'@angular/compiler': '@angular/compiler/bundles/compiler.umd.min.js',
		'@angular/core': '@angular/core/bundles/core.umd.min.js',
		'@angular/forms': '@angular/forms/bundles/forms.umd.min.js',
		'@angular/http': '@angular/http/bundles/http.umd.min.js',
		'@angular/platform-browser': '@angular/platform-browser/bundles/platform-browser.umd.min.js',
		'@angular/platform-browser-dynamic': '@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.min.js',
		'@angular/router': '@angular/router/bundles/router.umd.min.js',

		'rxjs': 'rxjs/bundles/Rx.min.js',
		'typescript': 'typescript/lib/typescript.js'
	},
	packages: {
		app: {
			main: './main.ts',
			defaultExtension: 'ts'
		},
		rxjs: {
			defaultExtension: 'js'
		}
	}
});

System.import('app').catch(console.error.bind(console));
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/user_spending';

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Track My Spending' });
});

module.exports = router;
<commit_msg>can communicate to db through URI's<commit_after>var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/user_spending';

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Track My Spending' });
});

router.get('/data', function(req, res) {
  var results = [];

  pg.connect(connectionString, function(err, client, done) {

    var query = client.query("SELECT * FROM spending;");

    query.on('row', function(row) {
      results.push(row);
    });

    query.on('end', function() {
      client.end();
      return res.json(results);
    })
    if(err) {
      console.log(err);
    }
  })
});

router.post('/data', function(req, res) {

      var results = [];

      var data = {id: req.body.id, name: req.body.name, cost: req.body.cost};

      pg.connect(connectionString, function(err, client, done) {

          client.query("INSERT INTO spending(id, name, cost) values($1, $2, $3)", [data.id, data.name, data.cost]);

          var query = client.query("SELECT * FROM spending ORDER BY id ASC");

          query.on('row', function(row) {
              results.push(row);
          });

          query.on('end', function() {
              client.end();
              return res.json(results);
          });

          // Handle Errors
          if(err) {
            console.log(err);
          }

      });
  });

module.exports = router;
<|endoftext|>