(function (t, e) {
  'use strict';
  function n() {
    if (!i.READY) {
      i.event.determineEventTypes();
      for (var t in i.gestures)
        i.gestures.hasOwnProperty(t) && i.detection.register(i.gestures[t]);
      i.event.onTouch(i.DOCUMENT, i.EVENT_MOVE, i.detection.detect), i.event.onTouch(i.DOCUMENT, i.EVENT_END, i.detection.detect), i.READY = !0;
    }
  }
  var i = function (t, e) {
    return new i.Instance(t, e || {});
  };
  i.defaults = {
    stop_browser_behavior: {
      userSelect: 'none',
      touchAction: 'none',
      touchCallout: 'none',
      contentZooming: 'none',
      userDrag: 'none',
      tapHighlightColor: 'rgba(0,0,0,0)'
    }
  }, i.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled, i.HAS_TOUCHEVENTS = 'ontouchstart' in t, i.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i, i.NO_MOUSEEVENTS = i.HAS_TOUCHEVENTS && navigator.userAgent.match(i.MOBILE_REGEX), i.EVENT_TYPES = {}, i.DIRECTION_DOWN = 'down', i.DIRECTION_LEFT = 'left', i.DIRECTION_UP = 'up', i.DIRECTION_RIGHT = 'right', i.POINTER_MOUSE = 'mouse', i.POINTER_TOUCH = 'touch', i.POINTER_PEN = 'pen', i.EVENT_START = 'start', i.EVENT_MOVE = 'move', i.EVENT_END = 'end', i.DOCUMENT = document, i.plugins = {}, i.READY = !1, i.Instance = function (t, e) {
    var r = this;
    return n(), this.element = t, this.enabled = !0, this.options = i.utils.extend(i.utils.extend({}, i.defaults), e || {}), this.options.stop_browser_behavior && i.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior), i.event.onTouch(t, i.EVENT_START, function (t) {
      r.enabled && i.detection.startDetect(r, t);
    }), this;
  }, i.Instance.prototype = {
    on: function (t, e) {
      for (var n = t.split(' '), i = 0; n.length > i; i++)
        this.element.addEventListener(n[i], e, !1);
      return this;
    },
    off: function (t, e) {
      for (var n = t.split(' '), i = 0; n.length > i; i++)
        this.element.removeEventListener(n[i], e, !1);
      return this;
    },
    trigger: function (t, e) {
      var n = i.DOCUMENT.createEvent('Event');
      n.initEvent(t, !0, !0), n.gesture = e;
      var r = this.element;
      return i.utils.hasParent(e.target, r) && (r = e.target), r.dispatchEvent(n), this;
    },
    enable: function (t) {
      return this.enabled = t, this;
    }
  };
  var r = null, o = !1, s = !1;
  i.event = {
    bindDom: function (t, e, n) {
      for (var i = e.split(' '), r = 0; i.length > r; r++)
        t.addEventListener(i[r], n, !1);
    },
    onTouch: function (t, e, n) {
      var a = this;
      this.bindDom(t, i.EVENT_TYPES[e], function (c) {
        var u = c.type.toLowerCase();
        if (!u.match(/mouse/) || !s) {
          (u.match(/touch/) || u.match(/pointerdown/) || u.match(/mouse/) && 1 === c.which) && (o = !0), u.match(/touch|pointer/) && (s = !0);
          var h = 0;
          o && (i.HAS_POINTEREVENTS && e != i.EVENT_END ? h = i.PointerEvent.updatePointer(e, c) : u.match(/touch/) ? h = c.touches.length : s || (h = u.match(/up/) ? 0 : 1), h > 0 && e == i.EVENT_END ? e = i.EVENT_MOVE : h || (e = i.EVENT_END), h || null === r ? r = c : c = r, n.call(i.detection, a.collectEventData(t, e, c)), i.HAS_POINTEREVENTS && e == i.EVENT_END && (h = i.PointerEvent.updatePointer(e, c))), h || (r = null, o = !1, s = !1, i.PointerEvent.reset());
        }
      });
    },
    determineEventTypes: function () {
      var t;
      t = i.HAS_POINTEREVENTS ? i.PointerEvent.getEvents() : i.NO_MOUSEEVENTS ? [
        'touchstart',
        'touchmove',
        'touchend touchcancel'
      ] : [
        'touchstart mousedown',
        'touchmove mousemove',
        'touchend touchcancel mouseup'
      ], i.EVENT_TYPES[i.EVENT_START] = t[0], i.EVENT_TYPES[i.EVENT_MOVE] = t[1], i.EVENT_TYPES[i.EVENT_END] = t[2];
    },
    getTouchList: function (t) {
      return i.HAS_POINTEREVENTS ? i.PointerEvent.getTouchList() : t.touches ? t.touches : [{
          identifier: 1,
          pageX: t.pageX,
          pageY: t.pageY,
          target: t.target
        }];
    },
    collectEventData: function (t, e, n) {
      var r = this.getTouchList(n, e), o = i.POINTER_TOUCH;
      return (n.type.match(/mouse/) || i.PointerEvent.matchType(i.POINTER_MOUSE, n)) && (o = i.POINTER_MOUSE), {
        center: i.utils.getCenter(r),
        timeStamp: new Date().getTime(),
        target: n.target,
        touches: r,
        eventType: e,
        pointerType: o,
        srcEvent: n,
        preventDefault: function () {
          this.srcEvent.preventManipulation && this.srcEvent.preventManipulation(), this.srcEvent.preventDefault && this.srcEvent.preventDefault();
        },
        stopPropagation: function () {
          this.srcEvent.stopPropagation();
        },
        stopDetect: function () {
          return i.detection.stopDetect();
        }
      };
    }
  }, i.PointerEvent = {
    pointers: {},
    getTouchList: function () {
      var t = this, e = [];
      return Object.keys(t.pointers).sort().forEach(function (n) {
        e.push(t.pointers[n]);
      }), e;
    },
    updatePointer: function (t, e) {
      return t == i.EVENT_END ? this.pointers = {} : (e.identifier = e.pointerId, this.pointers[e.pointerId] = e), Object.keys(this.pointers).length;
    },
    matchType: function (t, e) {
      if (!e.pointerType)
        return !1;
      var n = {};
      return n[i.POINTER_MOUSE] = e.pointerType == e.MSPOINTER_TYPE_MOUSE || e.pointerType == i.POINTER_MOUSE, n[i.POINTER_TOUCH] = e.pointerType == e.MSPOINTER_TYPE_TOUCH || e.pointerType == i.POINTER_TOUCH, n[i.POINTER_PEN] = e.pointerType == e.MSPOINTER_TYPE_PEN || e.pointerType == i.POINTER_PEN, n[t];
    },
    getEvents: function () {
      return [
        'pointerdown MSPointerDown',
        'pointermove MSPointerMove',
        'pointerup pointercancel MSPointerUp MSPointerCancel'
      ];
    },
    reset: function () {
      this.pointers = {};
    }
  }, i.utils = {
    extend: function (t, n, i) {
      for (var r in n)
        t[r] !== e && i || (t[r] = n[r]);
      return t;
    },
    hasParent: function (t, e) {
      for (; t;) {
        if (t == e)
          return !0;
        t = t.parentNode;
      }
      return !1;
    },
    getCenter: function (t) {
      for (var e = [], n = [], i = 0, r = t.length; r > i; i++)
        e.push(t[i].pageX), n.push(t[i].pageY);
      return {
        pageX: (Math.min.apply(Math, e) + Math.max.apply(Math, e)) / 2,
        pageY: (Math.min.apply(Math, n) + Math.max.apply(Math, n)) / 2
      };
    },
    getVelocity: function (t, e, n) {
      return {
        x: Math.abs(e / t) || 0,
        y: Math.abs(n / t) || 0
      };
    },
    getAngle: function (t, e) {
      var n = e.pageY - t.pageY, i = e.pageX - t.pageX;
      return 180 * Math.atan2(n, i) / Math.PI;
    },
    getDirection: function (t, e) {
      var n = Math.abs(t.pageX - e.pageX), r = Math.abs(t.pageY - e.pageY);
      return n >= r ? t.pageX - e.pageX > 0 ? i.DIRECTION_LEFT : i.DIRECTION_RIGHT : t.pageY - e.pageY > 0 ? i.DIRECTION_UP : i.DIRECTION_DOWN;
    },
    getDistance: function (t, e) {
      var n = e.pageX - t.pageX, i = e.pageY - t.pageY;
      return Math.sqrt(n * n + i * i);
    },
    getScale: function (t, e) {
      return t.length >= 2 && e.length >= 2 ? this.getDistance(e[0], e[1]) / this.getDistance(t[0], t[1]) : 1;
    },
    getRotation: function (t, e) {
      return t.length >= 2 && e.length >= 2 ? this.getAngle(e[1], e[0]) - this.getAngle(t[1], t[0]) : 0;
    },
    isVertical: function (t) {
      return t == i.DIRECTION_UP || t == i.DIRECTION_DOWN;
    },
    stopDefaultBrowserBehavior: function (t, e) {
      var n, i = [
          'webkit',
          'khtml',
          'moz',
          'ms',
          'o',
          ''
        ];
      if (e && t.style) {
        for (var r = 0; i.length > r; r++)
          for (var o in e)
            e.hasOwnProperty(o) && (n = o, i[r] && (n = i[r] + n.substring(0, 1).toUpperCase() + n.substring(1)), t.style[n] = e[o]);
        'none' == e.userSelect && (t.onselectstart = function () {
          return !1;
        });
      }
    }
  }, i.detection = {
    gestures: [],
    current: null,
    previous: null,
    stopped: !1,
    startDetect: function (t, e) {
      this.current || (this.stopped = !1, this.current = {
        inst: t,
        startEvent: i.utils.extend({}, e),
        lastEvent: !1,
        name: ''
      }, this.detect(e));
    },
    detect: function (t) {
      if (this.current && !this.stopped) {
        t = this.extendEventData(t);
        for (var e = this.current.inst.options, n = 0, r = this.gestures.length; r > n; n++) {
          var o = this.gestures[n];
          if (!this.stopped && e[o.name] !== !1 && o.handler.call(o, t, this.current.inst) === !1) {
            this.stopDetect();
            break;
          }
        }
        return this.current && (this.current.lastEvent = t), t.eventType == i.EVENT_END && !t.touches.length - 1 && this.stopDetect(), t;
      }
    },
    stopDetect: function () {
      this.previous = i.utils.extend({}, this.current), this.current = null, this.stopped = !0;
    },
    extendEventData: function (t) {
      var e = this.current.startEvent;
      if (e && (t.touches.length != e.touches.length || t.touches === e.touches)) {
        e.touches = [];
        for (var n = 0, r = t.touches.length; r > n; n++)
          e.touches.push(i.utils.extend({}, t.touches[n]));
      }
      var o = t.timeStamp - e.timeStamp, s = t.center.pageX - e.center.pageX, a = t.center.pageY - e.center.pageY, c = i.utils.getVelocity(o, s, a);
      return i.utils.extend(t, {
        deltaTime: o,
        deltaX: s,
        deltaY: a,
        velocityX: c.x,
        velocityY: c.y,
        distance: i.utils.getDistance(e.center, t.center),
        angle: i.utils.getAngle(e.center, t.center),
        direction: i.utils.getDirection(e.center, t.center),
        scale: i.utils.getScale(e.touches, t.touches),
        rotation: i.utils.getRotation(e.touches, t.touches),
        startEvent: e
      }), t;
    },
    register: function (t) {
      var n = t.defaults || {};
      return n[t.name] === e && (n[t.name] = !0), i.utils.extend(i.defaults, n, !0), t.index = t.index || 1000, this.gestures.push(t), this.gestures.sort(function (t, e) {
        return t.index < e.index ? -1 : t.index > e.index ? 1 : 0;
      }), this.gestures;
    }
  }, i.gestures = i.gestures || {}, i.gestures.Hold = {
    name: 'hold',
    index: 10,
    defaults: {
      hold_timeout: 500,
      hold_threshold: 1
    },
    timer: null,
    handler: function (t, e) {
      switch (t.eventType) {
      case i.EVENT_START:
        clearTimeout(this.timer), i.detection.current.name = this.name, this.timer = setTimeout(function () {
          'hold' == i.detection.current.name && e.trigger('hold', t);
        }, e.options.hold_timeout);
        break;
      case i.EVENT_MOVE:
        t.distance > e.options.hold_threshold && clearTimeout(this.timer);
        break;
      case i.EVENT_END:
        clearTimeout(this.timer);
      }
    }
  }, i.gestures.Tap = {
    name: 'tap',
    index: 100,
    defaults: {
      tap_max_touchtime: 250,
      tap_max_distance: 10,
      tap_always: !0,
      doubletap_distance: 20,
      doubletap_interval: 300
    },
    handler: function (t, e) {
      if (t.eventType == i.EVENT_END) {
        var n = i.detection.previous, r = !1;
        if (t.deltaTime > e.options.tap_max_touchtime || t.distance > e.options.tap_max_distance)
          return;
        n && 'tap' == n.name && t.timeStamp - n.lastEvent.timeStamp < e.options.doubletap_interval && t.distance < e.options.doubletap_distance && (e.trigger('doubletap', t), r = !0), (!r || e.options.tap_always) && (i.detection.current.name = 'tap', e.trigger(i.detection.current.name, t));
      }
    }
  }, i.gestures.Swipe = {
    name: 'swipe',
    index: 40,
    defaults: {
      swipe_max_touches: 1,
      swipe_velocity: 0.7
    },
    handler: function (t, e) {
      if (t.eventType == i.EVENT_END) {
        if (e.options.swipe_max_touches > 0 && t.touches.length > e.options.swipe_max_touches)
          return;
        (t.velocityX > e.options.swipe_velocity || t.velocityY > e.options.swipe_velocity) && (e.trigger(this.name, t), e.trigger(this.name + t.direction, t));
      }
    }
  }, i.gestures.Drag = {
    name: 'drag',
    index: 50,
    defaults: {
      drag_min_distance: 10,
      drag_max_touches: 1,
      drag_block_horizontal: !1,
      drag_block_vertical: !1,
      drag_lock_to_axis: !1,
      drag_lock_min_distance: 25
    },
    triggered: !1,
    handler: function (t, n) {
      if (i.detection.current.name != this.name && this.triggered)
        return n.trigger(this.name + 'end', t), this.triggered = !1, e;
      if (!(n.options.drag_max_touches > 0 && t.touches.length > n.options.drag_max_touches))
        switch (t.eventType) {
        case i.EVENT_START:
          this.triggered = !1;
          break;
        case i.EVENT_MOVE:
          if (t.distance < n.options.drag_min_distance && i.detection.current.name != this.name)
            return;
          i.detection.current.name = this.name, (i.detection.current.lastEvent.drag_locked_to_axis || n.options.drag_lock_to_axis && n.options.drag_lock_min_distance <= t.distance) && (t.drag_locked_to_axis = !0);
          var r = i.detection.current.lastEvent.direction;
          t.drag_locked_to_axis && r !== t.direction && (t.direction = i.utils.isVertical(r) ? 0 > t.deltaY ? i.DIRECTION_UP : i.DIRECTION_DOWN : 0 > t.deltaX ? i.DIRECTION_LEFT : i.DIRECTION_RIGHT), this.triggered || (n.trigger(this.name + 'start', t), this.triggered = !0), n.trigger(this.name, t), n.trigger(this.name + t.direction, t), (n.options.drag_block_vertical && i.utils.isVertical(t.direction) || n.options.drag_block_horizontal && !i.utils.isVertical(t.direction)) && t.preventDefault();
          break;
        case i.EVENT_END:
          this.triggered && n.trigger(this.name + 'end', t), this.triggered = !1;
        }
    }
  }, i.gestures.Transform = {
    name: 'transform',
    index: 45,
    defaults: {
      transform_min_scale: 0.01,
      transform_min_rotation: 1,
      transform_always_block: !1
    },
    triggered: !1,
    handler: function (t, n) {
      if (i.detection.current.name != this.name && this.triggered)
        return n.trigger(this.name + 'end', t), this.triggered = !1, e;
      if (!(2 > t.touches.length))
        switch (n.options.transform_always_block && t.preventDefault(), t.eventType) {
        case i.EVENT_START:
          this.triggered = !1;
          break;
        case i.EVENT_MOVE:
          var r = Math.abs(1 - t.scale), o = Math.abs(t.rotation);
          if (n.options.transform_min_scale > r && n.options.transform_min_rotation > o)
            return;
          i.detection.current.name = this.name, this.triggered || (n.trigger(this.name + 'start', t), this.triggered = !0), n.trigger(this.name, t), o > n.options.transform_min_rotation && n.trigger('rotate', t), r > n.options.transform_min_scale && (n.trigger('pinch', t), n.trigger('pinch' + (1 > t.scale ? 'in' : 'out'), t));
          break;
        case i.EVENT_END:
          this.triggered && n.trigger(this.name + 'end', t), this.triggered = !1;
        }
    }
  }, i.gestures.Touch = {
    name: 'touch',
    index: -1 / 0,
    defaults: {
      prevent_default: !1,
      prevent_mouseevents: !1
    },
    handler: function (t, n) {
      return n.options.prevent_mouseevents && t.pointerType == i.POINTER_MOUSE ? (t.stopDetect(), e) : (n.options.prevent_default && t.preventDefault(), t.eventType == i.EVENT_START && n.trigger(this.name, t), e);
    }
  }, i.gestures.Release = {
    name: 'release',
    index: 1 / 0,
    handler: function (t, e) {
      t.eventType == i.EVENT_END && e.trigger(this.name, t);
    }
  }, 'object' == typeof module && 'object' == typeof module.exports ? module.exports = i : (t.Hammer = i, 'function' == typeof t.define && t.define.amd && t.define('hammer', [], function () {
    return i;
  }));
}(this));
(function (e) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], e);
  } else if (typeof exports === 'object') {
    module.exports = e;
  } else {
    e(jQuery);
  }
}(function (e) {
  function o(t) {
    var n = t || window.event, s = [].slice.call(arguments, 1), o = 0, u = 0, a = 0, f = 0, l = 0, c;
    t = e.event.fix(n);
    t.type = 'mousewheel';
    if (n.wheelDelta) {
      o = n.wheelDelta;
    }
    if (n.detail) {
      o = n.detail * -1;
    }
    if (n.deltaY) {
      a = n.deltaY * -1;
      o = a;
    }
    if (n.deltaX) {
      u = n.deltaX;
      o = u * -1;
    }
    if (n.wheelDeltaY !== undefined) {
      a = n.wheelDeltaY;
    }
    if (n.wheelDeltaX !== undefined) {
      u = n.wheelDeltaX * -1;
    }
    f = Math.abs(o);
    if (!r || f < r) {
      r = f;
    }
    l = Math.max(Math.abs(a), Math.abs(u));
    if (!i || l < i) {
      i = l;
    }
    c = o > 0 ? 'floor' : 'ceil';
    o = Math[c](o / r);
    u = Math[c](u / i);
    a = Math[c](a / i);
    s.unshift(t, o, u, a);
    return (e.event.dispatch || e.event.handle).apply(this, s);
  }
  var t = [
      'wheel',
      'mousewheel',
      'DOMMouseScroll',
      'MozMousePixelScroll'
    ];
  var n = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : [
      'mousewheel',
      'DomMouseScroll',
      'MozMousePixelScroll'
    ];
  var r, i;
  if (e.event.fixHooks) {
    for (var s = t.length; s;) {
      e.event.fixHooks[t[--s]] = e.event.mouseHooks;
    }
  }
  e.event.special.mousewheel = {
    setup: function () {
      if (this.addEventListener) {
        for (var e = n.length; e;) {
          this.addEventListener(n[--e], o, false);
        }
      } else {
        this.onmousewheel = o;
      }
    },
    teardown: function () {
      if (this.removeEventListener) {
        for (var e = n.length; e;) {
          this.removeEventListener(n[--e], o, false);
        }
      } else {
        this.onmousewheel = null;
      }
    }
  };
  e.fn.extend({
    mousewheel: function (e) {
      return e ? this.bind('mousewheel', e) : this.trigger('mousewheel');
    },
    unmousewheel: function (e) {
      return this.unbind('mousewheel', e);
    }
  });
}));
window.requestAnimFrame = function () {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
    window.setTimeout(callback, 1000 / 60);
  };
}();
$(document).bind('contextmenu', function (e) {
  return false;
}, false);
$(document).bind('keyup', function (e) {
  if (e.keyCode == 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
    return false;
  }
}, false);
$(document).ready(function () {
  var $epubbyElement = $('html'), epubbyUnderCursor = null, $epubbyUnderCursor = null, epubbyHighlightClass = 'epubby-highlight', epubbyPageId = $('script#epubby_injectable').data('page'), epubbyPageIndex = parseInt(epubbyPageId.substring(5), false), $epubbyPage = window.parent.$('#' + epubbyPageId), epubbyParentWindow = $(window.parent.window), $epubbyWrap = $(document.getElementsByTagName(window.parent.CONFIG.marker)), $leftbar = $('div.epubby-leftbar'), $rightbar = $('div.epubby-rightbar'), $epubbyToolbarController = window.parent.window.$('#toolbarController'), $epubbyToolbar = window.parent.window.$('.tool-container:first'), epubbyFirstIdOrig = null, epubbyLastIdOrig = null, epubbyFirstId = null, epubbyLastId = null, isHead = false, isTail = false, epubbyAllowPanning = true, epubbyPanStartX = 0, epubbyPanStartY = 0, epubbyPanEndY = 0, epubbyPanEndX = 0, epubbyPanTop = 0, epubbyPanLeft = 0, epubbyMouseDown = false, epubbyToolbarPosArray = [], epubbyToolbarPos = 0, $epubbyPage2 = undefined, epubbyPage2Index = null, limitVertical = null, limitHorizontal = null, pane = undefined, epubbyPrevPanEndX = 0, epubbyPrevPanEndY = 0, tempId, tempIdOrig;
  hammer = Hammer($epubbyElement.get(0)), $scope = window.parent.$('[ng-controller="mainCtrl"]').scope(), BookOpts = window.parent.$('html').injector().get('BookOpts'), StateService = window.parent.$('html').injector().get('StateService');
  BookOpts.IS_PANNING = false;
  $epubbyElement.on('tap', function (e) {
    if (e.type !== 'mouseout') {
      $scope.safeApply(function () {
        StateService.removeMenuParams();
        BookOpts.showPanels = !BookOpts.showPanels;
      });
    }
  }).on('mousedown', function (e) {
    $(window.top.document.body).find('.hotspot-menu, .modal-hotSpot').remove();
    epubbyMouseDown = true;
    epubbyUnderCursor = e.target || e.srcElement;
    window.requestAnimFrame(update);
    $epubbyUnderCursor = $(epubbyUnderCursor);
    epubbyPanStartX = e.pageX;
    epubbyPanStartY = e.pageY;
    if ($epubbyUnderCursor.hasClass('epubby-bars')) {
      if ($epubbyUnderCursor.hasClass('epubby-leftbar') || $epubbyUnderCursor.hasClass('epubby-ldot') || $epubbyUnderCursor.hasClass('epubby-ldotSupport')) {
        epubbyUnderCursor = $(window.parent.CONFIG.marker + '.' + epubbyHighlightClass + ':first').get(0);
      } else {
        epubbyUnderCursor = $(window.parent.CONFIG.marker + '.' + epubbyHighlightClass + ':last').get(0);
      }
    }
    $epubbyUnderCursor = $(epubbyUnderCursor);
    epubbyUnderCursor = getTextIdElement($epubbyUnderCursor);
    $epubbyUnderCursor = $(epubbyUnderCursor);
    if (!$epubbyUnderCursor.hasClass(epubbyHighlightClass)) {
      removeHighlighting();
    }
    $scope.safeApply(function () {
      BookOpts.showToolbar = null;
    });
    if (isLooped(epubbyUnderCursor.id)) {
      if (epubbyFirstId === null || epubbyLastId === null) {
        epubbyFirstId = mutate(epubbyUnderCursor.id, 'first');
        epubbyLastId = mutate(epubbyUnderCursor.id, 'last');
      } else if (epubbyFirstId > epubbyLastId) {
        tempId = epubbyFirstId;
        tempIdOrig = epubbyFirstIdOrig;
        epubbyFirstId = epubbyLastId;
        epubbyFirstIdOrig = epubbyLastIdOrig;
        epubbyLastId = tempId;
        epubbyLastIdOrig = tempIdOrig;
      }
      if (epubbyUnderCursor === document.getElementsByClassName(epubbyHighlightClass)[0]) {
        isHead = true;
        isTail = false;
      } else {
        isHead = false;
        isTail = true;
      }
      if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
        if (BookOpts.enableHighlight && !$epubbyUnderCursor.hasClass('epubby-highlight_normal') && !$epubbyUnderCursor.hasClass('epubby-highlight_important') && !$epubbyUnderCursor.hasClass('epubby-note_normal') && !$epubbyUnderCursor.hasClass('epubby-note_normal')) {
          addHighlighting();
          moveLeftBar($('#' + epubbyFirstIdOrig));
          moveRightBar($('#' + epubbyLastIdOrig));
        }
      } else {
        if (BookOpts.enableHighlight && !epubbyUnderCursor.classList.contains('epubby-highlight_normal') && !epubbyUnderCursor.classList.contains('epubby-highlight_important') && !epubbyUnderCursor.classList.contains('epubby-note_normal') && !epubbyUnderCursor.classList.contains('epubby-note_important')) {
          addHighlighting();
          moveLeftBar($('#' + epubbyFirstIdOrig));
          moveRightBar($('#' + epubbyLastIdOrig));
        }
      }
    }
  }).on('mouseup', function (e) {
    epubbyMouseDown = false;
    epubbyToolbarPosArray = [
      epubbyFirstId,
      epubbyLastId
    ].sort(function (a, b) {
      return a - b;
    });
    epubbyToolbarPos = isTail ? epubbyToolbarPosArray[1] : epubbyToolbarPosArray[0];
    epubbyToolbarPos = epubbyToolbarPos === epubbyFirstId ? epubbyFirstIdOrig : epubbyLastIdOrig;
    $epubbyUnderCursor = $('#' + epubbyToolbarPos);
    epubbyUnderCursor = $epubbyUnderCursor.get(0);
    if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
      if (epubbyToolbarPos !== null && $epubbyUnderCursor.hasClass(epubbyHighlightClass) && !$epubbyUnderCursor.hasClass('epubby-highlight_normal') && !$epubbyUnderCursor.hasClass('epubby-highlight_important') && !$epubbyUnderCursor.hasClass('epubby-note_normal') && !$epubbyUnderCursor.hasClass('epubby-note_normal')) {
        BookOpts.toolbarData = {
          pageId: epubbyPageId,
          noteId: '',
          domId: epubbyToolbarPos,
          showClearOption: false,
          showSearchOption: true
        };
        $scope.safeApply(function () {
          BookOpts.showToolbar = true;
        });
      }
    } else {
      if (epubbyToolbarPos !== null && epubbyUnderCursor.classList.contains(epubbyHighlightClass) && !epubbyUnderCursor.classList.contains('epubby-highlight_normal') && !epubbyUnderCursor.classList.contains('epubby-highlight_important') && !epubbyUnderCursor.classList.contains('epubby-note_normal') && !epubbyUnderCursor.classList.contains('epubby-note_important')) {
        BookOpts.toolbarData = {
          pageId: epubbyPageId,
          noteId: '',
          domId: epubbyToolbarPos,
          showClearOption: false,
          showSearchOption: true
        };
        $scope.safeApply(function () {
          BookOpts.showToolbar = true;
        });
      }
    }
    BookOpts.IS_PANNING = false;
    epubbyFirstId = null;
    epubbyLastId = null;
    epubbyFirstIdOrig = null;
    epubbyLastIdOrig = null;
    epubbyAllowPanning = true;
  }).on('mousemove', function (e) {
    epubbyUnderCursor = e.target || e.srcElement;
    $epubbyUnderCursor = $(epubbyUnderCursor);
    epubbyPanEndX = e.pageX;
    epubbyPanEndY = e.pageY;
    if (epubbyAllowPanning && epubbyMouseDown && !BookOpts.SLIDING) {
      $epubbyPage2 = $epubbyPage.next('.epub-page').css('visibility') === 'visible' ? $epubbyPage.next('.epub-page') : $epubbyPage.prev('.epub-page').css('visibility') === 'visible' ? $epubbyPage.prev('.epub-page') : undefined;
      epubbyPage2Index = $epubbyPage2 ? parseInt($epubbyPage2.attr('id').substring(5), false) : null;
      pane = $epubbyPage2 ? 2 : 1;
      limitVertical = epubbyParentWindow.height() - $epubbyPage.height() * BookOpts.pageScale[epubbyPageIndex] - BookOpts.PAGE_PAD_BOTTOM();
      limitHorizontal = epubbyParentWindow.width() - ($epubbyPage.width() * BookOpts.pageScale[epubbyPageIndex] + BookOpts.PAGE_PAD_PANNING / pane) * pane;
      BookOpts.IS_PANNING = true;
    }
    if (!epubbyMouseDown || !isLooped(epubbyUnderCursor.id) || !$leftbar.is(':visible') || !$rightbar.is(':visible'))
      return;
    if (isTail) {
      epubbyLastId = mutate(epubbyUnderCursor.id, 'last');
    } else if (isHead) {
      epubbyFirstId = mutate(epubbyUnderCursor.id, 'first');
    }
    addHighlighting();
    if (epubbyFirstId <= epubbyLastId) {
      moveLeftBar($('#' + epubbyFirstIdOrig));
      moveRightBar($('#' + epubbyLastIdOrig));
    } else {
      moveLeftBar($('#' + epubbyLastIdOrig));
      moveRightBar($('#' + epubbyFirstIdOrig));
    }
  }).bind('mousewheel', function (e, delta) {
    if ($(e.target).next().length > 0) {
      if (!$(e.target).next().get(0).className === 'hotspot-menu') {
        $(window.top.document.body).find('.hotspot-menu, .modal-hotSpot').remove();
      }
    } else {
      $(window.top.document.body).find('.hotspot-menu, .modal-hotSpot').remove();
    }
    if (epubbyAllowPanning && !epubbyMouseDown && !BookOpts.SLIDING) {
      var $epubbyPage2 = $epubbyPage.next('.epub-page').css('visibility') === 'visible' ? $epubbyPage.next('.epub-page') : $epubbyPage.prev('.epub-page').css('visibility') === 'visible' ? $epubbyPage.prev('.epub-page') : undefined, epubbyPage2Index = $epubbyPage2 ? parseInt($epubbyPage2.attr('id').substring(5), false) : null, limitVertical = epubbyParentWindow.height() - $epubbyPage.height() * BookOpts.pageScale[epubbyPageIndex] - BookOpts.PAGE_PAD_BOTTOM(), epubbyPanTop = -100;
      if (delta === -1) {
        BookOpts.pageTop[epubbyPageIndex] += epubbyPanTop;
        if (BookOpts.pageTop[epubbyPageIndex] < limitVertical) {
          BookOpts.pageTop[epubbyPageIndex] = limitVertical;
          BookOpts.pageTop[epubbyPageIndex] = BookOpts.pageTop[epubbyPageIndex] > BookOpts.PAGE_PAD_TOP ? BookOpts.PAGE_PAD_TOP : BookOpts.pageTop[epubbyPageIndex];
        }
        $epubbyPage.css({ top: BookOpts.pageTop[epubbyPageIndex] });
        if (epubbyPage2Index !== null) {
          $epubbyPage2.css({ top: BookOpts.pageTop[epubbyPageIndex] });
          BookOpts.pageTop[epubbyPage2Index] = BookOpts.pageTop[epubbyPageIndex];
        }
      } else {
        BookOpts.pageTop[epubbyPageIndex] -= epubbyPanTop;
        if (BookOpts.pageTop[epubbyPageIndex] > BookOpts.PAGE_PAD_TOP) {
          BookOpts.pageTop[epubbyPageIndex] = BookOpts.PAGE_PAD_TOP;
        }
        $epubbyPage.css({ top: BookOpts.pageTop[epubbyPageIndex] });
        if (epubbyPage2Index !== null) {
          $epubbyPage2.css({ top: BookOpts.pageTop[epubbyPageIndex] });
          BookOpts.pageTop[epubbyPage2Index] = BookOpts.pageTop[epubbyPageIndex];
        }
      }
    }
  });
  function moveLeftBar($el) {
    if ($leftbar.length === 0)
      $leftbar = $('div.epubby-leftbar');
    var objPos;
    if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
      objPos = {
        top: $el.offset().top / BookOpts.pageScale[epubbyPageIndex],
        left: $el.offset().left / BookOpts.pageScale[epubbyPageIndex]
      };
    } else {
      objPos = $el.offset();
    }
    var barHeight = $el.height();
    $leftbar.css(objPos).css('height', barHeight).show();
  }
  function moveRightBar($el) {
    if ($rightbar.length === 0)
      $rightbar = $('div.epubby-rightbar');
    var objPos;
    if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
      objPos = {
        top: $el.offset().top / BookOpts.pageScale[epubbyPageIndex],
        left: $el.offset().left / BookOpts.pageScale[epubbyPageIndex]
      };
    } else {
      objPos = $el.offset();
    }
    var barHeight = $el.height();
    objPos.left += $el.width() - 4;
    $rightbar.css(objPos).css('height', barHeight).show();
  }
  function removeHighlighting() {
    $epubbyWrap = document.querySelectorAll ? $(document.querySelectorAll('.' + epubbyHighlightClass)) : $(document).find('.' + epubbyHighlightClass);
    $epubbyWrap.each(function () {
      if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
        $(this).removeClass(epubbyHighlightClass);
      } else {
        this.classList.remove(epubbyHighlightClass);
      }
    });
    $leftbar.hide();
    $rightbar.hide();
  }
  ;
  function addHighlighting() {
    var prefix = '#' + epubbyFirstIdOrig.match(/^p[0-9]+-textid/i), from = parseInt(epubbyFirstIdOrig.match(/[0-9]*$/i)[0], false), to = parseInt(epubbyLastIdOrig.match(/[0-9]*$/i)[0], false), temp = null, $temp = null, arrWrap = [], csvWrap = null;
    if (from > to) {
      temp = from;
      from = to;
      to = temp;
      temp = null;
    }
    epubbyAllowPanning = false;
    $epubbyWrap = document.querySelectorAll ? $(document.querySelectorAll('.' + epubbyHighlightClass)) : $(document).find('.' + epubbyHighlightClass);
    $epubbyWrap.each(function () {
      if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
        $(this).removeClass(epubbyHighlightClass);
      } else {
        this.classList.remove(epubbyHighlightClass);
      }
    });
    for (var i = from; i <= to; i++) {
      $temp = $(prefix + i).get(0);
      if (window.parent.BrowserDetect.browser === 'Internet Explorer' && window.parent.BrowserDetect.version < 10) {
        $temp = $($temp);
        if ($temp && !$temp.hasClass('epubby-highlight_normal') && !$temp.hasClass('epubby-highlight_important') && !$temp.hasClass('epubby-note_normal') && !$temp.hasClass('epubby-note_important')) {
          $temp.addClass(epubbyHighlightClass);
        }
        if (BookOpts.bookType === 'fixed' && !$temp.get(0).style.width) {
          $temp.css(window.parent.setDimensions($epubbyElement, $temp, BookOpts.pageScale[epubbyPageIndex]));
        }
      } else {
        if ($temp && !$temp.classList.contains('epubby-highlight_normal') && !$temp.classList.contains('epubby-highlight_important') && !$temp.classList.contains('epubby-note_normal') && !$temp.classList.contains('epubby-note_important')) {
          $temp.classList.add(epubbyHighlightClass);
        }
        if (BookOpts.bookType === 'fixed' && !$temp.style.width) {
          $($temp).css(window.parent.setDimensions($epubbyElement, $($temp)));
        }
      }
    }
  }
  function mutate(id, firstOrLast) {
    if (id === undefined)
      return false;
    if (!isTEXTID(id) && isCID(id)) {
      id = document.getElementById(id).parentNode.id;
    }
    var matches = id.match(/\d+$/);
    if (firstOrLast === 'first') {
      epubbyFirstIdOrig = id;
    } else if (firstOrLast === 'last') {
      epubbyLastIdOrig = id;
    }
    if ($.isArray(matches) && matches.length > 0) {
      return parseInt(matches[0], false);
    }
  }
  function getTextIdElement($element) {
    var id = $element.get(0).id;
    if (!id)
      return $element;
    if (!isTEXTID(id) && isCID(id)) {
      id = $element.get(0).parentNode.id;
    }
    if (!id)
      return $element;
    return document.getElementById(id);
  }
  function update() {
    if (epubbyAllowPanning && epubbyMouseDown && !BookOpts.SLIDING) {
      window.requestAnimFrame(update);
      if (epubbyPrevPanEndY !== epubbyPanEndY) {
        if (epubbyPanStartY > epubbyPanEndY) {
          epubbyPanTop = epubbyPanEndY - epubbyPanStartY;
          BookOpts.pageTop[epubbyPageIndex] += epubbyPanTop;
          if (BookOpts.pageTop[epubbyPageIndex] < limitVertical) {
            BookOpts.pageTop[epubbyPageIndex] = limitVertical;
            BookOpts.pageTop[epubbyPageIndex] = BookOpts.pageTop[epubbyPageIndex] > BookOpts.PAGE_PAD_TOP ? BookOpts.PAGE_PAD_TOP : BookOpts.pageTop[epubbyPageIndex];
          }
          $epubbyPage.css({ top: BookOpts.pageTop[epubbyPageIndex] });
          if (epubbyPage2Index !== null) {
            $epubbyPage2.css({ top: BookOpts.pageTop[epubbyPageIndex] });
            BookOpts.pageTop[epubbyPage2Index] = BookOpts.pageTop[epubbyPageIndex];
          }
        } else {
          epubbyPanTop = epubbyPanStartY - epubbyPanEndY;
          BookOpts.pageTop[epubbyPageIndex] -= epubbyPanTop;
          if (BookOpts.pageTop[epubbyPageIndex] > BookOpts.PAGE_PAD_TOP) {
            BookOpts.pageTop[epubbyPageIndex] = BookOpts.PAGE_PAD_TOP;
          }
          $epubbyPage.css({ top: BookOpts.pageTop[epubbyPageIndex] });
          if (epubbyPage2Index !== null) {
            $epubbyPage2.css({ top: BookOpts.pageTop[epubbyPageIndex] });
            BookOpts.pageTop[epubbyPage2Index] = BookOpts.pageTop[epubbyPageIndex];
          }
        }
      }
      if (epubbyPrevPanEndX !== epubbyPanEndX) {
        if (epubbyPanStartX > epubbyPanEndX) {
          epubbyPanLeft = epubbyPanEndX - epubbyPanStartX;
          BookOpts.pageLeft[epubbyPageIndex] += epubbyPanLeft;
          if (BookOpts.pageLeft[epubbyPageIndex] < limitHorizontal) {
            BookOpts.pageLeft[epubbyPageIndex] = limitHorizontal;
            BookOpts.pageLeft[epubbyPageIndex] = BookOpts.pageLeft[epubbyPageIndex] > 0 ? 0 : BookOpts.pageLeft[epubbyPageIndex];
          }
          $epubbyPage.css({ left: BookOpts.pageLeft[epubbyPageIndex] });
          if (epubbyPage2Index !== null) {
            $epubbyPage2.css({ left: BookOpts.pageLeft[epubbyPageIndex] });
            BookOpts.pageLeft[epubbyPage2Index] = BookOpts.pageLeft[epubbyPageIndex];
          }
        } else {
          epubbyPanLeft = epubbyPanStartX - epubbyPanEndX;
          BookOpts.pageLeft[epubbyPageIndex] -= epubbyPanLeft;
          if (BookOpts.pageLeft[epubbyPageIndex] > 0) {
            BookOpts.pageLeft[epubbyPageIndex] = 0;
          }
          $epubbyPage.css({ left: BookOpts.pageLeft[epubbyPageIndex] });
          if (epubbyPage2Index !== null) {
            $epubbyPage2.css({ left: BookOpts.pageLeft[epubbyPageIndex] });
            BookOpts.pageLeft[epubbyPage2Index] = BookOpts.pageLeft[epubbyPageIndex];
          }
        }
      }
      epubbyPrevPanEndY = epubbyPanEndY;
      epubbyPrevPanEndX = epubbyPanEndX;
    }
  }
  function isLooped(id) {
    if (id === undefined)
      return false;
    return isTEXTID(id) || isCID(id);
  }
  function isTEXTID(id) {
    return id.match(/p[0-9]+-textid[0-9]+/) !== null;
  }
  function isCID(id) {
    return id.match(/p[0-9]+-cid[0-9]+/) !== null;
  }
  (function renderActivities() {
    var arrActivity = BookOpts.arrActivities[epubbyPageIndex], $activity = null, options = '', storeActivity = JSON.parse(localStorage.getItem('epubby-activities') || '[]'), storeIndex = null;
    window.parent.window._.each(arrActivity, function (activity) {
      storeIndex = window.parent.window._.filter(window.parent.window._.map(storeActivity, function (sactivity, iteration) {
        return sactivity.name === activity.properties.name ? iteration : -1;
      }), function (index) {
        return index >= 0;
      })[0];
      $activity = $('<' + activity.properties.type + '/>');
      $activity.data('store-index', storeIndex);
      $activity.attr('data-groupname', activity.groupName);
      $activity.attr('name', activity.properties.name);
      $activity.attr('alt', activity.tooltip);
      $activity.attr('title', activity.tooltip);
      if (activity.properties.readonly) {
        $activity.attr('readonly', 'readonly');
      }
      if (activity.properties.required) {
        $activity.attr('required', '');
      }
      $activity.css({
        'position': 'absolute',
        'resize': 'none',
        'left': activity.position[0] + 'px',
        'top': activity.position[1] + 'px',
        'width': activity.position[2],
        'height': activity.position[3],
        'display': activity.properties.display,
        'background-color': '#' + activity.properties.backgroundColor,
        'border': '1px solid #' + activity.properties.borderColor,
        'color': '#' + activity.properties.color,
        'font-family': activity.properties.font,
        'font-size': activity.properties.fontSize + 'px',
        'opacity': activity.opacity / 100,
        'text-align': activity.properties.textAlign
      });
      if (activity.properties.type === 'input' || activity.properties.type === 'textarea') {
        $activity.attr('value', storeActivity[$activity.data().storeIndex].value);
        $activity.html(storeActivity[$activity.data().storeIndex].value);
        if (activity.properties.maxlength) {
          $activity.attr('maxlength', activity.properties.maxlength);
        }
        $activity.keyup(function () {
          storeActivity[$(this).data().storeIndex]['value'] = this.value;
          localStorage.setItem('epubby-activities', JSON.stringify(storeActivity));
        });
      } else {
        options = '<option></option>';
        window.parent.window._.each(activity.properties.items, function (item) {
          options += '<option value="' + item + '" ' + (storeActivity[$activity.data().storeIndex].value === item ? 'selected="selected"' : '') + '>' + item + '</option>';
        });
        $activity.html(options);
        $activity.change(function () {
          storeActivity[$(this).data().storeIndex]['value'] = this.value;
          localStorage.setItem('epubby-activities', JSON.stringify(storeActivity));
        });
      }
      $epubbyElement.append($activity);
    });
  }());
});