PageRenderTime 134ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 2ms

/libs/amazeui/1.0.1/js/amazeui.widgets.js

https://gitlab.com/mba811/static
JavaScript | 10217 lines | 9263 code | 37 blank | 917 comment | 1051 complexity | a030a638ad175041edc2a29fa8acd735 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. /*! Amaze UI v1.0.1 ~ widgets | by Amaze UI Team | (c) 2014 AllMobilize, Inc. | Licensed under MIT | 2014-11-07T07:11:14 UTC */
  2. /*! Sea.js 2.2.1 | seajs.org/LICENSE.md */
  3. !function(a,b){function c(a){return function(b){return{}.toString.call(b)=="[object "+a+"]"}}function d(){return A++}function e(a){return a.match(D)[0]}function f(a){for(a=a.replace(E,"/");a.match(F);)a=a.replace(F,"/");return a=a.replace(G,"$1/")}function g(a){var b=a.length-1,c=a.charAt(b);return"#"===c?a.substring(0,b):".js"===a.substring(b-2)||a.indexOf("?")>0||".css"===a.substring(b-3)||"/"===c?a:a+".js"}function h(a){var b=v.alias;return b&&x(b[a])?b[a]:a}function i(a){var b=v.paths,c;return b&&(c=a.match(H))&&x(b[c[1]])&&(a=b[c[1]]+c[2]),a}function j(a){var b=v.vars;return b&&a.indexOf("{")>-1&&(a=a.replace(I,function(a,c){return x(b[c])?b[c]:a})),a}function k(a){var b=v.map,c=a;if(b)for(var d=0,e=b.length;e>d;d++){var f=b[d];if(c=z(f)?f(a)||a:a.replace(f[0],f[1]),c!==a)break}return c}function l(a,b){var c,d=a.charAt(0);if(J.test(a))c=a;else if("."===d)c=f((b?e(b):v.cwd)+a);else if("/"===d){var g=v.cwd.match(K);c=g?g[0]+a.substring(1):a}else c=v.base+a;return 0===c.indexOf("//")&&(c=location.protocol+c),c}function m(a,b){if(!a)return"";a=h(a),a=i(a),a=j(a),a=g(a);var c=l(a,b);return c=k(c)}function n(a){return a.hasAttribute?a.src:a.getAttribute("src",4)}function o(a,b,c){var d=S.test(a),e=L.createElement(d?"link":"script");if(c){var f=z(c)?c(a):c;f&&(e.charset=f)}p(e,b,d,a),d?(e.rel="stylesheet",e.href=a):(e.async=!0,e.src=a),T=e,R?Q.insertBefore(e,R):Q.appendChild(e),T=null}function p(a,c,d,e){function f(){a.onload=a.onerror=a.onreadystatechange=null,d||v.debug||Q.removeChild(a),a=null,c()}var g="onload"in a;return!d||!V&&g?(g?(a.onload=f,a.onerror=function(){C("error",{uri:e,node:a}),f()}):a.onreadystatechange=function(){/loaded|complete/.test(a.readyState)&&f()},b):(setTimeout(function(){q(a,c)},1),b)}function q(a,b){var c=a.sheet,d;if(V)c&&(d=!0);else if(c)try{c.cssRules&&(d=!0)}catch(e){"NS_ERROR_DOM_SECURITY_ERR"===e.name&&(d=!0)}setTimeout(function(){d?b():q(a,b)},20)}function r(){if(T)return T;if(U&&"interactive"===U.readyState)return U;for(var a=Q.getElementsByTagName("script"),b=a.length-1;b>=0;b--){var c=a[b];if("interactive"===c.readyState)return U=c}}function s(a){var b=[];return a.replace(X,"").replace(W,function(a,c,d){d&&b.push(d)}),b}function t(a,b){this.uri=a,this.dependencies=b||[],this.exports=null,this.status=0,this._waitings={},this._remain=0}if(!a.seajs){var u=a.seajs={version:"2.2.1"},v=u.data={},w=c("Object"),x=c("String"),y=Array.isArray||c("Array"),z=c("Function"),A=0,B=v.events={};u.on=function(a,b){var c=B[a]||(B[a]=[]);return c.push(b),u},u.off=function(a,b){if(!a&&!b)return B=v.events={},u;var c=B[a];if(c)if(b)for(var d=c.length-1;d>=0;d--)c[d]===b&&c.splice(d,1);else delete B[a];return u};var C=u.emit=function(a,b){var c=B[a],d;if(c)for(c=c.slice();d=c.shift();)d(b);return u},D=/[^?#]*\//,E=/\/\.\//g,F=/\/[^/]+\/\.\.\//,G=/([^:/])\/\//g,H=/^([^/:]+)(\/.+)$/,I=/{([^{]+)}/g,J=/^\/\/.|:\//,K=/^.*?\/\/.*?\//,L=document,M=e(L.URL),N=L.scripts,O=L.getElementById("seajsnode")||N[N.length-1],P=e(n(O)||M);u.resolve=m;var Q=L.head||L.getElementsByTagName("head")[0]||L.documentElement,R=Q.getElementsByTagName("base")[0],S=/\.css(?:\?|$)/i,T,U,V=+navigator.userAgent.replace(/.*(?:AppleWebKit|AndroidWebKit)\/(\d+).*/,"$1")<536;u.request=o;var W=/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\/\*[\S\s]*?\*\/|\/(?:\\\/|[^\/\r\n])+\/(?=[^\/])|\/\/.*|\.\s*require|(?:^|[^$])\brequire\s*\(\s*(["'])(.+?)\1\s*\)/g,X=/\\\\/g,Y=u.cache={},Z,$={},_={},ab={},bb=t.STATUS={FETCHING:1,SAVED:2,LOADING:3,LOADED:4,EXECUTING:5,EXECUTED:6};t.prototype.resolve=function(){for(var a=this,b=a.dependencies,c=[],d=0,e=b.length;e>d;d++)c[d]=t.resolve(b[d],a.uri);return c},t.prototype.load=function(){var a=this;if(!(a.status>=bb.LOADING)){a.status=bb.LOADING;var c=a.resolve();C("load",c);for(var d=a._remain=c.length,e,f=0;d>f;f++)e=t.get(c[f]),e.status<bb.LOADED?e._waitings[a.uri]=(e._waitings[a.uri]||0)+1:a._remain--;if(0===a._remain)return a.onload(),b;var g={};for(f=0;d>f;f++)e=Y[c[f]],e.status<bb.FETCHING?e.fetch(g):e.status===bb.SAVED&&e.load();for(var h in g)g.hasOwnProperty(h)&&g[h]()}},t.prototype.onload=function(){var a=this;a.status=bb.LOADED,a.callback&&a.callback();var b=a._waitings,c,d;for(c in b)b.hasOwnProperty(c)&&(d=Y[c],d._remain-=b[c],0===d._remain&&d.onload());delete a._waitings,delete a._remain},t.prototype.fetch=function(a){function c(){u.request(g.requestUri,g.onRequest,g.charset)}function d(){delete $[h],_[h]=!0,Z&&(t.save(f,Z),Z=null);var a,b=ab[h];for(delete ab[h];a=b.shift();)a.load()}var e=this,f=e.uri;e.status=bb.FETCHING;var g={uri:f};C("fetch",g);var h=g.requestUri||f;return!h||_[h]?(e.load(),b):$[h]?(ab[h].push(e),b):($[h]=!0,ab[h]=[e],C("request",g={uri:f,requestUri:h,onRequest:d,charset:v.charset}),g.requested||(a?a[g.requestUri]=c:c()),b)},t.prototype.exec=function(){function a(b){return t.get(a.resolve(b)).exec()}var c=this;if(c.status>=bb.EXECUTING)return c.exports;c.status=bb.EXECUTING;var e=c.uri;a.resolve=function(a){return t.resolve(a,e)},a.async=function(b,c){return t.use(b,c,e+"_async_"+d()),a};var f=c.factory,g=z(f)?f(a,c.exports={},c):f;return g===b&&(g=c.exports),delete c.factory,c.exports=g,c.status=bb.EXECUTED,C("exec",c),g},t.resolve=function(a,b){var c={id:a,refUri:b};return C("resolve",c),c.uri||u.resolve(c.id,b)},t.define=function(a,c,d){var e=arguments.length;1===e?(d=a,a=b):2===e&&(d=c,y(a)?(c=a,a=b):c=b),!y(c)&&z(d)&&(c=s(""+d));var f={id:a,uri:t.resolve(a),deps:c,factory:d};if(!f.uri&&L.attachEvent){var g=r();g&&(f.uri=g.src)}C("define",f),f.uri?t.save(f.uri,f):Z=f},t.save=function(a,b){var c=t.get(a);c.status<bb.SAVED&&(c.id=b.id||a,c.dependencies=b.deps||[],c.factory=b.factory,c.status=bb.SAVED)},t.get=function(a,b){return Y[a]||(Y[a]=new t(a,b))},t.use=function(b,c,d){var e=t.get(d,y(b)?b:[b]);e.callback=function(){for(var b=[],d=e.resolve(),f=0,g=d.length;g>f;f++)b[f]=Y[d[f]].exec();c&&c.apply(a,b),delete e.callback},e.load()},t.preload=function(a){var b=v.preload,c=b.length;c?t.use(b,function(){b.splice(0,c),t.preload(a)},v.cwd+"_preload_"+d()):a()},u.use=function(a,b){return t.preload(function(){t.use(a,b,v.cwd+"_use_"+d())}),u},t.define.cmd={},a.define=t.define,u.Module=t,v.fetchedList=_,v.cid=d,u.require=function(a){var b=t.get(t.resolve(a));return b.status<bb.EXECUTING&&(b.onload(),b.exec()),b.exports};var cb=/^(.+?\/)(\?\?)?(seajs\/)+/;v.base=(P.match(cb)||["",P])[1],v.dir=P,v.cwd=M,v.charset="utf-8",v.preload=function(){var a=[],b=location.search.replace(/(seajs-\w+)(&|$)/g,"$1=1$2");return b+=" "+L.cookie,b.replace(/(seajs-\w+)=1/g,function(b,c){a.push(c)}),a}(),u.config=function(a){for(var b in a){var c=a[b],d=v[b];if(d&&w(d))for(var e in c)d[e]=c[e];else y(d)?c=d.concat(c):"base"===b&&("/"!==c.slice(-1)&&(c+="/"),c=l(c)),v[b]=c}return C("config",a),u}}}(this);
  4. define("core", [ "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5. "use strict";
  6. // Zepto animate extend
  7. require("zepto.extend.fx");
  8. // Zepto data extend
  9. require("zepto.extend.data");
  10. // Zeptzo selector extend
  11. require("zepto.extend.selector");
  12. /* jshint -W040 */
  13. var $ = window.Zepto;
  14. var UI = $.AMUI || {};
  15. var $win = $(window);
  16. var doc = window.document;
  17. var FastClick = require("util.fastclick");
  18. var $html = $("html");
  19. UI.support = {};
  20. UI.support.transition = function() {
  21. var transitionEnd = function() {
  22. // https://developer.mozilla.org/en-US/docs/Web/Events/transitionend#Browser_compatibility
  23. var element = doc.body || doc.documentElement;
  24. var transEndEventNames = {
  25. WebkitTransition: "webkitTransitionEnd",
  26. MozTransition: "transitionend",
  27. OTransition: "oTransitionEnd otransitionend",
  28. transition: "transitionend"
  29. };
  30. var name;
  31. for (name in transEndEventNames) {
  32. if (element.style[name] !== undefined) {
  33. return transEndEventNames[name];
  34. }
  35. }
  36. }();
  37. return transitionEnd && {
  38. end: transitionEnd
  39. };
  40. }();
  41. UI.support.animation = function() {
  42. var animationEnd = function() {
  43. var element = doc.body || doc.documentElement;
  44. var animEndEventNames = {
  45. WebkitAnimation: "webkitAnimationEnd",
  46. MozAnimation: "animationend",
  47. OAnimation: "oAnimationEnd oanimationend",
  48. animation: "animationend"
  49. };
  50. var name;
  51. for (name in animEndEventNames) {
  52. if (element.style[name] !== undefined) {
  53. return animEndEventNames[name];
  54. }
  55. }
  56. }();
  57. return animationEnd && {
  58. end: animationEnd
  59. };
  60. }();
  61. UI.support.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) {
  62. window.setTimeout(callback, 1e3 / 60);
  63. };
  64. /* jshint -W069 */
  65. UI.support.touch = "ontouchstart" in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/) || window.DocumentTouch && document instanceof window.DocumentTouch || window.navigator["msPointerEnabled"] && window.navigator["msMaxTouchPoints"] > 0 || //IE 10
  66. window.navigator["pointerEnabled"] && window.navigator["maxTouchPoints"] > 0 || //IE >=11
  67. false;
  68. // https://developer.mozilla.org/zh-CN/docs/DOM/MutationObserver
  69. UI.support.mutationobserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver || null;
  70. UI.utils = {};
  71. /**
  72. * Debounce function
  73. * @param {function} func Function to be debounced
  74. * @param {number} wait Function execution threshold in milliseconds
  75. * @param {bool} immediate Whether the function should be called at
  76. * the beginning of the delay instead of the
  77. * end. Default is false.
  78. * @desc Executes a function when it stops being invoked for n seconds
  79. * @via _.debounce() http://underscorejs.org
  80. */
  81. UI.utils.debounce = function(func, wait, immediate) {
  82. var timeout;
  83. return function() {
  84. var context = this;
  85. var args = arguments;
  86. var later = function() {
  87. timeout = null;
  88. if (!immediate) {
  89. func.apply(context, args);
  90. }
  91. };
  92. var callNow = immediate && !timeout;
  93. clearTimeout(timeout);
  94. timeout = setTimeout(later, wait);
  95. if (callNow) {
  96. func.apply(context, args);
  97. }
  98. };
  99. };
  100. UI.utils.isInView = function(element, options) {
  101. var $element = $(element);
  102. var visible = !!($element.width() || $element.height()) && $element.css("display") !== "none";
  103. if (!visible) {
  104. return false;
  105. }
  106. var windowLeft = $win.scrollLeft();
  107. var windowTop = $win.scrollTop();
  108. var offset = $element.offset();
  109. var left = offset.left;
  110. var top = offset.top;
  111. options = $.extend({
  112. topOffset: 0,
  113. leftOffset: 0
  114. }, options);
  115. return top + $element.height() >= windowTop && top - options.topOffset <= windowTop + $win.height() && left + $element.width() >= windowLeft && left - options.leftOffset <= windowLeft + $win.width();
  116. };
  117. /* jshint -W054 */
  118. UI.utils.parseOptions = UI.utils.options = function(string) {
  119. if ($.isPlainObject(string)) {
  120. return string;
  121. }
  122. var start = string ? string.indexOf("{") : -1;
  123. var options = {};
  124. if (start != -1) {
  125. try {
  126. options = new Function("", "var json = " + string.substr(start) + "; return JSON.parse(JSON.stringify(json));")();
  127. } catch (e) {}
  128. }
  129. return options;
  130. };
  131. /* jshint +W054 */
  132. UI.utils.generateGUID = function(namespace) {
  133. var uid = namespace + "-" || "am-";
  134. do {
  135. uid += Math.random().toString(36).substring(2, 7);
  136. } while (document.getElementById(uid));
  137. return uid;
  138. };
  139. // http://blog.alexmaccaw.com/css-transitions
  140. $.fn.emulateTransitionEnd = function(duration) {
  141. var called = false;
  142. var $el = this;
  143. $(this).one(UI.support.transition.end, function() {
  144. called = true;
  145. });
  146. var callback = function() {
  147. if (!called) {
  148. $($el).trigger(UI.support.transition.end);
  149. }
  150. $el.transitionEndTimmer = undefined;
  151. };
  152. this.transitionEndTimmer = setTimeout(callback, duration);
  153. return this;
  154. };
  155. $.fn.redraw = function() {
  156. $(this).each(function() {
  157. /* jshint unused:false */
  158. var redraw = this.offsetHeight;
  159. });
  160. return this;
  161. };
  162. /* jshint unused:true */
  163. $.fn.transitionEnd = function(callback) {
  164. var endEvent = UI.support.transition.end;
  165. var dom = this;
  166. function fireCallBack(e) {
  167. callback.call(this, e);
  168. endEvent && dom.off(endEvent, fireCallBack);
  169. }
  170. if (callback && endEvent) {
  171. dom.on(endEvent, fireCallBack);
  172. }
  173. return this;
  174. };
  175. $.fn.removeClassRegEx = function() {
  176. return this.each(function(regex) {
  177. var classes = $(this).attr("class");
  178. if (!classes || !regex) {
  179. return false;
  180. }
  181. var classArray = [];
  182. classes = classes.split(" ");
  183. for (var i = 0, len = classes.length; i < len; i++) {
  184. if (!classes[i].match(regex)) {
  185. classArray.push(classes[i]);
  186. }
  187. }
  188. $(this).attr("class", classArray.join(" "));
  189. });
  190. };
  191. //
  192. $.fn.alterClass = function(removals, additions) {
  193. var self = this;
  194. if (removals.indexOf("*") === -1) {
  195. // Use native jQuery methods if there is no wildcard matching
  196. self.removeClass(removals);
  197. return !additions ? self : self.addClass(additions);
  198. }
  199. var classPattern = new RegExp("\\s" + removals.replace(/\*/g, "[A-Za-z0-9-_]+").split(" ").join("\\s|\\s") + "\\s", "g");
  200. self.each(function(i, it) {
  201. var cn = " " + it.className + " ";
  202. while (classPattern.test(cn)) {
  203. cn = cn.replace(classPattern, " ");
  204. }
  205. it.className = $.trim(cn);
  206. });
  207. return !additions ? self : self.addClass(additions);
  208. };
  209. $.fn.getHeight = function() {
  210. var $ele = $(this);
  211. var height = "auto";
  212. if ($ele.is(":visible")) {
  213. height = $ele.height();
  214. } else {
  215. var tmp = {
  216. position: $ele.css("position"),
  217. visibility: $ele.css("visibility"),
  218. display: $ele.css("display")
  219. };
  220. height = $ele.css({
  221. position: "absolute",
  222. visibility: "hidden",
  223. display: "block"
  224. }).height();
  225. $ele.css(tmp);
  226. }
  227. return height;
  228. };
  229. $.fn.getSize = function() {
  230. var $el = $(this);
  231. if ($el.css("display") !== "none") {
  232. return {
  233. width: $el.width(),
  234. height: $el.height()
  235. };
  236. }
  237. var old = {
  238. position: $el.css("position"),
  239. visibility: $el.css("visibility"),
  240. display: $el.css("display")
  241. };
  242. var tmpStyle = {
  243. display: "block",
  244. position: "absolute",
  245. visibility: "hidden"
  246. };
  247. var width;
  248. var height;
  249. $el.css(tmpStyle);
  250. width = $el.width();
  251. height = $el.height();
  252. $el.css(old);
  253. return {
  254. width: width,
  255. height: height
  256. };
  257. };
  258. // adding :visible and :hidden to zepto
  259. // https://github.com/jquery/jquery/blob/73e120116ce13b992d5229b3e10fcc19f9505a15/src/css/hiddenVisibleSelectors.js
  260. var _is = $.fn.is;
  261. var _filter = $.fn.filter;
  262. function visible(elem) {
  263. elem = $(elem);
  264. return !!(elem.width() || elem.height()) && elem.css("display") !== "none";
  265. }
  266. $.fn.is = function(sel) {
  267. if (sel === ":visible") {
  268. return visible(this);
  269. }
  270. if (sel === ":hidden") {
  271. return !visible(this);
  272. }
  273. return _is.call(this, sel);
  274. };
  275. $.fn.filter = function(sel) {
  276. if (sel === ":visible") {
  277. return $([].filter.call(this, visible));
  278. }
  279. if (sel === ":hidden") {
  280. return $([].filter.call(this, function(elem) {
  281. return !visible(elem);
  282. }));
  283. }
  284. return _filter.call(this, sel);
  285. };
  286. // handle multiple browsers for requestAnimationFrame()
  287. // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  288. // https://github.com/gnarf/jquery-requestAnimationFrame
  289. UI.utils.rAF = function() {
  290. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || // if all else fails, use setTimeout
  291. function(callback) {
  292. return window.setTimeout(callback, 1e3 / 60);
  293. };
  294. }();
  295. // handle multiple browsers for cancelAnimationFrame()
  296. UI.utils.cancelAF = function() {
  297. return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || function(id) {
  298. window.clearTimeout(id);
  299. };
  300. }();
  301. // via http://davidwalsh.name/detect-scrollbar-width
  302. UI.utils.measureScrollbar = function() {
  303. if (document.body.clientWidth >= window.innerWidth) {
  304. return 0;
  305. }
  306. // if ($html.width() >= window.innerWidth) return;
  307. // var scrollbarWidth = window.innerWidth - $html.width();
  308. var $measure = $("<div " + 'style="width: 100px;height: 100px;overflow: scroll;' + 'position: absolute;top: -9999px;"></div>');
  309. $(document.body).append($measure);
  310. var scrollbarWidth = $measure[0].offsetWidth - $measure[0].clientWidth;
  311. $measure.remove();
  312. return scrollbarWidth;
  313. };
  314. UI.utils.imageLoader = function($image, callback) {
  315. function loaded() {
  316. callback($image[0]);
  317. }
  318. function bindLoad() {
  319. this.one("load", loaded);
  320. if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
  321. var src = this.attr("src"), param = src.match(/\?/) ? "&" : "?";
  322. param += "random=" + new Date().getTime();
  323. this.attr("src", src + param);
  324. }
  325. }
  326. if (!$image.attr("src")) {
  327. loaded();
  328. return;
  329. }
  330. if ($image[0].complete || $image[0].readyState === 4) {
  331. loaded();
  332. } else {
  333. bindLoad.call($image);
  334. }
  335. };
  336. /**
  337. * https://github.com/cho45/micro-template.js
  338. * (c) cho45 http://cho45.github.com/mit-license
  339. */
  340. /* jshint -W109 */
  341. UI.template = function(id, data) {
  342. var me = UI.template;
  343. if (!me.cache[id]) {
  344. me.cache[id] = function() {
  345. var name = id;
  346. var string = /^[\w\-]+$/.test(id) ? me.get(id) : (name = "template(string)", id);
  347. // no warnings
  348. var line = 1;
  349. var body = ("try { " + (me.variable ? "var " + me.variable + " = this.stash;" : "with (this.stash) { ") + "this.ret += '" + string.replace(/<%/g, "").replace(/%>/g, "").replace(/'(?![^\x11\x13]+?\x13)/g, "\\x27").replace(/^\s*|\s*$/g, "").replace(/\n/g, function() {
  350. return "';\nthis.line = " + ++line + "; this.ret += '\\n";
  351. }).replace(/\x11-(.+?)\x13/g, "' + ($1) + '").replace(/\x11=(.+?)\x13/g, "' + this.escapeHTML($1) + '").replace(/\x11(.+?)\x13/g, "'; $1; this.ret += '") + "'; " + (me.variable ? "" : "}") + "return this.ret;" + "} catch (e) { throw 'TemplateError: ' + e + ' (on " + name + "' + ' line ' + this.line + ')'; } " + "//@ sourceURL=" + name + "\n").replace(/this\.ret \+= '';/g, "");
  352. /* jshint -W054 */
  353. var func = new Function(body);
  354. var map = {
  355. "&": "&amp;",
  356. "<": "&lt;",
  357. ">": "&gt;",
  358. '"': "&#x22;",
  359. "'": "&#x27;"
  360. };
  361. var escapeHTML = function(string) {
  362. return ("" + string).replace(/[&<>\'\"]/g, function(_) {
  363. return map[_];
  364. });
  365. };
  366. return function(stash) {
  367. return func.call(me.context = {
  368. escapeHTML: escapeHTML,
  369. line: 1,
  370. ret: "",
  371. stash: stash
  372. });
  373. };
  374. }();
  375. }
  376. return data ? me.cache[id](data) : me.cache[id];
  377. };
  378. /* jshint +W109 */
  379. /* jshint +W054 */
  380. UI.template.cache = {};
  381. UI.template.get = function(id) {
  382. if (id) {
  383. var element = document.getElementById(id);
  384. return element && element.innerHTML || "";
  385. }
  386. };
  387. // Attach FastClick on touch devices
  388. if (UI.support.touch) {
  389. $html.addClass("am-touch");
  390. $(function() {
  391. FastClick.attach(document.body);
  392. });
  393. }
  394. $(function() {
  395. var $body = $("body");
  396. // trigger DOM ready event
  397. $(document).trigger("domready:amui");
  398. $html.removeClass("no-js").addClass("js");
  399. UI.support.animation && $html.addClass("cssanimations");
  400. // iOS standalone mode
  401. if (window.navigator.standalone) {
  402. $html.addClass("am-standalone");
  403. }
  404. $(".am-topbar-fixed-top").length && $body.addClass("am-with-topbar-fixed-top");
  405. $(".am-topbar-fixed-bottom").length && $body.addClass("am-with-topbar-fixed-bottom");
  406. // Remove responsive classes in .am-layout
  407. var $layout = $(".am-layout");
  408. $layout.find('[class*="md-block-grid"]').alterClass("md-block-grid-*");
  409. $layout.find('[class*="lg-block-grid"]').alterClass("lg-block-grid");
  410. // widgets not in .am-layout
  411. $("[data-am-widget]").each(function() {
  412. var $widget = $(this);
  413. // console.log($widget.parents('.am-layout').length)
  414. if ($widget.parents(".am-layout").length === 0) {
  415. $widget.addClass("am-no-layout");
  416. }
  417. });
  418. });
  419. $.AMUI = UI;
  420. module.exports = UI;
  421. });
  422. define("util.fastclick", [], function(require, exports, module) {
  423. "use strict";
  424. var $ = window.Zepto;
  425. /**
  426. * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
  427. *
  428. * @version 1.0.3
  429. * @codingstandard ftlabs-jsv2
  430. * @copyright The Financial Times Limited [All Rights Reserved]
  431. * @license MIT License (see LICENSE.txt)
  432. */
  433. /*jslint browser:true, node:true*/
  434. /*global define, Event, Node*/
  435. /**
  436. * Instantiate fast-clicking listeners on the specified layer.
  437. *
  438. * @constructor
  439. * @param {Element} layer The layer to listen on
  440. * @param {Object} options The options to override the defaults
  441. */
  442. function FastClick(layer, options) {
  443. var oldOnClick;
  444. options = options || {};
  445. /**
  446. * Whether a click is currently being tracked.
  447. *
  448. * @type boolean
  449. */
  450. this.trackingClick = false;
  451. /**
  452. * Timestamp for when click tracking started.
  453. *
  454. * @type number
  455. */
  456. this.trackingClickStart = 0;
  457. /**
  458. * The element being tracked for a click.
  459. *
  460. * @type EventTarget
  461. */
  462. this.targetElement = null;
  463. /**
  464. * X-coordinate of touch start event.
  465. *
  466. * @type number
  467. */
  468. this.touchStartX = 0;
  469. /**
  470. * Y-coordinate of touch start event.
  471. *
  472. * @type number
  473. */
  474. this.touchStartY = 0;
  475. /**
  476. * ID of the last touch, retrieved from Touch.identifier.
  477. *
  478. * @type number
  479. */
  480. this.lastTouchIdentifier = 0;
  481. /**
  482. * Touchmove boundary, beyond which a click will be cancelled.
  483. *
  484. * @type number
  485. */
  486. this.touchBoundary = options.touchBoundary || 10;
  487. /**
  488. * The FastClick layer.
  489. *
  490. * @type Element
  491. */
  492. this.layer = layer;
  493. /**
  494. * The minimum time between tap(touchstart and touchend) events
  495. *
  496. * @type number
  497. */
  498. this.tapDelay = options.tapDelay || 200;
  499. if (FastClick.notNeeded(layer)) {
  500. return;
  501. }
  502. // Some old versions of Android don't have Function.prototype.bind
  503. function bind(method, context) {
  504. return function() {
  505. return method.apply(context, arguments);
  506. };
  507. }
  508. var methods = [ "onMouse", "onClick", "onTouchStart", "onTouchMove", "onTouchEnd", "onTouchCancel" ];
  509. var context = this;
  510. for (var i = 0, l = methods.length; i < l; i++) {
  511. context[methods[i]] = bind(context[methods[i]], context);
  512. }
  513. // Set up event handlers as required
  514. if (deviceIsAndroid) {
  515. layer.addEventListener("mouseover", this.onMouse, true);
  516. layer.addEventListener("mousedown", this.onMouse, true);
  517. layer.addEventListener("mouseup", this.onMouse, true);
  518. }
  519. layer.addEventListener("click", this.onClick, true);
  520. layer.addEventListener("touchstart", this.onTouchStart, false);
  521. layer.addEventListener("touchmove", this.onTouchMove, false);
  522. layer.addEventListener("touchend", this.onTouchEnd, false);
  523. layer.addEventListener("touchcancel", this.onTouchCancel, false);
  524. // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  525. // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
  526. // layer when they are cancelled.
  527. if (!Event.prototype.stopImmediatePropagation) {
  528. layer.removeEventListener = function(type, callback, capture) {
  529. var rmv = Node.prototype.removeEventListener;
  530. if (type === "click") {
  531. rmv.call(layer, type, callback.hijacked || callback, capture);
  532. } else {
  533. rmv.call(layer, type, callback, capture);
  534. }
  535. };
  536. layer.addEventListener = function(type, callback, capture) {
  537. var adv = Node.prototype.addEventListener;
  538. if (type === "click") {
  539. adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
  540. if (!event.propagationStopped) {
  541. callback(event);
  542. }
  543. }), capture);
  544. } else {
  545. adv.call(layer, type, callback, capture);
  546. }
  547. };
  548. }
  549. // If a handler is already declared in the element's onclick attribute, it will be fired before
  550. // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
  551. // adding it as listener.
  552. if (typeof layer.onclick === "function") {
  553. // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
  554. // - the old one won't work if passed to addEventListener directly.
  555. oldOnClick = layer.onclick;
  556. layer.addEventListener("click", function(event) {
  557. oldOnClick(event);
  558. }, false);
  559. layer.onclick = null;
  560. }
  561. }
  562. /**
  563. * Android requires exceptions.
  564. *
  565. * @type boolean
  566. */
  567. var deviceIsAndroid = navigator.userAgent.indexOf("Android") > 0;
  568. /**
  569. * iOS requires exceptions.
  570. *
  571. * @type boolean
  572. */
  573. var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
  574. /**
  575. * iOS 4 requires an exception for select elements.
  576. *
  577. * @type boolean
  578. */
  579. var deviceIsIOS4 = deviceIsIOS && /OS 4_\d(_\d)?/.test(navigator.userAgent);
  580. /**
  581. * iOS 6.0(+?) requires the target element to be manually derived
  582. *
  583. * @type boolean
  584. */
  585. var deviceIsIOSWithBadTarget = deviceIsIOS && /OS ([6-9]|\d{2})_\d/.test(navigator.userAgent);
  586. /**
  587. * BlackBerry requires exceptions.
  588. *
  589. * @type boolean
  590. */
  591. var deviceIsBlackBerry10 = navigator.userAgent.indexOf("BB10") > 0;
  592. /**
  593. * Determine whether a given element requires a native click.
  594. *
  595. * @param {EventTarget|Element} target Target DOM element
  596. * @returns {boolean} Returns true if the element needs a native click
  597. */
  598. FastClick.prototype.needsClick = function(target) {
  599. switch (target.nodeName.toLowerCase()) {
  600. // Don't send a synthetic click to disabled inputs (issue #62)
  601. case "button":
  602. case "select":
  603. case "textarea":
  604. if (target.disabled) {
  605. return true;
  606. }
  607. break;
  608. case "input":
  609. // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
  610. if (deviceIsIOS && target.type === "file" || target.disabled) {
  611. return true;
  612. }
  613. break;
  614. case "label":
  615. case "video":
  616. return true;
  617. }
  618. return /\bneedsclick\b/.test(target.className);
  619. };
  620. /**
  621. * Determine whether a given element requires a call to focus to simulate click into element.
  622. *
  623. * @param {EventTarget|Element} target Target DOM element
  624. * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
  625. */
  626. FastClick.prototype.needsFocus = function(target) {
  627. switch (target.nodeName.toLowerCase()) {
  628. case "textarea":
  629. return true;
  630. case "select":
  631. return !deviceIsAndroid;
  632. case "input":
  633. switch (target.type) {
  634. case "button":
  635. case "checkbox":
  636. case "file":
  637. case "image":
  638. case "radio":
  639. case "submit":
  640. return false;
  641. }
  642. // No point in attempting to focus disabled inputs
  643. return !target.disabled && !target.readOnly;
  644. default:
  645. return /\bneedsfocus\b/.test(target.className);
  646. }
  647. };
  648. /**
  649. * Send a click event to the specified element.
  650. *
  651. * @param {EventTarget|Element} targetElement
  652. * @param {Event} event
  653. */
  654. FastClick.prototype.sendClick = function(targetElement, event) {
  655. var clickEvent, touch;
  656. // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
  657. if (document.activeElement && document.activeElement !== targetElement) {
  658. document.activeElement.blur();
  659. }
  660. touch = event.changedTouches[0];
  661. // Synthesise a click event, with an extra attribute so it can be tracked
  662. clickEvent = document.createEvent("MouseEvents");
  663. clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
  664. clickEvent.forwardedTouchEvent = true;
  665. targetElement.dispatchEvent(clickEvent);
  666. };
  667. FastClick.prototype.determineEventType = function(targetElement) {
  668. //Issue #159: Android Chrome Select Box does not open with a synthetic click event
  669. if (deviceIsAndroid && targetElement.tagName.toLowerCase() === "select") {
  670. return "mousedown";
  671. }
  672. return "click";
  673. };
  674. /**
  675. * @param {EventTarget|Element} targetElement
  676. */
  677. FastClick.prototype.focus = function(targetElement) {
  678. var length;
  679. // Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
  680. if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf("date") !== 0 && targetElement.type !== "time") {
  681. length = targetElement.value.length;
  682. targetElement.setSelectionRange(length, length);
  683. } else {
  684. targetElement.focus();
  685. }
  686. };
  687. /**
  688. * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
  689. *
  690. * @param {EventTarget|Element} targetElement
  691. */
  692. FastClick.prototype.updateScrollParent = function(targetElement) {
  693. var scrollParent, parentElement;
  694. scrollParent = targetElement.fastClickScrollParent;
  695. // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
  696. // target element was moved to another parent.
  697. if (!scrollParent || !scrollParent.contains(targetElement)) {
  698. parentElement = targetElement;
  699. do {
  700. if (parentElement.scrollHeight > parentElement.offsetHeight) {
  701. scrollParent = parentElement;
  702. targetElement.fastClickScrollParent = parentElement;
  703. break;
  704. }
  705. parentElement = parentElement.parentElement;
  706. } while (parentElement);
  707. }
  708. // Always update the scroll top tracker if possible.
  709. if (scrollParent) {
  710. scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
  711. }
  712. };
  713. /**
  714. * @param {EventTarget} targetElement
  715. * @returns {Element|EventTarget}
  716. */
  717. FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
  718. // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
  719. if (eventTarget.nodeType === Node.TEXT_NODE) {
  720. return eventTarget.parentNode;
  721. }
  722. return eventTarget;
  723. };
  724. /**
  725. * On touch start, record the position and scroll offset.
  726. *
  727. * @param {Event} event
  728. * @returns {boolean}
  729. */
  730. FastClick.prototype.onTouchStart = function(event) {
  731. var targetElement, touch, selection;
  732. // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
  733. if (event.targetTouches.length > 1) {
  734. return true;
  735. }
  736. targetElement = this.getTargetElementFromEventTarget(event.target);
  737. touch = event.targetTouches[0];
  738. if (deviceIsIOS) {
  739. // Only trusted events will deselect text on iOS (issue #49)
  740. selection = window.getSelection();
  741. if (selection.rangeCount && !selection.isCollapsed) {
  742. return true;
  743. }
  744. if (!deviceIsIOS4) {
  745. // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
  746. // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
  747. // with the same identifier as the touch event that previously triggered the click that triggered the alert.
  748. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
  749. // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
  750. // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
  751. // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
  752. // random integers, it's safe to to continue if the identifier is 0 here.
  753. if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
  754. event.preventDefault();
  755. return false;
  756. }
  757. this.lastTouchIdentifier = touch.identifier;
  758. // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
  759. // 1) the user does a fling scroll on the scrollable layer
  760. // 2) the user stops the fling scroll with another tap
  761. // then the event.target of the last 'touchend' event will be the element that was under the user's finger
  762. // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
  763. // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
  764. this.updateScrollParent(targetElement);
  765. }
  766. }
  767. this.trackingClick = true;
  768. this.trackingClickStart = event.timeStamp;
  769. this.targetElement = targetElement;
  770. this.touchStartX = touch.pageX;
  771. this.touchStartY = touch.pageY;
  772. // Prevent phantom clicks on fast double-tap (issue #36)
  773. if (event.timeStamp - this.lastClickTime < this.tapDelay) {
  774. event.preventDefault();
  775. }
  776. return true;
  777. };
  778. /**
  779. * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
  780. *
  781. * @param {Event} event
  782. * @returns {boolean}
  783. */
  784. FastClick.prototype.touchHasMoved = function(event) {
  785. var touch = event.changedTouches[0], boundary = this.touchBoundary;
  786. if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
  787. return true;
  788. }
  789. return false;
  790. };
  791. /**
  792. * Update the last position.
  793. *
  794. * @param {Event} event
  795. * @returns {boolean}
  796. */
  797. FastClick.prototype.onTouchMove = function(event) {
  798. if (!this.trackingClick) {
  799. return true;
  800. }
  801. // If the touch has moved, cancel the click tracking
  802. if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
  803. this.trackingClick = false;
  804. this.targetElement = null;
  805. }
  806. return true;
  807. };
  808. /**
  809. * Attempt to find the labelled control for the given label element.
  810. *
  811. * @param {EventTarget|HTMLLabelElement} labelElement
  812. * @returns {Element|null}
  813. */
  814. FastClick.prototype.findControl = function(labelElement) {
  815. // Fast path for newer browsers supporting the HTML5 control attribute
  816. if (labelElement.control !== undefined) {
  817. return labelElement.control;
  818. }
  819. // All browsers under test that support touch events also support the HTML5 htmlFor attribute
  820. if (labelElement.htmlFor) {
  821. return document.getElementById(labelElement.htmlFor);
  822. }
  823. // If no for attribute exists, attempt to retrieve the first labellable descendant element
  824. // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
  825. return labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea");
  826. };
  827. /**
  828. * On touch end, determine whether to send a click event at once.
  829. *
  830. * @param {Event} event
  831. * @returns {boolean}
  832. */
  833. FastClick.prototype.onTouchEnd = function(event) {
  834. var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
  835. if (!this.trackingClick) {
  836. return true;
  837. }
  838. // Prevent phantom clicks on fast double-tap (issue #36)
  839. if (event.timeStamp - this.lastClickTime < this.tapDelay) {
  840. this.cancelNextClick = true;
  841. return true;
  842. }
  843. // Reset to prevent wrong click cancel on input (issue #156).
  844. this.cancelNextClick = false;
  845. this.lastClickTime = event.timeStamp;
  846. trackingClickStart = this.trackingClickStart;
  847. this.trackingClick = false;
  848. this.trackingClickStart = 0;
  849. // On some iOS devices, the targetElement supplied with the event is invalid if the layer
  850. // is performing a transition or scroll, and has to be re-detected manually. Note that
  851. // for this to function correctly, it must be called *after* the event target is checked!
  852. // See issue #57; also filed as rdar://13048589 .
  853. if (deviceIsIOSWithBadTarget) {
  854. touch = event.changedTouches[0];
  855. // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
  856. targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
  857. targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
  858. }
  859. targetTagName = targetElement.tagName.toLowerCase();
  860. if (targetTagName === "label") {
  861. forElement = this.findControl(targetElement);
  862. if (forElement) {
  863. this.focus(targetElement);
  864. if (deviceIsAndroid) {
  865. return false;
  866. }
  867. targetElement = forElement;
  868. }
  869. } else if (this.needsFocus(targetElement)) {
  870. // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
  871. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
  872. if (event.timeStamp - trackingClickStart > 100 || deviceIsIOS && window.top !== window && targetTagName === "input") {
  873. this.targetElement = null;
  874. return false;
  875. }
  876. this.focus(targetElement);
  877. this.sendClick(targetElement, event);
  878. // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
  879. // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
  880. if (!deviceIsIOS || targetTagName !== "select") {
  881. this.targetElement = null;
  882. event.preventDefault();
  883. }
  884. return false;
  885. }
  886. if (deviceIsIOS && !deviceIsIOS4) {
  887. // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
  888. // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
  889. scrollParent = targetElement.fastClickScrollParent;
  890. if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
  891. return true;
  892. }
  893. }
  894. // Prevent the actual click from going though - unless the target node is marked as requiring
  895. // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
  896. if (!this.needsClick(targetElement)) {
  897. event.preventDefault();
  898. this.sendClick(targetElement, event);
  899. }
  900. return false;
  901. };
  902. /**
  903. * On touch cancel, stop tracking the click.
  904. *
  905. * @returns {void}
  906. */
  907. FastClick.prototype.onTouchCancel = function() {
  908. this.trackingClick = false;
  909. this.targetElement = null;
  910. };
  911. /**
  912. * Determine mouse events which should be permitted.
  913. *
  914. * @param {Event} event
  915. * @returns {boolean}
  916. */
  917. FastClick.prototype.onMouse = function(event) {
  918. // If a target element was never set (because a touch event was never fired) allow the event
  919. if (!this.targetElement) {
  920. return true;
  921. }
  922. if (event.forwardedTouchEvent) {
  923. return true;
  924. }
  925. // Programmatically generated events targeting a specific element should be permitted
  926. if (!event.cancelable) {
  927. return true;
  928. }
  929. // Derive and check the target element to see whether the mouse event needs to be permitted;
  930. // unless explicitly enabled, prevent non-touch click events from triggering actions,
  931. // to prevent ghost/doubleclicks.
  932. if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
  933. // Prevent any user-added listeners declared on FastClick element from being fired.
  934. if (event.stopImmediatePropagation) {
  935. event.stopImmediatePropagation();
  936. } else {
  937. // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  938. event.propagationStopped = true;
  939. }
  940. // Cancel the event
  941. event.stopPropagation();
  942. event.preventDefault();
  943. return false;
  944. }
  945. // If the mouse event is permitted, return true for the action to go through.
  946. return true;
  947. };
  948. /**
  949. * On actual clicks, determine whether this is a touch-generated click, a click action occurring
  950. * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
  951. * an actual click which should be permitted.
  952. *
  953. * @param {Event} event
  954. * @returns {boolean}
  955. */
  956. FastClick.prototype.onClick = function(event) {
  957. var permitted;
  958. // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
  959. if (this.trackingClick) {
  960. this.targetElement = null;
  961. this.trackingClick = false;
  962. return true;
  963. }
  964. // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
  965. if (event.target.type === "submit" && event.detail === 0) {
  966. return true;
  967. }
  968. permitted = this.onMouse(event);
  969. // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
  970. if (!permitted) {
  971. this.targetElement = null;
  972. }
  973. // If clicks are permitted, return true for the action to go through.
  974. return permitted;
  975. };
  976. /**
  977. * Remove all FastClick's event listeners.
  978. *
  979. * @returns {void}
  980. */
  981. FastClick.prototype.destroy = function() {
  982. var layer = this.layer;
  983. if (deviceIsAndroid) {
  984. layer.removeEventListener("mouseover", this.onMouse, true);
  985. layer.removeEventListener("mousedown", this.onMouse, true);
  986. layer.removeEventListener("mouseup", this.onMouse, true);
  987. }
  988. layer.removeEventListener("click", this.onClick, true);
  989. layer.removeEventListener("touchstart", this.onTouchStart, false);
  990. layer.removeEventListener("touchmove", this.onTouchMove, false);
  991. layer.removeEventListener("touchend", this.onTouchEnd, false);
  992. layer.removeEventListener("touchcancel", this.onTouchCancel, false);
  993. };
  994. /**
  995. * Check whether FastClick is needed.
  996. *
  997. * @param {Element} layer The layer to listen on
  998. */
  999. FastClick.notNeeded = function(layer) {
  1000. var metaViewport;
  1001. var chromeVersion;
  1002. var blackberryVersion;
  1003. // Devices that don't support touch don't need FastClick
  1004. if (typeof window.ontouchstart === "undefined") {
  1005. return true;
  1006. }
  1007. // Chrome version - zero for other browsers
  1008. chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [ , 0 ])[1];
  1009. if (chromeVersion) {
  1010. if (deviceIsAndroid) {
  1011. metaViewport = document.querySelector("meta[name=viewport]");
  1012. if (metaViewport) {
  1013. // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
  1014. if (metaViewport.content.indexOf("user-scalable=no") !== -1) {
  1015. return true;
  1016. }
  1017. // Chrome 32 and above with width=device-width or less don't need FastClick
  1018. if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
  1019. return true;
  1020. }
  1021. }
  1022. } else {
  1023. return true;
  1024. }
  1025. }
  1026. if (deviceIsBlackBerry10) {
  1027. blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
  1028. // BlackBerry 10.3+ does not require Fastclick library.
  1029. // https://github.com/ftlabs/fastclick/issues/251
  1030. if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
  1031. metaViewport = document.querySelector("meta[name=viewport]");
  1032. if (metaViewport) {
  1033. // user-scalable=no eliminates click delay.
  1034. if (metaViewport.content.indexOf("user-scalable=no") !== -1) {
  1035. return true;
  1036. }
  1037. // width=device-width (or less than device-width) eliminates click delay.
  1038. if (document.documentElement.scrollWidth <= window.outerWidth) {
  1039. return true;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
  1045. if (layer.style.msTouchAction === "none") {
  1046. return true;
  1047. }
  1048. return false;
  1049. };
  1050. /**
  1051. * Factory method for creating a FastClick object
  1052. *
  1053. * @param {Element} layer The layer to listen on
  1054. * @param {Object} options The options to override the defaults
  1055. */
  1056. FastClick.attach = function(layer, options) {
  1057. return new FastClick(layer, options);
  1058. };
  1059. module.exports = FastClick;
  1060. });
  1061. define("util.hammer", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  1062. "use strict";
  1063. require("core");
  1064. var $ = window.Zepto;
  1065. var UI = $.AMUI;
  1066. /**
  1067. * Hammer.js
  1068. * @via https://github.com/hammerjs/hammer.js
  1069. * @copyright Copyright (C) 2011-2014 by Jorik Tangelder (Eight Media)
  1070. * @license https://github.com/hammerjs/hammer.js/blob/master/LICENSE.md
  1071. */
  1072. var VENDOR_PREFIXES = [ "", "webkit", "moz", "MS", "ms", "o" ];
  1073. var TEST_ELEMENT = document.createElement("div");
  1074. var TYPE_FUNCTION = "function";
  1075. var round = Math.round;
  1076. var abs = Math.abs;
  1077. var now = Date.now;
  1078. /**
  1079. * set a timeout with a given scope
  1080. * @param {Function} fn
  1081. * @param {Number} timeout
  1082. * @param {Object} context
  1083. * @returns {number}
  1084. */
  1085. function setTimeoutContext(fn, timeout, context) {
  1086. return setTimeout(bindFn(fn, context), timeout);
  1087. }
  1088. /**
  1089. * if the argument is an array, we want to execute the fn on each entry
  1090. * if it aint an array we don't want to do a thing.
  1091. * this is used by all the methods that accept a single and array argument.
  1092. * @param {*|Array} arg
  1093. * @param {String} fn
  1094. * @param {Object} [context]
  1095. * @returns {Boolean}
  1096. */
  1097. function invokeArrayArg(arg, fn, context) {
  1098. if (Array.isArray(arg)) {
  1099. each(arg, context[fn], context);
  1100. return true;
  1101. }
  1102. return false;
  1103. }
  1104. /**
  1105. * walk objects and arrays
  1106. * @param {Object} obj
  1107. * @param {Function} iterator
  1108. * @param {Object} context
  1109. */
  1110. function each(obj, iterator, context) {
  1111. var i;
  1112. if (!obj) {
  1113. return;
  1114. }
  1115. if (obj.forEach) {
  1116. obj.forEach(iterator, context);
  1117. } else if (obj.length !== undefined) {
  1118. i = 0;
  1119. while (i < obj.length) {
  1120. iterator.call(context, obj[i], i, obj);
  1121. i++;
  1122. }
  1123. } else {
  1124. for (i in obj) {
  1125. obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
  1126. }
  1127. }
  1128. }
  1129. /**
  1130. * extend object.
  1131. * means that properties in dest will be overwritten by the ones in src.
  1132. * @param {Object} dest
  1133. * @param {Object} src
  1134. * @param {Boolean} [merge]
  1135. * @returns {Object} dest
  1136. */
  1137. function extend(dest, src, merge) {
  1138. var keys = Object.keys(src);
  1139. var i = 0;
  1140. while (i < keys.length) {
  1141. if (!merge || merge && dest[keys[i]] === undefined) {
  1142. dest[keys[i]] = src[keys[i]];
  1143. }
  1144. i++;
  1145. }
  1146. return dest;
  1147. }
  1148. /**
  1149. * merge the values from src in the dest.
  1150. * means that properties that exist in dest will not be overwritten by src
  1151. * @param {Object} dest
  1152. * @param {Object} src
  1153. * @returns {Object} dest
  1154. */
  1155. function merge(dest, src) {
  1156. return extend(dest, src, true);
  1157. }
  1158. /**
  1159. * simple class inheritance
  1160. * @param {Function} child
  1161. * @param {Function} base
  1162. * @param {Object} [properties]
  1163. */
  1164. function inherit(child, base, properties) {
  1165. var baseP = base.prototype, childP;
  1166. childP = child.prototype = Object.create(baseP);
  1167. childP.constructor = child;
  1168. childP._super = baseP;
  1169. if (properties) {
  1170. extend(childP, properties);
  1171. }
  1172. }
  1173. /**
  1174. * simple function bind
  1175. * @param {Function} fn
  1176. * @param {Object} context
  1177. * @returns {Function}
  1178. */
  1179. function bindFn(fn, context) {
  1180. return function boundFn() {
  1181. return fn.apply(context, arguments);
  1182. };
  1183. }
  1184. /**
  1185. * let a boolean value also be a function that must return a boolean
  1186. * this first item in args will be used as the context
  1187. * @param {Boolean|Function} val
  1188. * @param {Array} [args]
  1189. * @returns {Boolean}
  1190. */
  1191. function boolOrFn(val, args) {
  1192. if (typeof val == TYPE_FUNCTION) {
  1193. return val.apply(args ? args[0] || undefined : undefined, args);
  1194. }
  1195. return val;
  1196. }
  1197. /**
  1198. * use the val2 when val1 is undefined
  1199. * @param {*} val1
  1200. * @param {*} val2
  1201. * @returns {*}
  1202. */
  1203. function ifUndefined(val1, val2) {
  1204. return val1 === undefined ? val2 : val1;
  1205. }
  1206. /**
  1207. * addEventListener with multiple events at once
  1208. * @param {EventTarget} target
  1209. * @param {String} types
  1210. * @param {Function} handler
  1211. */
  1212. function addEventListeners(target, types, handler) {
  1213. each(splitStr(types), function(type) {
  1214. target.addEventListener(type, handler, false);
  1215. });
  1216. }
  1217. /**
  1218. * removeEventListener with multiple events at once
  1219. * @param {EventTarget} target
  1220. * @param {String} types
  1221. * @param {Function} handler
  1222. */
  1223. function removeEventListeners(target, types, handler) {
  1224. each(splitStr(types), function(type) {
  1225. target.removeEventListener(type, handler, false);
  1226. });
  1227. }
  1228. /**
  1229. * find if a node is in the given parent
  1230. * @method hasParent
  1231. * @param {HTMLElement} node
  1232. * @param {HTMLElement} parent
  1233. * @return {Boolean} found
  1234. */
  1235. function hasParent(node, parent) {
  1236. while (node) {
  1237. if (node == parent) {
  1238. return true;
  1239. }
  1240. node = node.parentNode;
  1241. }
  1242. return false;
  1243. }
  1244. /**
  1245. * small indexOf wrapper
  1246. * @param {String} str
  1247. * @param {String} find
  1248. * @returns {Boolean} found
  1249. */
  1250. function inStr(str, find) {
  1251. return str.indexOf(find) > -1;
  1252. }
  1253. /**
  1254. * split string on whitespace
  1255. * @param {String} str
  1256. * @returns {Array} words
  1257. */
  1258. function splitStr(str) {
  1259. return str.trim().split(/\s+/g);
  1260. }
  1261. /**
  1262. * find if a array contains the object using indexOf or a simple polyFill
  1263. * @param {Array} src
  1264. * @param {String} find
  1265. * @param {String} [findByKey]
  1266. * @return {Boolean|Number} false when not found, or the index
  1267. */
  1268. function inArray(src, find, findByKey) {
  1269. if (src.indexOf && !findByKey) {
  1270. return src.indexOf(find);
  1271. } else {
  1272. var i = 0;
  1273. while (i < src.length) {
  1274. if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {
  1275. return i;
  1276. }
  1277. i++;
  1278. }
  1279. return -1;
  1280. }
  1281. }
  1282. /**
  1283. * convert array-like objects to real arrays
  1284. * @param {Object} obj
  1285. * @returns {Array}
  1286. */
  1287. function toArray(obj) {
  1288. return Array.prototype.slice.call(obj, 0);
  1289. }
  1290. /**
  1291. * unique array with objects based on a key (like 'id') or just by the array's value
  1292. * @param {Array} src [{id:1},{id:2},{id:1}]
  1293. * @param {String} [key]
  1294. * @param {Boolean} [sort=False]
  1295. * @returns {Array} [{id:1},{id:2}]
  1296. */
  1297. function uniqueArray(src, key, sort) {
  1298. var results = [];
  1299. var values = [];
  1300. var i = 0;
  1301. while (i < src.length) {
  1302. var val = key ? src[i][key] : src[i];
  1303. if (inArray(values, val) < 0) {
  1304. results.push(src[i]);
  1305. }
  1306. values[i] = val;
  1307. i++;
  1308. }
  1309. if (sort) {
  1310. if (!key) {
  1311. results = results.sort();
  1312. } else {
  1313. results = results.sort(function sortUniqueArray(a, b) {
  1314. return a[key] > b[key];
  1315. });
  1316. }
  1317. }
  1318. return results;
  1319. }
  1320. /**
  1321. * get the prefixed property
  1322. * @param {Object} obj
  1323. * @param {String} property
  1324. * @returns {String|Undefined} prefixed
  1325. */
  1326. function prefixed(obj, property) {
  1327. var prefix, prop;
  1328. var camelProp = property[0].toUpperCase() + property.slice(1);
  1329. var i = 0;
  1330. while (i < VENDOR_PREFIXES.length) {
  1331. prefix = VENDOR_PREFIXES[i];
  1332. prop = prefix ? prefix + camelProp : property;
  1333. if (prop in obj) {
  1334. return prop;
  1335. }
  1336. i++;
  1337. }
  1338. return undefined;
  1339. }
  1340. /**
  1341. * get a unique id
  1342. * @returns {number} uniqueId
  1343. */
  1344. var _uniqueId = 1;
  1345. function uniqueId() {
  1346. return _uniqueId++;
  1347. }
  1348. /**
  1349. * get the window object of an element
  1350. * @param {HTMLElement} element
  1351. * @returns {DocumentView|Window}
  1352. */
  1353. function getWindowForElement(element) {
  1354. var doc = element.ownerDocument;
  1355. return doc.defaultView || doc.parentWindow;
  1356. }
  1357. var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  1358. var SUPPORT_TOUCH = "ontouchstart" in window;
  1359. var SUPPORT_POINTER_EVENTS = prefixed(window, "PointerEvent") !== undefined;
  1360. var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
  1361. var INPUT_TYPE_TOUCH = "touch";
  1362. var INPUT_TYPE_PEN = "pen";
  1363. var INPUT_TYPE_MOUSE = "mouse";
  1364. var INPUT_TYPE_KINECT = "kinect";
  1365. var COMPUTE_INTERVAL = 25;
  1366. var INPUT_START = 1;
  1367. var INPUT_MOVE = 2;
  1368. var INPUT_END = 4;
  1369. var INPUT_CANCEL = 8;
  1370. var DIRECTION_NONE = 1;
  1371. var DIRECTION_LEFT = 2;
  1372. var DIRECTION_RIGHT = 4;
  1373. var DIRECTION_UP = 8;
  1374. var DIRECTION_DOWN = 16;
  1375. var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
  1376. var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
  1377. var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
  1378. var PROPS_XY = [ "x", "y" ];
  1379. var PROPS_CLIENT_XY = [ "clientX", "clientY" ];
  1380. /**
  1381. * create new input type manager
  1382. * @param {Manager} manager
  1383. * @param {Function} callback
  1384. * @returns {Input}
  1385. * @constructor
  1386. */
  1387. function Input(manager, callback) {
  1388. var self = this;
  1389. this.manager = manager;
  1390. this.callback = callback;
  1391. this.element = manager.element;
  1392. this.target = manager.options.inputTarget;
  1393. // smaller wrapper around the handler, for the scope and the enabled state of the manager,
  1394. // so when disabled the input events are completely bypassed.
  1395. this.domHandler = function(ev) {
  1396. if (boolOrFn(manager.options.enable, [ manager ])) {
  1397. self.handler(ev);
  1398. }
  1399. };
  1400. this.init();
  1401. }
  1402. Input.prototype = {
  1403. /**
  1404. * should handle the inputEvent data and trigger the callback
  1405. * @virtual
  1406. */
  1407. handler: function() {},
  1408. /**
  1409. * bind the events
  1410. */
  1411. init: function() {
  1412. this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
  1413. this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
  1414. this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  1415. },
  1416. /**
  1417. * unbind the events
  1418. */
  1419. destroy: function() {
  1420. this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
  1421. this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
  1422. this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  1423. }
  1424. };
  1425. /**
  1426. * create new input type manager
  1427. * called by the Manager constructor
  1428. * @param {Hammer} manager
  1429. * @returns {Input}
  1430. */
  1431. function createInputInstance(manager) {
  1432. var Type;
  1433. var inputClass = manager.options.inputClass;
  1434. if (inputClass) {
  1435. Type = inputClass;
  1436. } else if (SUPPORT_POINTER_EVENTS) {
  1437. Type = PointerEventInput;
  1438. } else if (SUPPORT_ONLY_TOUCH) {
  1439. Type = TouchInput;
  1440. } else if (!SUPPORT_TOUCH) {
  1441. Type = MouseInput;
  1442. } else {
  1443. Type = TouchMouseInput;
  1444. }
  1445. return new Type(manager, inputHandler);
  1446. }
  1447. /**
  1448. * handle input events
  1449. * @param {Manager} manager
  1450. * @param {String} eventType
  1451. * @param {Object} input
  1452. */
  1453. function inputHandler(manager, eventType, input) {
  1454. var pointersLen = input.pointers.length;
  1455. var changedPointersLen = input.changedPointers.length;
  1456. var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
  1457. var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;
  1458. input.isFirst = !!isFirst;
  1459. input.isFinal = !!isFinal;
  1460. if (isFirst) {
  1461. manager.session = {};
  1462. }
  1463. // source event is the normalized value of the domEvents
  1464. // like 'touchstart, mouseup, pointerdown'
  1465. input.eventType = eventType;
  1466. // compute scale, rotation etc
  1467. computeInputData(manager, input);
  1468. // emit secret event
  1469. manager.emit("hammer.input", input);
  1470. manager.recognize(input);
  1471. manager.session.prevInput = input;
  1472. }
  1473. /**
  1474. * extend the data with some usable properties like scale, rotate, velocity etc
  1475. * @param {Object} manager
  1476. * @param {Object} input
  1477. */
  1478. function computeInputData(manager, input) {
  1479. var session = manager.session;
  1480. var pointers = input.pointers;
  1481. var pointersLength = pointers.length;
  1482. // store the first input to calculate the distance and direction
  1483. if (!session.firstInput) {
  1484. session.firstInput = simpleCloneInputData(input);
  1485. }
  1486. // to compute scale and rotation we need to store the multiple touches
  1487. if (pointersLength > 1 && !session.firstMultiple) {
  1488. session.firstMultiple = simpleCloneInputData(input);
  1489. } else if (pointersLength === 1) {
  1490. session.firstMultiple = false;
  1491. }
  1492. var firstInput = session.firstInput;
  1493. var firstMultiple = session.firstMultiple;
  1494. var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
  1495. var center = input.center = getCenter(pointers);
  1496. input.timeStamp = now();
  1497. input.deltaTime = input.timeStamp - firstInput.timeStamp;
  1498. input.angle = getAngle(offsetCenter, center);
  1499. input.distance = getDistance(offsetCenter, center);
  1500. computeDeltaXY(session, input);
  1501. input.offsetDirection = getDirection(input.deltaX, input.deltaY);
  1502. input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
  1503. input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
  1504. computeIntervalInputData(session, input);
  1505. // find the correct target
  1506. var target = manager.element;
  1507. if (hasParent(input.srcEvent.target, target)) {
  1508. target = input.srcEvent.target;
  1509. }
  1510. input.target = target;
  1511. }
  1512. function computeDeltaXY(session, input) {
  1513. var center = input.center;
  1514. var offset = session.offsetDelta || {};
  1515. var prevDelta = session.prevDelta || {};
  1516. var prevInput = session.prevInput || {};
  1517. if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
  1518. prevDelta = session.prevDelta = {
  1519. x: prevInput.deltaX || 0,
  1520. y: prevInput.deltaY || 0
  1521. };
  1522. offset = session.offsetDelta = {
  1523. x: center.x,
  1524. y: center.y
  1525. };
  1526. }
  1527. input.deltaX = prevDelta.x + (center.x - offset.x);
  1528. input.deltaY = prevDelta.y + (center.y - offset.y);
  1529. }
  1530. /**
  1531. * velocity is calculated every x ms
  1532. * @param {Object} session
  1533. * @param {Object} input
  1534. */
  1535. function computeIntervalInputData(session, input) {
  1536. var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction;
  1537. if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
  1538. var deltaX = last.deltaX - input.deltaX;
  1539. var deltaY = last.deltaY - input.deltaY;
  1540. var v = getVelocity(deltaTime, deltaX, deltaY);
  1541. velocityX = v.x;
  1542. velocityY = v.y;
  1543. velocity = abs(v.x) > abs(v.y) ? v.x : v.y;
  1544. direction = getDirection(deltaX, deltaY);
  1545. session.lastInterval = input;
  1546. } else {
  1547. // use latest velocity info if it doesn't overtake a minimum period
  1548. velocity = last.velocity;
  1549. velocityX = last.velocityX;
  1550. velocityY = last.velocityY;
  1551. direction = last.direction;
  1552. }
  1553. input.velocity = velocity;
  1554. input.velocityX = velocityX;
  1555. input.velocityY = velocityY;
  1556. input.direction = direction;
  1557. }
  1558. /**
  1559. * create a simple clone from the input used for storage of firstInput and firstMultiple
  1560. * @param {Object} input
  1561. * @returns {Object} clonedInputData
  1562. */
  1563. function simpleCloneInputData(input) {
  1564. // make a simple copy of the pointers because we will get a reference if we don't
  1565. // we only need clientXY for the calculations
  1566. var pointers = [];
  1567. var i = 0;
  1568. while (i < input.pointers.length) {
  1569. pointers[i] = {
  1570. clientX: round(input.pointers[i].clientX),
  1571. clientY: round(input.pointers[i].clientY)
  1572. };
  1573. i++;
  1574. }
  1575. return {
  1576. timeStamp: now(),
  1577. pointers: pointers,
  1578. center: getCenter(pointers),
  1579. deltaX: input.deltaX,
  1580. deltaY: input.deltaY
  1581. };
  1582. }
  1583. /**
  1584. * get the center of all the pointers
  1585. * @param {Array} pointers
  1586. * @return {Object} center contains `x` and `y` properties
  1587. */
  1588. function getCenter(pointers) {
  1589. var pointersLength = pointers.length;
  1590. // no need to loop when only one touch
  1591. if (pointersLength === 1) {
  1592. return {
  1593. x: round(pointers[0].clientX),
  1594. y: round(pointers[0].clientY)
  1595. };
  1596. }
  1597. var x = 0, y = 0, i = 0;
  1598. while (i < pointersLength) {
  1599. x += pointers[i].clientX;
  1600. y += pointers[i].clientY;
  1601. i++;
  1602. }
  1603. return {
  1604. x: round(x / pointersLength),
  1605. y: round(y / pointersLength)
  1606. };
  1607. }
  1608. /**
  1609. * calculate the velocity between two points. unit is in px per ms.
  1610. * @param {Number} deltaTime
  1611. * @param {Number} x
  1612. * @param {Number} y
  1613. * @return {Object} velocity `x` and `y`
  1614. */
  1615. function getVelocity(deltaTime, x, y) {
  1616. return {
  1617. x: x / deltaTime || 0,
  1618. y: y / deltaTime || 0
  1619. };
  1620. }
  1621. /**
  1622. * get the direction between two points
  1623. * @param {Number} x
  1624. * @param {Number} y
  1625. * @return {Number} direction
  1626. */
  1627. function getDirection(x, y) {
  1628. if (x === y) {
  1629. return DIRECTION_NONE;
  1630. }
  1631. if (abs(x) >= abs(y)) {
  1632. return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  1633. }
  1634. return y > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  1635. }
  1636. /**
  1637. * calculate the absolute distance between two points
  1638. * @param {Object} p1 {x, y}
  1639. * @param {Object} p2 {x, y}
  1640. * @param {Array} [props] containing x and y keys
  1641. * @return {Number} distance
  1642. */
  1643. function getDistance(p1, p2, props) {
  1644. if (!props) {
  1645. props = PROPS_XY;
  1646. }
  1647. var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
  1648. return Math.sqrt(x * x + y * y);
  1649. }
  1650. /**
  1651. * calculate the angle between two coordinates
  1652. * @param {Object} p1
  1653. * @param {Object} p2
  1654. * @param {Array} [props] containing x and y keys
  1655. * @return {Number} angle
  1656. */
  1657. function getAngle(p1, p2, props) {
  1658. if (!props) {
  1659. props = PROPS_XY;
  1660. }
  1661. var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
  1662. return Math.atan2(y, x) * 180 / Math.PI;
  1663. }
  1664. /**
  1665. * calculate the rotation degrees between two pointersets
  1666. * @param {Array} start array of pointers
  1667. * @param {Array} end array of pointers
  1668. * @return {Number} rotation
  1669. */
  1670. function getRotation(start, end) {
  1671. return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY);
  1672. }
  1673. /**
  1674. * calculate the scale factor between two pointersets
  1675. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  1676. * @param {Array} start array of pointers
  1677. * @param {Array} end array of pointers
  1678. * @return {Number} scale
  1679. */
  1680. function getScale(start, end) {
  1681. return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
  1682. }
  1683. var MOUSE_INPUT_MAP = {
  1684. mousedown: INPUT_START,
  1685. mousemove: INPUT_MOVE,
  1686. mouseup: INPUT_END
  1687. };
  1688. var MOUSE_ELEMENT_EVENTS = "mousedown";
  1689. var MOUSE_WINDOW_EVENTS = "mousemove mouseup";
  1690. /**
  1691. * Mouse events input
  1692. * @constructor
  1693. * @extends Input
  1694. */
  1695. function MouseInput() {
  1696. this.evEl = MOUSE_ELEMENT_EVENTS;
  1697. this.evWin = MOUSE_WINDOW_EVENTS;
  1698. this.allow = true;
  1699. // used by Input.TouchMouse to disable mouse events
  1700. this.pressed = false;
  1701. // mousedown state
  1702. Input.apply(this, arguments);
  1703. }
  1704. inherit(MouseInput, Input, {
  1705. /**
  1706. * handle mouse events
  1707. * @param {Object} ev
  1708. */
  1709. handler: function MEhandler(ev) {
  1710. var eventType = MOUSE_INPUT_MAP[ev.type];
  1711. // on start we want to have the left mouse button down
  1712. if (eventType & INPUT_START && ev.button === 0) {
  1713. this.pressed = true;
  1714. }
  1715. if (eventType & INPUT_MOVE && ev.which !== 1) {
  1716. eventType = INPUT_END;
  1717. }
  1718. // mouse must be down, and mouse events are allowed (see the TouchMouse input)
  1719. if (!this.pressed || !this.allow) {
  1720. return;
  1721. }
  1722. if (eventType & INPUT_END) {
  1723. this.pressed = false;
  1724. }
  1725. this.callback(this.manager, eventType, {
  1726. pointers: [ ev ],
  1727. changedPointers: [ ev ],
  1728. pointerType: INPUT_TYPE_MOUSE,
  1729. srcEvent: ev
  1730. });
  1731. }
  1732. });
  1733. var POINTER_INPUT_MAP = {
  1734. pointerdown: INPUT_START,
  1735. pointermove: INPUT_MOVE,
  1736. pointerup: INPUT_END,
  1737. pointercancel: INPUT_CANCEL,
  1738. pointerout: INPUT_CANCEL
  1739. };
  1740. // in IE10 the pointer types is defined as an enum
  1741. var IE10_POINTER_TYPE_ENUM = {
  1742. 2: INPUT_TYPE_TOUCH,
  1743. 3: INPUT_TYPE_PEN,
  1744. 4: INPUT_TYPE_MOUSE,
  1745. 5: INPUT_TYPE_KINECT
  1746. };
  1747. var POINTER_ELEMENT_EVENTS = "pointerdown";
  1748. var POINTER_WINDOW_EVENTS = "pointermove pointerup pointercancel";
  1749. // IE10 has prefixed support, and case-sensitive
  1750. if (window.MSPointerEvent) {
  1751. POINTER_ELEMENT_EVENTS = "MSPointerDown";
  1752. POINTER_WINDOW_EVENTS = "MSPointerMove MSPointerUp MSPointerCancel";
  1753. }
  1754. /**
  1755. * Pointer events input
  1756. * @constructor
  1757. * @extends Input
  1758. */
  1759. function PointerEventInput() {
  1760. this.evEl = POINTER_ELEMENT_EVENTS;
  1761. this.evWin = POINTER_WINDOW_EVENTS;
  1762. Input.apply(this, arguments);
  1763. this.store = this.manager.session.pointerEvents = [];
  1764. }
  1765. inherit(PointerEventInput, Input, {
  1766. /**
  1767. * handle mouse events
  1768. * @param {Object} ev
  1769. */
  1770. handler: function PEhandler(ev) {
  1771. var store = this.store;
  1772. var removePointer = false;
  1773. var eventTypeNormalized = ev.type.toLowerCase().replace("ms", "");
  1774. var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
  1775. var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
  1776. var isTouch = pointerType == INPUT_TYPE_TOUCH;
  1777. // start and mouse must be down
  1778. if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
  1779. store.push(ev);
  1780. } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
  1781. removePointer = true;
  1782. }
  1783. // get index of the event in the store
  1784. // it not found, so the pointer hasn't been down (so it's probably a hover)
  1785. var storeIndex = inArray(store, ev.pointerId, "pointerId");
  1786. if (storeIndex < 0) {
  1787. return;
  1788. }
  1789. // update the event in the store
  1790. store[storeIndex] = ev;
  1791. this.callback(this.manager, eventType, {
  1792. pointers: store,
  1793. changedPointers: [ ev ],
  1794. pointerType: pointerType,
  1795. srcEvent: ev
  1796. });
  1797. if (removePointer) {
  1798. // remove from the store
  1799. store.splice(storeIndex, 1);
  1800. }
  1801. }
  1802. });
  1803. var TOUCH_INPUT_MAP = {
  1804. touchstart: INPUT_START,
  1805. touchmove: INPUT_MOVE,
  1806. touchend: INPUT_END,
  1807. touchcancel: INPUT_CANCEL
  1808. };
  1809. var TOUCH_TARGET_EVENTS = "touchstart touchmove touchend touchcancel";
  1810. /**
  1811. * Touch events input
  1812. * @constructor
  1813. * @extends Input
  1814. */
  1815. function TouchInput() {
  1816. this.evTarget = TOUCH_TARGET_EVENTS;
  1817. this.targetIds = {};
  1818. Input.apply(this, arguments);
  1819. }
  1820. inherit(TouchInput, Input, {
  1821. /**
  1822. * handle touch events
  1823. * @param {Object} ev
  1824. */
  1825. handler: function TEhandler(ev) {
  1826. var type = TOUCH_INPUT_MAP[ev.type];
  1827. var touches = getTouches.call(this, ev, type);
  1828. if (!touches) {
  1829. return;
  1830. }
  1831. this.callback(this.manager, type, {
  1832. pointers: touches[0],
  1833. changedPointers: touches[1],
  1834. pointerType: INPUT_TYPE_TOUCH,
  1835. srcEvent: ev
  1836. });
  1837. }
  1838. });
  1839. /**
  1840. * @this {TouchInput}
  1841. * @param {Object} ev
  1842. * @param {Number} type flag
  1843. * @returns {undefined|Array} [all, changed]
  1844. */
  1845. function getTouches(ev, type) {
  1846. var allTouches = toArray(ev.touches);
  1847. var targetIds = this.targetIds;
  1848. // when there is only one touch, the process can be simplified
  1849. if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
  1850. targetIds[allTouches[0].identifier] = true;
  1851. return [ allTouches, allTouches ];
  1852. }
  1853. var i, targetTouches = toArray(ev.targetTouches), changedTouches = toArray(ev.changedTouches), changedTargetTouches = [];
  1854. // collect touches
  1855. if (type === INPUT_START) {
  1856. i = 0;
  1857. while (i < targetTouches.length) {
  1858. targetIds[targetTouches[i].identifier] = true;
  1859. i++;
  1860. }
  1861. }
  1862. // filter changed touches to only contain touches that exist in the collected target ids
  1863. i = 0;
  1864. while (i < changedTouches.length) {
  1865. if (targetIds[changedTouches[i].identifier]) {
  1866. changedTargetTouches.push(changedTouches[i]);
  1867. }
  1868. // cleanup removed touches
  1869. if (type & (INPUT_END | INPUT_CANCEL)) {
  1870. delete targetIds[changedTouches[i].identifier];
  1871. }
  1872. i++;
  1873. }
  1874. if (!changedTargetTouches.length) {
  1875. return;
  1876. }
  1877. return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
  1878. uniqueArray(targetTouches.concat(changedTargetTouches), "identifier", true), changedTargetTouches ];
  1879. }
  1880. /**
  1881. * Combined touch and mouse input
  1882. *
  1883. * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
  1884. * This because touch devices also emit mouse events while doing a touch.
  1885. *
  1886. * @constructor
  1887. * @extends Input
  1888. */
  1889. function TouchMouseInput() {
  1890. Input.apply(this, arguments);
  1891. var handler = bindFn(this.handler, this);
  1892. this.touch = new TouchInput(this.manager, handler);
  1893. this.mouse = new MouseInput(this.manager, handler);
  1894. }
  1895. inherit(TouchMouseInput, Input, {
  1896. /**
  1897. * handle mouse and touch events
  1898. * @param {Hammer} manager
  1899. * @param {String} inputEvent
  1900. * @param {Object} inputData
  1901. */
  1902. handler: function TMEhandler(manager, inputEvent, inputData) {
  1903. var isTouch = inputData.pointerType == INPUT_TYPE_TOUCH, isMouse = inputData.pointerType == INPUT_TYPE_MOUSE;
  1904. // when we're in a touch event, so block all upcoming mouse events
  1905. // most mobile browser also emit mouseevents, right after touchstart
  1906. if (isTouch) {
  1907. this.mouse.allow = false;
  1908. } else if (isMouse && !this.mouse.allow) {
  1909. return;
  1910. }
  1911. // reset the allowMouse when we're done
  1912. if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
  1913. this.mouse.allow = true;
  1914. }
  1915. this.callback(manager, inputEvent, inputData);
  1916. },
  1917. /**
  1918. * remove the event listeners
  1919. */
  1920. destroy: function destroy() {
  1921. this.touch.destroy();
  1922. this.mouse.destroy();
  1923. }
  1924. });
  1925. var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, "touchAction");
  1926. var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
  1927. // magical touchAction value
  1928. var TOUCH_ACTION_COMPUTE = "compute";
  1929. var TOUCH_ACTION_AUTO = "auto";
  1930. var TOUCH_ACTION_MANIPULATION = "manipulation";
  1931. // not implemented
  1932. var TOUCH_ACTION_NONE = "none";
  1933. var TOUCH_ACTION_PAN_X = "pan-x";
  1934. var TOUCH_ACTION_PAN_Y = "pan-y";
  1935. /**
  1936. * Touch Action
  1937. * sets the touchAction property or uses the js alternative
  1938. * @param {Manager} manager
  1939. * @param {String} value
  1940. * @constructor
  1941. */
  1942. function TouchAction(manager, value) {
  1943. this.manager = manager;
  1944. this.set(value);
  1945. }
  1946. TouchAction.prototype = {
  1947. /**
  1948. * set the touchAction value on the element or enable the polyfill
  1949. * @param {String} value
  1950. */
  1951. set: function(value) {
  1952. // find out the touch-action by the event handlers
  1953. if (value == TOUCH_ACTION_COMPUTE) {
  1954. value = this.compute();
  1955. }
  1956. if (NATIVE_TOUCH_ACTION) {
  1957. this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
  1958. }
  1959. this.actions = value.toLowerCase().trim();
  1960. },
  1961. /**
  1962. * just re-set the touchAction value
  1963. */
  1964. update: function() {
  1965. this.set(this.manager.options.touchAction);
  1966. },
  1967. /**
  1968. * compute the value for the touchAction property based on the recognizer's settings
  1969. * @returns {String} value
  1970. */
  1971. compute: function() {
  1972. var actions = [];
  1973. each(this.manager.recognizers, function(recognizer) {
  1974. if (boolOrFn(recognizer.options.enable, [ recognizer ])) {
  1975. actions = actions.concat(recognizer.getTouchAction());
  1976. }
  1977. });
  1978. return cleanTouchActions(actions.join(" "));
  1979. },
  1980. /**
  1981. * this method is called on each input cycle and provides the preventing of the browser behavior
  1982. * @param {Object} input
  1983. */
  1984. preventDefaults: function(input) {
  1985. // not needed with native support for the touchAction property
  1986. if (NATIVE_TOUCH_ACTION) {
  1987. return;
  1988. }
  1989. var srcEvent = input.srcEvent;
  1990. var direction = input.offsetDirection;
  1991. // if the touch action did prevented once this session
  1992. if (this.manager.session.prevented) {
  1993. srcEvent.preventDefault();
  1994. return;
  1995. }
  1996. var actions = this.actions;
  1997. var hasNone = inStr(actions, TOUCH_ACTION_NONE);
  1998. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  1999. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  2000. if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
  2001. return this.preventSrc(srcEvent);
  2002. }
  2003. },
  2004. /**
  2005. * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
  2006. * @param {Object} srcEvent
  2007. */
  2008. preventSrc: function(srcEvent) {
  2009. this.manager.session.prevented = true;
  2010. srcEvent.preventDefault();
  2011. }
  2012. };
  2013. /**
  2014. * when the touchActions are collected they are not a valid value, so we need to clean things up. *
  2015. * @param {String} actions
  2016. * @returns {*}
  2017. */
  2018. function cleanTouchActions(actions) {
  2019. // none
  2020. if (inStr(actions, TOUCH_ACTION_NONE)) {
  2021. return TOUCH_ACTION_NONE;
  2022. }
  2023. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  2024. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  2025. // pan-x and pan-y can be combined
  2026. if (hasPanX && hasPanY) {
  2027. return TOUCH_ACTION_PAN_X + " " + TOUCH_ACTION_PAN_Y;
  2028. }
  2029. // pan-x OR pan-y
  2030. if (hasPanX || hasPanY) {
  2031. return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
  2032. }
  2033. // manipulation
  2034. if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
  2035. return TOUCH_ACTION_MANIPULATION;
  2036. }
  2037. return TOUCH_ACTION_AUTO;
  2038. }
  2039. /**
  2040. * Recognizer flow explained; *
  2041. * All recognizers have the initial state of POSSIBLE when a input session starts.
  2042. * The definition of a input session is from the first input until the last input, with all it's movement in it. *
  2043. * Example session for mouse-input: mousedown -> mousemove -> mouseup
  2044. *
  2045. * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
  2046. * which determines with state it should be.
  2047. *
  2048. * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
  2049. * POSSIBLE to give it another change on the next cycle.
  2050. *
  2051. * Possible
  2052. * |
  2053. * +-----+---------------+
  2054. * | |
  2055. * +-----+-----+ |
  2056. * | | |
  2057. * Failed Cancelled |
  2058. * +-------+------+
  2059. * | |
  2060. * Recognized Began
  2061. * |
  2062. * Changed
  2063. * |
  2064. * Ended/Recognized
  2065. */
  2066. var STATE_POSSIBLE = 1;
  2067. var STATE_BEGAN = 2;
  2068. var STATE_CHANGED = 4;
  2069. var STATE_ENDED = 8;
  2070. var STATE_RECOGNIZED = STATE_ENDED;
  2071. var STATE_CANCELLED = 16;
  2072. var STATE_FAILED = 32;
  2073. /**
  2074. * Recognizer
  2075. * Every recognizer needs to extend from this class.
  2076. * @constructor
  2077. * @param {Object} options
  2078. */
  2079. function Recognizer(options) {
  2080. this.id = uniqueId();
  2081. this.manager = null;
  2082. this.options = merge(options || {}, this.defaults);
  2083. // default is enable true
  2084. this.options.enable = ifUndefined(this.options.enable, true);
  2085. this.state = STATE_POSSIBLE;
  2086. this.simultaneous = {};
  2087. this.requireFail = [];
  2088. }
  2089. Recognizer.prototype = {
  2090. /**
  2091. * @virtual
  2092. * @type {Object}
  2093. */
  2094. defaults: {},
  2095. /**
  2096. * set options
  2097. * @param {Object} options
  2098. * @return {Recognizer}
  2099. */
  2100. set: function(options) {
  2101. extend(this.options, options);
  2102. // also update the touchAction, in case something changed about the directions/enabled state
  2103. this.manager && this.manager.touchAction.update();
  2104. return this;
  2105. },
  2106. /**
  2107. * recognize simultaneous with an other recognizer.
  2108. * @param {Recognizer} otherRecognizer
  2109. * @returns {Recognizer} this
  2110. */
  2111. recognizeWith: function(otherRecognizer) {
  2112. if (invokeArrayArg(otherRecognizer, "recognizeWith", this)) {
  2113. return this;
  2114. }
  2115. var simultaneous = this.simultaneous;
  2116. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2117. if (!simultaneous[otherRecognizer.id]) {
  2118. simultaneous[otherRecognizer.id] = otherRecognizer;
  2119. otherRecognizer.recognizeWith(this);
  2120. }
  2121. return this;
  2122. },
  2123. /**
  2124. * drop the simultaneous link. it doesnt remove the link on the other recognizer.
  2125. * @param {Recognizer} otherRecognizer
  2126. * @returns {Recognizer} this
  2127. */
  2128. dropRecognizeWith: function(otherRecognizer) {
  2129. if (invokeArrayArg(otherRecognizer, "dropRecognizeWith", this)) {
  2130. return this;
  2131. }
  2132. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2133. delete this.simultaneous[otherRecognizer.id];
  2134. return this;
  2135. },
  2136. /**
  2137. * recognizer can only run when an other is failing
  2138. * @param {Recognizer} otherRecognizer
  2139. * @returns {Recognizer} this
  2140. */
  2141. requireFailure: function(otherRecognizer) {
  2142. if (invokeArrayArg(otherRecognizer, "requireFailure", this)) {
  2143. return this;
  2144. }
  2145. var requireFail = this.requireFail;
  2146. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2147. if (inArray(requireFail, otherRecognizer) === -1) {
  2148. requireFail.push(otherRecognizer);
  2149. otherRecognizer.requireFailure(this);
  2150. }
  2151. return this;
  2152. },
  2153. /**
  2154. * drop the requireFailure link. it does not remove the link on the other recognizer.
  2155. * @param {Recognizer} otherRecognizer
  2156. * @returns {Recognizer} this
  2157. */
  2158. dropRequireFailure: function(otherRecognizer) {
  2159. if (invokeArrayArg(otherRecognizer, "dropRequireFailure", this)) {
  2160. return this;
  2161. }
  2162. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2163. var index = inArray(this.requireFail, otherRecognizer);
  2164. if (index > -1) {
  2165. this.requireFail.splice(index, 1);
  2166. }
  2167. return this;
  2168. },
  2169. /**
  2170. * has require failures boolean
  2171. * @returns {boolean}
  2172. */
  2173. hasRequireFailures: function() {
  2174. return this.requireFail.length > 0;
  2175. },
  2176. /**
  2177. * if the recognizer can recognize simultaneous with an other recognizer
  2178. * @param {Recognizer} otherRecognizer
  2179. * @returns {Boolean}
  2180. */
  2181. canRecognizeWith: function(otherRecognizer) {
  2182. return !!this.simultaneous[otherRecognizer.id];
  2183. },
  2184. /**
  2185. * You should use `tryEmit` instead of `emit` directly to check
  2186. * that all the needed recognizers has failed before emitting.
  2187. * @param {Object} input
  2188. */
  2189. emit: function(input) {
  2190. var self = this;
  2191. var state = this.state;
  2192. function emit(withState) {
  2193. self.manager.emit(self.options.event + (withState ? stateStr(state) : ""), input);
  2194. }
  2195. // 'panstart' and 'panmove'
  2196. if (state < STATE_ENDED) {
  2197. emit(true);
  2198. }
  2199. emit();
  2200. // simple 'eventName' events
  2201. // panend and pancancel
  2202. if (state >= STATE_ENDED) {
  2203. emit(true);
  2204. }
  2205. },
  2206. /**
  2207. * Check that all the require failure recognizers has failed,
  2208. * if true, it emits a gesture event,
  2209. * otherwise, setup the state to FAILED.
  2210. * @param {Object} input
  2211. */
  2212. tryEmit: function(input) {
  2213. if (this.canEmit()) {
  2214. return this.emit(input);
  2215. }
  2216. // it's failing anyway
  2217. this.state = STATE_FAILED;
  2218. },
  2219. /**
  2220. * can we emit?
  2221. * @returns {boolean}
  2222. */
  2223. canEmit: function() {
  2224. var i = 0;
  2225. while (i < this.requireFail.length) {
  2226. if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
  2227. return false;
  2228. }
  2229. i++;
  2230. }
  2231. return true;
  2232. },
  2233. /**
  2234. * update the recognizer
  2235. * @param {Object} inputData
  2236. */
  2237. recognize: function(inputData) {
  2238. // make a new copy of the inputData
  2239. // so we can change the inputData without messing up the other recognizers
  2240. var inputDataClone = extend({}, inputData);
  2241. // is is enabled and allow recognizing?
  2242. if (!boolOrFn(this.options.enable, [ this, inputDataClone ])) {
  2243. this.reset();
  2244. this.state = STATE_FAILED;
  2245. return;
  2246. }
  2247. // reset when we've reached the end
  2248. if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
  2249. this.state = STATE_POSSIBLE;
  2250. }
  2251. this.state = this.process(inputDataClone);
  2252. // the recognizer has recognized a gesture
  2253. // so trigger an event
  2254. if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
  2255. this.tryEmit(inputDataClone);
  2256. }
  2257. },
  2258. /**
  2259. * return the state of the recognizer
  2260. * the actual recognizing happens in this method
  2261. * @virtual
  2262. * @param {Object} inputData
  2263. * @returns {Const} STATE
  2264. */
  2265. process: function(inputData) {},
  2266. // jshint ignore:line
  2267. /**
  2268. * return the preferred touch-action
  2269. * @virtual
  2270. * @returns {Array}
  2271. */
  2272. getTouchAction: function() {},
  2273. /**
  2274. * called when the gesture isn't allowed to recognize
  2275. * like when another is being recognized or it is disabled
  2276. * @virtual
  2277. */
  2278. reset: function() {}
  2279. };
  2280. /**
  2281. * get a usable string, used as event postfix
  2282. * @param {Const} state
  2283. * @returns {String} state
  2284. */
  2285. function stateStr(state) {
  2286. if (state & STATE_CANCELLED) {
  2287. return "cancel";
  2288. } else if (state & STATE_ENDED) {
  2289. return "end";
  2290. } else if (state & STATE_CHANGED) {
  2291. return "move";
  2292. } else if (state & STATE_BEGAN) {
  2293. return "start";
  2294. }
  2295. return "";
  2296. }
  2297. /**
  2298. * direction cons to string
  2299. * @param {Const} direction
  2300. * @returns {String}
  2301. */
  2302. function directionStr(direction) {
  2303. if (direction == DIRECTION_DOWN) {
  2304. return "down";
  2305. } else if (direction == DIRECTION_UP) {
  2306. return "up";
  2307. } else if (direction == DIRECTION_LEFT) {
  2308. return "left";
  2309. } else if (direction == DIRECTION_RIGHT) {
  2310. return "right";
  2311. }
  2312. return "";
  2313. }
  2314. /**
  2315. * get a recognizer by name if it is bound to a manager
  2316. * @param {Recognizer|String} otherRecognizer
  2317. * @param {Recognizer} recognizer
  2318. * @returns {Recognizer}
  2319. */
  2320. function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
  2321. var manager = recognizer.manager;
  2322. if (manager) {
  2323. return manager.get(otherRecognizer);
  2324. }
  2325. return otherRecognizer;
  2326. }
  2327. /**
  2328. * This recognizer is just used as a base for the simple attribute recognizers.
  2329. * @constructor
  2330. * @extends Recognizer
  2331. */
  2332. function AttrRecognizer() {
  2333. Recognizer.apply(this, arguments);
  2334. }
  2335. inherit(AttrRecognizer, Recognizer, {
  2336. /**
  2337. * @namespace
  2338. * @memberof AttrRecognizer
  2339. */
  2340. defaults: {
  2341. /**
  2342. * @type {Number}
  2343. * @default 1
  2344. */
  2345. pointers: 1
  2346. },
  2347. /**
  2348. * Used to check if it the recognizer receives valid input, like input.distance > 10.
  2349. * @memberof AttrRecognizer
  2350. * @param {Object} input
  2351. * @returns {Boolean} recognized
  2352. */
  2353. attrTest: function(input) {
  2354. var optionPointers = this.options.pointers;
  2355. return optionPointers === 0 || input.pointers.length === optionPointers;
  2356. },
  2357. /**
  2358. * Process the input and return the state for the recognizer
  2359. * @memberof AttrRecognizer
  2360. * @param {Object} input
  2361. * @returns {*} State
  2362. */
  2363. process: function(input) {
  2364. var state = this.state;
  2365. var eventType = input.eventType;
  2366. var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
  2367. var isValid = this.attrTest(input);
  2368. // on cancel input and we've recognized before, return STATE_CANCELLED
  2369. if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
  2370. return state | STATE_CANCELLED;
  2371. } else if (isRecognized || isValid) {
  2372. if (eventType & INPUT_END) {
  2373. return state | STATE_ENDED;
  2374. } else if (!(state & STATE_BEGAN)) {
  2375. return STATE_BEGAN;
  2376. }
  2377. return state | STATE_CHANGED;
  2378. }
  2379. return STATE_FAILED;
  2380. }
  2381. });
  2382. /**
  2383. * Pan
  2384. * Recognized when the pointer is down and moved in the allowed direction.
  2385. * @constructor
  2386. * @extends AttrRecognizer
  2387. */
  2388. function PanRecognizer() {
  2389. AttrRecognizer.apply(this, arguments);
  2390. this.pX = null;
  2391. this.pY = null;
  2392. }
  2393. inherit(PanRecognizer, AttrRecognizer, {
  2394. /**
  2395. * @namespace
  2396. * @memberof PanRecognizer
  2397. */
  2398. defaults: {
  2399. event: "pan",
  2400. threshold: 10,
  2401. pointers: 1,
  2402. direction: DIRECTION_ALL
  2403. },
  2404. getTouchAction: function() {
  2405. var direction = this.options.direction;
  2406. var actions = [];
  2407. if (direction & DIRECTION_HORIZONTAL) {
  2408. actions.push(TOUCH_ACTION_PAN_Y);
  2409. }
  2410. if (direction & DIRECTION_VERTICAL) {
  2411. actions.push(TOUCH_ACTION_PAN_X);
  2412. }
  2413. return actions;
  2414. },
  2415. directionTest: function(input) {
  2416. var options = this.options;
  2417. var hasMoved = true;
  2418. var distance = input.distance;
  2419. var direction = input.direction;
  2420. var x = input.deltaX;
  2421. var y = input.deltaY;
  2422. // lock to axis?
  2423. if (!(direction & options.direction)) {
  2424. if (options.direction & DIRECTION_HORIZONTAL) {
  2425. direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  2426. hasMoved = x != this.pX;
  2427. distance = Math.abs(input.deltaX);
  2428. } else {
  2429. direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
  2430. hasMoved = y != this.pY;
  2431. distance = Math.abs(input.deltaY);
  2432. }
  2433. }
  2434. input.direction = direction;
  2435. return hasMoved && distance > options.threshold && direction & options.direction;
  2436. },
  2437. attrTest: function(input) {
  2438. return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));
  2439. },
  2440. emit: function(input) {
  2441. this.pX = input.deltaX;
  2442. this.pY = input.deltaY;
  2443. var direction = directionStr(input.direction);
  2444. if (direction) {
  2445. this.manager.emit(this.options.event + direction, input);
  2446. }
  2447. this._super.emit.call(this, input);
  2448. }
  2449. });
  2450. /**
  2451. * Pinch
  2452. * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
  2453. * @constructor
  2454. * @extends AttrRecognizer
  2455. */
  2456. function PinchRecognizer() {
  2457. AttrRecognizer.apply(this, arguments);
  2458. }
  2459. inherit(PinchRecognizer, AttrRecognizer, {
  2460. /**
  2461. * @namespace
  2462. * @memberof PinchRecognizer
  2463. */
  2464. defaults: {
  2465. event: "pinch",
  2466. threshold: 0,
  2467. pointers: 2
  2468. },
  2469. getTouchAction: function() {
  2470. return [ TOUCH_ACTION_NONE ];
  2471. },
  2472. attrTest: function(input) {
  2473. return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
  2474. },
  2475. emit: function(input) {
  2476. this._super.emit.call(this, input);
  2477. if (input.scale !== 1) {
  2478. var inOut = input.scale < 1 ? "in" : "out";
  2479. this.manager.emit(this.options.event + inOut, input);
  2480. }
  2481. }
  2482. });
  2483. /**
  2484. * Press
  2485. * Recognized when the pointer is down for x ms without any movement.
  2486. * @constructor
  2487. * @extends Recognizer
  2488. */
  2489. function PressRecognizer() {
  2490. Recognizer.apply(this, arguments);
  2491. this._timer = null;
  2492. this._input = null;
  2493. }
  2494. inherit(PressRecognizer, Recognizer, {
  2495. /**
  2496. * @namespace
  2497. * @memberof PressRecognizer
  2498. */
  2499. defaults: {
  2500. event: "press",
  2501. pointers: 1,
  2502. time: 500,
  2503. // minimal time of the pointer to be pressed
  2504. threshold: 5
  2505. },
  2506. getTouchAction: function() {
  2507. return [ TOUCH_ACTION_AUTO ];
  2508. },
  2509. process: function(input) {
  2510. var options = this.options;
  2511. var validPointers = input.pointers.length === options.pointers;
  2512. var validMovement = input.distance < options.threshold;
  2513. var validTime = input.deltaTime > options.time;
  2514. this._input = input;
  2515. // we only allow little movement
  2516. // and we've reached an end event, so a tap is possible
  2517. if (!validMovement || !validPointers || input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime) {
  2518. this.reset();
  2519. } else if (input.eventType & INPUT_START) {
  2520. this.reset();
  2521. this._timer = setTimeoutContext(function() {
  2522. this.state = STATE_RECOGNIZED;
  2523. this.tryEmit();
  2524. }, options.time, this);
  2525. } else if (input.eventType & INPUT_END) {
  2526. return STATE_RECOGNIZED;
  2527. }
  2528. return STATE_FAILED;
  2529. },
  2530. reset: function() {
  2531. clearTimeout(this._timer);
  2532. },
  2533. emit: function(input) {
  2534. if (this.state !== STATE_RECOGNIZED) {
  2535. return;
  2536. }
  2537. if (input && input.eventType & INPUT_END) {
  2538. this.manager.emit(this.options.event + "up", input);
  2539. } else {
  2540. this._input.timeStamp = now();
  2541. this.manager.emit(this.options.event, this._input);
  2542. }
  2543. }
  2544. });
  2545. /**
  2546. * Rotate
  2547. * Recognized when two or more pointer are moving in a circular motion.
  2548. * @constructor
  2549. * @extends AttrRecognizer
  2550. */
  2551. function RotateRecognizer() {
  2552. AttrRecognizer.apply(this, arguments);
  2553. }
  2554. inherit(RotateRecognizer, AttrRecognizer, {
  2555. /**
  2556. * @namespace
  2557. * @memberof RotateRecognizer
  2558. */
  2559. defaults: {
  2560. event: "rotate",
  2561. threshold: 0,
  2562. pointers: 2
  2563. },
  2564. getTouchAction: function() {
  2565. return [ TOUCH_ACTION_NONE ];
  2566. },
  2567. attrTest: function(input) {
  2568. return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
  2569. }
  2570. });
  2571. /**
  2572. * Swipe
  2573. * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
  2574. * @constructor
  2575. * @extends AttrRecognizer
  2576. */
  2577. function SwipeRecognizer() {
  2578. AttrRecognizer.apply(this, arguments);
  2579. }
  2580. inherit(SwipeRecognizer, AttrRecognizer, {
  2581. /**
  2582. * @namespace
  2583. * @memberof SwipeRecognizer
  2584. */
  2585. defaults: {
  2586. event: "swipe",
  2587. threshold: 10,
  2588. velocity: .65,
  2589. direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
  2590. pointers: 1
  2591. },
  2592. getTouchAction: function() {
  2593. return PanRecognizer.prototype.getTouchAction.call(this);
  2594. },
  2595. attrTest: function(input) {
  2596. var direction = this.options.direction;
  2597. var velocity;
  2598. if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
  2599. velocity = input.velocity;
  2600. } else if (direction & DIRECTION_HORIZONTAL) {
  2601. velocity = input.velocityX;
  2602. } else if (direction & DIRECTION_VERTICAL) {
  2603. velocity = input.velocityY;
  2604. }
  2605. return this._super.attrTest.call(this, input) && direction & input.direction && input.distance > this.options.threshold && abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
  2606. },
  2607. emit: function(input) {
  2608. var direction = directionStr(input.direction);
  2609. if (direction) {
  2610. this.manager.emit(this.options.event + direction, input);
  2611. }
  2612. this.manager.emit(this.options.event, input);
  2613. }
  2614. });
  2615. /**
  2616. * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
  2617. * between the given interval and position. The delay option can be used to recognize multi-taps without firing
  2618. * a single tap.
  2619. *
  2620. * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
  2621. * multi-taps being recognized.
  2622. * @constructor
  2623. * @extends Recognizer
  2624. */
  2625. function TapRecognizer() {
  2626. Recognizer.apply(this, arguments);
  2627. // previous time and center,
  2628. // used for tap counting
  2629. this.pTime = false;
  2630. this.pCenter = false;
  2631. this._timer = null;
  2632. this._input = null;
  2633. this.count = 0;
  2634. }
  2635. inherit(TapRecognizer, Recognizer, {
  2636. /**
  2637. * @namespace
  2638. * @memberof PinchRecognizer
  2639. */
  2640. defaults: {
  2641. event: "tap",
  2642. pointers: 1,
  2643. taps: 1,
  2644. interval: 300,
  2645. // max time between the multi-tap taps
  2646. time: 250,
  2647. // max time of the pointer to be down (like finger on the screen)
  2648. threshold: 2,
  2649. // a minimal movement is ok, but keep it low
  2650. posThreshold: 10
  2651. },
  2652. getTouchAction: function() {
  2653. return [ TOUCH_ACTION_MANIPULATION ];
  2654. },
  2655. process: function(input) {
  2656. var options = this.options;
  2657. var validPointers = input.pointers.length === options.pointers;
  2658. var validMovement = input.distance < options.threshold;
  2659. var validTouchTime = input.deltaTime < options.time;
  2660. this.reset();
  2661. if (input.eventType & INPUT_START && this.count === 0) {
  2662. return this.failTimeout();
  2663. }
  2664. // we only allow little movement
  2665. // and we've reached an end event, so a tap is possible
  2666. if (validMovement && validTouchTime && validPointers) {
  2667. if (input.eventType != INPUT_END) {
  2668. return this.failTimeout();
  2669. }
  2670. var validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;
  2671. var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
  2672. this.pTime = input.timeStamp;
  2673. this.pCenter = input.center;
  2674. if (!validMultiTap || !validInterval) {
  2675. this.count = 1;
  2676. } else {
  2677. this.count += 1;
  2678. }
  2679. this._input = input;
  2680. // if tap count matches we have recognized it,
  2681. // else it has began recognizing...
  2682. var tapCount = this.count % options.taps;
  2683. if (tapCount === 0) {
  2684. // no failing requirements, immediately trigger the tap event
  2685. // or wait as long as the multitap interval to trigger
  2686. if (!this.hasRequireFailures()) {
  2687. return STATE_RECOGNIZED;
  2688. } else {
  2689. this._timer = setTimeoutContext(function() {
  2690. this.state = STATE_RECOGNIZED;
  2691. this.tryEmit();
  2692. }, options.interval, this);
  2693. return STATE_BEGAN;
  2694. }
  2695. }
  2696. }
  2697. return STATE_FAILED;
  2698. },
  2699. failTimeout: function() {
  2700. this._timer = setTimeoutContext(function() {
  2701. this.state = STATE_FAILED;
  2702. }, this.options.interval, this);
  2703. return STATE_FAILED;
  2704. },
  2705. reset: function() {
  2706. clearTimeout(this._timer);
  2707. },
  2708. emit: function() {
  2709. if (this.state == STATE_RECOGNIZED) {
  2710. this._input.tapCount = this.count;
  2711. this.manager.emit(this.options.event, this._input);
  2712. }
  2713. }
  2714. });
  2715. /**
  2716. * Simple way to create an manager with a default set of recognizers.
  2717. * @param {HTMLElement} element
  2718. * @param {Object} [options]
  2719. * @constructor
  2720. */
  2721. function Hammer(element, options) {
  2722. options = options || {};
  2723. options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
  2724. return new Manager(element, options);
  2725. }
  2726. /**
  2727. * @const {string}
  2728. */
  2729. Hammer.VERSION = "2.0.3";
  2730. /**
  2731. * default settings
  2732. * @namespace
  2733. */
  2734. Hammer.defaults = {
  2735. /**
  2736. * set if DOM events are being triggered.
  2737. * But this is slower and unused by simple implementations, so disabled by default.
  2738. * @type {Boolean}
  2739. * @default false
  2740. */
  2741. domEvents: false,
  2742. /**
  2743. * The value for the touchAction property/fallback.
  2744. * When set to `compute` it will magically set the correct value based on the added recognizers.
  2745. * @type {String}
  2746. * @default compute
  2747. */
  2748. touchAction: TOUCH_ACTION_COMPUTE,
  2749. /**
  2750. * @type {Boolean}
  2751. * @default true
  2752. */
  2753. enable: true,
  2754. /**
  2755. * EXPERIMENTAL FEATURE -- can be removed/changed
  2756. * Change the parent input target element.
  2757. * If Null, then it is being set the to main element.
  2758. * @type {Null|EventTarget}
  2759. * @default null
  2760. */
  2761. inputTarget: null,
  2762. /**
  2763. * force an input class
  2764. * @type {Null|Function}
  2765. * @default null
  2766. */
  2767. inputClass: null,
  2768. /**
  2769. * Default recognizer setup when calling `Hammer()`
  2770. * When creating a new Manager these will be skipped.
  2771. * @type {Array}
  2772. */
  2773. preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
  2774. [ RotateRecognizer, {
  2775. enable: false
  2776. } ], [ PinchRecognizer, {
  2777. enable: false
  2778. }, [ "rotate" ] ], [ SwipeRecognizer, {
  2779. direction: DIRECTION_HORIZONTAL
  2780. } ], [ PanRecognizer, {
  2781. direction: DIRECTION_HORIZONTAL
  2782. }, [ "swipe" ] ], [ TapRecognizer ], [ TapRecognizer, {
  2783. event: "doubletap",
  2784. taps: 2
  2785. }, [ "tap" ] ], [ PressRecognizer ] ],
  2786. /**
  2787. * Some CSS properties can be used to improve the working of Hammer.
  2788. * Add them to this method and they will be set when creating a new Manager.
  2789. * @namespace
  2790. */
  2791. cssProps: {
  2792. /**
  2793. * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
  2794. * @type {String}
  2795. * @default 'none'
  2796. */
  2797. userSelect: "none",
  2798. /**
  2799. * Disable the Windows Phone grippers when pressing an element.
  2800. * @type {String}
  2801. * @default 'none'
  2802. */
  2803. touchSelect: "none",
  2804. /**
  2805. * Disables the default callout shown when you touch and hold a touch target.
  2806. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  2807. * a callout containing information about the link. This property allows you to disable that callout.
  2808. * @type {String}
  2809. * @default 'none'
  2810. */
  2811. touchCallout: "none",
  2812. /**
  2813. * Specifies whether zooming is enabled. Used by IE10>
  2814. * @type {String}
  2815. * @default 'none'
  2816. */
  2817. contentZooming: "none",
  2818. /**
  2819. * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
  2820. * @type {String}
  2821. * @default 'none'
  2822. */
  2823. userDrag: "none",
  2824. /**
  2825. * Overrides the highlight color shown when the user taps a link or a JavaScript
  2826. * clickable element in iOS. This property obeys the alpha value, if specified.
  2827. * @type {String}
  2828. * @default 'rgba(0,0,0,0)'
  2829. */
  2830. tapHighlightColor: "rgba(0,0,0,0)"
  2831. }
  2832. };
  2833. var STOP = 1;
  2834. var FORCED_STOP = 2;
  2835. /**
  2836. * Manager
  2837. * @param {HTMLElement} element
  2838. * @param {Object} [options]
  2839. * @constructor
  2840. */
  2841. function Manager(element, options) {
  2842. options = options || {};
  2843. this.options = merge(options, Hammer.defaults);
  2844. this.options.inputTarget = this.options.inputTarget || element;
  2845. this.handlers = {};
  2846. this.session = {};
  2847. this.recognizers = [];
  2848. this.element = element;
  2849. this.input = createInputInstance(this);
  2850. this.touchAction = new TouchAction(this, this.options.touchAction);
  2851. toggleCssProps(this, true);
  2852. each(options.recognizers, function(item) {
  2853. var recognizer = this.add(new item[0](item[1]));
  2854. item[2] && recognizer.recognizeWith(item[2]);
  2855. item[3] && recognizer.requireFailure(item[3]);
  2856. }, this);
  2857. }
  2858. Manager.prototype = {
  2859. /**
  2860. * set options
  2861. * @param {Object} options
  2862. * @returns {Manager}
  2863. */
  2864. set: function(options) {
  2865. extend(this.options, options);
  2866. // Options that need a little more setup
  2867. if (options.touchAction) {
  2868. this.touchAction.update();
  2869. }
  2870. if (options.inputTarget) {
  2871. // Clean up existing event listeners and reinitialize
  2872. this.input.destroy();
  2873. this.input.target = options.inputTarget;
  2874. this.input.init();
  2875. }
  2876. return this;
  2877. },
  2878. /**
  2879. * stop recognizing for this session.
  2880. * This session will be discarded, when a new [input]start event is fired.
  2881. * When forced, the recognizer cycle is stopped immediately.
  2882. * @param {Boolean} [force]
  2883. */
  2884. stop: function(force) {
  2885. this.session.stopped = force ? FORCED_STOP : STOP;
  2886. },
  2887. /**
  2888. * run the recognizers!
  2889. * called by the inputHandler function on every movement of the pointers (touches)
  2890. * it walks through all the recognizers and tries to detect the gesture that is being made
  2891. * @param {Object} inputData
  2892. */
  2893. recognize: function(inputData) {
  2894. var session = this.session;
  2895. if (session.stopped) {
  2896. return;
  2897. }
  2898. // run the touch-action polyfill
  2899. this.touchAction.preventDefaults(inputData);
  2900. var recognizer;
  2901. var recognizers = this.recognizers;
  2902. // this holds the recognizer that is being recognized.
  2903. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
  2904. // if no recognizer is detecting a thing, it is set to `null`
  2905. var curRecognizer = session.curRecognizer;
  2906. // reset when the last recognizer is recognized
  2907. // or when we're in a new session
  2908. if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {
  2909. curRecognizer = session.curRecognizer = null;
  2910. }
  2911. var i = 0;
  2912. while (i < recognizers.length) {
  2913. recognizer = recognizers[i];
  2914. // find out if we are allowed try to recognize the input for this one.
  2915. // 1. allow if the session is NOT forced stopped (see the .stop() method)
  2916. // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
  2917. // that is being recognized.
  2918. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
  2919. // this can be setup with the `recognizeWith()` method on the recognizer.
  2920. if (session.stopped !== FORCED_STOP && (// 1
  2921. !curRecognizer || recognizer == curRecognizer || // 2
  2922. recognizer.canRecognizeWith(curRecognizer))) {
  2923. // 3
  2924. recognizer.recognize(inputData);
  2925. } else {
  2926. recognizer.reset();
  2927. }
  2928. // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
  2929. // current active recognizer. but only if we don't already have an active recognizer
  2930. if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
  2931. curRecognizer = session.curRecognizer = recognizer;
  2932. }
  2933. i++;
  2934. }
  2935. },
  2936. /**
  2937. * get a recognizer by its event name.
  2938. * @param {Recognizer|String} recognizer
  2939. * @returns {Recognizer|Null}
  2940. */
  2941. get: function(recognizer) {
  2942. if (recognizer instanceof Recognizer) {
  2943. return recognizer;
  2944. }
  2945. var recognizers = this.recognizers;
  2946. for (var i = 0; i < recognizers.length; i++) {
  2947. if (recognizers[i].options.event == recognizer) {
  2948. return recognizers[i];
  2949. }
  2950. }
  2951. return null;
  2952. },
  2953. /**
  2954. * add a recognizer to the manager
  2955. * existing recognizers with the same event name will be removed
  2956. * @param {Recognizer} recognizer
  2957. * @returns {Recognizer|Manager}
  2958. */
  2959. add: function(recognizer) {
  2960. if (invokeArrayArg(recognizer, "add", this)) {
  2961. return this;
  2962. }
  2963. // remove existing
  2964. var existing = this.get(recognizer.options.event);
  2965. if (existing) {
  2966. this.remove(existing);
  2967. }
  2968. this.recognizers.push(recognizer);
  2969. recognizer.manager = this;
  2970. this.touchAction.update();
  2971. return recognizer;
  2972. },
  2973. /**
  2974. * remove a recognizer by name or instance
  2975. * @param {Recognizer|String} recognizer
  2976. * @returns {Manager}
  2977. */
  2978. remove: function(recognizer) {
  2979. if (invokeArrayArg(recognizer, "remove", this)) {
  2980. return this;
  2981. }
  2982. var recognizers = this.recognizers;
  2983. recognizer = this.get(recognizer);
  2984. recognizers.splice(inArray(recognizers, recognizer), 1);
  2985. this.touchAction.update();
  2986. return this;
  2987. },
  2988. /**
  2989. * bind event
  2990. * @param {String} events
  2991. * @param {Function} handler
  2992. * @returns {EventEmitter} this
  2993. */
  2994. on: function(events, handler) {
  2995. var handlers = this.handlers;
  2996. each(splitStr(events), function(event) {
  2997. handlers[event] = handlers[event] || [];
  2998. handlers[event].push(handler);
  2999. });
  3000. return this;
  3001. },
  3002. /**
  3003. * unbind event, leave emit blank to remove all handlers
  3004. * @param {String} events
  3005. * @param {Function} [handler]
  3006. * @returns {EventEmitter} this
  3007. */
  3008. off: function(events, handler) {
  3009. var handlers = this.handlers;
  3010. each(splitStr(events), function(event) {
  3011. if (!handler) {
  3012. delete handlers[event];
  3013. } else {
  3014. handlers[event].splice(inArray(handlers[event], handler), 1);
  3015. }
  3016. });
  3017. return this;
  3018. },
  3019. /**
  3020. * emit event to the listeners
  3021. * @param {String} event
  3022. * @param {Object} data
  3023. */
  3024. emit: function(event, data) {
  3025. // we also want to trigger dom events
  3026. if (this.options.domEvents) {
  3027. triggerDomEvent(event, data);
  3028. }
  3029. // no handlers, so skip it all
  3030. var handlers = this.handlers[event] && this.handlers[event].slice();
  3031. if (!handlers || !handlers.length) {
  3032. return;
  3033. }
  3034. data.type = event;
  3035. data.preventDefault = function() {
  3036. data.srcEvent.preventDefault();
  3037. };
  3038. var i = 0;
  3039. while (i < handlers.length) {
  3040. handlers[i](data);
  3041. i++;
  3042. }
  3043. },
  3044. /**
  3045. * destroy the manager and unbinds all events
  3046. * it doesn't unbind dom events, that is the user own responsibility
  3047. */
  3048. destroy: function() {
  3049. this.element && toggleCssProps(this, false);
  3050. this.handlers = {};
  3051. this.session = {};
  3052. this.input.destroy();
  3053. this.element = null;
  3054. }
  3055. };
  3056. /**
  3057. * add/remove the css properties as defined in manager.options.cssProps
  3058. * @param {Manager} manager
  3059. * @param {Boolean} add
  3060. */
  3061. function toggleCssProps(manager, add) {
  3062. var element = manager.element;
  3063. each(manager.options.cssProps, function(value, name) {
  3064. element.style[prefixed(element.style, name)] = add ? value : "";
  3065. });
  3066. }
  3067. /**
  3068. * trigger dom event
  3069. * @param {String} event
  3070. * @param {Object} data
  3071. */
  3072. function triggerDomEvent(event, data) {
  3073. var gestureEvent = document.createEvent("Event");
  3074. gestureEvent.initEvent(event, true, true);
  3075. gestureEvent.gesture = data;
  3076. data.target.dispatchEvent(gestureEvent);
  3077. }
  3078. extend(Hammer, {
  3079. INPUT_START: INPUT_START,
  3080. INPUT_MOVE: INPUT_MOVE,
  3081. INPUT_END: INPUT_END,
  3082. INPUT_CANCEL: INPUT_CANCEL,
  3083. STATE_POSSIBLE: STATE_POSSIBLE,
  3084. STATE_BEGAN: STATE_BEGAN,
  3085. STATE_CHANGED: STATE_CHANGED,
  3086. STATE_ENDED: STATE_ENDED,
  3087. STATE_RECOGNIZED: STATE_RECOGNIZED,
  3088. STATE_CANCELLED: STATE_CANCELLED,
  3089. STATE_FAILED: STATE_FAILED,
  3090. DIRECTION_NONE: DIRECTION_NONE,
  3091. DIRECTION_LEFT: DIRECTION_LEFT,
  3092. DIRECTION_RIGHT: DIRECTION_RIGHT,
  3093. DIRECTION_UP: DIRECTION_UP,
  3094. DIRECTION_DOWN: DIRECTION_DOWN,
  3095. DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
  3096. DIRECTION_VERTICAL: DIRECTION_VERTICAL,
  3097. DIRECTION_ALL: DIRECTION_ALL,
  3098. Manager: Manager,
  3099. Input: Input,
  3100. TouchAction: TouchAction,
  3101. TouchInput: TouchInput,
  3102. MouseInput: MouseInput,
  3103. PointerEventInput: PointerEventInput,
  3104. TouchMouseInput: TouchMouseInput,
  3105. Recognizer: Recognizer,
  3106. AttrRecognizer: AttrRecognizer,
  3107. Tap: TapRecognizer,
  3108. Pan: PanRecognizer,
  3109. Swipe: SwipeRecognizer,
  3110. Pinch: PinchRecognizer,
  3111. Rotate: RotateRecognizer,
  3112. Press: PressRecognizer,
  3113. on: addEventListeners,
  3114. off: removeEventListeners,
  3115. each: each,
  3116. merge: merge,
  3117. extend: extend,
  3118. inherit: inherit,
  3119. bindFn: bindFn,
  3120. prefixed: prefixed
  3121. });
  3122. UI.hammer = Hammer;
  3123. module.exports = Hammer;
  3124. function hammerify(el, options) {
  3125. var $el = $(el);
  3126. if (!$el.data("hammer")) {
  3127. $el.data("hammer", new Hammer($el[0], options));
  3128. }
  3129. }
  3130. // extend the emit method to also trigger jQuery events
  3131. Hammer.Manager.prototype.emit = function(originalEmit) {
  3132. return function(type, data) {
  3133. originalEmit.call(this, type, data);
  3134. // console.log('trigger....%s', type);
  3135. $(this.element).trigger({
  3136. type: type,
  3137. gesture: data
  3138. });
  3139. };
  3140. }(Hammer.Manager.prototype.emit);
  3141. $.fn.hammer = function(options) {
  3142. return this.each(function() {
  3143. hammerify(this, options);
  3144. });
  3145. };
  3146. });
  3147. define("zepto.outerdemension", [], function(require, exports, module) {
  3148. var $ = window.Zepto;
  3149. // Create outerHeight and outerWidth methods
  3150. [ "width", "height" ].forEach(function(dimension) {
  3151. var offset, Dimension = dimension.replace(/./, function(m) {
  3152. return m[0].toUpperCase();
  3153. });
  3154. $.fn["outer" + Dimension] = function(margin) {
  3155. var elem = this;
  3156. if (elem) {
  3157. var size = elem[dimension]();
  3158. var sides = {
  3159. width: [ "left", "right" ],
  3160. height: [ "top", "bottom" ]
  3161. };
  3162. sides[dimension].forEach(function(side) {
  3163. if (margin) size += parseInt(elem.css("margin-" + side), 10);
  3164. });
  3165. return size;
  3166. } else {
  3167. return null;
  3168. }
  3169. };
  3170. });
  3171. });
  3172. define("zepto.extend.data", [], function(require, exports, module) {
  3173. var $ = window.Zepto;
  3174. // Zepto.js
  3175. // (c) 2010-2014 Thomas Fuchs
  3176. // Zepto.js may be freely distributed under the MIT license.
  3177. // The following code is heavily inspired by jQuery's $.fn.data()
  3178. var data = {}, dataAttr = $.fn.data, camelize = $.camelCase, exp = $.expando = "Zepto" + +new Date(), emptyArray = [];
  3179. // Get value from node:
  3180. // 1. first try key as given,
  3181. // 2. then try camelized key,
  3182. // 3. fall back to reading "data-*" attribute.
  3183. function getData(node, name) {
  3184. var id = node[exp], store = id && data[id];
  3185. if (name === undefined) return store || setData(node); else {
  3186. if (store) {
  3187. if (name in store) return store[name];
  3188. var camelName = camelize(name);
  3189. if (camelName in store) return store[camelName];
  3190. }
  3191. return dataAttr.call($(node), name);
  3192. }
  3193. }
  3194. // Store value under camelized key on node
  3195. function setData(node, name, value) {
  3196. var id = node[exp] || (node[exp] = ++$.uuid), store = data[id] || (data[id] = attributeData(node));
  3197. if (name !== undefined) store[camelize(name)] = value;
  3198. return store;
  3199. }
  3200. // Read all "data-*" attributes from a node
  3201. function attributeData(node) {
  3202. var store = {};
  3203. $.each(node.attributes || emptyArray, function(i, attr) {
  3204. if (attr.name.indexOf("data-") == 0) store[camelize(attr.name.replace("data-", ""))] = $.zepto.deserializeValue(attr.value);
  3205. });
  3206. return store;
  3207. }
  3208. $.fn.data = function(name, value) {
  3209. return value === undefined ? // set multiple values via object
  3210. $.isPlainObject(name) ? this.each(function(i, node) {
  3211. $.each(name, function(key, value) {
  3212. setData(node, key, value);
  3213. });
  3214. }) : // get value from first element
  3215. 0 in this ? getData(this[0], name) : undefined : // set value on all elements
  3216. this.each(function() {
  3217. setData(this, name, value);
  3218. });
  3219. };
  3220. $.fn.removeData = function(names) {
  3221. if (typeof names == "string") names = names.split(/\s+/);
  3222. return this.each(function() {
  3223. var id = this[exp], store = id && data[id];
  3224. if (store) $.each(names || store, function(key) {
  3225. delete store[names ? camelize(this) : key];
  3226. });
  3227. });
  3228. };
  3229. [ "remove", "empty" ].forEach(function(methodName) {
  3230. var origFn = $.fn[methodName];
  3231. $.fn[methodName] = function() {
  3232. var elements = this.find("*");
  3233. if (methodName === "remove") elements = elements.add(this);
  3234. elements.removeData();
  3235. return origFn.call(this);
  3236. };
  3237. });
  3238. });
  3239. define("zepto.extend.fx", [], function(require, exports, module) {
  3240. var $ = window.Zepto;
  3241. // Zepto.js
  3242. // (c) 2010-2014 Thomas Fuchs
  3243. // Zepto.js may be freely distributed under the MIT license.
  3244. var prefix = "", eventPrefix, endEventName, endAnimationName, vendors = {
  3245. Webkit: "webkit",
  3246. Moz: "",
  3247. O: "o"
  3248. }, document = window.document, testEl = document.createElement("div"), supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i, transform, transitionProperty, transitionDuration, transitionTiming, transitionDelay, animationName, animationDuration, animationTiming, animationDelay, cssReset = {};
  3249. function dasherize(str) {
  3250. return str.replace(/([a-z])([A-Z])/, "$1-$2").toLowerCase();
  3251. }
  3252. function normalizeEvent(name) {
  3253. return eventPrefix ? eventPrefix + name : name.toLowerCase();
  3254. }
  3255. $.each(vendors, function(vendor, event) {
  3256. if (testEl.style[vendor + "TransitionProperty"] !== undefined) {
  3257. prefix = "-" + vendor.toLowerCase() + "-";
  3258. eventPrefix = event;
  3259. return false;
  3260. }
  3261. });
  3262. transform = prefix + "transform";
  3263. cssReset[transitionProperty = prefix + "transition-property"] = cssReset[transitionDuration = prefix + "transition-duration"] = cssReset[transitionDelay = prefix + "transition-delay"] = cssReset[transitionTiming = prefix + "transition-timing-function"] = cssReset[animationName = prefix + "animation-name"] = cssReset[animationDuration = prefix + "animation-duration"] = cssReset[animationDelay = prefix + "animation-delay"] = cssReset[animationTiming = prefix + "animation-timing-function"] = "";
  3264. $.fx = {
  3265. off: eventPrefix === undefined && testEl.style.transitionProperty === undefined,
  3266. speeds: {
  3267. _default: 400,
  3268. fast: 200,
  3269. slow: 600
  3270. },
  3271. cssPrefix: prefix,
  3272. transitionEnd: normalizeEvent("TransitionEnd"),
  3273. animationEnd: normalizeEvent("AnimationEnd")
  3274. };
  3275. $.fn.animate = function(properties, duration, ease, callback, delay) {
  3276. if ($.isFunction(duration)) callback = duration, ease = undefined, duration = undefined;
  3277. if ($.isFunction(ease)) callback = ease, ease = undefined;
  3278. if ($.isPlainObject(duration)) ease = duration.easing, callback = duration.complete,
  3279. delay = duration.delay, duration = duration.duration;
  3280. if (duration) duration = (typeof duration == "number" ? duration : $.fx.speeds[duration] || $.fx.speeds._default) / 1e3;
  3281. if (delay) delay = parseFloat(delay) / 1e3;
  3282. return this.anim(properties, duration, ease, callback, delay);
  3283. };
  3284. $.fn.anim = function(properties, duration, ease, callback, delay) {
  3285. var key, cssValues = {}, cssProperties, transforms = "", that = this, wrappedCallback, endEvent = $.fx.transitionEnd, fired = false;
  3286. if (duration === undefined) duration = $.fx.speeds._default / 1e3;
  3287. if (delay === undefined) delay = 0;
  3288. if ($.fx.off) duration = 0;
  3289. if (typeof properties == "string") {
  3290. // keyframe animation
  3291. cssValues[animationName] = properties;
  3292. cssValues[animationDuration] = duration + "s";
  3293. cssValues[animationDelay] = delay + "s";
  3294. cssValues[animationTiming] = ease || "linear";
  3295. endEvent = $.fx.animationEnd;
  3296. } else {
  3297. cssProperties = [];
  3298. // CSS transitions
  3299. for (key in properties) if (supportedTransforms.test(key)) transforms += key + "(" + properties[key] + ") "; else cssValues[key] = properties[key],
  3300. cssProperties.push(dasherize(key));
  3301. if (transforms) cssValues[transform] = transforms, cssProperties.push(transform);
  3302. if (duration > 0 && typeof properties === "object") {
  3303. cssValues[transitionProperty] = cssProperties.join(", ");
  3304. cssValues[transitionDuration] = duration + "s";
  3305. cssValues[transitionDelay] = delay + "s";
  3306. cssValues[transitionTiming] = ease || "linear";
  3307. }
  3308. }
  3309. wrappedCallback = function(event) {
  3310. if (typeof event !== "undefined") {
  3311. if (event.target !== event.currentTarget) return;
  3312. // makes sure the event didn't bubble from "below"
  3313. $(event.target).unbind(endEvent, wrappedCallback);
  3314. } else $(this).unbind(endEvent, wrappedCallback);
  3315. // triggered by setTimeout
  3316. fired = true;
  3317. $(this).css(cssReset);
  3318. callback && callback.call(this);
  3319. };
  3320. if (duration > 0) {
  3321. this.bind(endEvent, wrappedCallback);
  3322. // transitionEnd is not always firing on older Android phones
  3323. // so make sure it gets fired
  3324. setTimeout(function() {
  3325. if (fired) return;
  3326. wrappedCallback.call(that);
  3327. }, duration * 1e3 + 25);
  3328. }
  3329. // trigger page reflow so new elements can animate
  3330. this.size() && this.get(0).clientLeft;
  3331. this.css(cssValues);
  3332. if (duration <= 0) setTimeout(function() {
  3333. that.each(function() {
  3334. wrappedCallback.call(this);
  3335. });
  3336. }, 0);
  3337. return this;
  3338. };
  3339. testEl = null;
  3340. });
  3341. define("zepto.extend.selector", [], function(require, exports, module) {
  3342. var $ = window.Zepto;
  3343. // Zepto.js
  3344. // (c) 2010-2014 Thomas Fuchs
  3345. // Zepto.js may be freely distributed under the MIT license.
  3346. var zepto = $.zepto, oldQsa = zepto.qsa, oldMatches = zepto.matches;
  3347. function visible(elem) {
  3348. elem = $(elem);
  3349. return !!(elem.width() || elem.height()) && elem.css("display") !== "none";
  3350. }
  3351. // Implements a subset from:
  3352. // http://api.jquery.com/category/selectors/jquery-selector-extensions/
  3353. //
  3354. // Each filter function receives the current index, all nodes in the
  3355. // considered set, and a value if there were parentheses. The value
  3356. // of `this` is the node currently being considered. The function returns the
  3357. // resulting node(s), null, or undefined.
  3358. //
  3359. // Complex selectors are not supported:
  3360. // li:has(label:contains("foo")) + li:has(label:contains("bar"))
  3361. // ul.inner:first > li
  3362. var filters = $.expr[":"] = {
  3363. visible: function() {
  3364. if (visible(this)) return this;
  3365. },
  3366. hidden: function() {
  3367. if (!visible(this)) return this;
  3368. },
  3369. selected: function() {
  3370. if (this.selected) return this;
  3371. },
  3372. checked: function() {
  3373. if (this.checked) return this;
  3374. },
  3375. parent: function() {
  3376. return this.parentNode;
  3377. },
  3378. first: function(idx) {
  3379. if (idx === 0) return this;
  3380. },
  3381. last: function(idx, nodes) {
  3382. if (idx === nodes.length - 1) return this;
  3383. },
  3384. eq: function(idx, _, value) {
  3385. if (idx === value) return this;
  3386. },
  3387. contains: function(idx, _, text) {
  3388. if ($(this).text().indexOf(text) > -1) return this;
  3389. },
  3390. has: function(idx, _, sel) {
  3391. if (zepto.qsa(this, sel).length) return this;
  3392. }
  3393. };
  3394. var filterRe = new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"), childRe = /^\s*>/, classTag = "Zepto" + +new Date();
  3395. function process(sel, fn) {
  3396. // quote the hash in `a[href^=#]` expression
  3397. sel = sel.replace(/=#\]/g, '="#"]');
  3398. var filter, arg, match = filterRe.exec(sel);
  3399. if (match && match[2] in filters) {
  3400. filter = filters[match[2]], arg = match[3];
  3401. sel = match[1];
  3402. if (arg) {
  3403. var num = Number(arg);
  3404. if (isNaN(num)) arg = arg.replace(/^["']|["']$/g, ""); else arg = num;
  3405. }
  3406. }
  3407. return fn(sel, filter, arg);
  3408. }
  3409. zepto.qsa = function(node, selector) {
  3410. return process(selector, function(sel, filter, arg) {
  3411. try {
  3412. var taggedParent;
  3413. if (!sel && filter) sel = "*"; else if (childRe.test(sel)) // support "> *" child queries by tagging the parent node with a
  3414. // unique class and prepending that classname onto the selector
  3415. taggedParent = $(node).addClass(classTag), sel = "." + classTag + " " + sel;
  3416. var nodes = oldQsa(node, sel);
  3417. } catch (e) {
  3418. console.error("error performing selector: %o", selector);
  3419. throw e;
  3420. } finally {
  3421. if (taggedParent) taggedParent.removeClass(classTag);
  3422. }
  3423. return !filter ? nodes : zepto.uniq($.map(nodes, function(n, i) {
  3424. return filter.call(n, i, nodes, arg);
  3425. }));
  3426. });
  3427. };
  3428. zepto.matches = function(node, selector) {
  3429. return process(selector, function(sel, filter, arg) {
  3430. return (!sel || oldMatches(node, sel)) && (!filter || filter.call(node, null, arg) === node);
  3431. });
  3432. };
  3433. });
  3434. define("ui.add2home", [], function(require, exports, module) {
  3435. "use strict";
  3436. var $ = window.Zepto;
  3437. /* jshint -W101, -W106 */
  3438. /* Add to Homescreen v3.0.8 ~ (c) 2014 Matteo Spinelli ~ @license: http://cubiq.org/license */
  3439. // Check if document is loaded, needed by autostart
  3440. var _DOMReady = false;
  3441. if (document.readyState === "complete") {
  3442. _DOMReady = true;
  3443. } else {
  3444. window.addEventListener("load", loaded, false);
  3445. }
  3446. function loaded() {
  3447. window.removeEventListener("load", loaded, false);
  3448. _DOMReady = true;
  3449. }
  3450. // regex used to detect if app has been added to the homescreen
  3451. var _reSmartURL = /\/ath(\/)?$/;
  3452. var _reQueryString = /([\?&]ath=[^&]*$|&ath=[^&]*(&))/;
  3453. // singleton
  3454. var _instance;
  3455. function ath(options) {
  3456. _instance = _instance || new ath.Class(options);
  3457. return _instance;
  3458. }
  3459. // message in all supported languages
  3460. ath.intl = {
  3461. en_us: {
  3462. message: "To add this web app to the home screen: tap %icon and then <strong>%action</strong>.",
  3463. action: {
  3464. ios: "Add to Home Screen",
  3465. android: "Add to homescreen",
  3466. windows: "pin to start"
  3467. }
  3468. },
  3469. zh_cn: {
  3470. message: "如要把应用程式加至主屏幕,请点击%icon, 然后<strong>%action</strong>",
  3471. action: {
  3472. ios: "加至主屏幕",
  3473. android: "加至主屏幕",
  3474. windows: "按住启动"
  3475. }
  3476. },
  3477. zh_tw: {
  3478. message: "如要把應用程式加至主屏幕, 請點擊%icon, 然後<strong>%action</strong>.",
  3479. action: {
  3480. ios: "加至主屏幕",
  3481. android: "加至主屏幕",
  3482. windows: "按住啟動"
  3483. }
  3484. }
  3485. };
  3486. // Add 2 characters language support (Android mostly)
  3487. for (var lang in ath.intl) {
  3488. ath.intl[lang.substr(0, 2)] = ath.intl[lang];
  3489. }
  3490. // default options
  3491. ath.defaults = {
  3492. appID: "org.cubiq.addtohome",
  3493. // local storage name (no need to change)
  3494. fontSize: 15,
  3495. // base font size, used to properly resize the popup based on viewport scale factor
  3496. debug: false,
  3497. // override browser checks
  3498. modal: false,
  3499. // prevent further actions until the message is closed
  3500. mandatory: false,
  3501. // you can't proceed if you don't add the app to the homescreen
  3502. autostart: true,
  3503. // show the message automatically
  3504. skipFirstVisit: false,
  3505. // show only to returning visitors (ie: skip the first time you visit)
  3506. startDelay: 1,
  3507. // display the message after that many seconds from page load
  3508. lifespan: 15,
  3509. // life of the message in seconds
  3510. displayPace: 1440,
  3511. // minutes before the message is shown again (0: display every time, default 24 hours)
  3512. maxDisplayCount: 0,
  3513. // absolute maximum number of times the message will be shown to the user (0: no limit)
  3514. icon: true,
  3515. // add touch icon to the message
  3516. message: "",
  3517. // the message can be customized
  3518. validLocation: [],
  3519. // list of pages where the message will be shown (array of regexes)
  3520. onInit: null,
  3521. // executed on instance creation
  3522. onShow: null,
  3523. // executed when the message is shown
  3524. onRemove: null,
  3525. // executed when the message is removed
  3526. onAdd: null,
  3527. // when the application is launched the first time from the homescreen (guesstimate)
  3528. onPrivate: null,
  3529. // executed if user is in private mode
  3530. detectHomescreen: false
  3531. };
  3532. // browser info and capability
  3533. var _ua = window.navigator.userAgent;
  3534. var _nav = window.navigator;
  3535. _extend(ath, {
  3536. hasToken: document.location.hash == "#ath" || _reSmartURL.test(document.location.href) || _reQueryString.test(document.location.search),
  3537. isRetina: window.devicePixelRatio && window.devicePixelRatio > 1,
  3538. isIDevice: /iphone|ipod|ipad/i.test(_ua),
  3539. isMobileChrome: _ua.indexOf("Android") > -1 && /Chrome\/[.0-9]*/.test(_ua),
  3540. isMobileIE: _ua.indexOf("Windows Phone") > -1,
  3541. language: _nav.language && _nav.language.toLowerCase().replace("-", "_") || ""
  3542. });
  3543. // falls back to en_us if language is unsupported
  3544. ath.language = ath.language && ath.language in ath.intl ? ath.language : "en_us";
  3545. ath.isMobileSafari = ath.isIDevice && _ua.indexOf("Safari") > -1 && _ua.indexOf("CriOS") < 0;
  3546. ath.OS = ath.isIDevice ? "ios" : ath.isMobileChrome ? "android" : ath.isMobileIE ? "windows" : "unsupported";
  3547. ath.OSVersion = _ua.match(/(OS|Android) (\d+[_\.]\d+)/);
  3548. ath.OSVersion = ath.OSVersion && ath.OSVersion[2] ? +ath.OSVersion[2].replace("_", ".") : 0;
  3549. ath.isStandalone = window.navigator.standalone || ath.isMobileChrome && screen.height - document.documentElement.clientHeight < 40;
  3550. // TODO: check the lame polyfill
  3551. ath.isTablet = ath.isMobileSafari && _ua.indexOf("iPad") > -1 || ath.isMobileChrome && _ua.indexOf("Mobile") < 0;
  3552. ath.isCompatible = ath.isMobileSafari && ath.OSVersion >= 6 || ath.isMobileChrome;
  3553. // TODO: add winphone
  3554. var _defaultSession = {
  3555. lastDisplayTime: 0,
  3556. // last time we displayed the message
  3557. returningVisitor: false,
  3558. // is this the first time you visit
  3559. displayCount: 0,
  3560. // number of times the message has been shown
  3561. optedout: false,
  3562. // has the user opted out
  3563. added: false
  3564. };
  3565. ath.removeSession = function(appID) {
  3566. try {
  3567. localStorage.removeItem(appID || ath.defaults.appID);
  3568. } catch (e) {}
  3569. };
  3570. ath.Class = function(options) {
  3571. // merge default options with user config
  3572. this.options = _extend({}, ath.defaults);
  3573. _extend(this.options, options);
  3574. // normalize some options
  3575. this.options.mandatory = this.options.mandatory && ("standalone" in window.navigator || this.options.debug);
  3576. this.options.modal = this.options.modal || this.options.mandatory;
  3577. if (this.options.mandatory) {
  3578. this.options.startDelay = -.5;
  3579. }
  3580. this.options.detectHomescreen = this.options.detectHomescreen === true ? "hash" : this.options.detectHomescreen;
  3581. // setup the debug environment
  3582. if (this.options.debug) {
  3583. ath.isCompatible = true;
  3584. ath.OS = typeof this.options.debug == "string" ? this.options.debug : ath.OS == "unsupported" ? "android" : ath.OS;
  3585. ath.OSVersion = ath.OS == "ios" ? "8" : "4";
  3586. }
  3587. // the element the message will be appended to
  3588. this.container = document.documentElement;
  3589. // load session
  3590. this.session = localStorage.getItem(this.options.appID);
  3591. this.session = this.session ? JSON.parse(this.session) : undefined;
  3592. // user most likely came from a direct link containing our token, we don't need it and we remove it
  3593. if (ath.hasToken && (!ath.isCompatible || !this.session)) {
  3594. ath.hasToken = false;
  3595. _removeToken();
  3596. }
  3597. // the device is not supported
  3598. if (!ath.isCompatible) {
  3599. return;
  3600. }
  3601. this.session = this.session || _defaultSession;
  3602. // check if we can use the local storage
  3603. try {
  3604. localStorage.setItem(this.options.appID, JSON.stringify(this.session));
  3605. ath.hasLocalStorage = true;
  3606. } catch (e) {
  3607. // we are most likely in private mode
  3608. ath.hasLocalStorage = false;
  3609. if (this.options.onPrivate) {
  3610. this.options.onPrivate.call(this);
  3611. }
  3612. }
  3613. // check if this is a valid location
  3614. var isValidLocation = !this.options.validLocation.length;
  3615. for (var i = this.options.validLocation.length; i--; ) {
  3616. if (this.options.validLocation[i].test(document.location.href)) {
  3617. isValidLocation = true;
  3618. break;
  3619. }
  3620. }
  3621. // check compatibility with old versions of add to homescreen. Opt-out if an old session is found
  3622. if (localStorage.getItem("addToHome")) {
  3623. this.optOut();
  3624. }
  3625. // critical errors:
  3626. // user opted out, already added to the homescreen, not a valid location
  3627. if (this.session.optedout || this.session.added || !isValidLocation) {
  3628. return;
  3629. }
  3630. // check if the app is in stand alone mode
  3631. if (ath.isStandalone) {
  3632. // execute the onAdd event if we haven't already
  3633. if (!this.session.added) {
  3634. this.session.added = true;
  3635. this.updateSession();
  3636. if (this.options.onAdd && ath.hasLocalStorage) {
  3637. // double check on localstorage to avoid multiple calls to the custom event
  3638. this.options.onAdd.call(this);
  3639. }
  3640. }
  3641. return;
  3642. }
  3643. // (try to) check if the page has been added to the homescreen
  3644. if (this.options.detectHomescreen) {
  3645. // the URL has the token, we are likely coming from the homescreen
  3646. if (ath.hasToken) {
  3647. _removeToken();
  3648. // we don't actually need the token anymore, we remove it to prevent redistribution
  3649. // this is called the first time the user opens the app from the homescreen
  3650. if (!this.session.added) {
  3651. this.session.added = true;
  3652. this.updateSession();
  3653. if (this.options.onAdd && ath.hasLocalStorage) {
  3654. // double check on localstorage to avoid multiple calls to the custom event
  3655. this.options.onAdd.call(this);
  3656. }
  3657. }
  3658. return;
  3659. }
  3660. // URL doesn't have the token, so add it
  3661. if (this.options.detectHomescreen == "hash") {
  3662. history.replaceState("", window.document.title, document.location.href + "#ath");
  3663. } else if (this.options.detectHomescreen == "smartURL") {
  3664. history.replaceState("", window.document.title, document.location.href.replace(/(\/)?$/, "/ath$1"));
  3665. } else {
  3666. history.replaceState("", window.document.title, document.location.href + (document.location.search ? "&" : "?") + "ath=");
  3667. }
  3668. }
  3669. // check if this is a returning visitor
  3670. if (!this.session.returningVisitor) {
  3671. this.session.returningVisitor = true;
  3672. this.updateSession();
  3673. // we do not show the message if this is your first visit
  3674. if (this.options.skipFirstVisit) {
  3675. return;
  3676. }
  3677. }
  3678. // we do no show the message in private mode
  3679. if (!ath.hasLocalStorage) {
  3680. return;
  3681. }
  3682. // all checks passed, ready to display
  3683. this.ready = true;
  3684. if (this.options.onInit) {
  3685. this.options.onInit.call(this);
  3686. }
  3687. if (this.options.autostart) {
  3688. this.show();
  3689. }
  3690. };
  3691. ath.Class.prototype = {
  3692. // event type to method conversion
  3693. events: {
  3694. load: "_delayedShow",
  3695. error: "_delayedShow",
  3696. orientationchange: "resize",
  3697. resize: "resize",
  3698. scroll: "resize",
  3699. click: "remove",
  3700. touchmove: "_preventDefault",
  3701. transitionend: "_removeElements",
  3702. webkitTransitionEnd: "_removeElements",
  3703. MSTransitionEnd: "_removeElements"
  3704. },
  3705. handleEvent: function(e) {
  3706. var type = this.events[e.type];
  3707. if (type) {
  3708. this[type](e);
  3709. }
  3710. },
  3711. show: function(force) {
  3712. // in autostart mode wait for the document to be ready
  3713. if (this.options.autostart && !_DOMReady) {
  3714. setTimeout(this.show.bind(this), 50);
  3715. return;
  3716. }
  3717. // message already on screen
  3718. if (this.shown) {
  3719. return;
  3720. }
  3721. var now = Date.now();
  3722. var lastDisplayTime = this.session.lastDisplayTime;
  3723. if (force !== true) {
  3724. // this is needed if autostart is disabled and you programmatically call the show() method
  3725. if (!this.ready) {
  3726. return;
  3727. }
  3728. // we obey the display pace (prevent the message to popup too often)
  3729. if (now - lastDisplayTime < this.options.displayPace * 6e4) {
  3730. return;
  3731. }
  3732. // obey the maximum number of display count
  3733. if (this.options.maxDisplayCount && this.session.displayCount >= this.options.maxDisplayCount) {
  3734. return;
  3735. }
  3736. }
  3737. this.shown = true;
  3738. // increment the display count
  3739. this.session.lastDisplayTime = now;
  3740. this.session.displayCount++;
  3741. this.updateSession();
  3742. // try to get the highest resolution application icon
  3743. if (!this.applicationIcon) {
  3744. if (ath.OS == "ios") {
  3745. this.applicationIcon = document.querySelector('head link[rel^=apple-touch-icon][sizes="152x152"],head link[rel^=apple-touch-icon][sizes="144x144"],head link[rel^=apple-touch-icon][sizes="120x120"],head link[rel^=apple-touch-icon][sizes="114x114"],head link[rel^=apple-touch-icon]');
  3746. } else {
  3747. this.applicationIcon = document.querySelector('head link[rel^="shortcut icon"][sizes="196x196"],head link[rel^=apple-touch-icon]');
  3748. }
  3749. }
  3750. var message = "";
  3751. if (this.options.message in ath.intl) {
  3752. // you can force the locale
  3753. message = ath.intl[this.options.message].message.replace("%action", ath.intl[this.options.message].action[ath.OS]);
  3754. } else if (this.options.message !== "") {
  3755. // or use a custom message
  3756. message = this.options.message;
  3757. } else {
  3758. // otherwise we use our message
  3759. message = ath.intl[ath.language].message.replace("%action", ath.intl[ath.language].action[ath.OS]);
  3760. }
  3761. // add the action icon
  3762. message = "<p>" + message.replace("%icon", '<span class="ath-action-icon">icon</span>') + "</p>";
  3763. // create the message container
  3764. this.viewport = document.createElement("div");
  3765. this.viewport.className = "ath-viewport";
  3766. if (this.options.modal) {
  3767. this.viewport.className += " ath-modal";
  3768. }
  3769. if (this.options.mandatory) {
  3770. this.viewport.className += " ath-mandatory";
  3771. }
  3772. this.viewport.style.position = "absolute";
  3773. // create the actual message element
  3774. this.element = document.createElement("div");
  3775. this.element.className = "ath-container ath-" + ath.OS + " ath-" + ath.OS + (ath.OSVersion + "").substr(0, 1) + " ath-" + (ath.isTablet ? "tablet" : "phone");
  3776. this.element.style.cssText = "-webkit-transition-property:-webkit-transform,opacity;-webkit-transition-duration:0;-webkit-transform:translate3d(0,0,0);transition-property:transform,opacity;transition-duration:0;transform:translate3d(0,0,0);-webkit-transition-timing-function:ease-out";
  3777. this.element.style.webkitTransform = "translate3d(0,-" + window.innerHeight + "px,0)";
  3778. this.element.style.webkitTransitionDuration = "0s";
  3779. // add the application icon
  3780. if (this.options.icon && this.applicationIcon) {
  3781. this.element.className += " ath-icon";
  3782. this.img = document.createElement("img");
  3783. this.img.className = "ath-application-icon";
  3784. this.img.addEventListener("load", this, false);
  3785. this.img.addEventListener("error", this, false);
  3786. this.img.src = this.applicationIcon.href;
  3787. this.element.appendChild(this.img);
  3788. }
  3789. this.element.innerHTML += message;
  3790. // we are not ready to show, place the message out of sight
  3791. this.viewport.style.left = "-99999em";
  3792. // attach all elements to the DOM
  3793. this.viewport.appendChild(this.element);
  3794. this.container.appendChild(this.viewport);
  3795. // if we don't have to wait for an image to load, show the message right away
  3796. if (!this.img) {
  3797. this._delayedShow();
  3798. }
  3799. },
  3800. _delayedShow: function(e) {
  3801. setTimeout(this._show.bind(this), this.options.startDelay * 1e3 + 500);
  3802. },
  3803. _show: function() {
  3804. var that = this;
  3805. // update the viewport size and orientation
  3806. this.updateViewport();
  3807. // reposition/resize the message on orientation change
  3808. window.addEventListener("resize", this, false);
  3809. window.addEventListener("scroll", this, false);
  3810. window.addEventListener("orientationchange", this, false);
  3811. if (this.options.modal) {
  3812. // lock any other interaction
  3813. document.addEventListener("touchmove", this, true);
  3814. }
  3815. // Enable closing after 1 second
  3816. if (!this.options.mandatory) {
  3817. setTimeout(function() {
  3818. that.element.addEventListener("click", that, true);
  3819. }, 1e3);
  3820. }
  3821. // kick the animation
  3822. setTimeout(function() {
  3823. that.element.style.webkitTransform = "translate3d(0,0,0)";
  3824. that.element.style.webkitTransitionDuration = "1.2s";
  3825. }, 0);
  3826. // set the destroy timer
  3827. if (this.options.lifespan) {
  3828. this.removeTimer = setTimeout(this.remove.bind(this), this.options.lifespan * 1e3);
  3829. }
  3830. // fire the custom onShow event
  3831. if (this.options.onShow) {
  3832. this.options.onShow.call(this);
  3833. }
  3834. },
  3835. remove: function() {
  3836. clearTimeout(this.removeTimer);
  3837. // clear up the event listeners
  3838. if (this.img) {
  3839. this.img.removeEventListener("load", this, false);
  3840. this.img.removeEventListener("error", this, false);
  3841. }
  3842. window.removeEventListener("resize", this, false);
  3843. window.removeEventListener("scroll", this, false);
  3844. window.removeEventListener("orientationchange", this, false);
  3845. document.removeEventListener("touchmove", this, true);
  3846. this.element.removeEventListener("click", this, true);
  3847. // remove the message element on transition end
  3848. this.element.addEventListener("transitionend", this, false);
  3849. this.element.addEventListener("webkitTransitionEnd", this, false);
  3850. this.element.addEventListener("MSTransitionEnd", this, false);
  3851. // start the fade out animation
  3852. this.element.style.webkitTransitionDuration = "0.3s";
  3853. this.element.style.opacity = "0";
  3854. },
  3855. _removeElements: function() {
  3856. this.element.removeEventListener("transitionend", this, false);
  3857. this.element.removeEventListener("webkitTransitionEnd", this, false);
  3858. this.element.removeEventListener("MSTransitionEnd", this, false);
  3859. // remove the message from the DOM
  3860. this.container.removeChild(this.viewport);
  3861. this.shown = false;
  3862. // fire the custom onRemove event
  3863. if (this.options.onRemove) {
  3864. this.options.onRemove.call(this);
  3865. }
  3866. },
  3867. updateViewport: function() {
  3868. if (!this.shown) {
  3869. return;
  3870. }
  3871. this.viewport.style.width = window.innerWidth + "px";
  3872. this.viewport.style.height = window.innerHeight + "px";
  3873. this.viewport.style.left = window.scrollX + "px";
  3874. this.viewport.style.top = window.scrollY + "px";
  3875. var clientWidth = document.documentElement.clientWidth;
  3876. this.orientation = clientWidth > document.documentElement.clientHeight ? "landscape" : "portrait";
  3877. var screenWidth = ath.OS == "ios" ? this.orientation == "portrait" ? screen.width : screen.height : screen.width;
  3878. this.scale = screen.width > clientWidth ? 1 : screenWidth / window.innerWidth;
  3879. this.element.style.fontSize = this.options.fontSize / this.scale + "px";
  3880. },
  3881. resize: function() {
  3882. clearTimeout(this.resizeTimer);
  3883. this.resizeTimer = setTimeout(this.updateViewport.bind(this), 100);
  3884. },
  3885. updateSession: function() {
  3886. if (ath.hasLocalStorage === false) {
  3887. return;
  3888. }
  3889. localStorage.setItem(this.options.appID, JSON.stringify(this.session));
  3890. },
  3891. clearSession: function() {
  3892. this.session = _defaultSession;
  3893. this.updateSession();
  3894. },
  3895. optOut: function() {
  3896. this.session.optedout = true;
  3897. this.updateSession();
  3898. },
  3899. optIn: function() {
  3900. this.session.optedout = false;
  3901. this.updateSession();
  3902. },
  3903. clearDisplayCount: function() {
  3904. this.session.displayCount = 0;
  3905. this.updateSession();
  3906. },
  3907. _preventDefault: function(e) {
  3908. e.preventDefault();
  3909. e.stopPropagation();
  3910. }
  3911. };
  3912. // utility
  3913. function _extend(target, obj) {
  3914. for (var i in obj) {
  3915. target[i] = obj[i];
  3916. }
  3917. return target;
  3918. }
  3919. function _removeToken() {
  3920. if (document.location.hash == "#ath") {
  3921. history.replaceState("", window.document.title, document.location.href.split("#")[0]);
  3922. }
  3923. if (_reSmartURL.test(document.location.href)) {
  3924. history.replaceState("", window.document.title, document.location.href.replace(_reSmartURL, "$1"));
  3925. }
  3926. if (_reQueryString.test(document.location.search)) {
  3927. history.replaceState("", window.document.title, document.location.href.replace(_reQueryString, "$2"));
  3928. }
  3929. }
  3930. /* jshint +W101, +W106 */
  3931. $.AMUI.addToHomescreen = ath;
  3932. module.exports = ath;
  3933. });
  3934. define("ui.collapse", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  3935. "use strict";
  3936. require("core");
  3937. var $ = window.Zepto;
  3938. var UI = $.AMUI;
  3939. /**
  3940. * @via https://github.com/twbs/bootstrap/blob/master/js/collapse.js
  3941. * @copyright (c) 2011-2014 Twitter, Inc
  3942. * @license The MIT License
  3943. */
  3944. var Collapse = function(element, options) {
  3945. this.$element = $(element);
  3946. this.options = $.extend({}, Collapse.DEFAULTS, options);
  3947. this.transitioning = null;
  3948. if (this.options.parent) {
  3949. this.$parent = $(this.options.parent);
  3950. }
  3951. if (this.options.toggle) {
  3952. this.toggle();
  3953. }
  3954. };
  3955. Collapse.DEFAULTS = {
  3956. toggle: true
  3957. };
  3958. Collapse.prototype.open = function() {
  3959. if (this.transitioning || this.$element.hasClass("am-in")) {
  3960. return;
  3961. }
  3962. var startEvent = $.Event("open:collapse:amui");
  3963. this.$element.trigger(startEvent);
  3964. if (startEvent.isDefaultPrevented()) {
  3965. return;
  3966. }
  3967. var actives = this.$parent && this.$parent.find("> .am-panel > .am-in");
  3968. if (actives && actives.length) {
  3969. var hasData = actives.data("amui.collapse");
  3970. if (hasData && hasData.transitioning) {
  3971. return;
  3972. }
  3973. Plugin.call(actives, "close");
  3974. hasData || actives.data("amui.collapse", null);
  3975. }
  3976. this.$element.removeClass("am-collapse").addClass("am-collapsing").height(0);
  3977. this.transitioning = 1;
  3978. var complete = function() {
  3979. this.$element.removeClass("am-collapsing").addClass("am-collapse am-in").height("");
  3980. this.transitioning = 0;
  3981. this.$element.trigger("opened:collapse:amui");
  3982. };
  3983. if (!UI.support.transition) {
  3984. return complete.call(this);
  3985. }
  3986. this.$element.one(UI.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd(300).height(this.$element[0].scrollHeight);
  3987. };
  3988. Collapse.prototype.close = function() {
  3989. if (this.transitioning || !this.$element.hasClass("am-in")) {
  3990. return;
  3991. }
  3992. var startEvent = $.Event("close:collapse:amui");
  3993. this.$element.trigger(startEvent);
  3994. if (startEvent.isDefaultPrevented()) {
  3995. return;
  3996. }
  3997. this.$element.height(this.$element.height());
  3998. this.$element[0].offsetHeight;
  3999. this.$element.addClass("am-collapsing").removeClass("am-collapse").removeClass("am-in");
  4000. this.transitioning = 1;
  4001. var complete = function() {
  4002. this.transitioning = 0;
  4003. this.$element.trigger("closed:collapse:amui").removeClass("am-collapsing").addClass("am-collapse");
  4004. };
  4005. if (!UI.support.transition) {
  4006. return complete.call(this);
  4007. }
  4008. this.$element.height(0).one(UI.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd(350);
  4009. };
  4010. Collapse.prototype.toggle = function() {
  4011. this[this.$element.hasClass("am-in") ? "close" : "open"]();
  4012. };
  4013. // Collapse Plugin
  4014. function Plugin(option) {
  4015. return this.each(function() {
  4016. var $this = $(this);
  4017. var data = $this.data("amui.collapse");
  4018. var options = $.extend({}, Collapse.DEFAULTS, UI.utils.options($this.attr("data-am-collapse")), typeof option == "object" && option);
  4019. if (!data && options.toggle && option == "open") {
  4020. option = !option;
  4021. }
  4022. if (!data) {
  4023. $this.data("amui.collapse", data = new Collapse(this, options));
  4024. }
  4025. if (typeof option == "string") {
  4026. data[option]();
  4027. }
  4028. });
  4029. }
  4030. $.fn.collapse = Plugin;
  4031. // Init code
  4032. $(document).on("click.collapse.amui", "[data-am-collapse]", function(e) {
  4033. var href;
  4034. var $this = $(this);
  4035. var options = UI.utils.options($this.attr("data-am-collapse"));
  4036. var target = options.target || e.preventDefault() || (href = $this.attr("href")) && href.replace(/.*(?=#[^\s]+$)/, "");
  4037. var $target = $(target);
  4038. var data = $target.data("amui.collapse");
  4039. var option = data ? "toggle" : options;
  4040. var parent = options.parent;
  4041. var $parent = parent && $(parent);
  4042. if (!data || !data.transitioning) {
  4043. if ($parent) {
  4044. // '[data-am-collapse*="{parent: \'' + parent + '"]
  4045. $parent.find("[data-am-collapse]").not($this).addClass("am-collapsed");
  4046. }
  4047. $this[$target.hasClass("am-in") ? "addClass" : "removeClass"]("am-collapsed");
  4048. }
  4049. Plugin.call($target, option);
  4050. });
  4051. UI.collapse = Collapse;
  4052. module.exports = Collapse;
  4053. });
  4054. define("ui.dimmer", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  4055. "use strict";
  4056. require("core");
  4057. var $ = window.Zepto;
  4058. var UI = $.AMUI;
  4059. var $doc = $(document);
  4060. var transition = UI.support.transition;
  4061. var Dimmer = function() {
  4062. this.id = UI.utils.generateGUID("am-dimmer");
  4063. this.$element = $(Dimmer.DEFAULTS.tpl, {
  4064. id: this.id
  4065. });
  4066. this.inited = false;
  4067. this.scrollbarWidth = 0;
  4068. this.used = $([]);
  4069. };
  4070. Dimmer.DEFAULTS = {
  4071. tpl: '<div class="am-dimmer" data-am-dimmer></div>'
  4072. };
  4073. Dimmer.prototype.init = function() {
  4074. if (!this.inited) {
  4075. $(document.body).append(this.$element);
  4076. this.inited = true;
  4077. $doc.trigger("init:dimmer:amui");
  4078. }
  4079. return this;
  4080. };
  4081. Dimmer.prototype.open = function(relatedElement) {
  4082. if (!this.inited) {
  4083. this.init();
  4084. }
  4085. var $element = this.$element;
  4086. // 用于多重调用
  4087. if (relatedElement) {
  4088. this.used = this.used.add($(relatedElement));
  4089. }
  4090. this.checkScrollbar().setScrollbar();
  4091. $element.show().trigger("open:dimmer:amui");
  4092. setTimeout(function() {
  4093. $element.addClass("am-active");
  4094. }, 0);
  4095. return this;
  4096. };
  4097. Dimmer.prototype.close = function(relatedElement, force) {
  4098. this.used = this.used.not($(relatedElement));
  4099. if (!force && this.used.length) {
  4100. return this;
  4101. }
  4102. var $element = this.$element;
  4103. $element.removeClass("am-active").trigger("close:dimmer:amui");
  4104. function complete() {
  4105. this.resetScrollbar();
  4106. $element.hide();
  4107. }
  4108. transition ? $element.one(transition.end, $.proxy(complete, this)).emulateTransitionEnd(150) : complete.call(this);
  4109. return this;
  4110. };
  4111. Dimmer.prototype.checkScrollbar = function() {
  4112. this.scrollbarWidth = UI.utils.measureScrollbar();
  4113. return this;
  4114. };
  4115. Dimmer.prototype.setScrollbar = function() {
  4116. var $body = $(document.body);
  4117. var bodyPaddingRight = parseInt($body.css("padding-right") || 0, 10);
  4118. if (this.scrollbarWidth) {
  4119. $body.css("padding-right", bodyPaddingRight + this.scrollbarWidth);
  4120. }
  4121. $body.addClass("am-dimmer-active");
  4122. return this;
  4123. };
  4124. Dimmer.prototype.resetScrollbar = function() {
  4125. $(document.body).css("padding-right", "").removeClass("am-dimmer-active");
  4126. return this;
  4127. };
  4128. var dimmer = new Dimmer();
  4129. UI.dimmer = dimmer;
  4130. module.exports = dimmer;
  4131. });
  4132. define("ui.iscroll-lite", [], function(require, exports, module) {
  4133. "use strict";
  4134. /* jshint unused: false */
  4135. /* jshint -W101, -W116, -W109 */
  4136. /*! iScroll v5.1.3
  4137. * (c) 2008-2014 Matteo Spinelli
  4138. * http://cubiq.org/license
  4139. */
  4140. (function(window, document, Math) {
  4141. var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
  4142. window.setTimeout(callback, 1e3 / 60);
  4143. };
  4144. var utils = function() {
  4145. var me = {};
  4146. var _elementStyle = document.createElement("div").style;
  4147. var _vendor = function() {
  4148. var vendors = [ "t", "webkitT", "MozT", "msT", "OT" ], transform, i = 0, l = vendors.length;
  4149. for (;i < l; i++) {
  4150. transform = vendors[i] + "ransform";
  4151. if (transform in _elementStyle) return vendors[i].substr(0, vendors[i].length - 1);
  4152. }
  4153. return false;
  4154. }();
  4155. function _prefixStyle(style) {
  4156. if (_vendor === false) return false;
  4157. if (_vendor === "") return style;
  4158. return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
  4159. }
  4160. me.getTime = Date.now || function getTime() {
  4161. return new Date().getTime();
  4162. };
  4163. me.extend = function(target, obj) {
  4164. for (var i in obj) {
  4165. target[i] = obj[i];
  4166. }
  4167. };
  4168. me.addEvent = function(el, type, fn, capture) {
  4169. el.addEventListener(type, fn, !!capture);
  4170. };
  4171. me.removeEvent = function(el, type, fn, capture) {
  4172. el.removeEventListener(type, fn, !!capture);
  4173. };
  4174. me.prefixPointerEvent = function(pointerEvent) {
  4175. return window.MSPointerEvent ? "MSPointer" + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10) : pointerEvent;
  4176. };
  4177. me.momentum = function(current, start, time, lowerMargin, wrapperSize, deceleration) {
  4178. var distance = current - start, speed = Math.abs(distance) / time, destination, duration;
  4179. deceleration = deceleration === undefined ? 6e-4 : deceleration;
  4180. destination = current + speed * speed / (2 * deceleration) * (distance < 0 ? -1 : 1);
  4181. duration = speed / deceleration;
  4182. if (destination < lowerMargin) {
  4183. destination = wrapperSize ? lowerMargin - wrapperSize / 2.5 * (speed / 8) : lowerMargin;
  4184. distance = Math.abs(destination - current);
  4185. duration = distance / speed;
  4186. } else if (destination > 0) {
  4187. destination = wrapperSize ? wrapperSize / 2.5 * (speed / 8) : 0;
  4188. distance = Math.abs(current) + destination;
  4189. duration = distance / speed;
  4190. }
  4191. return {
  4192. destination: Math.round(destination),
  4193. duration: duration
  4194. };
  4195. };
  4196. var _transform = _prefixStyle("transform");
  4197. me.extend(me, {
  4198. hasTransform: _transform !== false,
  4199. hasPerspective: _prefixStyle("perspective") in _elementStyle,
  4200. hasTouch: "ontouchstart" in window,
  4201. hasPointer: window.PointerEvent || window.MSPointerEvent,
  4202. // IE10 is prefixed
  4203. hasTransition: _prefixStyle("transition") in _elementStyle
  4204. });
  4205. // This should find all Android browsers lower than build 535.19 (both stock browser and webview)
  4206. me.isBadAndroid = /Android /.test(window.navigator.appVersion) && !/Chrome\/\d/.test(window.navigator.appVersion);
  4207. me.extend(me.style = {}, {
  4208. transform: _transform,
  4209. transitionTimingFunction: _prefixStyle("transitionTimingFunction"),
  4210. transitionDuration: _prefixStyle("transitionDuration"),
  4211. transitionDelay: _prefixStyle("transitionDelay"),
  4212. transformOrigin: _prefixStyle("transformOrigin")
  4213. });
  4214. me.hasClass = function(e, c) {
  4215. var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
  4216. return re.test(e.className);
  4217. };
  4218. me.addClass = function(e, c) {
  4219. if (me.hasClass(e, c)) {
  4220. return;
  4221. }
  4222. var newclass = e.className.split(" ");
  4223. newclass.push(c);
  4224. e.className = newclass.join(" ");
  4225. };
  4226. me.removeClass = function(e, c) {
  4227. if (!me.hasClass(e, c)) {
  4228. return;
  4229. }
  4230. var re = new RegExp("(^|\\s)" + c + "(\\s|$)", "g");
  4231. e.className = e.className.replace(re, " ");
  4232. };
  4233. me.offset = function(el) {
  4234. var left = -el.offsetLeft, top = -el.offsetTop;
  4235. // jshint -W084
  4236. while (el = el.offsetParent) {
  4237. left -= el.offsetLeft;
  4238. top -= el.offsetTop;
  4239. }
  4240. // jshint +W084
  4241. return {
  4242. left: left,
  4243. top: top
  4244. };
  4245. };
  4246. me.preventDefaultException = function(el, exceptions) {
  4247. for (var i in exceptions) {
  4248. if (exceptions[i].test(el[i])) {
  4249. return true;
  4250. }
  4251. }
  4252. return false;
  4253. };
  4254. me.extend(me.eventType = {}, {
  4255. touchstart: 1,
  4256. touchmove: 1,
  4257. touchend: 1,
  4258. mousedown: 2,
  4259. mousemove: 2,
  4260. mouseup: 2,
  4261. pointerdown: 3,
  4262. pointermove: 3,
  4263. pointerup: 3,
  4264. MSPointerDown: 3,
  4265. MSPointerMove: 3,
  4266. MSPointerUp: 3
  4267. });
  4268. me.extend(me.ease = {}, {
  4269. quadratic: {
  4270. style: "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
  4271. fn: function(k) {
  4272. return k * (2 - k);
  4273. }
  4274. },
  4275. circular: {
  4276. style: "cubic-bezier(0.1, 0.57, 0.1, 1)",
  4277. // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
  4278. fn: function(k) {
  4279. return Math.sqrt(1 - --k * k);
  4280. }
  4281. },
  4282. back: {
  4283. style: "cubic-bezier(0.175, 0.885, 0.32, 1.275)",
  4284. fn: function(k) {
  4285. var b = 4;
  4286. return (k = k - 1) * k * ((b + 1) * k + b) + 1;
  4287. }
  4288. },
  4289. bounce: {
  4290. style: "",
  4291. fn: function(k) {
  4292. if ((k /= 1) < 1 / 2.75) {
  4293. return 7.5625 * k * k;
  4294. } else if (k < 2 / 2.75) {
  4295. return 7.5625 * (k -= 1.5 / 2.75) * k + .75;
  4296. } else if (k < 2.5 / 2.75) {
  4297. return 7.5625 * (k -= 2.25 / 2.75) * k + .9375;
  4298. } else {
  4299. return 7.5625 * (k -= 2.625 / 2.75) * k + .984375;
  4300. }
  4301. }
  4302. },
  4303. elastic: {
  4304. style: "",
  4305. fn: function(k) {
  4306. var f = .22, e = .4;
  4307. if (k === 0) {
  4308. return 0;
  4309. }
  4310. if (k == 1) {
  4311. return 1;
  4312. }
  4313. return e * Math.pow(2, -10 * k) * Math.sin((k - f / 4) * 2 * Math.PI / f) + 1;
  4314. }
  4315. }
  4316. });
  4317. me.tap = function(e, eventName) {
  4318. var ev = document.createEvent("Event");
  4319. ev.initEvent(eventName, true, true);
  4320. ev.pageX = e.pageX;
  4321. ev.pageY = e.pageY;
  4322. e.target.dispatchEvent(ev);
  4323. };
  4324. me.click = function(e) {
  4325. var target = e.target, ev;
  4326. if (!/(SELECT|INPUT|TEXTAREA)/i.test(target.tagName)) {
  4327. ev = document.createEvent("MouseEvents");
  4328. ev.initMouseEvent("click", true, true, e.view, 1, target.screenX, target.screenY, target.clientX, target.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null);
  4329. ev._constructed = true;
  4330. target.dispatchEvent(ev);
  4331. }
  4332. };
  4333. return me;
  4334. }();
  4335. function IScroll(el, options) {
  4336. this.wrapper = typeof el == "string" ? document.querySelector(el) : el;
  4337. this.scroller = this.wrapper.children[0];
  4338. this.scrollerStyle = this.scroller.style;
  4339. // cache style for better performance
  4340. this.options = {
  4341. // INSERT POINT: OPTIONS
  4342. startX: 0,
  4343. startY: 0,
  4344. scrollY: true,
  4345. directionLockThreshold: 5,
  4346. momentum: true,
  4347. bounce: true,
  4348. bounceTime: 600,
  4349. bounceEasing: "",
  4350. preventDefault: true,
  4351. preventDefaultException: {
  4352. tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/
  4353. },
  4354. HWCompositing: true,
  4355. useTransition: true,
  4356. useTransform: true
  4357. };
  4358. for (var i in options) {
  4359. this.options[i] = options[i];
  4360. }
  4361. // Normalize options
  4362. this.translateZ = this.options.HWCompositing && utils.hasPerspective ? " translateZ(0)" : "";
  4363. this.options.useTransition = utils.hasTransition && this.options.useTransition;
  4364. this.options.useTransform = utils.hasTransform && this.options.useTransform;
  4365. this.options.eventPassthrough = this.options.eventPassthrough === true ? "vertical" : this.options.eventPassthrough;
  4366. this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;
  4367. // If you want eventPassthrough I have to lock one of the axes
  4368. this.options.scrollY = this.options.eventPassthrough == "vertical" ? false : this.options.scrollY;
  4369. this.options.scrollX = this.options.eventPassthrough == "horizontal" ? false : this.options.scrollX;
  4370. // With eventPassthrough we also need lockDirection mechanism
  4371. this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
  4372. this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;
  4373. this.options.bounceEasing = typeof this.options.bounceEasing == "string" ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;
  4374. this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;
  4375. if (this.options.tap === true) {
  4376. this.options.tap = "tap";
  4377. }
  4378. // INSERT POINT: NORMALIZATION
  4379. // Some defaults
  4380. this.x = 0;
  4381. this.y = 0;
  4382. this.directionX = 0;
  4383. this.directionY = 0;
  4384. this._events = {};
  4385. // INSERT POINT: DEFAULTS
  4386. this._init();
  4387. this.refresh();
  4388. this.scrollTo(this.options.startX, this.options.startY);
  4389. this.enable();
  4390. }
  4391. IScroll.prototype = {
  4392. version: "5.1.3",
  4393. _init: function() {
  4394. this._initEvents();
  4395. },
  4396. destroy: function() {
  4397. this._initEvents(true);
  4398. this._execEvent("destroy");
  4399. },
  4400. _transitionEnd: function(e) {
  4401. if (e.target != this.scroller || !this.isInTransition) {
  4402. return;
  4403. }
  4404. this._transitionTime();
  4405. if (!this.resetPosition(this.options.bounceTime)) {
  4406. this.isInTransition = false;
  4407. this._execEvent("scrollEnd");
  4408. }
  4409. },
  4410. _start: function(e) {
  4411. // React to left mouse button only
  4412. if (utils.eventType[e.type] != 1) {
  4413. if (e.button !== 0) {
  4414. return;
  4415. }
  4416. }
  4417. if (!this.enabled || this.initiated && utils.eventType[e.type] !== this.initiated) {
  4418. return;
  4419. }
  4420. if (this.options.preventDefault && !utils.isBadAndroid && !utils.preventDefaultException(e.target, this.options.preventDefaultException)) {
  4421. e.preventDefault();
  4422. }
  4423. var point = e.touches ? e.touches[0] : e, pos;
  4424. this.initiated = utils.eventType[e.type];
  4425. this.moved = false;
  4426. this.distX = 0;
  4427. this.distY = 0;
  4428. this.directionX = 0;
  4429. this.directionY = 0;
  4430. this.directionLocked = 0;
  4431. this._transitionTime();
  4432. this.startTime = utils.getTime();
  4433. if (this.options.useTransition && this.isInTransition) {
  4434. this.isInTransition = false;
  4435. pos = this.getComputedPosition();
  4436. this._translate(Math.round(pos.x), Math.round(pos.y));
  4437. this._execEvent("scrollEnd");
  4438. } else if (!this.options.useTransition && this.isAnimating) {
  4439. this.isAnimating = false;
  4440. this._execEvent("scrollEnd");
  4441. }
  4442. this.startX = this.x;
  4443. this.startY = this.y;
  4444. this.absStartX = this.x;
  4445. this.absStartY = this.y;
  4446. this.pointX = point.pageX;
  4447. this.pointY = point.pageY;
  4448. this._execEvent("beforeScrollStart");
  4449. },
  4450. _move: function(e) {
  4451. if (!this.enabled || utils.eventType[e.type] !== this.initiated) {
  4452. return;
  4453. }
  4454. if (this.options.preventDefault) {
  4455. // increases performance on Android? TODO: check!
  4456. e.preventDefault();
  4457. }
  4458. var point = e.touches ? e.touches[0] : e, deltaX = point.pageX - this.pointX, deltaY = point.pageY - this.pointY, timestamp = utils.getTime(), newX, newY, absDistX, absDistY;
  4459. this.pointX = point.pageX;
  4460. this.pointY = point.pageY;
  4461. this.distX += deltaX;
  4462. this.distY += deltaY;
  4463. absDistX = Math.abs(this.distX);
  4464. absDistY = Math.abs(this.distY);
  4465. // We need to move at least 10 pixels for the scrolling to initiate
  4466. if (timestamp - this.endTime > 300 && absDistX < 10 && absDistY < 10) {
  4467. return;
  4468. }
  4469. // If you are scrolling in one direction lock the other
  4470. if (!this.directionLocked && !this.options.freeScroll) {
  4471. if (absDistX > absDistY + this.options.directionLockThreshold) {
  4472. this.directionLocked = "h";
  4473. } else if (absDistY >= absDistX + this.options.directionLockThreshold) {
  4474. this.directionLocked = "v";
  4475. } else {
  4476. this.directionLocked = "n";
  4477. }
  4478. }
  4479. if (this.directionLocked == "h") {
  4480. if (this.options.eventPassthrough == "vertical") {
  4481. e.preventDefault();
  4482. } else if (this.options.eventPassthrough == "horizontal") {
  4483. this.initiated = false;
  4484. return;
  4485. }
  4486. deltaY = 0;
  4487. } else if (this.directionLocked == "v") {
  4488. if (this.options.eventPassthrough == "horizontal") {
  4489. e.preventDefault();
  4490. } else if (this.options.eventPassthrough == "vertical") {
  4491. this.initiated = false;
  4492. return;
  4493. }
  4494. deltaX = 0;
  4495. }
  4496. deltaX = this.hasHorizontalScroll ? deltaX : 0;
  4497. deltaY = this.hasVerticalScroll ? deltaY : 0;
  4498. newX = this.x + deltaX;
  4499. newY = this.y + deltaY;
  4500. // Slow down if outside of the boundaries
  4501. if (newX > 0 || newX < this.maxScrollX) {
  4502. newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
  4503. }
  4504. if (newY > 0 || newY < this.maxScrollY) {
  4505. newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
  4506. }
  4507. this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
  4508. this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
  4509. if (!this.moved) {
  4510. this._execEvent("scrollStart");
  4511. }
  4512. this.moved = true;
  4513. this._translate(newX, newY);
  4514. /* REPLACE START: _move */
  4515. if (timestamp - this.startTime > 300) {
  4516. this.startTime = timestamp;
  4517. this.startX = this.x;
  4518. this.startY = this.y;
  4519. }
  4520. },
  4521. _end: function(e) {
  4522. if (!this.enabled || utils.eventType[e.type] !== this.initiated) {
  4523. return;
  4524. }
  4525. if (this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException)) {
  4526. e.preventDefault();
  4527. }
  4528. var point = e.changedTouches ? e.changedTouches[0] : e, momentumX, momentumY, duration = utils.getTime() - this.startTime, newX = Math.round(this.x), newY = Math.round(this.y), distanceX = Math.abs(newX - this.startX), distanceY = Math.abs(newY - this.startY), time = 0, easing = "";
  4529. this.isInTransition = 0;
  4530. this.initiated = 0;
  4531. this.endTime = utils.getTime();
  4532. // reset if we are outside of the boundaries
  4533. if (this.resetPosition(this.options.bounceTime)) {
  4534. return;
  4535. }
  4536. this.scrollTo(newX, newY);
  4537. // ensures that the last position is rounded
  4538. // we scrolled less than 10 pixels
  4539. if (!this.moved) {
  4540. if (this.options.tap) {
  4541. utils.tap(e, this.options.tap);
  4542. }
  4543. if (this.options.click) {
  4544. utils.click(e);
  4545. }
  4546. this._execEvent("scrollCancel");
  4547. return;
  4548. }
  4549. if (this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100) {
  4550. this._execEvent("flick");
  4551. return;
  4552. }
  4553. // start momentum animation if needed
  4554. if (this.options.momentum && duration < 300) {
  4555. momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options.deceleration) : {
  4556. destination: newX,
  4557. duration: 0
  4558. };
  4559. momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options.deceleration) : {
  4560. destination: newY,
  4561. duration: 0
  4562. };
  4563. newX = momentumX.destination;
  4564. newY = momentumY.destination;
  4565. time = Math.max(momentumX.duration, momentumY.duration);
  4566. this.isInTransition = 1;
  4567. }
  4568. // INSERT POINT: _end
  4569. if (newX != this.x || newY != this.y) {
  4570. // change easing function when scroller goes out of the boundaries
  4571. if (newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY) {
  4572. easing = utils.ease.quadratic;
  4573. }
  4574. this.scrollTo(newX, newY, time, easing);
  4575. return;
  4576. }
  4577. this._execEvent("scrollEnd");
  4578. },
  4579. _resize: function() {
  4580. var that = this;
  4581. clearTimeout(this.resizeTimeout);
  4582. this.resizeTimeout = setTimeout(function() {
  4583. that.refresh();
  4584. }, this.options.resizePolling);
  4585. },
  4586. resetPosition: function(time) {
  4587. var x = this.x, y = this.y;
  4588. time = time || 0;
  4589. if (!this.hasHorizontalScroll || this.x > 0) {
  4590. x = 0;
  4591. } else if (this.x < this.maxScrollX) {
  4592. x = this.maxScrollX;
  4593. }
  4594. if (!this.hasVerticalScroll || this.y > 0) {
  4595. y = 0;
  4596. } else if (this.y < this.maxScrollY) {
  4597. y = this.maxScrollY;
  4598. }
  4599. if (x == this.x && y == this.y) {
  4600. return false;
  4601. }
  4602. this.scrollTo(x, y, time, this.options.bounceEasing);
  4603. return true;
  4604. },
  4605. disable: function() {
  4606. this.enabled = false;
  4607. },
  4608. enable: function() {
  4609. this.enabled = true;
  4610. },
  4611. refresh: function() {
  4612. var rf = this.wrapper.offsetHeight;
  4613. // Force reflow
  4614. this.wrapperWidth = this.wrapper.clientWidth;
  4615. this.wrapperHeight = this.wrapper.clientHeight;
  4616. /* REPLACE START: refresh */
  4617. this.scrollerWidth = this.scroller.offsetWidth;
  4618. this.scrollerHeight = this.scroller.offsetHeight;
  4619. this.maxScrollX = this.wrapperWidth - this.scrollerWidth;
  4620. this.maxScrollY = this.wrapperHeight - this.scrollerHeight;
  4621. /* REPLACE END: refresh */
  4622. this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0;
  4623. this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0;
  4624. if (!this.hasHorizontalScroll) {
  4625. this.maxScrollX = 0;
  4626. this.scrollerWidth = this.wrapperWidth;
  4627. }
  4628. if (!this.hasVerticalScroll) {
  4629. this.maxScrollY = 0;
  4630. this.scrollerHeight = this.wrapperHeight;
  4631. }
  4632. this.endTime = 0;
  4633. this.directionX = 0;
  4634. this.directionY = 0;
  4635. this.wrapperOffset = utils.offset(this.wrapper);
  4636. this._execEvent("refresh");
  4637. this.resetPosition();
  4638. },
  4639. on: function(type, fn) {
  4640. if (!this._events[type]) {
  4641. this._events[type] = [];
  4642. }
  4643. this._events[type].push(fn);
  4644. },
  4645. off: function(type, fn) {
  4646. if (!this._events[type]) {
  4647. return;
  4648. }
  4649. var index = this._events[type].indexOf(fn);
  4650. if (index > -1) {
  4651. this._events[type].splice(index, 1);
  4652. }
  4653. },
  4654. _execEvent: function(type) {
  4655. if (!this._events[type]) {
  4656. return;
  4657. }
  4658. var i = 0, l = this._events[type].length;
  4659. if (!l) {
  4660. return;
  4661. }
  4662. for (;i < l; i++) {
  4663. this._events[type][i].apply(this, [].slice.call(arguments, 1));
  4664. }
  4665. },
  4666. scrollBy: function(x, y, time, easing) {
  4667. x = this.x + x;
  4668. y = this.y + y;
  4669. time = time || 0;
  4670. this.scrollTo(x, y, time, easing);
  4671. },
  4672. scrollTo: function(x, y, time, easing) {
  4673. easing = easing || utils.ease.circular;
  4674. this.isInTransition = this.options.useTransition && time > 0;
  4675. if (!time || this.options.useTransition && easing.style) {
  4676. this._transitionTimingFunction(easing.style);
  4677. this._transitionTime(time);
  4678. this._translate(x, y);
  4679. } else {
  4680. this._animate(x, y, time, easing.fn);
  4681. }
  4682. },
  4683. scrollToElement: function(el, time, offsetX, offsetY, easing) {
  4684. el = el.nodeType ? el : this.scroller.querySelector(el);
  4685. if (!el) {
  4686. return;
  4687. }
  4688. var pos = utils.offset(el);
  4689. pos.left -= this.wrapperOffset.left;
  4690. pos.top -= this.wrapperOffset.top;
  4691. // if offsetX/Y are true we center the element to the screen
  4692. if (offsetX === true) {
  4693. offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2);
  4694. }
  4695. if (offsetY === true) {
  4696. offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2);
  4697. }
  4698. pos.left -= offsetX || 0;
  4699. pos.top -= offsetY || 0;
  4700. pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
  4701. pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top;
  4702. time = time === undefined || time === null || time === "auto" ? Math.max(Math.abs(this.x - pos.left), Math.abs(this.y - pos.top)) : time;
  4703. this.scrollTo(pos.left, pos.top, time, easing);
  4704. },
  4705. _transitionTime: function(time) {
  4706. time = time || 0;
  4707. this.scrollerStyle[utils.style.transitionDuration] = time + "ms";
  4708. if (!time && utils.isBadAndroid) {
  4709. this.scrollerStyle[utils.style.transitionDuration] = "0.001s";
  4710. }
  4711. },
  4712. _transitionTimingFunction: function(easing) {
  4713. this.scrollerStyle[utils.style.transitionTimingFunction] = easing;
  4714. },
  4715. _translate: function(x, y) {
  4716. if (this.options.useTransform) {
  4717. /* REPLACE START: _translate */
  4718. this.scrollerStyle[utils.style.transform] = "translate(" + x + "px," + y + "px)" + this.translateZ;
  4719. } else {
  4720. x = Math.round(x);
  4721. y = Math.round(y);
  4722. this.scrollerStyle.left = x + "px";
  4723. this.scrollerStyle.top = y + "px";
  4724. }
  4725. this.x = x;
  4726. this.y = y;
  4727. },
  4728. _initEvents: function(remove) {
  4729. var eventType = remove ? utils.removeEvent : utils.addEvent, target = this.options.bindToWrapper ? this.wrapper : window;
  4730. eventType(window, "orientationchange", this);
  4731. eventType(window, "resize", this);
  4732. if (this.options.click) {
  4733. eventType(this.wrapper, "click", this, true);
  4734. }
  4735. if (!this.options.disableMouse) {
  4736. eventType(this.wrapper, "mousedown", this);
  4737. eventType(target, "mousemove", this);
  4738. eventType(target, "mousecancel", this);
  4739. eventType(target, "mouseup", this);
  4740. }
  4741. if (utils.hasPointer && !this.options.disablePointer) {
  4742. eventType(this.wrapper, utils.prefixPointerEvent("pointerdown"), this);
  4743. eventType(target, utils.prefixPointerEvent("pointermove"), this);
  4744. eventType(target, utils.prefixPointerEvent("pointercancel"), this);
  4745. eventType(target, utils.prefixPointerEvent("pointerup"), this);
  4746. }
  4747. if (utils.hasTouch && !this.options.disableTouch) {
  4748. eventType(this.wrapper, "touchstart", this);
  4749. eventType(target, "touchmove", this);
  4750. eventType(target, "touchcancel", this);
  4751. eventType(target, "touchend", this);
  4752. }
  4753. eventType(this.scroller, "transitionend", this);
  4754. eventType(this.scroller, "webkitTransitionEnd", this);
  4755. eventType(this.scroller, "oTransitionEnd", this);
  4756. eventType(this.scroller, "MSTransitionEnd", this);
  4757. },
  4758. getComputedPosition: function() {
  4759. var matrix = window.getComputedStyle(this.scroller, null), x, y;
  4760. if (this.options.useTransform) {
  4761. matrix = matrix[utils.style.transform].split(")")[0].split(", ");
  4762. x = +(matrix[12] || matrix[4]);
  4763. y = +(matrix[13] || matrix[5]);
  4764. } else {
  4765. x = +matrix.left.replace(/[^-\d.]/g, "");
  4766. y = +matrix.top.replace(/[^-\d.]/g, "");
  4767. }
  4768. return {
  4769. x: x,
  4770. y: y
  4771. };
  4772. },
  4773. _animate: function(destX, destY, duration, easingFn) {
  4774. var that = this, startX = this.x, startY = this.y, startTime = utils.getTime(), destTime = startTime + duration;
  4775. function step() {
  4776. var now = utils.getTime(), newX, newY, easing;
  4777. if (now >= destTime) {
  4778. that.isAnimating = false;
  4779. that._translate(destX, destY);
  4780. if (!that.resetPosition(that.options.bounceTime)) {
  4781. that._execEvent("scrollEnd");
  4782. }
  4783. return;
  4784. }
  4785. now = (now - startTime) / duration;
  4786. easing = easingFn(now);
  4787. newX = (destX - startX) * easing + startX;
  4788. newY = (destY - startY) * easing + startY;
  4789. that._translate(newX, newY);
  4790. if (that.isAnimating) {
  4791. rAF(step);
  4792. }
  4793. }
  4794. this.isAnimating = true;
  4795. step();
  4796. },
  4797. handleEvent: function(e) {
  4798. switch (e.type) {
  4799. case "touchstart":
  4800. case "pointerdown":
  4801. case "MSPointerDown":
  4802. case "mousedown":
  4803. this._start(e);
  4804. break;
  4805. case "touchmove":
  4806. case "pointermove":
  4807. case "MSPointerMove":
  4808. case "mousemove":
  4809. this._move(e);
  4810. break;
  4811. case "touchend":
  4812. case "pointerup":
  4813. case "MSPointerUp":
  4814. case "mouseup":
  4815. case "touchcancel":
  4816. case "pointercancel":
  4817. case "MSPointerCancel":
  4818. case "mousecancel":
  4819. this._end(e);
  4820. break;
  4821. case "orientationchange":
  4822. case "resize":
  4823. this._resize();
  4824. break;
  4825. case "transitionend":
  4826. case "webkitTransitionEnd":
  4827. case "oTransitionEnd":
  4828. case "MSTransitionEnd":
  4829. this._transitionEnd(e);
  4830. break;
  4831. case "wheel":
  4832. case "DOMMouseScroll":
  4833. case "mousewheel":
  4834. this._wheel(e);
  4835. break;
  4836. case "keydown":
  4837. this._key(e);
  4838. break;
  4839. case "click":
  4840. if (!e._constructed) {
  4841. e.preventDefault();
  4842. e.stopPropagation();
  4843. }
  4844. break;
  4845. }
  4846. }
  4847. };
  4848. IScroll.utils = utils;
  4849. if (typeof module != "undefined" && module.exports) {
  4850. module.exports = IScroll;
  4851. } else {
  4852. window.IScroll = IScroll;
  4853. }
  4854. })(window, document, Math);
  4855. });
  4856. define("ui.modal", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.dimmer" ], function(require, exports, module) {
  4857. "use strict";
  4858. require("core");
  4859. var dimmer = require("ui.dimmer");
  4860. var $ = window.Zepto;
  4861. var UI = $.AMUI;
  4862. var $doc = $(document);
  4863. var supportTransition = UI.support.transition;
  4864. /**
  4865. * @reference https://github.com/nolimits4web/Framework7/blob/master/src/js/modals.js
  4866. * @license https://github.com/nolimits4web/Framework7/blob/master/LICENSE
  4867. */
  4868. var Modal = function(element, options) {
  4869. this.options = $.extend({}, Modal.DEFAULTS, options || {});
  4870. this.$element = $(element);
  4871. if (!this.$element.attr("id")) {
  4872. this.$element.attr("id", UI.utils.generateGUID("am-modal"));
  4873. }
  4874. this.isPopup = this.$element.hasClass("am-popup");
  4875. this.active = this.transitioning = null;
  4876. this.events();
  4877. };
  4878. Modal.DEFAULTS = {
  4879. className: {
  4880. active: "am-modal-active",
  4881. out: "am-modal-out"
  4882. },
  4883. selector: {
  4884. modal: ".am-modal",
  4885. active: ".am-modal-active"
  4886. },
  4887. cancelable: true,
  4888. onConfirm: function() {},
  4889. onCancel: function() {},
  4890. duration: 300,
  4891. // must equal the CSS transition duration
  4892. transitionEnd: supportTransition.end && supportTransition.end + ".modal.amui"
  4893. };
  4894. Modal.prototype.toggle = function(relatedElement) {
  4895. return this.active ? this.close() : this.open(relatedElement);
  4896. };
  4897. Modal.prototype.open = function(relatedElement) {
  4898. var $element = this.$element;
  4899. var options = this.options;
  4900. var isPopup = this.isPopup;
  4901. if (this.active) {
  4902. return;
  4903. }
  4904. if (!this.$element.length) {
  4905. return;
  4906. }
  4907. // 判断如果还在动画,就先触发之前的closed事件
  4908. if (this.transitioning) {
  4909. clearTimeout($element.transitionEndTimmer);
  4910. $element.transitionEndTimmer = null;
  4911. $element.trigger(options.transitionEnd).off(options.transitionEnd);
  4912. }
  4913. isPopup && this.$element.show();
  4914. this.active = true;
  4915. $element.trigger($.Event("open:modal:amui", {
  4916. relatedElement: relatedElement
  4917. }));
  4918. dimmer.open($element);
  4919. $element.show().redraw();
  4920. !isPopup && $element.css({
  4921. marginTop: -parseInt($element.height() / 2, 10) + "px"
  4922. });
  4923. $element.removeClass(options.className.out).addClass(options.className.active);
  4924. this.transitioning = 1;
  4925. var complete = function() {
  4926. $element.trigger($.Event("opened:modal:amui", {
  4927. relatedElement: relatedElement
  4928. }));
  4929. this.transitioning = 0;
  4930. };
  4931. if (!supportTransition) {
  4932. return complete.call(this);
  4933. }
  4934. $element.one(options.transitionEnd, $.proxy(complete, this)).emulateTransitionEnd(options.duration);
  4935. };
  4936. Modal.prototype.close = function(relatedElement) {
  4937. if (!this.active) {
  4938. return;
  4939. }
  4940. var $element = this.$element;
  4941. var options = this.options;
  4942. var isPopup = this.isPopup;
  4943. // 判断如果还在动画,就先触发之前的opened事件
  4944. if (this.transitioning) {
  4945. clearTimeout($element.transitionEndTimmer);
  4946. $element.transitionEndTimmer = null;
  4947. $element.trigger(options.transitionEnd).off(options.transitionEnd);
  4948. dimmer.close($element, true);
  4949. }
  4950. this.$element.trigger($.Event("close:modal:amui", {
  4951. relatedElement: relatedElement
  4952. }));
  4953. this.transitioning = 1;
  4954. var complete = function() {
  4955. $element.trigger("closed:modal:amui");
  4956. isPopup && $element.removeClass(options.className.out);
  4957. $element.hide();
  4958. this.transitioning = 0;
  4959. };
  4960. $element.removeClass(options.className.active).addClass(options.className.out);
  4961. if (!supportTransition) {
  4962. return complete.call(this);
  4963. }
  4964. $element.one(options.transitionEnd, $.proxy(complete, this)).emulateTransitionEnd(options.duration);
  4965. // 不强制关闭 Dimmer,以便多个 Modal 可以共享 Dimmer
  4966. dimmer.close($element, false);
  4967. this.active = false;
  4968. };
  4969. Modal.prototype.events = function() {
  4970. var that = this;
  4971. var $element = this.$element;
  4972. var $ipt = $element.find(".am-modal-prompt-input");
  4973. if (this.options.cancelable) {
  4974. $element.on("keyup.modal.amui", $.proxy(function(e) {
  4975. if (this.active && e.which === 27) {
  4976. this.options.onCancel();
  4977. this.close();
  4978. }
  4979. }, that));
  4980. dimmer.$element.on("click", function(e) {
  4981. that.close();
  4982. });
  4983. }
  4984. // Close button
  4985. $element.find("[data-am-modal-close]").on("click.modal.amui", function(e) {
  4986. e.preventDefault();
  4987. that.close();
  4988. });
  4989. $element.find(".am-modal-btn").on("click.modal.amui", function(e) {
  4990. that.close();
  4991. });
  4992. $element.find("[data-am-modal-confirm]").on("click.modal.amui", function() {
  4993. that.options.onConfirm($ipt.val());
  4994. });
  4995. $element.find("[data-am-modal-cancel]").on("click.modal.amui", function() {
  4996. that.options.onCancel($ipt.val());
  4997. });
  4998. };
  4999. function Plugin(option, relatedElement) {
  5000. return this.each(function() {
  5001. var $this = $(this);
  5002. var data = $this.data("am.modal");
  5003. var options = $.extend({}, Modal.DEFAULTS, typeof option == "object" && option);
  5004. if (!data) {
  5005. $this.data("am.modal", data = new Modal(this, options));
  5006. }
  5007. if (typeof option == "string") {
  5008. data[option](relatedElement);
  5009. } else {
  5010. data.toggle(option && option.relatedElement || undefined);
  5011. }
  5012. });
  5013. }
  5014. $.fn.modal = Plugin;
  5015. $doc.on("click", "[data-am-modal]", function() {
  5016. var $this = $(this);
  5017. var options = UI.utils.parseOptions($this.attr("data-am-modal"));
  5018. var $target = $(options.target || this.href && this.href.replace(/.*(?=#[^\s]+$)/, ""));
  5019. var option = $target.data("am.modal") ? "toggle" : options;
  5020. Plugin.call($target, option, this);
  5021. });
  5022. UI.modal = Modal;
  5023. module.exports = Modal;
  5024. });
  5025. define("ui.offcanvas", [ "zepto.outerdemension", "zepto.extend.data", "core", "zepto.extend.fx", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5026. "use strict";
  5027. require("zepto.outerdemension");
  5028. require("zepto.extend.data");
  5029. require("core");
  5030. var $ = window.Zepto;
  5031. var UI = $.AMUI;
  5032. var $win = $(window);
  5033. var $doc = $(document);
  5034. var scrollPos;
  5035. /**
  5036. * @via https://github.com/uikit/uikit/blob/master/src/js/offcanvas.js
  5037. * @license https://github.com/uikit/uikit/blob/master/LICENSE.md
  5038. */
  5039. var OffCanvas = function(element, options) {
  5040. this.$element = $(element);
  5041. this.options = options;
  5042. this.active = null;
  5043. this.events();
  5044. };
  5045. OffCanvas.DEFAULTS = {
  5046. duration: 300,
  5047. effect: "overlay"
  5048. };
  5049. OffCanvas.prototype.open = function(relatedElement) {
  5050. var $element = this.$element;
  5051. if (!$element.length || $element.hasClass("am-active")) {
  5052. return;
  5053. }
  5054. var effect = this.options.effect;
  5055. var $html = $("html");
  5056. var $body = $("body");
  5057. var $bar = $element.find(".am-offcanvas-bar").first();
  5058. var dir = $bar.hasClass("am-offcanvas-bar-flip") ? -1 : 1;
  5059. $bar.addClass("am-offcanvas-bar-" + effect);
  5060. scrollPos = {
  5061. x: window.scrollX,
  5062. y: window.scrollY
  5063. };
  5064. $element.addClass("am-active");
  5065. $body.css({
  5066. width: window.innerWidth,
  5067. height: $win.height()
  5068. }).addClass("am-offcanvas-page");
  5069. if (effect !== "overlay") {
  5070. $body.css({
  5071. "margin-left": $bar.outerWidth() * dir
  5072. }).width();
  5073. }
  5074. $html.css("margin-top", scrollPos.y * -1);
  5075. setTimeout(function() {
  5076. $bar.addClass("am-offcanvas-bar-active").width();
  5077. }, 0);
  5078. $doc.trigger("open:offcanvas:amui");
  5079. this.active = 1;
  5080. $element.off(".offcanvas.amui").on("click.offcanvas.amui swipe.offcanvas.amui", $.proxy(function(e) {
  5081. var $target = $(e.target);
  5082. if (!e.type.match(/swipe/)) {
  5083. if ($target.hasClass("am-offcanvas-bar")) {
  5084. return;
  5085. }
  5086. if ($target.parents(".am-offcanvas-bar").first().length) {
  5087. return;
  5088. }
  5089. }
  5090. // https://developer.mozilla.org/zh-CN/docs/DOM/event.stopImmediatePropagation
  5091. e.stopImmediatePropagation();
  5092. this.close();
  5093. }, this));
  5094. $html.on("keydown.offcanvas.amui", $.proxy(function(e) {
  5095. if (e.keyCode === 27) {
  5096. // ESC
  5097. this.close();
  5098. }
  5099. }, this));
  5100. };
  5101. OffCanvas.prototype.close = function(relatedElement) {
  5102. var me = this;
  5103. var $html = $("html");
  5104. var $body = $("body");
  5105. var $element = this.$element;
  5106. var $bar = $element.find(".am-offcanvas-bar").first();
  5107. if (!$element.length || !$element.hasClass("am-active")) {
  5108. return;
  5109. }
  5110. $doc.trigger("close:offcanvas:amui");
  5111. function complete() {
  5112. $body.removeClass("am-offcanvas-page").css({
  5113. width: "",
  5114. height: "",
  5115. "margin-left": "",
  5116. "margin-right": ""
  5117. });
  5118. $element.removeClass("am-active");
  5119. $bar.removeClass("am-offcanvas-bar-active");
  5120. $html.css("margin-top", "");
  5121. window.scrollTo(scrollPos.x, scrollPos.y);
  5122. $doc.trigger("closed:offcanvas:amui");
  5123. me.active = 0;
  5124. }
  5125. if (UI.support.transition) {
  5126. setTimeout(function() {
  5127. $bar.removeClass("am-offcanvas-bar-active");
  5128. }, 0);
  5129. $body.css("margin-left", "").one(UI.support.transition.end, function() {
  5130. complete();
  5131. }).emulateTransitionEnd(this.options.duration);
  5132. } else {
  5133. complete();
  5134. }
  5135. $element.off(".offcanvas.amui");
  5136. $html.off(".offcanvas.amui");
  5137. };
  5138. OffCanvas.prototype.events = function() {
  5139. $doc.on("click.offcanvas.amui", '[data-am-dismiss="offcanvas"]', $.proxy(function(e) {
  5140. e.preventDefault();
  5141. this.close();
  5142. }, this));
  5143. $win.on("resize.offcanvas.amui orientationchange.offcanvas.amui", $.proxy(function(e) {
  5144. this.active && this.close();
  5145. }, this));
  5146. return this;
  5147. };
  5148. function Plugin(option, relatedElement) {
  5149. return this.each(function() {
  5150. var $this = $(this);
  5151. var data = $this.data("am.offcanvas");
  5152. var options = $.extend({}, OffCanvas.DEFAULTS, typeof option == "object" && option);
  5153. if (!data) {
  5154. $this.data("am.offcanvas", data = new OffCanvas(this, options));
  5155. data.open(relatedElement);
  5156. }
  5157. if (typeof option == "string") {
  5158. data[option] && data[option](relatedElement);
  5159. }
  5160. });
  5161. }
  5162. $.fn.offCanvas = Plugin;
  5163. // Init code
  5164. $doc.on("click.offcanvas.amui", "[data-am-offcanvas]", function(e) {
  5165. e.preventDefault();
  5166. var $this = $(this);
  5167. var options = UI.utils.parseOptions($this.data("amOffcanvas"));
  5168. var $target = $(options.target || this.href && this.href.replace(/.*(?=#[^\s]+$)/, ""));
  5169. var option = $target.data("am.offcanvas") ? "open" : options;
  5170. Plugin.call($target, option, this);
  5171. });
  5172. UI.offcanvas = OffCanvas;
  5173. module.exports = OffCanvas;
  5174. });
  5175. define("ui.pureview", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "zepto.pinchzoom", "util.hammer" ], function(require, exports, module) {
  5176. "use strict";
  5177. require("core");
  5178. var PinchZoom = require("zepto.pinchzoom");
  5179. var Hammer = require("util.hammer");
  5180. var $ = window.Zepto;
  5181. var UI = $.AMUI;
  5182. var animation = UI.support.animation;
  5183. var transition = UI.support.transition;
  5184. /**
  5185. * PureView
  5186. * @desc Image browser for Mobile
  5187. * @param element
  5188. * @param options
  5189. * @constructor
  5190. */
  5191. var PureView = function(element, options) {
  5192. this.$element = $(element);
  5193. this.$body = $(document.body);
  5194. this.options = $.extend({}, PureView.DEFAULTS, options);
  5195. this.$pureview = $(this.options.tpl, {
  5196. id: UI.utils.generateGUID("am-pureview")
  5197. });
  5198. this.$slides = null;
  5199. this.transitioning = null;
  5200. this.scrollbarWidth = 0;
  5201. this.init();
  5202. };
  5203. PureView.DEFAULTS = {
  5204. tpl: '<div class="am-pureview am-pureview-bar-active">' + '<ul class="am-pureview-slider"></ul>' + '<ul class="am-pureview-direction">' + '<li class="am-pureview-prev"><a href=""></a></li>' + '<li class="am-pureview-next"><a href=""></a></li></ul>' + '<ol class="am-pureview-nav"></ol>' + '<div class="am-pureview-bar am-active">' + '<span class="am-pureview-title"></span>' + '<span class="am-pureview-current"></span> / ' + '<span class="am-pureview-total"></span></div>' + '<div class="am-pureview-actions am-active">' + '<a href="javascript: void(0)" class="am-icon-chevron-left" ' + 'data-am-close="pureview"></a></div>' + "</div>",
  5205. className: {
  5206. prevSlide: "am-pureview-slide-prev",
  5207. nextSlide: "am-pureview-slide-next",
  5208. onlyOne: "am-pureview-only",
  5209. active: "am-active",
  5210. barActive: "am-pureview-bar-active",
  5211. activeBody: "am-pureview-active"
  5212. },
  5213. selector: {
  5214. slider: ".am-pureview-slider",
  5215. close: '[data-am-close="pureview"]',
  5216. total: ".am-pureview-total",
  5217. current: ".am-pureview-current",
  5218. title: ".am-pureview-title",
  5219. actions: ".am-pureview-actions",
  5220. bar: ".am-pureview-bar",
  5221. pinchZoom: ".am-pinch-zoom",
  5222. nav: ".am-pureview-nav"
  5223. },
  5224. shareBtn: false,
  5225. // 从何处获取图片,img 可以使用 data-rel 指定大图
  5226. target: "img",
  5227. // 微信 Webview 中调用微信的图片浏览器
  5228. // 实现图片保存、分享好友、收藏图片等功能
  5229. weChatImagePreview: true
  5230. };
  5231. PureView.prototype.init = function() {
  5232. var me = this;
  5233. var options = this.options;
  5234. var $element = this.$element;
  5235. var $pureview = this.$pureview;
  5236. var $slider = $pureview.find(options.selector.slider);
  5237. var $nav = $pureview.find(options.selector.nav);
  5238. var $slides = $([]);
  5239. var $navItems = $([]);
  5240. var $images = $element.find(options.target);
  5241. var total = $images.length;
  5242. var imgUrls = [];
  5243. if (!total) {
  5244. return;
  5245. }
  5246. if (total === 1) {
  5247. $pureview.addClass(options.className.onlyOne);
  5248. }
  5249. $images.each(function(i, item) {
  5250. var src;
  5251. var title;
  5252. if (options.target == "a") {
  5253. src = item.href;
  5254. // to absolute path
  5255. title = item.title || "";
  5256. } else {
  5257. src = $(item).data("rel") || item.src;
  5258. // <img src='' data-rel='' />
  5259. title = $(item).attr("alt") || "";
  5260. }
  5261. // hide bar: wechat_webview_type=1
  5262. // http://tmt.io/wechat/ not working?
  5263. imgUrls.push(src);
  5264. $slides = $slides.add($('<li><div class="am-pinch-zoom">' + '<img src="' + src + '" alt="' + title + '"/></div></li>'));
  5265. $navItems = $navItems.add($("<li>" + (i + 1) + "</li>"));
  5266. });
  5267. $slider.append($slides);
  5268. $nav.append($navItems);
  5269. $("body").append($pureview);
  5270. $pureview.find(options.selector.total).text(total);
  5271. this.$title = $pureview.find(options.selector.title);
  5272. this.$current = $pureview.find(options.selector.current);
  5273. this.$bar = $pureview.find(options.selector.bar);
  5274. this.$actions = $pureview.find(options.selector.actions);
  5275. this.$navItems = $nav.find("li");
  5276. this.$slides = $slider.find("li");
  5277. if (options.shareBtn) {
  5278. this.$actions.append('<a href="javascript: void(0)" ' + 'class="am-icon-share-square-o" data-am-toggle="share"></a>');
  5279. }
  5280. $slider.find(options.selector.pinchZoom).each(function() {
  5281. $(this).data("amui.pinchzoom", new PinchZoom($(this), {}));
  5282. $(this).on("pz_doubletap", function(e) {});
  5283. });
  5284. $images.on("click.pureview.amui", function(e) {
  5285. e.preventDefault();
  5286. var clicked = $images.index(this);
  5287. // Invoke WeChat ImagePreview in WeChat
  5288. // TODO: detect WeChat before init
  5289. if (options.weChatImagePreview && window.WeixinJSBridge) {
  5290. window.WeixinJSBridge.invoke("imagePreview", {
  5291. current: imgUrls[clicked],
  5292. urls: imgUrls
  5293. });
  5294. } else {
  5295. me.open(clicked);
  5296. }
  5297. });
  5298. $pureview.find(".am-pureview-direction a").on("click.direction.pureview.amui", function(e) {
  5299. e.preventDefault();
  5300. var $clicked = $(e.target).parent("li");
  5301. if ($clicked.is(".am-pureview-prev")) {
  5302. me.prevSlide();
  5303. } else {
  5304. me.nextSlide();
  5305. }
  5306. });
  5307. // Nav Contorl
  5308. this.$navItems.on("click.nav.pureview.amui", function() {
  5309. var index = me.$navItems.index($(this));
  5310. me.activate(me.$slides.eq(index));
  5311. });
  5312. // Close Icon
  5313. $pureview.find(options.selector.close).on("click.close.pureview.amui", function(e) {
  5314. e.preventDefault();
  5315. me.close();
  5316. });
  5317. $slider.hammer().on("press.pureview.amui", function(e) {
  5318. e.preventDefault();
  5319. me.toggleToolBar();
  5320. }).on("swipeleft.pureview.amui", function(e) {
  5321. e.preventDefault();
  5322. me.nextSlide();
  5323. }).on("swiperight.pureview.amui", function(e) {
  5324. e.preventDefault();
  5325. me.prevSlide();
  5326. });
  5327. $slider.data("hammer").get("swipe").set({
  5328. direction: Hammer.DIRECTION_HORIZONTAL,
  5329. velocity: .35
  5330. });
  5331. $(document).on("keydown.pureview.amui", $.proxy(function(e) {
  5332. var keyCode = e.keyCode;
  5333. if (keyCode == 37) {
  5334. this.prevSlide();
  5335. } else if (keyCode == 39) {
  5336. this.nextSlide();
  5337. } else if (keyCode == 27) {
  5338. this.close();
  5339. }
  5340. }, this));
  5341. };
  5342. PureView.prototype.activate = function($slide) {
  5343. var options = this.options;
  5344. var $slides = this.$slides;
  5345. var activeIndex = $slides.index($slide);
  5346. var alt = $slide.find("img").attr("alt") || "";
  5347. var active = options.className.active;
  5348. UI.utils.imageLoader($slide.find("img"), function(image) {
  5349. $(image).addClass("am-img-loaded");
  5350. });
  5351. if ($slides.find("." + active).is($slide)) {
  5352. return;
  5353. }
  5354. if (this.transitioning) {
  5355. return;
  5356. }
  5357. this.transitioning = 1;
  5358. this.$title.text(alt);
  5359. this.$current.text(activeIndex + 1);
  5360. $slides.removeClass();
  5361. $slide.addClass(active);
  5362. $slides.eq(activeIndex - 1).addClass(options.className.prevSlide);
  5363. $slides.eq(activeIndex + 1).addClass(options.className.nextSlide);
  5364. this.$navItems.removeClass().eq(activeIndex).addClass(options.className.active);
  5365. if (transition) {
  5366. $slide.one(transition.end, $.proxy(function() {
  5367. this.transitioning = 0;
  5368. }, this)).emulateTransitionEnd(300);
  5369. } else {
  5370. this.transitioning = 0;
  5371. }
  5372. };
  5373. PureView.prototype.nextSlide = function() {
  5374. if (this.$slides.length === 1) {
  5375. return;
  5376. }
  5377. var $slides = this.$slides;
  5378. var $active = $slides.filter(".am-active");
  5379. var activeIndex = $slides.index($active);
  5380. var rightSpring = "am-animation-right-spring";
  5381. if (activeIndex + 1 >= $slides.length) {
  5382. // last one
  5383. animation && $active.addClass(rightSpring).on(animation.end, function() {
  5384. $active.removeClass(rightSpring);
  5385. });
  5386. } else {
  5387. this.activate($slides.eq(activeIndex + 1));
  5388. }
  5389. };
  5390. PureView.prototype.prevSlide = function() {
  5391. if (this.$slides.length === 1) {
  5392. return;
  5393. }
  5394. var $slides = this.$slides;
  5395. var $active = $slides.filter(".am-active");
  5396. var activeIndex = this.$slides.index($active);
  5397. var leftSpring = "am-animation-left-spring";
  5398. if (activeIndex === 0) {
  5399. // first one
  5400. animation && $active.addClass(leftSpring).on(animation.end, function() {
  5401. $active.removeClass(leftSpring);
  5402. });
  5403. } else {
  5404. this.activate($slides.eq(activeIndex - 1));
  5405. }
  5406. };
  5407. PureView.prototype.toggleToolBar = function() {
  5408. this.$pureview.toggleClass(this.options.className.barActive);
  5409. };
  5410. PureView.prototype.open = function(index) {
  5411. var active = index || 0;
  5412. this.checkScrollbar();
  5413. this.setScrollbar();
  5414. this.activate(this.$slides.eq(active));
  5415. this.$pureview.addClass(this.options.className.active);
  5416. this.$body.addClass(this.options.className.activeBody);
  5417. };
  5418. PureView.prototype.close = function() {
  5419. var options = this.options;
  5420. this.$pureview.removeClass(options.className.active);
  5421. this.$slides.removeClass();
  5422. function resetBody() {
  5423. this.$body.removeClass(options.className.activeBody);
  5424. this.resetScrollbar();
  5425. }
  5426. if (transition) {
  5427. this.$pureview.one(transition.end, $.proxy(resetBody, this));
  5428. } else {
  5429. resetBody.call(this);
  5430. }
  5431. };
  5432. PureView.prototype.checkScrollbar = function() {
  5433. this.scrollbarWidth = UI.utils.measureScrollbar();
  5434. };
  5435. PureView.prototype.setScrollbar = function() {
  5436. var bodyPaddingRight = parseInt(this.$body.css("padding-right") || 0, 10);
  5437. if (this.scrollbarWidth) {
  5438. this.$body.css("padding-right", bodyPaddingRight + this.scrollbarWidth);
  5439. }
  5440. };
  5441. PureView.prototype.resetScrollbar = function() {
  5442. this.$body.css("padding-right", "");
  5443. };
  5444. function Plugin(option) {
  5445. return this.each(function() {
  5446. var $this = $(this);
  5447. var data = $this.data("am.pureview");
  5448. var options = $.extend({}, UI.utils.parseOptions($this.data("amPureview")), typeof option == "object" && option);
  5449. if (!data) {
  5450. $this.data("am.pureview", data = new PureView(this, options));
  5451. }
  5452. if (typeof option == "string") {
  5453. data[option]();
  5454. }
  5455. });
  5456. }
  5457. $.fn.pureview = Plugin;
  5458. // Init code
  5459. $(function() {
  5460. $("[data-am-pureview]").pureview();
  5461. });
  5462. UI.pureview = PureView;
  5463. module.exports = PureView;
  5464. });
  5465. define("ui.share", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.modal", "ui.dimmer", "util.qrcode" ], function(require, exports, module) {
  5466. "use strict";
  5467. require("core");
  5468. require("ui.modal");
  5469. var QRCode = require("util.qrcode");
  5470. var $ = window.Zepto;
  5471. var UI = $.AMUI;
  5472. var doc = document;
  5473. var $doc = $(doc);
  5474. var Share = function(options) {
  5475. this.options = $.extend({}, Share.DEFAULTS, options || {});
  5476. this.$element = null;
  5477. this.$wechatQr = null;
  5478. this.pics = null;
  5479. this.inited = false;
  5480. this.active = false;
  5481. };
  5482. Share.DEFAULTS = {
  5483. sns: [ "weibo", "qq", "qzone", "tqq", "wechat", "renren" ],
  5484. title: "分享到",
  5485. cancel: "取消",
  5486. closeOnShare: true,
  5487. id: UI.utils.generateGUID("am-share"),
  5488. desc: "Hi,孤夜观天象,发现一个不错的西西,分享一下下 ;-)",
  5489. via: "Amaze UI",
  5490. tpl: '<div class="am-share am-modal-actions" id="<%= id %>">' + '<h3 class="am-share-title"><%= title %></h3>' + '<ul class="am-share-sns sm-block-grid-3">' + "<% for(var i = 0; i < sns.length; i++) {%>" + "<li>" + '<a href="<%= sns[i].shareUrl %>" ' + 'data-am-share-to="<%= sns[i].id %>" >' + '<i class="am-icon-<%= sns[i].icon %>"></i>' + "<span><%= sns[i].title %></span>" + "</a></li>" + "<% } %></ul>" + '<div class="am-share-footer">' + '<button class="am-btn am-btn-default am-btn-block" ' + "data-am-share-close><%= cancel %></button></div>" + "</div>"
  5491. };
  5492. Share.SNS = {
  5493. weibo: {
  5494. title: "新浪微博",
  5495. url: "http://service.weibo.com/share/share.php",
  5496. width: 620,
  5497. height: 450,
  5498. icon: "weibo"
  5499. },
  5500. // url 链接地址
  5501. // title:”, 分享的文字内容(可选,默认为所在页面的title)
  5502. // appkey:”, 您申请的应用appkey,显示分享来源(可选)
  5503. // pic:”, 分享图片的路径(可选)
  5504. // ralateUid:”, 关联用户的UID,分享微博会@该用户(可选)
  5505. // NOTE: 会自动抓取图片,不用指定 pic
  5506. qq: {
  5507. title: "QQ 好友",
  5508. url: "http://connect.qq.com/widget/shareqq/index.html",
  5509. icon: "qq"
  5510. },
  5511. // url:,
  5512. // title:'', 分享标题(可选)
  5513. // pics:'', 分享图片的路径(可选)
  5514. // summary:'', 分享摘要(可选)
  5515. // site:'', 分享来源 如:腾讯网(可选)
  5516. // desc: '' 发送给用户的消息
  5517. // NOTE: 经过测试,最终发给用户的只有 url 和 desc
  5518. qzone: {
  5519. title: "QQ 空间",
  5520. url: "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey",
  5521. icon: "star"
  5522. },
  5523. // http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=xxx&title=xxx&desc=&summary=&site=
  5524. // url:,
  5525. // title:'', 分享标题(可选)
  5526. // desc:'', 默认分享理由(可选)
  5527. // summary:'', 分享摘要(可选)
  5528. // site:'', 分享来源 如:腾讯网(可选)
  5529. // pics:'', 分享图片的路径(可选),不会自动抓取,多个图片用|分隔
  5530. tqq: {
  5531. title: "腾讯微博",
  5532. url: "http://v.t.qq.com/share/share.php",
  5533. icon: "tencent-weibo"
  5534. },
  5535. // url=xx&title=&appkey=801cf76d3cfc44ada52ec13114e84a96
  5536. // url
  5537. // title
  5538. // pic 多个图片用 | 分隔
  5539. // appkey
  5540. // NOTE: 不会自动抓取图片
  5541. wechat: {
  5542. title: "微信",
  5543. url: "[qrcode]",
  5544. icon: "wechat"
  5545. },
  5546. // 生成一个二维码 供用户扫描
  5547. // 相关接口 https://github.com/zxlie/WeixinApi
  5548. renren: {
  5549. title: "人人网",
  5550. url: "http://widget.renren.com/dialog/share",
  5551. icon: "renren"
  5552. },
  5553. // http://widget.renren.com/dialog/share?resourceUrl=www&srcUrl=www&title=ww&description=xxx
  5554. // 550 * 400
  5555. // resourceUrl : '', // 分享的资源Url
  5556. // srcUrl : '', // 分享的资源来源Url,
  5557. // // 默认为header中的Referer,如果分享失败可以调整此值为resourceUrl试试
  5558. // pic : '', // 分享的主题图片,会自动抓取
  5559. // title : '', // 分享的标题
  5560. // description : '' // 分享的详细描述
  5561. // NOTE: 经过测试,直接使用 url 参数即可
  5562. douban: {
  5563. title: "豆瓣",
  5564. url: "http://www.douban.com/recommend/",
  5565. icon: "share-alt"
  5566. },
  5567. // http://www.douban.com/service/sharebutton
  5568. // 450 * 330
  5569. // http://www.douban.com/share/service?bm=1&image=&href=xxx&updated=&name=
  5570. // href 链接
  5571. // name 标题
  5572. /* void (function() {
  5573. var d = document, e = encodeURIComponent,
  5574. s1 = window.getSelection, s2 = d.getSelection,
  5575. s3 = d.selection, s = s1 ? s1()
  5576. : s2 ? s2() : s3 ? s3.createRange().text : '',
  5577. r = 'http://www.douban.com/recommend/?url=&title=&sel=&v=1&r=1'
  5578. })();
  5579. */
  5580. // tsohu: '',
  5581. // http://t.sohu.com/third/post.jsp?url=&title=&content=utf-8&pic=
  5582. // print: '',
  5583. mail: {
  5584. title: "邮件分享",
  5585. url: "mailto:",
  5586. icon: "envelope-o"
  5587. },
  5588. sms: {
  5589. title: "短信分享",
  5590. url: "sms:",
  5591. icon: "comment"
  5592. }
  5593. };
  5594. Share.prototype.render = function() {
  5595. var options = this.options;
  5596. var snsData = [];
  5597. var title = encodeURIComponent(doc.title);
  5598. var link = encodeURIComponent(doc.location);
  5599. var msgBody = "?body=" + title + link;
  5600. options.sns.forEach(function(item, i) {
  5601. if (Share.SNS[item]) {
  5602. var tmp = Share.SNS[item];
  5603. var shareUrl;
  5604. tmp.id = item;
  5605. if (item === "mail") {
  5606. shareUrl = msgBody + "&subject=" + options.desc;
  5607. } else if (item === "sms") {
  5608. shareUrl = msgBody;
  5609. } else {
  5610. shareUrl = "?url=" + link + "&title=" + title;
  5611. }
  5612. tmp.shareUrl = tmp.url + shareUrl;
  5613. snsData.push(tmp);
  5614. }
  5615. });
  5616. return UI.template(options.tpl, $.extend({}, options, {
  5617. sns: snsData
  5618. }));
  5619. };
  5620. Share.prototype.init = function() {
  5621. if (this.inited) {
  5622. return;
  5623. }
  5624. var me = this;
  5625. var shareItem = "[data-am-share-to]";
  5626. $doc.ready($.proxy(function() {
  5627. $("body").append(this.render());
  5628. // append share DOM to body
  5629. this.$element = $("#" + this.options.id);
  5630. this.$element.find("[data-am-share-close]").on("click.share.amui", function() {
  5631. me.close();
  5632. });
  5633. }, this));
  5634. $doc.on("click.share.amui", shareItem, $.proxy(function(e) {
  5635. var $clicked = $(e.target);
  5636. var $target = $clicked.is(shareItem) && $clicked || $clicked.parent(shareItem);
  5637. var sns = $target.attr("data-am-share-to");
  5638. if (!(sns === "mail" || sns === "sms")) {
  5639. e.preventDefault();
  5640. this.shareTo(sns, this.setData(sns));
  5641. }
  5642. this.close();
  5643. }, this));
  5644. this.inited = true;
  5645. };
  5646. Share.prototype.open = function() {
  5647. !this.inited && this.init();
  5648. this.$element && this.$element.modal("open");
  5649. this.$element.trigger("open:share:amui");
  5650. this.active = true;
  5651. };
  5652. Share.prototype.close = function() {
  5653. this.$element && this.$element.modal("close");
  5654. this.$element.trigger("close:share:amui");
  5655. this.active = false;
  5656. };
  5657. Share.prototype.toggle = function() {
  5658. this.active ? this.close() : this.open();
  5659. };
  5660. Share.prototype.setData = function(sns) {
  5661. if (!sns) {
  5662. return;
  5663. }
  5664. var shareData = {
  5665. url: doc.location,
  5666. title: doc.title
  5667. };
  5668. var desc = this.options.desc;
  5669. var imgSrc = this.pics || [];
  5670. var qqReg = /^(qzone|qq|tqq)$/;
  5671. if (qqReg.test(sns) && !imgSrc.length) {
  5672. var allImages = doc.images;
  5673. for (var i = 0; i < allImages.length && i < 10; i++) {
  5674. !!allImages[i].src && imgSrc.push(encodeURIComponent(allImages[i].src));
  5675. }
  5676. this.pics = imgSrc;
  5677. }
  5678. switch (sns) {
  5679. case "qzone":
  5680. shareData.desc = desc;
  5681. shareData.site = this.options.via;
  5682. shareData.pics = imgSrc.join("|");
  5683. // TODO: 抓取图片多张
  5684. break;
  5685. case "qq":
  5686. shareData.desc = desc;
  5687. shareData.site = this.options.via;
  5688. shareData.pics = imgSrc[0];
  5689. // 抓取一张图片
  5690. break;
  5691. case "tqq":
  5692. // 抓取图片多张
  5693. shareData.pic = imgSrc.join("|");
  5694. break;
  5695. }
  5696. return shareData;
  5697. };
  5698. Share.prototype.shareTo = function(sns, data) {
  5699. var snsInfo = Share.SNS[sns];
  5700. if (!snsInfo) {
  5701. return;
  5702. }
  5703. if (sns === "wechat" || sns === "weixin") {
  5704. return this.wechatQr();
  5705. }
  5706. var query = [];
  5707. for (var key in data) {
  5708. if (data[key]) {
  5709. // 避免 encode 图片分隔符 |
  5710. query.push(key.toString() + "=" + (key === "pic" || key === "pics" ? data[key] : encodeURIComponent(data[key])));
  5711. }
  5712. }
  5713. window.open(snsInfo.url + "?" + query.join("&"));
  5714. };
  5715. Share.prototype.wechatQr = function() {
  5716. if (!this.$wechatQr) {
  5717. var qrId = UI.utils.generateGUID("am-share-wechat");
  5718. var $qr = $('<div class="am-modal am-modal-no-btn am-share-wechat-qr">' + '<div class="am-modal-dialog"><div class="am-modal-hd">分享到微信 ' + '<a href="" class="am-close am-close-spin" ' + "data-am-modal-close>&times;</a> </div>" + '<div class="am-modal-bd">' + '<div class="am-share-wx-qr"></div>' + '<div class="am-share-wechat-tip">' + "打开微信,点击底部的<em>发现</em>,<br/> " + "使用<em>扫一扫</em>将网页分享至朋友圈</div></div></div></div>", {
  5719. id: qrId
  5720. });
  5721. var qrNode = new QRCode({
  5722. render: "canvas",
  5723. correctLevel: 0,
  5724. text: doc.location.href,
  5725. width: 180,
  5726. height: 180,
  5727. background: "#fff",
  5728. foreground: "#000"
  5729. });
  5730. $qr.find(".am-share-wx-qr").html(qrNode);
  5731. $qr.appendTo($("body"));
  5732. this.$wechatQr = $("#" + qrId);
  5733. }
  5734. this.$wechatQr.modal("open");
  5735. };
  5736. var share = new Share();
  5737. $doc.on("click.share.amui", '[data-am-toggle="share"]', function(e) {
  5738. e.preventDefault();
  5739. share.toggle();
  5740. });
  5741. UI.share = share;
  5742. module.exports = share;
  5743. });
  5744. define("ui.smooth-scroll", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5745. "use strict";
  5746. var UI = require("core");
  5747. var rAF = UI.utils.rAF;
  5748. var $ = window.Zepto;
  5749. /**
  5750. * Smooth Scroll
  5751. * @param position
  5752. * @via http://mir.aculo.us/2014/01/19/scrolling-dom-elements-to-the-top-a-zepto-plugin/
  5753. */
  5754. // Usage: $(window).smoothScroll([options])
  5755. // only allow one scroll to top operation to be in progress at a time,
  5756. // which is probably what you want
  5757. var smoothScrollInProgress = false;
  5758. $.fn.smoothScroll = function(options) {
  5759. options = options || {};
  5760. var $this = this, targetY = parseInt(options.position) || 0, initialY = $this.scrollTop(), lastY = initialY, delta = targetY - initialY, // duration in ms, make it a bit shorter for short distances
  5761. // this is not scientific and you might want to adjust this for
  5762. // your preferences
  5763. speed = options.speed || Math.min(750, Math.min(1500, Math.abs(initialY - targetY))), // temp variables (t will be a position between 0 and 1, y is the calculated scrollTop)
  5764. start, t, y, cancelScroll = function() {
  5765. abort();
  5766. };
  5767. // abort if already in progress or nothing to scroll
  5768. if (smoothScrollInProgress) {
  5769. return;
  5770. }
  5771. if (delta === 0) {
  5772. return;
  5773. }
  5774. // quint ease-in-out smoothing, from
  5775. // https://github.com/madrobby/scripty2/blob/master/src/effects/transitions/penner.js#L127-L136
  5776. function smooth(pos) {
  5777. if ((pos /= .5) < 1) {
  5778. return .5 * Math.pow(pos, 5);
  5779. }
  5780. return .5 * (Math.pow(pos - 2, 5) + 2);
  5781. }
  5782. function abort() {
  5783. $this.off("touchstart.smoothscroll.amui", cancelScroll);
  5784. smoothScrollInProgress = false;
  5785. }
  5786. // when there's a touch detected while scrolling is in progress, abort
  5787. // the scrolling (emulates native scrolling behavior)
  5788. $this.on("touchstart.smoothscroll.amui", cancelScroll);
  5789. smoothScrollInProgress = true;
  5790. // start rendering away! note the function given to frame
  5791. // is named "render" so we can reference it again further down
  5792. rAF(function render(now) {
  5793. if (!smoothScrollInProgress) {
  5794. return;
  5795. }
  5796. if (!start) {
  5797. start = now;
  5798. }
  5799. // calculate t, position of animation in [0..1]
  5800. t = Math.min(1, Math.max((now - start) / speed, 0));
  5801. // calculate the new scrollTop position (don't forget to smooth)
  5802. y = Math.round(initialY + delta * smooth(t));
  5803. // bracket scrollTop so we're never over-scrolling
  5804. if (delta > 0 && y > targetY) y = targetY;
  5805. if (delta < 0 && y < targetY) y = targetY;
  5806. // only actually set scrollTop if there was a change fromt he last frame
  5807. if (lastY != y) $this.scrollTop(y);
  5808. lastY = y;
  5809. // if we're not done yet, queue up an other frame to render,
  5810. // or clean up
  5811. if (y !== targetY) {
  5812. rAF(render);
  5813. } else {
  5814. abort();
  5815. }
  5816. });
  5817. };
  5818. // Init code
  5819. $(document).on("click.smoothScroll.amui", "[data-am-smooth-scroll]", function(e) {
  5820. e.preventDefault();
  5821. var options = UI.utils.parseOptions($(this).attr("data-am-smooth-scroll"));
  5822. $(window).smoothScroll(options);
  5823. });
  5824. });
  5825. define("ui.tabs", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "util.hammer" ], function(require, exports, module) {
  5826. "use strict";
  5827. require("core");
  5828. var Hammer = require("util.hammer");
  5829. var $ = window.Zepto;
  5830. var UI = $.AMUI;
  5831. var supportTransition = UI.support.transition;
  5832. var animation = UI.support.animation;
  5833. /**
  5834. * @via https://github.com/twbs/bootstrap/blob/master/js/tab.js
  5835. * @copyright 2011-2014 Twitter, Inc.
  5836. * @license MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  5837. */
  5838. var Tabs = function(element, options) {
  5839. this.$element = $(element);
  5840. this.options = $.extend({}, Tabs.DEFAULTS, options || {});
  5841. this.$tabNav = this.$element.find(this.options.selector.nav);
  5842. this.$navs = this.$tabNav.find("a");
  5843. this.$content = this.$element.find(this.options.selector.content);
  5844. this.$tabPanels = this.$content.find(this.options.selector.panel);
  5845. this.transitioning = null;
  5846. this.init();
  5847. };
  5848. Tabs.DEFAULTS = {
  5849. selector: {
  5850. nav: ".am-tabs-nav",
  5851. content: ".am-tabs-bd",
  5852. panel: ".am-tab-panel"
  5853. },
  5854. className: {
  5855. active: "am-active"
  5856. }
  5857. };
  5858. Tabs.prototype.init = function() {
  5859. var me = this;
  5860. var options = this.options;
  5861. // Activate the first Tab when no active Tab or multiple active Tabs
  5862. if (this.$tabNav.find("> .am-active").length !== 1) {
  5863. var $tabNav = this.$tabNav;
  5864. this.activate($tabNav.children("li").first(), $tabNav);
  5865. this.activate(this.$tabPanels.first(), this.$content);
  5866. }
  5867. this.$navs.on("click.tabs.amui", function(e) {
  5868. e.preventDefault();
  5869. me.open($(this));
  5870. });
  5871. if (!options.noSwipe) {
  5872. var hammer = new Hammer(this.$content[0]);
  5873. hammer.get("pan").set({
  5874. direction: Hammer.DIRECTION_HORIZONTAL,
  5875. threshold: 120
  5876. });
  5877. hammer.on("panleft", UI.utils.debounce(function(e) {
  5878. e.preventDefault();
  5879. var $target = $(e.target);
  5880. if (!$target.is(options.selector.panel)) {
  5881. $target = $target.closest(options.selector.panel);
  5882. }
  5883. $target.focus();
  5884. var $nav = me.getNextNav($target);
  5885. $nav && me.open($nav);
  5886. }, 100));
  5887. hammer.on("panright", UI.utils.debounce(function(e) {
  5888. e.preventDefault();
  5889. var $target = $(e.target);
  5890. if (!$target.is(options.selector.panel)) {
  5891. $target = $target.closest(options.selector.panel);
  5892. }
  5893. var $nav = me.getPrevNav($target);
  5894. $nav && me.open($nav);
  5895. }, 100));
  5896. }
  5897. };
  5898. Tabs.prototype.open = function($nav) {
  5899. if (!$nav || this.transitioning || $nav.parent("li").hasClass("am-active")) {
  5900. return;
  5901. }
  5902. var $tabNav = this.$tabNav;
  5903. var $navs = this.$navs;
  5904. var $tabContent = this.$content;
  5905. var href = $nav.attr("href");
  5906. var regexHash = /^#.+$/;
  5907. var $target = regexHash.test(href) && this.$content.find(href) || this.$tabPanels.eq($navs.index($nav));
  5908. var previous = $tabNav.find(".am-active a")[0];
  5909. var e = $.Event("open:tabs:amui", {
  5910. relatedTarget: previous
  5911. });
  5912. $nav.trigger(e);
  5913. if (e.isDefaultPrevented()) {
  5914. return;
  5915. }
  5916. // activate Tab nav
  5917. this.activate($nav.closest("li"), $tabNav);
  5918. // activate Tab content
  5919. this.activate($target, $tabContent, function() {
  5920. $nav.trigger({
  5921. type: "opened:tabs:amui",
  5922. relatedTarget: previous
  5923. });
  5924. });
  5925. };
  5926. Tabs.prototype.activate = function($element, $container, callback) {
  5927. this.transitioning = true;
  5928. var $active = $container.find("> .am-active");
  5929. var transition = callback && supportTransition && !!$active.length;
  5930. $active.removeClass("am-active am-in");
  5931. $element.addClass("am-active");
  5932. if (transition) {
  5933. $element.redraw();
  5934. // reflow for transition
  5935. $element.addClass("am-in");
  5936. } else {
  5937. $element.removeClass("am-fade");
  5938. }
  5939. function complete() {
  5940. callback && callback();
  5941. this.transitioning = false;
  5942. }
  5943. transition ? $active.one(supportTransition.end, $.proxy(complete, this)) : $.proxy(complete, this)();
  5944. };
  5945. Tabs.prototype.getNextNav = function($panel) {
  5946. var navIndex = this.$tabPanels.index($panel);
  5947. var rightSpring = "am-animation-right-spring";
  5948. if (navIndex + 1 >= this.$navs.length) {
  5949. // last one
  5950. animation && $panel.addClass(rightSpring).on(animation.end, function() {
  5951. $panel.removeClass(rightSpring);
  5952. });
  5953. return null;
  5954. } else {
  5955. return this.$navs.eq(navIndex + 1);
  5956. }
  5957. };
  5958. Tabs.prototype.getPrevNav = function($panel) {
  5959. var navIndex = this.$tabPanels.index($panel);
  5960. var leftSpring = "am-animation-left-spring";
  5961. if (navIndex === 0) {
  5962. // first one
  5963. animation && $panel.addClass(leftSpring).on(animation.end, function() {
  5964. $panel.removeClass(leftSpring);
  5965. });
  5966. return null;
  5967. } else {
  5968. return this.$navs.eq(navIndex - 1);
  5969. }
  5970. };
  5971. // Plugin
  5972. function Plugin(option) {
  5973. return this.each(function() {
  5974. var $this = $(this);
  5975. var $tabs = $this.is(".am-tabs") && $this || $this.closest(".am-tabs");
  5976. var data = $tabs.data("amui.tabs");
  5977. var options = $.extend({}, $.isPlainObject(option) ? option : {}, UI.utils.parseOptions($this.data("amTabs")));
  5978. if (!data) {
  5979. $tabs.data("amui.tabs", data = new Tabs($tabs[0], options));
  5980. }
  5981. if (typeof option == "string" && $this.is(".am-tabs-nav a")) {
  5982. data[option]($this);
  5983. }
  5984. });
  5985. }
  5986. $.fn.tabs = Plugin;
  5987. // Init code
  5988. $(document).on("ready", function(e) {
  5989. $("[data-am-tabs]").tabs();
  5990. });
  5991. UI.tabs = Tabs;
  5992. module.exports = Tabs;
  5993. });
  5994. define("util.cookie", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5995. "use strict";
  5996. require("core");
  5997. var $ = window.Zepto;
  5998. var UI = $.AMUI;
  5999. var cookie = {
  6000. get: function(name) {
  6001. var cookieName = encodeURIComponent(name) + "=";
  6002. var cookieStart = document.cookie.indexOf(cookieName);
  6003. var cookieValue = null;
  6004. var cookieEnd;
  6005. if (cookieStart > -1) {
  6006. cookieEnd = document.cookie.indexOf(";", cookieStart);
  6007. if (cookieEnd == -1) {
  6008. cookieEnd = document.cookie.length;
  6009. }
  6010. cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
  6011. }
  6012. return cookieValue;
  6013. },
  6014. set: function(name, value, expires, path, domain, secure) {
  6015. var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
  6016. if (expires instanceof Date) {
  6017. cookieText += "; expires=" + expires.toGMTString();
  6018. }
  6019. if (path) {
  6020. cookieText += "; path=" + path;
  6021. }
  6022. if (domain) {
  6023. cookieText += "; domain=" + domain;
  6024. }
  6025. if (secure) {
  6026. cookieText += "; secure";
  6027. }
  6028. document.cookie = cookieText;
  6029. },
  6030. unset: function(name, path, domain, secure) {
  6031. this.set(name, "", new Date(0), path, domain, secure);
  6032. }
  6033. };
  6034. UI.utils.cookie = cookie;
  6035. module.exports = cookie;
  6036. });
  6037. define("util.qrcode", [], function(require, exports, module) {
  6038. var $ = Zepto;
  6039. /**
  6040. * @ver 1.1.0
  6041. * @via https://github.com/aralejs/qrcode/blob/master/src/qrcode.js
  6042. * @license http://aralejs.org/
  6043. */
  6044. var qrcodeAlgObjCache = [];
  6045. /**
  6046. * 二维码构造函数,主要用于绘制
  6047. * @param {参数列表} opt 传递参数
  6048. * @return {}
  6049. */
  6050. var qrcode = function(opt) {
  6051. if (typeof opt === "string") {
  6052. // 只编码ASCII字符串
  6053. opt = {
  6054. text: opt
  6055. };
  6056. }
  6057. //设置默认参数
  6058. this.options = $.extend({}, {
  6059. text: "",
  6060. render: "",
  6061. width: 256,
  6062. height: 256,
  6063. correctLevel: 3,
  6064. background: "#ffffff",
  6065. foreground: "#000000"
  6066. }, opt);
  6067. //使用QRCodeAlg创建二维码结构
  6068. var qrCodeAlg = null;
  6069. for (var i = 0, l = qrcodeAlgObjCache.length; i < l; i++) {
  6070. if (qrcodeAlgObjCache[i].text == this.options.text && qrcodeAlgObjCache[i].text.correctLevel == this.options.correctLevel) {
  6071. qrCodeAlg = qrcodeAlgObjCache[i].obj;
  6072. break;
  6073. }
  6074. }
  6075. if (i == l) {
  6076. qrCodeAlg = new QRCodeAlg(this.options.text, this.options.correctLevel);
  6077. qrcodeAlgObjCache.push({
  6078. text: this.options.text,
  6079. correctLevel: this.options.correctLevel,
  6080. obj: qrCodeAlg
  6081. });
  6082. }
  6083. if (this.options.render) {
  6084. switch (this.options.render) {
  6085. case "canvas":
  6086. return this.createCanvas(qrCodeAlg);
  6087. case "table":
  6088. return this.createTable(qrCodeAlg);
  6089. case "svg":
  6090. return this.createSVG(qrCodeAlg);
  6091. default:
  6092. return this.createDefault(qrCodeAlg);
  6093. }
  6094. }
  6095. return this.createDefault(qrCodeAlg);
  6096. };
  6097. /**
  6098. * 使用Canvas来画二维码
  6099. * @return {}
  6100. */
  6101. qrcode.prototype.createDefault = function(qrCodeAlg) {
  6102. var canvas = document.createElement("canvas");
  6103. if (canvas.getContext) return this.createCanvas(qrCodeAlg);
  6104. if (!!document.createElementNS && !!document.createElementNS(SVG_NS, "svg").createSVGRect) return this.createSVG(qrCodeAlg);
  6105. return this.createTable(qrCodeAlg);
  6106. };
  6107. qrcode.prototype.createCanvas = function(qrCodeAlg) {
  6108. //创建canvas节点
  6109. var canvas = document.createElement("canvas");
  6110. canvas.width = this.options.width;
  6111. canvas.height = this.options.height;
  6112. var ctx = canvas.getContext("2d");
  6113. //计算每个点的长宽
  6114. var tileW = (this.options.width / qrCodeAlg.getModuleCount()).toPrecision(4);
  6115. var tileH = this.options.height / qrCodeAlg.getModuleCount().toPrecision(4);
  6116. //绘制
  6117. for (var row = 0; row < qrCodeAlg.getModuleCount(); row++) {
  6118. for (var col = 0; col < qrCodeAlg.getModuleCount(); col++) {
  6119. ctx.fillStyle = qrCodeAlg.modules[row][col] ? this.options.foreground : this.options.background;
  6120. var w = Math.ceil((col + 1) * tileW) - Math.floor(col * tileW);
  6121. var h = Math.ceil((row + 1) * tileW) - Math.floor(row * tileW);
  6122. ctx.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h);
  6123. }
  6124. }
  6125. //返回绘制的节点
  6126. return canvas;
  6127. };
  6128. /**
  6129. * 使用table来绘制二维码
  6130. * @return {}
  6131. */
  6132. qrcode.prototype.createTable = function(qrCodeAlg) {
  6133. //创建table节点
  6134. var s = [];
  6135. s.push('<table style="border:0px; margin:0px; padding:0px; border-collapse:collapse; background-color: ' + this.options.background + ';">');
  6136. // 计算每个节点的长宽;取整,防止点之间出现分离
  6137. var tileW = -1, tileH = -1, caculateW = -1, caculateH = -1;
  6138. tileW = caculateW = Math.floor(this.options.width / qrCodeAlg.getModuleCount());
  6139. tileH = caculateH = Math.floor(this.options.height / qrCodeAlg.getModuleCount());
  6140. if (caculateW <= 0) {
  6141. if (qrCodeAlg.getModuleCount() < 80) {
  6142. tileW = 2;
  6143. } else {
  6144. tileW = 1;
  6145. }
  6146. }
  6147. if (caculateH <= 0) {
  6148. if (qrCodeAlg.getModuleCount() < 80) {
  6149. tileH = 2;
  6150. } else {
  6151. tileH = 1;
  6152. }
  6153. }
  6154. // 绘制二维码
  6155. foreTd = '<td style="border:0px; margin:0px; padding:0px; width:' + tileW + "px; background-color: " + this.options.foreground + '"></td>',
  6156. backTd = '<td style="border:0px; margin:0px; padding:0px; width:' + tileW + "px; background-color: " + this.options.background + '"></td>',
  6157. l = qrCodeAlg.getModuleCount();
  6158. for (var row = 0; row < l; row++) {
  6159. s.push('<tr style="border:0px; margin:0px; padding:0px; height: ' + tileH + 'px">');
  6160. for (var col = 0; col < l; col++) {
  6161. s.push(qrCodeAlg.modules[row][col] ? foreTd : backTd);
  6162. }
  6163. s.push("</tr>");
  6164. }
  6165. s.push("</table>");
  6166. var span = document.createElement("span");
  6167. span.innerHTML = s.join("");
  6168. return span.firstChild;
  6169. };
  6170. /**
  6171. * 使用SVG开绘制二维码
  6172. * @return {}
  6173. */
  6174. qrcode.prototype.createSVG = function(qrCodeAlg) {
  6175. var x, dx, y, dy, moduleCount = qrCodeAlg.getModuleCount(), scale = this.options.height / this.options.width, svg = '<svg xmlns="http://www.w3.org/2000/svg" ' + 'width="' + this.options.width + 'px" height="' + this.options.height + 'px" ' + 'viewbox="0 0 ' + moduleCount * 10 + " " + moduleCount * 10 * scale + '">', rectHead = "<path ", foreRect = ' style="stroke-width:0.5;stroke:' + this.options.foreground + ";fill:" + this.options.foreground + ';"></path>', backRect = ' style="stroke-width:0.5;stroke:' + this.options.background + ";fill:" + this.options.background + ';"></path>';
  6176. // draw in the svg
  6177. for (var row = 0; row < moduleCount; row++) {
  6178. for (var col = 0; col < moduleCount; col++) {
  6179. x = col * 10;
  6180. y = row * 10 * scale;
  6181. dx = (col + 1) * 10;
  6182. dy = (row + 1) * 10 * scale;
  6183. svg += rectHead + 'd="M ' + x + "," + y + " L " + dx + "," + y + " L " + dx + "," + dy + " L " + x + "," + dy + ' Z"';
  6184. svg += qrCodeAlg.modules[row][col] ? foreRect : backRect;
  6185. }
  6186. }
  6187. svg += "</svg>";
  6188. // return just built svg
  6189. return $(svg)[0];
  6190. };
  6191. module.exports = qrcode;
  6192. $.AMUI.qrcode = qrcode;
  6193. /**
  6194. * 获取单个字符的utf8编码
  6195. * unicode BMP平面约65535个字符
  6196. * @param {num} code
  6197. * return {array}
  6198. */
  6199. function unicodeFormat8(code) {
  6200. // 1 byte
  6201. if (code < 128) {
  6202. return [ code ];
  6203. } else if (code < 2048) {
  6204. c0 = 192 + (code >> 6);
  6205. c1 = 128 + (code & 63);
  6206. return [ c0, c1 ];
  6207. } else {
  6208. c0 = 224 + (code >> 12);
  6209. c1 = 128 + (code >> 6 & 63);
  6210. c2 = 128 + (code & 63);
  6211. return [ c0, c1, c2 ];
  6212. }
  6213. }
  6214. /**
  6215. * 获取字符串的utf8编码字节串
  6216. * @param {string} string
  6217. * @return {array}
  6218. */
  6219. function getUTF8Bytes(string) {
  6220. var utf8codes = [];
  6221. for (var i = 0; i < string.length; i++) {
  6222. var code = string.charCodeAt(i);
  6223. var utf8 = unicodeFormat8(code);
  6224. for (var j = 0; j < utf8.length; j++) {
  6225. utf8codes.push(utf8[j]);
  6226. }
  6227. }
  6228. return utf8codes;
  6229. }
  6230. /**
  6231. * 二维码算法实现
  6232. * @param {string} data 要编码的信息字符串
  6233. * @param {num} errorCorrectLevel 纠错等级
  6234. */
  6235. function QRCodeAlg(data, errorCorrectLevel) {
  6236. this.typeNumber = -1;
  6237. //版本
  6238. this.errorCorrectLevel = errorCorrectLevel;
  6239. this.modules = null;
  6240. //二维矩阵,存放最终结果
  6241. this.moduleCount = 0;
  6242. //矩阵大小
  6243. this.dataCache = null;
  6244. //数据缓存
  6245. this.rsBlocks = null;
  6246. //版本数据信息
  6247. this.totalDataCount = -1;
  6248. //可使用的数据量
  6249. this.data = data;
  6250. this.utf8bytes = getUTF8Bytes(data);
  6251. this.make();
  6252. }
  6253. QRCodeAlg.prototype = {
  6254. constructor: QRCodeAlg,
  6255. /**
  6256. * 获取二维码矩阵大小
  6257. * @return {num} 矩阵大小
  6258. */
  6259. getModuleCount: function() {
  6260. return this.moduleCount;
  6261. },
  6262. /**
  6263. * 编码
  6264. */
  6265. make: function() {
  6266. this.getRightType();
  6267. this.dataCache = this.createData();
  6268. this.createQrcode();
  6269. },
  6270. /**
  6271. * 设置二位矩阵功能图形
  6272. * @param {bool} test 表示是否在寻找最好掩膜阶段
  6273. * @param {num} maskPattern 掩膜的版本
  6274. */
  6275. makeImpl: function(maskPattern) {
  6276. this.moduleCount = this.typeNumber * 4 + 17;
  6277. this.modules = new Array(this.moduleCount);
  6278. for (var row = 0; row < this.moduleCount; row++) {
  6279. this.modules[row] = new Array(this.moduleCount);
  6280. }
  6281. this.setupPositionProbePattern(0, 0);
  6282. this.setupPositionProbePattern(this.moduleCount - 7, 0);
  6283. this.setupPositionProbePattern(0, this.moduleCount - 7);
  6284. this.setupPositionAdjustPattern();
  6285. this.setupTimingPattern();
  6286. this.setupTypeInfo(true, maskPattern);
  6287. if (this.typeNumber >= 7) {
  6288. this.setupTypeNumber(true);
  6289. }
  6290. this.mapData(this.dataCache, maskPattern);
  6291. },
  6292. /**
  6293. * 设置二维码的位置探测图形
  6294. * @param {num} row 探测图形的中心横坐标
  6295. * @param {num} col 探测图形的中心纵坐标
  6296. */
  6297. setupPositionProbePattern: function(row, col) {
  6298. for (var r = -1; r <= 7; r++) {
  6299. if (row + r <= -1 || this.moduleCount <= row + r) continue;
  6300. for (var c = -1; c <= 7; c++) {
  6301. if (col + c <= -1 || this.moduleCount <= col + c) continue;
  6302. if (0 <= r && r <= 6 && (c == 0 || c == 6) || 0 <= c && c <= 6 && (r == 0 || r == 6) || 2 <= r && r <= 4 && 2 <= c && c <= 4) {
  6303. this.modules[row + r][col + c] = true;
  6304. } else {
  6305. this.modules[row + r][col + c] = false;
  6306. }
  6307. }
  6308. }
  6309. },
  6310. /**
  6311. * 创建二维码
  6312. * @return {[type]} [description]
  6313. */
  6314. createQrcode: function() {
  6315. var minLostPoint = 0;
  6316. var pattern = 0;
  6317. var bestModules = null;
  6318. for (var i = 0; i < 8; i++) {
  6319. this.makeImpl(i);
  6320. var lostPoint = QRUtil.getLostPoint(this);
  6321. if (i == 0 || minLostPoint > lostPoint) {
  6322. minLostPoint = lostPoint;
  6323. pattern = i;
  6324. bestModules = this.modules;
  6325. }
  6326. }
  6327. this.modules = bestModules;
  6328. this.setupTypeInfo(false, pattern);
  6329. if (this.typeNumber >= 7) {
  6330. this.setupTypeNumber(false);
  6331. }
  6332. },
  6333. /**
  6334. * 设置定位图形
  6335. * @return {[type]} [description]
  6336. */
  6337. setupTimingPattern: function() {
  6338. for (var r = 8; r < this.moduleCount - 8; r++) {
  6339. if (this.modules[r][6] != null) {
  6340. continue;
  6341. }
  6342. this.modules[r][6] = r % 2 == 0;
  6343. if (this.modules[6][r] != null) {
  6344. continue;
  6345. }
  6346. this.modules[6][r] = r % 2 == 0;
  6347. }
  6348. },
  6349. /**
  6350. * 设置矫正图形
  6351. * @return {[type]} [description]
  6352. */
  6353. setupPositionAdjustPattern: function() {
  6354. var pos = QRUtil.getPatternPosition(this.typeNumber);
  6355. for (var i = 0; i < pos.length; i++) {
  6356. for (var j = 0; j < pos.length; j++) {
  6357. var row = pos[i];
  6358. var col = pos[j];
  6359. if (this.modules[row][col] != null) {
  6360. continue;
  6361. }
  6362. for (var r = -2; r <= 2; r++) {
  6363. for (var c = -2; c <= 2; c++) {
  6364. if (r == -2 || r == 2 || c == -2 || c == 2 || r == 0 && c == 0) {
  6365. this.modules[row + r][col + c] = true;
  6366. } else {
  6367. this.modules[row + r][col + c] = false;
  6368. }
  6369. }
  6370. }
  6371. }
  6372. }
  6373. },
  6374. /**
  6375. * 设置版本信息(7以上版本才有)
  6376. * @param {bool} test 是否处于判断最佳掩膜阶段
  6377. * @return {[type]} [description]
  6378. */
  6379. setupTypeNumber: function(test) {
  6380. var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
  6381. for (var i = 0; i < 18; i++) {
  6382. var mod = !test && (bits >> i & 1) == 1;
  6383. this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
  6384. this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
  6385. }
  6386. },
  6387. /**
  6388. * 设置格式信息(纠错等级和掩膜版本)
  6389. * @param {bool} test
  6390. * @param {num} maskPattern 掩膜版本
  6391. * @return {}
  6392. */
  6393. setupTypeInfo: function(test, maskPattern) {
  6394. var data = QRErrorCorrectLevel[this.errorCorrectLevel] << 3 | maskPattern;
  6395. var bits = QRUtil.getBCHTypeInfo(data);
  6396. // vertical
  6397. for (var i = 0; i < 15; i++) {
  6398. var mod = !test && (bits >> i & 1) == 1;
  6399. if (i < 6) {
  6400. this.modules[i][8] = mod;
  6401. } else if (i < 8) {
  6402. this.modules[i + 1][8] = mod;
  6403. } else {
  6404. this.modules[this.moduleCount - 15 + i][8] = mod;
  6405. }
  6406. // horizontal
  6407. var mod = !test && (bits >> i & 1) == 1;
  6408. if (i < 8) {
  6409. this.modules[8][this.moduleCount - i - 1] = mod;
  6410. } else if (i < 9) {
  6411. this.modules[8][15 - i - 1 + 1] = mod;
  6412. } else {
  6413. this.modules[8][15 - i - 1] = mod;
  6414. }
  6415. }
  6416. // fixed module
  6417. this.modules[this.moduleCount - 8][8] = !test;
  6418. },
  6419. /**
  6420. * 数据编码
  6421. * @return {[type]} [description]
  6422. */
  6423. createData: function() {
  6424. var buffer = new QRBitBuffer();
  6425. var lengthBits = this.typeNumber > 9 ? 16 : 8;
  6426. buffer.put(4, 4);
  6427. //添加模式
  6428. buffer.put(this.utf8bytes.length, lengthBits);
  6429. for (var i = 0, l = this.utf8bytes.length; i < l; i++) {
  6430. buffer.put(this.utf8bytes[i], 8);
  6431. }
  6432. if (buffer.length + 4 <= this.totalDataCount * 8) {
  6433. buffer.put(0, 4);
  6434. }
  6435. // padding
  6436. while (buffer.length % 8 != 0) {
  6437. buffer.putBit(false);
  6438. }
  6439. // padding
  6440. while (true) {
  6441. if (buffer.length >= this.totalDataCount * 8) {
  6442. break;
  6443. }
  6444. buffer.put(QRCodeAlg.PAD0, 8);
  6445. if (buffer.length >= this.totalDataCount * 8) {
  6446. break;
  6447. }
  6448. buffer.put(QRCodeAlg.PAD1, 8);
  6449. }
  6450. return this.createBytes(buffer);
  6451. },
  6452. /**
  6453. * 纠错码编码
  6454. * @param {buffer} buffer 数据编码
  6455. * @return {[type]}
  6456. */
  6457. createBytes: function(buffer) {
  6458. var offset = 0;
  6459. var maxDcCount = 0;
  6460. var maxEcCount = 0;
  6461. var length = this.rsBlock.length / 3;
  6462. var rsBlocks = new Array();
  6463. for (var i = 0; i < length; i++) {
  6464. var count = this.rsBlock[i * 3 + 0];
  6465. var totalCount = this.rsBlock[i * 3 + 1];
  6466. var dataCount = this.rsBlock[i * 3 + 2];
  6467. for (var j = 0; j < count; j++) {
  6468. rsBlocks.push([ dataCount, totalCount ]);
  6469. }
  6470. }
  6471. var dcdata = new Array(rsBlocks.length);
  6472. var ecdata = new Array(rsBlocks.length);
  6473. for (var r = 0; r < rsBlocks.length; r++) {
  6474. var dcCount = rsBlocks[r][0];
  6475. var ecCount = rsBlocks[r][1] - dcCount;
  6476. maxDcCount = Math.max(maxDcCount, dcCount);
  6477. maxEcCount = Math.max(maxEcCount, ecCount);
  6478. dcdata[r] = new Array(dcCount);
  6479. for (var i = 0; i < dcdata[r].length; i++) {
  6480. dcdata[r][i] = 255 & buffer.buffer[i + offset];
  6481. }
  6482. offset += dcCount;
  6483. var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
  6484. var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
  6485. var modPoly = rawPoly.mod(rsPoly);
  6486. ecdata[r] = new Array(rsPoly.getLength() - 1);
  6487. for (var i = 0; i < ecdata[r].length; i++) {
  6488. var modIndex = i + modPoly.getLength() - ecdata[r].length;
  6489. ecdata[r][i] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
  6490. }
  6491. }
  6492. var data = new Array(this.totalDataCount);
  6493. var index = 0;
  6494. for (var i = 0; i < maxDcCount; i++) {
  6495. for (var r = 0; r < rsBlocks.length; r++) {
  6496. if (i < dcdata[r].length) {
  6497. data[index++] = dcdata[r][i];
  6498. }
  6499. }
  6500. }
  6501. for (var i = 0; i < maxEcCount; i++) {
  6502. for (var r = 0; r < rsBlocks.length; r++) {
  6503. if (i < ecdata[r].length) {
  6504. data[index++] = ecdata[r][i];
  6505. }
  6506. }
  6507. }
  6508. return data;
  6509. },
  6510. /**
  6511. * 布置模块,构建最终信息
  6512. * @param {} data
  6513. * @param {} maskPattern
  6514. * @return {}
  6515. */
  6516. mapData: function(data, maskPattern) {
  6517. var inc = -1;
  6518. var row = this.moduleCount - 1;
  6519. var bitIndex = 7;
  6520. var byteIndex = 0;
  6521. for (var col = this.moduleCount - 1; col > 0; col -= 2) {
  6522. if (col == 6) col--;
  6523. while (true) {
  6524. for (var c = 0; c < 2; c++) {
  6525. if (this.modules[row][col - c] == null) {
  6526. var dark = false;
  6527. if (byteIndex < data.length) {
  6528. dark = (data[byteIndex] >>> bitIndex & 1) == 1;
  6529. }
  6530. var mask = QRUtil.getMask(maskPattern, row, col - c);
  6531. if (mask) {
  6532. dark = !dark;
  6533. }
  6534. this.modules[row][col - c] = dark;
  6535. bitIndex--;
  6536. if (bitIndex == -1) {
  6537. byteIndex++;
  6538. bitIndex = 7;
  6539. }
  6540. }
  6541. }
  6542. row += inc;
  6543. if (row < 0 || this.moduleCount <= row) {
  6544. row -= inc;
  6545. inc = -inc;
  6546. break;
  6547. }
  6548. }
  6549. }
  6550. }
  6551. };
  6552. /**
  6553. * 填充字段
  6554. */
  6555. QRCodeAlg.PAD0 = 236;
  6556. QRCodeAlg.PAD1 = 17;
  6557. //---------------------------------------------------------------------
  6558. // 纠错等级对应的编码
  6559. //---------------------------------------------------------------------
  6560. var QRErrorCorrectLevel = [ 1, 0, 3, 2 ];
  6561. //---------------------------------------------------------------------
  6562. // 掩膜版本
  6563. //---------------------------------------------------------------------
  6564. var QRMaskPattern = {
  6565. PATTERN000: 0,
  6566. PATTERN001: 1,
  6567. PATTERN010: 2,
  6568. PATTERN011: 3,
  6569. PATTERN100: 4,
  6570. PATTERN101: 5,
  6571. PATTERN110: 6,
  6572. PATTERN111: 7
  6573. };
  6574. //---------------------------------------------------------------------
  6575. // 工具类
  6576. //---------------------------------------------------------------------
  6577. var QRUtil = {
  6578. /*
  6579. 每个版本矫正图形的位置
  6580. */
  6581. PATTERN_POSITION_TABLE: [ [], [ 6, 18 ], [ 6, 22 ], [ 6, 26 ], [ 6, 30 ], [ 6, 34 ], [ 6, 22, 38 ], [ 6, 24, 42 ], [ 6, 26, 46 ], [ 6, 28, 50 ], [ 6, 30, 54 ], [ 6, 32, 58 ], [ 6, 34, 62 ], [ 6, 26, 46, 66 ], [ 6, 26, 48, 70 ], [ 6, 26, 50, 74 ], [ 6, 30, 54, 78 ], [ 6, 30, 56, 82 ], [ 6, 30, 58, 86 ], [ 6, 34, 62, 90 ], [ 6, 28, 50, 72, 94 ], [ 6, 26, 50, 74, 98 ], [ 6, 30, 54, 78, 102 ], [ 6, 28, 54, 80, 106 ], [ 6, 32, 58, 84, 110 ], [ 6, 30, 58, 86, 114 ], [ 6, 34, 62, 90, 118 ], [ 6, 26, 50, 74, 98, 122 ], [ 6, 30, 54, 78, 102, 126 ], [ 6, 26, 52, 78, 104, 130 ], [ 6, 30, 56, 82, 108, 134 ], [ 6, 34, 60, 86, 112, 138 ], [ 6, 30, 58, 86, 114, 142 ], [ 6, 34, 62, 90, 118, 146 ], [ 6, 30, 54, 78, 102, 126, 150 ], [ 6, 24, 50, 76, 102, 128, 154 ], [ 6, 28, 54, 80, 106, 132, 158 ], [ 6, 32, 58, 84, 110, 136, 162 ], [ 6, 26, 54, 82, 110, 138, 166 ], [ 6, 30, 58, 86, 114, 142, 170 ] ],
  6582. G15: 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0,
  6583. G18: 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0,
  6584. G15_MASK: 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1,
  6585. /*
  6586. BCH编码格式信息
  6587. */
  6588. getBCHTypeInfo: function(data) {
  6589. var d = data << 10;
  6590. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
  6591. d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);
  6592. }
  6593. return (data << 10 | d) ^ QRUtil.G15_MASK;
  6594. },
  6595. /*
  6596. BCH编码版本信息
  6597. */
  6598. getBCHTypeNumber: function(data) {
  6599. var d = data << 12;
  6600. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
  6601. d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);
  6602. }
  6603. return data << 12 | d;
  6604. },
  6605. /*
  6606. 获取BCH位信息
  6607. */
  6608. getBCHDigit: function(data) {
  6609. var digit = 0;
  6610. while (data != 0) {
  6611. digit++;
  6612. data >>>= 1;
  6613. }
  6614. return digit;
  6615. },
  6616. /*
  6617. 获取版本对应的矫正图形位置
  6618. */
  6619. getPatternPosition: function(typeNumber) {
  6620. return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
  6621. },
  6622. /*
  6623. 掩膜算法
  6624. */
  6625. getMask: function(maskPattern, i, j) {
  6626. switch (maskPattern) {
  6627. case QRMaskPattern.PATTERN000:
  6628. return (i + j) % 2 == 0;
  6629. case QRMaskPattern.PATTERN001:
  6630. return i % 2 == 0;
  6631. case QRMaskPattern.PATTERN010:
  6632. return j % 3 == 0;
  6633. case QRMaskPattern.PATTERN011:
  6634. return (i + j) % 3 == 0;
  6635. case QRMaskPattern.PATTERN100:
  6636. return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
  6637. case QRMaskPattern.PATTERN101:
  6638. return i * j % 2 + i * j % 3 == 0;
  6639. case QRMaskPattern.PATTERN110:
  6640. return (i * j % 2 + i * j % 3) % 2 == 0;
  6641. case QRMaskPattern.PATTERN111:
  6642. return (i * j % 3 + (i + j) % 2) % 2 == 0;
  6643. default:
  6644. throw new Error("bad maskPattern:" + maskPattern);
  6645. }
  6646. },
  6647. /*
  6648. 获取RS的纠错多项式
  6649. */
  6650. getErrorCorrectPolynomial: function(errorCorrectLength) {
  6651. var a = new QRPolynomial([ 1 ], 0);
  6652. for (var i = 0; i < errorCorrectLength; i++) {
  6653. a = a.multiply(new QRPolynomial([ 1, QRMath.gexp(i) ], 0));
  6654. }
  6655. return a;
  6656. },
  6657. /*
  6658. 获取评价
  6659. */
  6660. getLostPoint: function(qrCode) {
  6661. var moduleCount = qrCode.getModuleCount(), lostPoint = 0, darkCount = 0;
  6662. for (var row = 0; row < moduleCount; row++) {
  6663. var sameCount = 0;
  6664. var head = qrCode.modules[row][0];
  6665. for (var col = 0; col < moduleCount; col++) {
  6666. var current = qrCode.modules[row][col];
  6667. //level 3 评价
  6668. if (col < moduleCount - 6) {
  6669. if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) {
  6670. if (col < moduleCount - 10) {
  6671. if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) {
  6672. lostPoint += 40;
  6673. }
  6674. } else if (col > 3) {
  6675. if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) {
  6676. lostPoint += 40;
  6677. }
  6678. }
  6679. }
  6680. }
  6681. //level 2 评价
  6682. if (row < moduleCount - 1 && col < moduleCount - 1) {
  6683. var count = 0;
  6684. if (current) count++;
  6685. if (qrCode.modules[row + 1][col]) count++;
  6686. if (qrCode.modules[row][col + 1]) count++;
  6687. if (qrCode.modules[row + 1][col + 1]) count++;
  6688. if (count == 0 || count == 4) {
  6689. lostPoint += 3;
  6690. }
  6691. }
  6692. //level 1 评价
  6693. if (head ^ current) {
  6694. sameCount++;
  6695. } else {
  6696. head = current;
  6697. if (sameCount >= 5) {
  6698. lostPoint += 3 + sameCount - 5;
  6699. }
  6700. sameCount = 1;
  6701. }
  6702. //level 4 评价
  6703. if (current) {
  6704. darkCount++;
  6705. }
  6706. }
  6707. }
  6708. for (var col = 0; col < moduleCount; col++) {
  6709. var sameCount = 0;
  6710. var head = qrCode.modules[0][col];
  6711. for (var row = 0; row < moduleCount; row++) {
  6712. var current = qrCode.modules[row][col];
  6713. //level 3 评价
  6714. if (row < moduleCount - 6) {
  6715. if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) {
  6716. if (row < moduleCount - 10) {
  6717. if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) {
  6718. lostPoint += 40;
  6719. }
  6720. } else if (row > 3) {
  6721. if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) {
  6722. lostPoint += 40;
  6723. }
  6724. }
  6725. }
  6726. }
  6727. //level 1 评价
  6728. if (head ^ current) {
  6729. sameCount++;
  6730. } else {
  6731. head = current;
  6732. if (sameCount >= 5) {
  6733. lostPoint += 3 + sameCount - 5;
  6734. }
  6735. sameCount = 1;
  6736. }
  6737. }
  6738. }
  6739. // LEVEL4
  6740. var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
  6741. lostPoint += ratio * 10;
  6742. return lostPoint;
  6743. }
  6744. };
  6745. //---------------------------------------------------------------------
  6746. // QRMath使用的数学工具
  6747. //---------------------------------------------------------------------
  6748. var QRMath = {
  6749. /*
  6750. 将n转化为a^m
  6751. */
  6752. glog: function(n) {
  6753. if (n < 1) {
  6754. throw new Error("glog(" + n + ")");
  6755. }
  6756. return QRMath.LOG_TABLE[n];
  6757. },
  6758. /*
  6759. 将a^m转化为n
  6760. */
  6761. gexp: function(n) {
  6762. while (n < 0) {
  6763. n += 255;
  6764. }
  6765. while (n >= 256) {
  6766. n -= 255;
  6767. }
  6768. return QRMath.EXP_TABLE[n];
  6769. },
  6770. EXP_TABLE: new Array(256),
  6771. LOG_TABLE: new Array(256)
  6772. };
  6773. for (var i = 0; i < 8; i++) {
  6774. QRMath.EXP_TABLE[i] = 1 << i;
  6775. }
  6776. for (var i = 8; i < 256; i++) {
  6777. QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
  6778. }
  6779. for (var i = 0; i < 255; i++) {
  6780. QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
  6781. }
  6782. //---------------------------------------------------------------------
  6783. // QRPolynomial 多项式
  6784. //---------------------------------------------------------------------
  6785. /**
  6786. * 多项式类
  6787. * @param {Array} num 系数
  6788. * @param {num} shift a^shift
  6789. */
  6790. function QRPolynomial(num, shift) {
  6791. if (num.length == undefined) {
  6792. throw new Error(num.length + "/" + shift);
  6793. }
  6794. var offset = 0;
  6795. while (offset < num.length && num[offset] == 0) {
  6796. offset++;
  6797. }
  6798. this.num = new Array(num.length - offset + shift);
  6799. for (var i = 0; i < num.length - offset; i++) {
  6800. this.num[i] = num[i + offset];
  6801. }
  6802. }
  6803. QRPolynomial.prototype = {
  6804. get: function(index) {
  6805. return this.num[index];
  6806. },
  6807. getLength: function() {
  6808. return this.num.length;
  6809. },
  6810. /**
  6811. * 多项式乘法
  6812. * @param {QRPolynomial} e 被乘多项式
  6813. * @return {[type]} [description]
  6814. */
  6815. multiply: function(e) {
  6816. var num = new Array(this.getLength() + e.getLength() - 1);
  6817. for (var i = 0; i < this.getLength(); i++) {
  6818. for (var j = 0; j < e.getLength(); j++) {
  6819. num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
  6820. }
  6821. }
  6822. return new QRPolynomial(num, 0);
  6823. },
  6824. /**
  6825. * 多项式模运算
  6826. * @param {QRPolynomial} e 模多项式
  6827. * @return {}
  6828. */
  6829. mod: function(e) {
  6830. var tl = this.getLength(), el = e.getLength();
  6831. if (tl - el < 0) {
  6832. return this;
  6833. }
  6834. var num = new Array(tl);
  6835. for (var i = 0; i < tl; i++) {
  6836. num[i] = this.get(i);
  6837. }
  6838. while (num.length >= el) {
  6839. var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0));
  6840. for (var i = 0; i < e.getLength(); i++) {
  6841. num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
  6842. }
  6843. while (num[0] == 0) {
  6844. num.shift();
  6845. }
  6846. }
  6847. return new QRPolynomial(num, 0);
  6848. }
  6849. };
  6850. //---------------------------------------------------------------------
  6851. // RS_BLOCK_TABLE
  6852. //---------------------------------------------------------------------
  6853. /*
  6854. 二维码各个版本信息[块数, 每块中的数据块数, 每块中的信息块数]
  6855. */
  6856. var RS_BLOCK_TABLE = [ // L
  6857. // M
  6858. // Q
  6859. // H
  6860. // 1
  6861. [ 1, 26, 19 ], [ 1, 26, 16 ], [ 1, 26, 13 ], [ 1, 26, 9 ], // 2
  6862. [ 1, 44, 34 ], [ 1, 44, 28 ], [ 1, 44, 22 ], [ 1, 44, 16 ], // 3
  6863. [ 1, 70, 55 ], [ 1, 70, 44 ], [ 2, 35, 17 ], [ 2, 35, 13 ], // 4
  6864. [ 1, 100, 80 ], [ 2, 50, 32 ], [ 2, 50, 24 ], [ 4, 25, 9 ], // 5
  6865. [ 1, 134, 108 ], [ 2, 67, 43 ], [ 2, 33, 15, 2, 34, 16 ], [ 2, 33, 11, 2, 34, 12 ], // 6
  6866. [ 2, 86, 68 ], [ 4, 43, 27 ], [ 4, 43, 19 ], [ 4, 43, 15 ], // 7
  6867. [ 2, 98, 78 ], [ 4, 49, 31 ], [ 2, 32, 14, 4, 33, 15 ], [ 4, 39, 13, 1, 40, 14 ], // 8
  6868. [ 2, 121, 97 ], [ 2, 60, 38, 2, 61, 39 ], [ 4, 40, 18, 2, 41, 19 ], [ 4, 40, 14, 2, 41, 15 ], // 9
  6869. [ 2, 146, 116 ], [ 3, 58, 36, 2, 59, 37 ], [ 4, 36, 16, 4, 37, 17 ], [ 4, 36, 12, 4, 37, 13 ], // 10
  6870. [ 2, 86, 68, 2, 87, 69 ], [ 4, 69, 43, 1, 70, 44 ], [ 6, 43, 19, 2, 44, 20 ], [ 6, 43, 15, 2, 44, 16 ], // 11
  6871. [ 4, 101, 81 ], [ 1, 80, 50, 4, 81, 51 ], [ 4, 50, 22, 4, 51, 23 ], [ 3, 36, 12, 8, 37, 13 ], // 12
  6872. [ 2, 116, 92, 2, 117, 93 ], [ 6, 58, 36, 2, 59, 37 ], [ 4, 46, 20, 6, 47, 21 ], [ 7, 42, 14, 4, 43, 15 ], // 13
  6873. [ 4, 133, 107 ], [ 8, 59, 37, 1, 60, 38 ], [ 8, 44, 20, 4, 45, 21 ], [ 12, 33, 11, 4, 34, 12 ], // 14
  6874. [ 3, 145, 115, 1, 146, 116 ], [ 4, 64, 40, 5, 65, 41 ], [ 11, 36, 16, 5, 37, 17 ], [ 11, 36, 12, 5, 37, 13 ], // 15
  6875. [ 5, 109, 87, 1, 110, 88 ], [ 5, 65, 41, 5, 66, 42 ], [ 5, 54, 24, 7, 55, 25 ], [ 11, 36, 12 ], // 16
  6876. [ 5, 122, 98, 1, 123, 99 ], [ 7, 73, 45, 3, 74, 46 ], [ 15, 43, 19, 2, 44, 20 ], [ 3, 45, 15, 13, 46, 16 ], // 17
  6877. [ 1, 135, 107, 5, 136, 108 ], [ 10, 74, 46, 1, 75, 47 ], [ 1, 50, 22, 15, 51, 23 ], [ 2, 42, 14, 17, 43, 15 ], // 18
  6878. [ 5, 150, 120, 1, 151, 121 ], [ 9, 69, 43, 4, 70, 44 ], [ 17, 50, 22, 1, 51, 23 ], [ 2, 42, 14, 19, 43, 15 ], // 19
  6879. [ 3, 141, 113, 4, 142, 114 ], [ 3, 70, 44, 11, 71, 45 ], [ 17, 47, 21, 4, 48, 22 ], [ 9, 39, 13, 16, 40, 14 ], // 20
  6880. [ 3, 135, 107, 5, 136, 108 ], [ 3, 67, 41, 13, 68, 42 ], [ 15, 54, 24, 5, 55, 25 ], [ 15, 43, 15, 10, 44, 16 ], // 21
  6881. [ 4, 144, 116, 4, 145, 117 ], [ 17, 68, 42 ], [ 17, 50, 22, 6, 51, 23 ], [ 19, 46, 16, 6, 47, 17 ], // 22
  6882. [ 2, 139, 111, 7, 140, 112 ], [ 17, 74, 46 ], [ 7, 54, 24, 16, 55, 25 ], [ 34, 37, 13 ], // 23
  6883. [ 4, 151, 121, 5, 152, 122 ], [ 4, 75, 47, 14, 76, 48 ], [ 11, 54, 24, 14, 55, 25 ], [ 16, 45, 15, 14, 46, 16 ], // 24
  6884. [ 6, 147, 117, 4, 148, 118 ], [ 6, 73, 45, 14, 74, 46 ], [ 11, 54, 24, 16, 55, 25 ], [ 30, 46, 16, 2, 47, 17 ], // 25
  6885. [ 8, 132, 106, 4, 133, 107 ], [ 8, 75, 47, 13, 76, 48 ], [ 7, 54, 24, 22, 55, 25 ], [ 22, 45, 15, 13, 46, 16 ], // 26
  6886. [ 10, 142, 114, 2, 143, 115 ], [ 19, 74, 46, 4, 75, 47 ], [ 28, 50, 22, 6, 51, 23 ], [ 33, 46, 16, 4, 47, 17 ], // 27
  6887. [ 8, 152, 122, 4, 153, 123 ], [ 22, 73, 45, 3, 74, 46 ], [ 8, 53, 23, 26, 54, 24 ], [ 12, 45, 15, 28, 46, 16 ], // 28
  6888. [ 3, 147, 117, 10, 148, 118 ], [ 3, 73, 45, 23, 74, 46 ], [ 4, 54, 24, 31, 55, 25 ], [ 11, 45, 15, 31, 46, 16 ], // 29
  6889. [ 7, 146, 116, 7, 147, 117 ], [ 21, 73, 45, 7, 74, 46 ], [ 1, 53, 23, 37, 54, 24 ], [ 19, 45, 15, 26, 46, 16 ], // 30
  6890. [ 5, 145, 115, 10, 146, 116 ], [ 19, 75, 47, 10, 76, 48 ], [ 15, 54, 24, 25, 55, 25 ], [ 23, 45, 15, 25, 46, 16 ], // 31
  6891. [ 13, 145, 115, 3, 146, 116 ], [ 2, 74, 46, 29, 75, 47 ], [ 42, 54, 24, 1, 55, 25 ], [ 23, 45, 15, 28, 46, 16 ], // 32
  6892. [ 17, 145, 115 ], [ 10, 74, 46, 23, 75, 47 ], [ 10, 54, 24, 35, 55, 25 ], [ 19, 45, 15, 35, 46, 16 ], // 33
  6893. [ 17, 145, 115, 1, 146, 116 ], [ 14, 74, 46, 21, 75, 47 ], [ 29, 54, 24, 19, 55, 25 ], [ 11, 45, 15, 46, 46, 16 ], // 34
  6894. [ 13, 145, 115, 6, 146, 116 ], [ 14, 74, 46, 23, 75, 47 ], [ 44, 54, 24, 7, 55, 25 ], [ 59, 46, 16, 1, 47, 17 ], // 35
  6895. [ 12, 151, 121, 7, 152, 122 ], [ 12, 75, 47, 26, 76, 48 ], [ 39, 54, 24, 14, 55, 25 ], [ 22, 45, 15, 41, 46, 16 ], // 36
  6896. [ 6, 151, 121, 14, 152, 122 ], [ 6, 75, 47, 34, 76, 48 ], [ 46, 54, 24, 10, 55, 25 ], [ 2, 45, 15, 64, 46, 16 ], // 37
  6897. [ 17, 152, 122, 4, 153, 123 ], [ 29, 74, 46, 14, 75, 47 ], [ 49, 54, 24, 10, 55, 25 ], [ 24, 45, 15, 46, 46, 16 ], // 38
  6898. [ 4, 152, 122, 18, 153, 123 ], [ 13, 74, 46, 32, 75, 47 ], [ 48, 54, 24, 14, 55, 25 ], [ 42, 45, 15, 32, 46, 16 ], // 39
  6899. [ 20, 147, 117, 4, 148, 118 ], [ 40, 75, 47, 7, 76, 48 ], [ 43, 54, 24, 22, 55, 25 ], [ 10, 45, 15, 67, 46, 16 ], // 40
  6900. [ 19, 148, 118, 6, 149, 119 ], [ 18, 75, 47, 31, 76, 48 ], [ 34, 54, 24, 34, 55, 25 ], [ 20, 45, 15, 61, 46, 16 ] ];
  6901. /**
  6902. * 根据数据获取对应版本
  6903. * @return {[type]} [description]
  6904. */
  6905. QRCodeAlg.prototype.getRightType = function() {
  6906. for (var typeNumber = 1; typeNumber < 41; typeNumber++) {
  6907. var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel];
  6908. if (rsBlock == undefined) {
  6909. throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel);
  6910. }
  6911. var length = rsBlock.length / 3;
  6912. var totalDataCount = 0;
  6913. for (var i = 0; i < length; i++) {
  6914. var count = rsBlock[i * 3 + 0];
  6915. var dataCount = rsBlock[i * 3 + 2];
  6916. totalDataCount += dataCount * count;
  6917. }
  6918. var lengthBytes = typeNumber > 9 ? 2 : 1;
  6919. if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) {
  6920. this.typeNumber = typeNumber;
  6921. this.rsBlock = rsBlock;
  6922. this.totalDataCount = totalDataCount;
  6923. break;
  6924. }
  6925. }
  6926. };
  6927. //---------------------------------------------------------------------
  6928. // QRBitBuffer
  6929. //---------------------------------------------------------------------
  6930. function QRBitBuffer() {
  6931. this.buffer = new Array();
  6932. this.length = 0;
  6933. }
  6934. QRBitBuffer.prototype = {
  6935. get: function(index) {
  6936. var bufIndex = Math.floor(index / 8);
  6937. return this.buffer[bufIndex] >>> 7 - index % 8 & 1;
  6938. },
  6939. put: function(num, length) {
  6940. for (var i = 0; i < length; i++) {
  6941. this.putBit(num >>> length - i - 1 & 1);
  6942. }
  6943. },
  6944. putBit: function(bit) {
  6945. var bufIndex = Math.floor(this.length / 8);
  6946. if (this.buffer.length <= bufIndex) {
  6947. this.buffer.push(0);
  6948. }
  6949. if (bit) {
  6950. this.buffer[bufIndex] |= 128 >>> this.length % 8;
  6951. }
  6952. this.length++;
  6953. }
  6954. };
  6955. /**
  6956. * 获取单个字符的utf8编码
  6957. * unicode BMP平面约65535个字符
  6958. * @param {num} code
  6959. * return {array}
  6960. */
  6961. function unicodeFormat8(code) {
  6962. // 1 byte
  6963. if (code < 128) {
  6964. return [ code ];
  6965. } else if (code < 2048) {
  6966. c0 = 192 + (code >> 6);
  6967. c1 = 128 + (code & 63);
  6968. return [ c0, c1 ];
  6969. } else {
  6970. c0 = 224 + (code >> 12);
  6971. c1 = 128 + (code >> 6 & 63);
  6972. c2 = 128 + (code & 63);
  6973. return [ c0, c1, c2 ];
  6974. }
  6975. }
  6976. /**
  6977. * 获取字符串的utf8编码字节串
  6978. * @param {string} string
  6979. * @return {array}
  6980. */
  6981. function getUTF8Bytes(string) {
  6982. var utf8codes = [];
  6983. for (var i = 0; i < string.length; i++) {
  6984. var code = string.charCodeAt(i);
  6985. var utf8 = unicodeFormat8(code);
  6986. for (var j = 0; j < utf8.length; j++) {
  6987. utf8codes.push(utf8[j]);
  6988. }
  6989. }
  6990. return utf8codes;
  6991. }
  6992. /**
  6993. * 二维码算法实现
  6994. * @param {string} data 要编码的信息字符串
  6995. * @param {num} errorCorrectLevel 纠错等级
  6996. */
  6997. function QRCodeAlg(data, errorCorrectLevel) {
  6998. this.typeNumber = -1;
  6999. //版本
  7000. this.errorCorrectLevel = errorCorrectLevel;
  7001. this.modules = null;
  7002. //二维矩阵,存放最终结果
  7003. this.moduleCount = 0;
  7004. //矩阵大小
  7005. this.dataCache = null;
  7006. //数据缓存
  7007. this.rsBlocks = null;
  7008. //版本数据信息
  7009. this.totalDataCount = -1;
  7010. //可使用的数据量
  7011. this.data = data;
  7012. this.utf8bytes = getUTF8Bytes(data);
  7013. this.make();
  7014. }
  7015. QRCodeAlg.prototype = {
  7016. constructor: QRCodeAlg,
  7017. /**
  7018. * 获取二维码矩阵大小
  7019. * @return {num} 矩阵大小
  7020. */
  7021. getModuleCount: function() {
  7022. return this.moduleCount;
  7023. },
  7024. /**
  7025. * 编码
  7026. */
  7027. make: function() {
  7028. this.getRightType();
  7029. this.dataCache = this.createData();
  7030. this.createQrcode();
  7031. },
  7032. /**
  7033. * 设置二位矩阵功能图形
  7034. * @param {bool} test 表示是否在寻找最好掩膜阶段
  7035. * @param {num} maskPattern 掩膜的版本
  7036. */
  7037. makeImpl: function(maskPattern) {
  7038. this.moduleCount = this.typeNumber * 4 + 17;
  7039. this.modules = new Array(this.moduleCount);
  7040. for (var row = 0; row < this.moduleCount; row++) {
  7041. this.modules[row] = new Array(this.moduleCount);
  7042. }
  7043. this.setupPositionProbePattern(0, 0);
  7044. this.setupPositionProbePattern(this.moduleCount - 7, 0);
  7045. this.setupPositionProbePattern(0, this.moduleCount - 7);
  7046. this.setupPositionAdjustPattern();
  7047. this.setupTimingPattern();
  7048. this.setupTypeInfo(true, maskPattern);
  7049. if (this.typeNumber >= 7) {
  7050. this.setupTypeNumber(true);
  7051. }
  7052. this.mapData(this.dataCache, maskPattern);
  7053. },
  7054. /**
  7055. * 设置二维码的位置探测图形
  7056. * @param {num} row 探测图形的中心横坐标
  7057. * @param {num} col 探测图形的中心纵坐标
  7058. */
  7059. setupPositionProbePattern: function(row, col) {
  7060. for (var r = -1; r <= 7; r++) {
  7061. if (row + r <= -1 || this.moduleCount <= row + r) continue;
  7062. for (var c = -1; c <= 7; c++) {
  7063. if (col + c <= -1 || this.moduleCount <= col + c) continue;
  7064. if (0 <= r && r <= 6 && (c == 0 || c == 6) || 0 <= c && c <= 6 && (r == 0 || r == 6) || 2 <= r && r <= 4 && 2 <= c && c <= 4) {
  7065. this.modules[row + r][col + c] = true;
  7066. } else {
  7067. this.modules[row + r][col + c] = false;
  7068. }
  7069. }
  7070. }
  7071. },
  7072. /**
  7073. * 创建二维码
  7074. * @return {[type]} [description]
  7075. */
  7076. createQrcode: function() {
  7077. var minLostPoint = 0;
  7078. var pattern = 0;
  7079. var bestModules = null;
  7080. for (var i = 0; i < 8; i++) {
  7081. this.makeImpl(i);
  7082. var lostPoint = QRUtil.getLostPoint(this);
  7083. if (i == 0 || minLostPoint > lostPoint) {
  7084. minLostPoint = lostPoint;
  7085. pattern = i;
  7086. bestModules = this.modules;
  7087. }
  7088. }
  7089. this.modules = bestModules;
  7090. this.setupTypeInfo(false, pattern);
  7091. if (this.typeNumber >= 7) {
  7092. this.setupTypeNumber(false);
  7093. }
  7094. },
  7095. /**
  7096. * 设置定位图形
  7097. * @return {[type]} [description]
  7098. */
  7099. setupTimingPattern: function() {
  7100. for (var r = 8; r < this.moduleCount - 8; r++) {
  7101. if (this.modules[r][6] != null) {
  7102. continue;
  7103. }
  7104. this.modules[r][6] = r % 2 == 0;
  7105. if (this.modules[6][r] != null) {
  7106. continue;
  7107. }
  7108. this.modules[6][r] = r % 2 == 0;
  7109. }
  7110. },
  7111. /**
  7112. * 设置矫正图形
  7113. * @return {[type]} [description]
  7114. */
  7115. setupPositionAdjustPattern: function() {
  7116. var pos = QRUtil.getPatternPosition(this.typeNumber);
  7117. for (var i = 0; i < pos.length; i++) {
  7118. for (var j = 0; j < pos.length; j++) {
  7119. var row = pos[i];
  7120. var col = pos[j];
  7121. if (this.modules[row][col] != null) {
  7122. continue;
  7123. }
  7124. for (var r = -2; r <= 2; r++) {
  7125. for (var c = -2; c <= 2; c++) {
  7126. if (r == -2 || r == 2 || c == -2 || c == 2 || r == 0 && c == 0) {
  7127. this.modules[row + r][col + c] = true;
  7128. } else {
  7129. this.modules[row + r][col + c] = false;
  7130. }
  7131. }
  7132. }
  7133. }
  7134. }
  7135. },
  7136. /**
  7137. * 设置版本信息(7以上版本才有)
  7138. * @param {bool} test 是否处于判断最佳掩膜阶段
  7139. * @return {[type]} [description]
  7140. */
  7141. setupTypeNumber: function(test) {
  7142. var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
  7143. for (var i = 0; i < 18; i++) {
  7144. var mod = !test && (bits >> i & 1) == 1;
  7145. this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
  7146. this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
  7147. }
  7148. },
  7149. /**
  7150. * 设置格式信息(纠错等级和掩膜版本)
  7151. * @param {bool} test
  7152. * @param {num} maskPattern 掩膜版本
  7153. * @return {}
  7154. */
  7155. setupTypeInfo: function(test, maskPattern) {
  7156. var data = QRErrorCorrectLevel[this.errorCorrectLevel] << 3 | maskPattern;
  7157. var bits = QRUtil.getBCHTypeInfo(data);
  7158. // vertical
  7159. for (var i = 0; i < 15; i++) {
  7160. var mod = !test && (bits >> i & 1) == 1;
  7161. if (i < 6) {
  7162. this.modules[i][8] = mod;
  7163. } else if (i < 8) {
  7164. this.modules[i + 1][8] = mod;
  7165. } else {
  7166. this.modules[this.moduleCount - 15 + i][8] = mod;
  7167. }
  7168. // horizontal
  7169. var mod = !test && (bits >> i & 1) == 1;
  7170. if (i < 8) {
  7171. this.modules[8][this.moduleCount - i - 1] = mod;
  7172. } else if (i < 9) {
  7173. this.modules[8][15 - i - 1 + 1] = mod;
  7174. } else {
  7175. this.modules[8][15 - i - 1] = mod;
  7176. }
  7177. }
  7178. // fixed module
  7179. this.modules[this.moduleCount - 8][8] = !test;
  7180. },
  7181. /**
  7182. * 数据编码
  7183. * @return {[type]} [description]
  7184. */
  7185. createData: function() {
  7186. var buffer = new QRBitBuffer();
  7187. var lengthBits = this.typeNumber > 9 ? 16 : 8;
  7188. buffer.put(4, 4);
  7189. //添加模式
  7190. buffer.put(this.utf8bytes.length, lengthBits);
  7191. for (var i = 0, l = this.utf8bytes.length; i < l; i++) {
  7192. buffer.put(this.utf8bytes[i], 8);
  7193. }
  7194. if (buffer.length + 4 <= this.totalDataCount * 8) {
  7195. buffer.put(0, 4);
  7196. }
  7197. // padding
  7198. while (buffer.length % 8 != 0) {
  7199. buffer.putBit(false);
  7200. }
  7201. // padding
  7202. while (true) {
  7203. if (buffer.length >= this.totalDataCount * 8) {
  7204. break;
  7205. }
  7206. buffer.put(QRCodeAlg.PAD0, 8);
  7207. if (buffer.length >= this.totalDataCount * 8) {
  7208. break;
  7209. }
  7210. buffer.put(QRCodeAlg.PAD1, 8);
  7211. }
  7212. return this.createBytes(buffer);
  7213. },
  7214. /**
  7215. * 纠错码编码
  7216. * @param {buffer} buffer 数据编码
  7217. * @return {[type]}
  7218. */
  7219. createBytes: function(buffer) {
  7220. var offset = 0;
  7221. var maxDcCount = 0;
  7222. var maxEcCount = 0;
  7223. var length = this.rsBlock.length / 3;
  7224. var rsBlocks = new Array();
  7225. for (var i = 0; i < length; i++) {
  7226. var count = this.rsBlock[i * 3 + 0];
  7227. var totalCount = this.rsBlock[i * 3 + 1];
  7228. var dataCount = this.rsBlock[i * 3 + 2];
  7229. for (var j = 0; j < count; j++) {
  7230. rsBlocks.push([ dataCount, totalCount ]);
  7231. }
  7232. }
  7233. var dcdata = new Array(rsBlocks.length);
  7234. var ecdata = new Array(rsBlocks.length);
  7235. for (var r = 0; r < rsBlocks.length; r++) {
  7236. var dcCount = rsBlocks[r][0];
  7237. var ecCount = rsBlocks[r][1] - dcCount;
  7238. maxDcCount = Math.max(maxDcCount, dcCount);
  7239. maxEcCount = Math.max(maxEcCount, ecCount);
  7240. dcdata[r] = new Array(dcCount);
  7241. for (var i = 0; i < dcdata[r].length; i++) {
  7242. dcdata[r][i] = 255 & buffer.buffer[i + offset];
  7243. }
  7244. offset += dcCount;
  7245. var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
  7246. var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
  7247. var modPoly = rawPoly.mod(rsPoly);
  7248. ecdata[r] = new Array(rsPoly.getLength() - 1);
  7249. for (var i = 0; i < ecdata[r].length; i++) {
  7250. var modIndex = i + modPoly.getLength() - ecdata[r].length;
  7251. ecdata[r][i] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
  7252. }
  7253. }
  7254. var data = new Array(this.totalDataCount);
  7255. var index = 0;
  7256. for (var i = 0; i < maxDcCount; i++) {
  7257. for (var r = 0; r < rsBlocks.length; r++) {
  7258. if (i < dcdata[r].length) {
  7259. data[index++] = dcdata[r][i];
  7260. }
  7261. }
  7262. }
  7263. for (var i = 0; i < maxEcCount; i++) {
  7264. for (var r = 0; r < rsBlocks.length; r++) {
  7265. if (i < ecdata[r].length) {
  7266. data[index++] = ecdata[r][i];
  7267. }
  7268. }
  7269. }
  7270. return data;
  7271. },
  7272. /**
  7273. * 布置模块,构建最终信息
  7274. * @param {} data
  7275. * @param {} maskPattern
  7276. * @return {}
  7277. */
  7278. mapData: function(data, maskPattern) {
  7279. var inc = -1;
  7280. var row = this.moduleCount - 1;
  7281. var bitIndex = 7;
  7282. var byteIndex = 0;
  7283. for (var col = this.moduleCount - 1; col > 0; col -= 2) {
  7284. if (col == 6) col--;
  7285. while (true) {
  7286. for (var c = 0; c < 2; c++) {
  7287. if (this.modules[row][col - c] == null) {
  7288. var dark = false;
  7289. if (byteIndex < data.length) {
  7290. dark = (data[byteIndex] >>> bitIndex & 1) == 1;
  7291. }
  7292. var mask = QRUtil.getMask(maskPattern, row, col - c);
  7293. if (mask) {
  7294. dark = !dark;
  7295. }
  7296. this.modules[row][col - c] = dark;
  7297. bitIndex--;
  7298. if (bitIndex == -1) {
  7299. byteIndex++;
  7300. bitIndex = 7;
  7301. }
  7302. }
  7303. }
  7304. row += inc;
  7305. if (row < 0 || this.moduleCount <= row) {
  7306. row -= inc;
  7307. inc = -inc;
  7308. break;
  7309. }
  7310. }
  7311. }
  7312. }
  7313. };
  7314. /**
  7315. * 填充字段
  7316. */
  7317. QRCodeAlg.PAD0 = 236;
  7318. QRCodeAlg.PAD1 = 17;
  7319. //---------------------------------------------------------------------
  7320. // 纠错等级对应的编码
  7321. //---------------------------------------------------------------------
  7322. var QRErrorCorrectLevel = [ 1, 0, 3, 2 ];
  7323. //---------------------------------------------------------------------
  7324. // 掩膜版本
  7325. //---------------------------------------------------------------------
  7326. var QRMaskPattern = {
  7327. PATTERN000: 0,
  7328. PATTERN001: 1,
  7329. PATTERN010: 2,
  7330. PATTERN011: 3,
  7331. PATTERN100: 4,
  7332. PATTERN101: 5,
  7333. PATTERN110: 6,
  7334. PATTERN111: 7
  7335. };
  7336. //---------------------------------------------------------------------
  7337. // 工具类
  7338. //---------------------------------------------------------------------
  7339. var QRUtil = {
  7340. /*
  7341. 每个版本矫正图形的位置
  7342. */
  7343. PATTERN_POSITION_TABLE: [ [], [ 6, 18 ], [ 6, 22 ], [ 6, 26 ], [ 6, 30 ], [ 6, 34 ], [ 6, 22, 38 ], [ 6, 24, 42 ], [ 6, 26, 46 ], [ 6, 28, 50 ], [ 6, 30, 54 ], [ 6, 32, 58 ], [ 6, 34, 62 ], [ 6, 26, 46, 66 ], [ 6, 26, 48, 70 ], [ 6, 26, 50, 74 ], [ 6, 30, 54, 78 ], [ 6, 30, 56, 82 ], [ 6, 30, 58, 86 ], [ 6, 34, 62, 90 ], [ 6, 28, 50, 72, 94 ], [ 6, 26, 50, 74, 98 ], [ 6, 30, 54, 78, 102 ], [ 6, 28, 54, 80, 106 ], [ 6, 32, 58, 84, 110 ], [ 6, 30, 58, 86, 114 ], [ 6, 34, 62, 90, 118 ], [ 6, 26, 50, 74, 98, 122 ], [ 6, 30, 54, 78, 102, 126 ], [ 6, 26, 52, 78, 104, 130 ], [ 6, 30, 56, 82, 108, 134 ], [ 6, 34, 60, 86, 112, 138 ], [ 6, 30, 58, 86, 114, 142 ], [ 6, 34, 62, 90, 118, 146 ], [ 6, 30, 54, 78, 102, 126, 150 ], [ 6, 24, 50, 76, 102, 128, 154 ], [ 6, 28, 54, 80, 106, 132, 158 ], [ 6, 32, 58, 84, 110, 136, 162 ], [ 6, 26, 54, 82, 110, 138, 166 ], [ 6, 30, 58, 86, 114, 142, 170 ] ],
  7344. G15: 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0,
  7345. G18: 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0,
  7346. G15_MASK: 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1,
  7347. /*
  7348. BCH编码格式信息
  7349. */
  7350. getBCHTypeInfo: function(data) {
  7351. var d = data << 10;
  7352. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
  7353. d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);
  7354. }
  7355. return (data << 10 | d) ^ QRUtil.G15_MASK;
  7356. },
  7357. /*
  7358. BCH编码版本信息
  7359. */
  7360. getBCHTypeNumber: function(data) {
  7361. var d = data << 12;
  7362. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
  7363. d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);
  7364. }
  7365. return data << 12 | d;
  7366. },
  7367. /*
  7368. 获取BCH位信息
  7369. */
  7370. getBCHDigit: function(data) {
  7371. var digit = 0;
  7372. while (data != 0) {
  7373. digit++;
  7374. data >>>= 1;
  7375. }
  7376. return digit;
  7377. },
  7378. /*
  7379. 获取版本对应的矫正图形位置
  7380. */
  7381. getPatternPosition: function(typeNumber) {
  7382. return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
  7383. },
  7384. /*
  7385. 掩膜算法
  7386. */
  7387. getMask: function(maskPattern, i, j) {
  7388. switch (maskPattern) {
  7389. case QRMaskPattern.PATTERN000:
  7390. return (i + j) % 2 == 0;
  7391. case QRMaskPattern.PATTERN001:
  7392. return i % 2 == 0;
  7393. case QRMaskPattern.PATTERN010:
  7394. return j % 3 == 0;
  7395. case QRMaskPattern.PATTERN011:
  7396. return (i + j) % 3 == 0;
  7397. case QRMaskPattern.PATTERN100:
  7398. return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
  7399. case QRMaskPattern.PATTERN101:
  7400. return i * j % 2 + i * j % 3 == 0;
  7401. case QRMaskPattern.PATTERN110:
  7402. return (i * j % 2 + i * j % 3) % 2 == 0;
  7403. case QRMaskPattern.PATTERN111:
  7404. return (i * j % 3 + (i + j) % 2) % 2 == 0;
  7405. default:
  7406. throw new Error("bad maskPattern:" + maskPattern);
  7407. }
  7408. },
  7409. /*
  7410. 获取RS的纠错多项式
  7411. */
  7412. getErrorCorrectPolynomial: function(errorCorrectLength) {
  7413. var a = new QRPolynomial([ 1 ], 0);
  7414. for (var i = 0; i < errorCorrectLength; i++) {
  7415. a = a.multiply(new QRPolynomial([ 1, QRMath.gexp(i) ], 0));
  7416. }
  7417. return a;
  7418. },
  7419. /*
  7420. 获取评价
  7421. */
  7422. getLostPoint: function(qrCode) {
  7423. var moduleCount = qrCode.getModuleCount(), lostPoint = 0, darkCount = 0;
  7424. for (var row = 0; row < moduleCount; row++) {
  7425. var sameCount = 0;
  7426. var head = qrCode.modules[row][0];
  7427. for (var col = 0; col < moduleCount; col++) {
  7428. var current = qrCode.modules[row][col];
  7429. //level 3 评价
  7430. if (col < moduleCount - 6) {
  7431. if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) {
  7432. if (col < moduleCount - 10) {
  7433. if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) {
  7434. lostPoint += 40;
  7435. }
  7436. } else if (col > 3) {
  7437. if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) {
  7438. lostPoint += 40;
  7439. }
  7440. }
  7441. }
  7442. }
  7443. //level 2 评价
  7444. if (row < moduleCount - 1 && col < moduleCount - 1) {
  7445. var count = 0;
  7446. if (current) count++;
  7447. if (qrCode.modules[row + 1][col]) count++;
  7448. if (qrCode.modules[row][col + 1]) count++;
  7449. if (qrCode.modules[row + 1][col + 1]) count++;
  7450. if (count == 0 || count == 4) {
  7451. lostPoint += 3;
  7452. }
  7453. }
  7454. //level 1 评价
  7455. if (head ^ current) {
  7456. sameCount++;
  7457. } else {
  7458. head = current;
  7459. if (sameCount >= 5) {
  7460. lostPoint += 3 + sameCount - 5;
  7461. }
  7462. sameCount = 1;
  7463. }
  7464. //level 4 评价
  7465. if (current) {
  7466. darkCount++;
  7467. }
  7468. }
  7469. }
  7470. for (var col = 0; col < moduleCount; col++) {
  7471. var sameCount = 0;
  7472. var head = qrCode.modules[0][col];
  7473. for (var row = 0; row < moduleCount; row++) {
  7474. var current = qrCode.modules[row][col];
  7475. //level 3 评价
  7476. if (row < moduleCount - 6) {
  7477. if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) {
  7478. if (row < moduleCount - 10) {
  7479. if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) {
  7480. lostPoint += 40;
  7481. }
  7482. } else if (row > 3) {
  7483. if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) {
  7484. lostPoint += 40;
  7485. }
  7486. }
  7487. }
  7488. }
  7489. //level 1 评价
  7490. if (head ^ current) {
  7491. sameCount++;
  7492. } else {
  7493. head = current;
  7494. if (sameCount >= 5) {
  7495. lostPoint += 3 + sameCount - 5;
  7496. }
  7497. sameCount = 1;
  7498. }
  7499. }
  7500. }
  7501. // LEVEL4
  7502. var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
  7503. lostPoint += ratio * 10;
  7504. return lostPoint;
  7505. }
  7506. };
  7507. //---------------------------------------------------------------------
  7508. // QRMath使用的数学工具
  7509. //---------------------------------------------------------------------
  7510. var QRMath = {
  7511. /*
  7512. 将n转化为a^m
  7513. */
  7514. glog: function(n) {
  7515. if (n < 1) {
  7516. throw new Error("glog(" + n + ")");
  7517. }
  7518. return QRMath.LOG_TABLE[n];
  7519. },
  7520. /*
  7521. 将a^m转化为n
  7522. */
  7523. gexp: function(n) {
  7524. while (n < 0) {
  7525. n += 255;
  7526. }
  7527. while (n >= 256) {
  7528. n -= 255;
  7529. }
  7530. return QRMath.EXP_TABLE[n];
  7531. },
  7532. EXP_TABLE: new Array(256),
  7533. LOG_TABLE: new Array(256)
  7534. };
  7535. for (var i = 0; i < 8; i++) {
  7536. QRMath.EXP_TABLE[i] = 1 << i;
  7537. }
  7538. for (var i = 8; i < 256; i++) {
  7539. QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
  7540. }
  7541. for (var i = 0; i < 255; i++) {
  7542. QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
  7543. }
  7544. //---------------------------------------------------------------------
  7545. // QRPolynomial 多项式
  7546. //---------------------------------------------------------------------
  7547. /**
  7548. * 多项式类
  7549. * @param {Array} num 系数
  7550. * @param {num} shift a^shift
  7551. */
  7552. function QRPolynomial(num, shift) {
  7553. if (num.length == undefined) {
  7554. throw new Error(num.length + "/" + shift);
  7555. }
  7556. var offset = 0;
  7557. while (offset < num.length && num[offset] == 0) {
  7558. offset++;
  7559. }
  7560. this.num = new Array(num.length - offset + shift);
  7561. for (var i = 0; i < num.length - offset; i++) {
  7562. this.num[i] = num[i + offset];
  7563. }
  7564. }
  7565. QRPolynomial.prototype = {
  7566. get: function(index) {
  7567. return this.num[index];
  7568. },
  7569. getLength: function() {
  7570. return this.num.length;
  7571. },
  7572. /**
  7573. * 多项式乘法
  7574. * @param {QRPolynomial} e 被乘多项式
  7575. * @return {[type]} [description]
  7576. */
  7577. multiply: function(e) {
  7578. var num = new Array(this.getLength() + e.getLength() - 1);
  7579. for (var i = 0; i < this.getLength(); i++) {
  7580. for (var j = 0; j < e.getLength(); j++) {
  7581. num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
  7582. }
  7583. }
  7584. return new QRPolynomial(num, 0);
  7585. },
  7586. /**
  7587. * 多项式模运算
  7588. * @param {QRPolynomial} e 模多项式
  7589. * @return {}
  7590. */
  7591. mod: function(e) {
  7592. var tl = this.getLength(), el = e.getLength();
  7593. if (tl - el < 0) {
  7594. return this;
  7595. }
  7596. var num = new Array(tl);
  7597. for (var i = 0; i < tl; i++) {
  7598. num[i] = this.get(i);
  7599. }
  7600. while (num.length >= el) {
  7601. var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0));
  7602. for (var i = 0; i < e.getLength(); i++) {
  7603. num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
  7604. }
  7605. while (num[0] == 0) {
  7606. num.shift();
  7607. }
  7608. }
  7609. return new QRPolynomial(num, 0);
  7610. }
  7611. };
  7612. //---------------------------------------------------------------------
  7613. // RS_BLOCK_TABLE
  7614. //---------------------------------------------------------------------
  7615. /*
  7616. 二维码各个版本信息[块数, 每块中的数据块数, 每块中的信息块数]
  7617. */
  7618. RS_BLOCK_TABLE = [ // L
  7619. // M
  7620. // Q
  7621. // H
  7622. // 1
  7623. [ 1, 26, 19 ], [ 1, 26, 16 ], [ 1, 26, 13 ], [ 1, 26, 9 ], // 2
  7624. [ 1, 44, 34 ], [ 1, 44, 28 ], [ 1, 44, 22 ], [ 1, 44, 16 ], // 3
  7625. [ 1, 70, 55 ], [ 1, 70, 44 ], [ 2, 35, 17 ], [ 2, 35, 13 ], // 4
  7626. [ 1, 100, 80 ], [ 2, 50, 32 ], [ 2, 50, 24 ], [ 4, 25, 9 ], // 5
  7627. [ 1, 134, 108 ], [ 2, 67, 43 ], [ 2, 33, 15, 2, 34, 16 ], [ 2, 33, 11, 2, 34, 12 ], // 6
  7628. [ 2, 86, 68 ], [ 4, 43, 27 ], [ 4, 43, 19 ], [ 4, 43, 15 ], // 7
  7629. [ 2, 98, 78 ], [ 4, 49, 31 ], [ 2, 32, 14, 4, 33, 15 ], [ 4, 39, 13, 1, 40, 14 ], // 8
  7630. [ 2, 121, 97 ], [ 2, 60, 38, 2, 61, 39 ], [ 4, 40, 18, 2, 41, 19 ], [ 4, 40, 14, 2, 41, 15 ], // 9
  7631. [ 2, 146, 116 ], [ 3, 58, 36, 2, 59, 37 ], [ 4, 36, 16, 4, 37, 17 ], [ 4, 36, 12, 4, 37, 13 ], // 10
  7632. [ 2, 86, 68, 2, 87, 69 ], [ 4, 69, 43, 1, 70, 44 ], [ 6, 43, 19, 2, 44, 20 ], [ 6, 43, 15, 2, 44, 16 ], // 11
  7633. [ 4, 101, 81 ], [ 1, 80, 50, 4, 81, 51 ], [ 4, 50, 22, 4, 51, 23 ], [ 3, 36, 12, 8, 37, 13 ], // 12
  7634. [ 2, 116, 92, 2, 117, 93 ], [ 6, 58, 36, 2, 59, 37 ], [ 4, 46, 20, 6, 47, 21 ], [ 7, 42, 14, 4, 43, 15 ], // 13
  7635. [ 4, 133, 107 ], [ 8, 59, 37, 1, 60, 38 ], [ 8, 44, 20, 4, 45, 21 ], [ 12, 33, 11, 4, 34, 12 ], // 14
  7636. [ 3, 145, 115, 1, 146, 116 ], [ 4, 64, 40, 5, 65, 41 ], [ 11, 36, 16, 5, 37, 17 ], [ 11, 36, 12, 5, 37, 13 ], // 15
  7637. [ 5, 109, 87, 1, 110, 88 ], [ 5, 65, 41, 5, 66, 42 ], [ 5, 54, 24, 7, 55, 25 ], [ 11, 36, 12 ], // 16
  7638. [ 5, 122, 98, 1, 123, 99 ], [ 7, 73, 45, 3, 74, 46 ], [ 15, 43, 19, 2, 44, 20 ], [ 3, 45, 15, 13, 46, 16 ], // 17
  7639. [ 1, 135, 107, 5, 136, 108 ], [ 10, 74, 46, 1, 75, 47 ], [ 1, 50, 22, 15, 51, 23 ], [ 2, 42, 14, 17, 43, 15 ], // 18
  7640. [ 5, 150, 120, 1, 151, 121 ], [ 9, 69, 43, 4, 70, 44 ], [ 17, 50, 22, 1, 51, 23 ], [ 2, 42, 14, 19, 43, 15 ], // 19
  7641. [ 3, 141, 113, 4, 142, 114 ], [ 3, 70, 44, 11, 71, 45 ], [ 17, 47, 21, 4, 48, 22 ], [ 9, 39, 13, 16, 40, 14 ], // 20
  7642. [ 3, 135, 107, 5, 136, 108 ], [ 3, 67, 41, 13, 68, 42 ], [ 15, 54, 24, 5, 55, 25 ], [ 15, 43, 15, 10, 44, 16 ], // 21
  7643. [ 4, 144, 116, 4, 145, 117 ], [ 17, 68, 42 ], [ 17, 50, 22, 6, 51, 23 ], [ 19, 46, 16, 6, 47, 17 ], // 22
  7644. [ 2, 139, 111, 7, 140, 112 ], [ 17, 74, 46 ], [ 7, 54, 24, 16, 55, 25 ], [ 34, 37, 13 ], // 23
  7645. [ 4, 151, 121, 5, 152, 122 ], [ 4, 75, 47, 14, 76, 48 ], [ 11, 54, 24, 14, 55, 25 ], [ 16, 45, 15, 14, 46, 16 ], // 24
  7646. [ 6, 147, 117, 4, 148, 118 ], [ 6, 73, 45, 14, 74, 46 ], [ 11, 54, 24, 16, 55, 25 ], [ 30, 46, 16, 2, 47, 17 ], // 25
  7647. [ 8, 132, 106, 4, 133, 107 ], [ 8, 75, 47, 13, 76, 48 ], [ 7, 54, 24, 22, 55, 25 ], [ 22, 45, 15, 13, 46, 16 ], // 26
  7648. [ 10, 142, 114, 2, 143, 115 ], [ 19, 74, 46, 4, 75, 47 ], [ 28, 50, 22, 6, 51, 23 ], [ 33, 46, 16, 4, 47, 17 ], // 27
  7649. [ 8, 152, 122, 4, 153, 123 ], [ 22, 73, 45, 3, 74, 46 ], [ 8, 53, 23, 26, 54, 24 ], [ 12, 45, 15, 28, 46, 16 ], // 28
  7650. [ 3, 147, 117, 10, 148, 118 ], [ 3, 73, 45, 23, 74, 46 ], [ 4, 54, 24, 31, 55, 25 ], [ 11, 45, 15, 31, 46, 16 ], // 29
  7651. [ 7, 146, 116, 7, 147, 117 ], [ 21, 73, 45, 7, 74, 46 ], [ 1, 53, 23, 37, 54, 24 ], [ 19, 45, 15, 26, 46, 16 ], // 30
  7652. [ 5, 145, 115, 10, 146, 116 ], [ 19, 75, 47, 10, 76, 48 ], [ 15, 54, 24, 25, 55, 25 ], [ 23, 45, 15, 25, 46, 16 ], // 31
  7653. [ 13, 145, 115, 3, 146, 116 ], [ 2, 74, 46, 29, 75, 47 ], [ 42, 54, 24, 1, 55, 25 ], [ 23, 45, 15, 28, 46, 16 ], // 32
  7654. [ 17, 145, 115 ], [ 10, 74, 46, 23, 75, 47 ], [ 10, 54, 24, 35, 55, 25 ], [ 19, 45, 15, 35, 46, 16 ], // 33
  7655. [ 17, 145, 115, 1, 146, 116 ], [ 14, 74, 46, 21, 75, 47 ], [ 29, 54, 24, 19, 55, 25 ], [ 11, 45, 15, 46, 46, 16 ], // 34
  7656. [ 13, 145, 115, 6, 146, 116 ], [ 14, 74, 46, 23, 75, 47 ], [ 44, 54, 24, 7, 55, 25 ], [ 59, 46, 16, 1, 47, 17 ], // 35
  7657. [ 12, 151, 121, 7, 152, 122 ], [ 12, 75, 47, 26, 76, 48 ], [ 39, 54, 24, 14, 55, 25 ], [ 22, 45, 15, 41, 46, 16 ], // 36
  7658. [ 6, 151, 121, 14, 152, 122 ], [ 6, 75, 47, 34, 76, 48 ], [ 46, 54, 24, 10, 55, 25 ], [ 2, 45, 15, 64, 46, 16 ], // 37
  7659. [ 17, 152, 122, 4, 153, 123 ], [ 29, 74, 46, 14, 75, 47 ], [ 49, 54, 24, 10, 55, 25 ], [ 24, 45, 15, 46, 46, 16 ], // 38
  7660. [ 4, 152, 122, 18, 153, 123 ], [ 13, 74, 46, 32, 75, 47 ], [ 48, 54, 24, 14, 55, 25 ], [ 42, 45, 15, 32, 46, 16 ], // 39
  7661. [ 20, 147, 117, 4, 148, 118 ], [ 40, 75, 47, 7, 76, 48 ], [ 43, 54, 24, 22, 55, 25 ], [ 10, 45, 15, 67, 46, 16 ], // 40
  7662. [ 19, 148, 118, 6, 149, 119 ], [ 18, 75, 47, 31, 76, 48 ], [ 34, 54, 24, 34, 55, 25 ], [ 20, 45, 15, 61, 46, 16 ] ];
  7663. /**
  7664. * 根据数据获取对应版本
  7665. * @return {[type]} [description]
  7666. */
  7667. QRCodeAlg.prototype.getRightType = function() {
  7668. for (var typeNumber = 1; typeNumber < 41; typeNumber++) {
  7669. var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel];
  7670. if (rsBlock == undefined) {
  7671. throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel);
  7672. }
  7673. var length = rsBlock.length / 3;
  7674. var totalDataCount = 0;
  7675. for (var i = 0; i < length; i++) {
  7676. var count = rsBlock[i * 3 + 0];
  7677. var dataCount = rsBlock[i * 3 + 2];
  7678. totalDataCount += dataCount * count;
  7679. }
  7680. var lengthBytes = typeNumber > 9 ? 2 : 1;
  7681. if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) {
  7682. this.typeNumber = typeNumber;
  7683. this.rsBlock = rsBlock;
  7684. this.totalDataCount = totalDataCount;
  7685. break;
  7686. }
  7687. }
  7688. };
  7689. //---------------------------------------------------------------------
  7690. // QRBitBuffer
  7691. //---------------------------------------------------------------------
  7692. function QRBitBuffer() {
  7693. this.buffer = new Array();
  7694. this.length = 0;
  7695. }
  7696. QRBitBuffer.prototype = {
  7697. get: function(index) {
  7698. var bufIndex = Math.floor(index / 8);
  7699. return this.buffer[bufIndex] >>> 7 - index % 8 & 1;
  7700. },
  7701. put: function(num, length) {
  7702. for (var i = 0; i < length; i++) {
  7703. this.putBit(num >>> length - i - 1 & 1);
  7704. }
  7705. },
  7706. putBit: function(bit) {
  7707. var bufIndex = Math.floor(this.length / 8);
  7708. if (this.buffer.length <= bufIndex) {
  7709. this.buffer.push(0);
  7710. }
  7711. if (bit) {
  7712. this.buffer[bufIndex] |= 128 >>> this.length % 8;
  7713. }
  7714. this.length++;
  7715. }
  7716. };
  7717. });
  7718. define("zepto.flexslider", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  7719. var $ = window.Zepto;
  7720. require("core");
  7721. require("zepto.extend.data");
  7722. // Zepto $.data patch
  7723. $.data = function(elem, key, value) {
  7724. return $(elem).data(key, value);
  7725. };
  7726. //scrollLeft
  7727. [ "Left", "Top" ].forEach(function(name, i) {
  7728. var method = "scroll" + name;
  7729. function isWindow(obj) {
  7730. return obj && typeof obj === "object" && "setInterval" in obj;
  7731. }
  7732. function getWindow(elem) {
  7733. return isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
  7734. }
  7735. $.fn[method] = function(val) {
  7736. var elem, win;
  7737. if (val === undefined) {
  7738. elem = this[0];
  7739. if (!elem) {
  7740. return null;
  7741. }
  7742. win = getWindow(elem);
  7743. // Return the scroll offset
  7744. return win ? "pageXOffset" in win ? win[i ? "pageYOffset" : "pageXOffset"] : win.document.documentElement[method] || win.document.body[method] : elem[method];
  7745. }
  7746. // Set the scroll offset
  7747. this.each(function() {
  7748. win = getWindow(this);
  7749. if (win) {
  7750. var xCoord = !i ? val : $(win).scrollLeft();
  7751. var yCoord = i ? val : $(win).scrollTop();
  7752. win.scrollTo(xCoord, yCoord);
  7753. } else {
  7754. this[method] = val;
  7755. }
  7756. });
  7757. };
  7758. });
  7759. // Create outerHeight and outerWidth methods
  7760. [ "width", "height" ].forEach(function(dimension) {
  7761. var offset, Dimension = dimension.replace(/./, function(m) {
  7762. return m[0].toUpperCase();
  7763. });
  7764. $.fn["outer" + Dimension] = function(margin) {
  7765. var elem = this;
  7766. if (elem) {
  7767. var size = elem[dimension]();
  7768. var sides = {
  7769. width: [ "left", "right" ],
  7770. height: [ "top", "bottom" ]
  7771. };
  7772. sides[dimension].forEach(function(side) {
  7773. if (margin) size += parseInt(elem.css("margin-" + side), 10);
  7774. });
  7775. return size;
  7776. } else {
  7777. return null;
  7778. }
  7779. };
  7780. });
  7781. /*
  7782. * Zepto FlexSlider v2.3
  7783. * @desc Porting from jQuery FlexSlider v2.3, Contributing Author: Tyler Smith
  7784. * @license Copyright 2012 WooThemes GPLv2
  7785. */
  7786. //FlexSlider: Object Instance
  7787. $.flexslider = function(el, options) {
  7788. var slider = $(el);
  7789. // making variables public
  7790. slider.vars = $.extend({}, $.flexslider.defaults, options);
  7791. var namespace = slider.vars.namespace, msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, touch = ("ontouchstart" in window || msGesture || window.DocumentTouch && document instanceof DocumentTouch) && slider.vars.touch, // depricating this idea, as devices are being released with both of these events
  7792. //eventType = (touch) ? "touchend" : "click",
  7793. eventType = "click touchend MSPointerUp keyup", watchedEvent = "", watchedEventClearTimer, vertical = slider.vars.direction === "vertical", reverse = slider.vars.reverse, carousel = slider.vars.itemWidth > 0, fade = slider.vars.animation === "fade", asNav = slider.vars.asNavFor !== "", methods = {}, focused = true;
  7794. // Store a reference to the slider object
  7795. $.data(el, "flexslider", slider);
  7796. // Private slider methods
  7797. methods = {
  7798. init: function() {
  7799. slider.animating = false;
  7800. // Get current slide and make sure it is a number
  7801. slider.currentSlide = parseInt(slider.vars.startAt ? slider.vars.startAt : 0, 10);
  7802. if (isNaN(slider.currentSlide)) slider.currentSlide = 0;
  7803. slider.animatingTo = slider.currentSlide;
  7804. slider.atEnd = slider.currentSlide === 0 || slider.currentSlide === slider.last;
  7805. slider.containerSelector = slider.vars.selector.substr(0, slider.vars.selector.search(" "));
  7806. slider.slides = $(slider.vars.selector, slider);
  7807. slider.container = $(slider.containerSelector, slider);
  7808. slider.count = slider.slides.length;
  7809. // SYNC:
  7810. slider.syncExists = $(slider.vars.sync).length > 0;
  7811. // SLIDE:
  7812. if (slider.vars.animation === "slide") slider.vars.animation = "swing";
  7813. slider.prop = vertical ? "top" : "marginLeft";
  7814. slider.args = {};
  7815. // SLIDESHOW:
  7816. slider.manualPause = false;
  7817. slider.stopped = false;
  7818. //PAUSE WHEN INVISIBLE
  7819. slider.started = false;
  7820. slider.startTimeout = null;
  7821. // TOUCH/USECSS:
  7822. slider.transitions = !slider.vars.video && !fade && slider.vars.useCSS && function() {
  7823. var obj = document.createElement("div"), props = [ "perspectiveProperty", "WebkitPerspective", "MozPerspective", "OPerspective", "msPerspective" ];
  7824. for (var i in props) {
  7825. if (obj.style[props[i]] !== undefined) {
  7826. slider.pfx = props[i].replace("Perspective", "").toLowerCase();
  7827. slider.prop = "-" + slider.pfx + "-transform";
  7828. return true;
  7829. }
  7830. }
  7831. return false;
  7832. }();
  7833. slider.ensureAnimationEnd = "";
  7834. // CONTROLSCONTAINER:
  7835. if (slider.vars.controlsContainer !== "") slider.controlsContainer = $(slider.vars.controlsContainer).length > 0 && $(slider.vars.controlsContainer);
  7836. // MANUAL:
  7837. if (slider.vars.manualControls !== "") slider.manualControls = $(slider.vars.manualControls).length > 0 && $(slider.vars.manualControls);
  7838. // RANDOMIZE:
  7839. if (slider.vars.randomize) {
  7840. slider.slides.sort(function() {
  7841. return Math.round(Math.random()) - .5;
  7842. });
  7843. slider.container.empty().append(slider.slides);
  7844. }
  7845. slider.doMath();
  7846. // INIT
  7847. slider.setup("init");
  7848. // CONTROLNAV:
  7849. if (slider.vars.controlNav) methods.controlNav.setup();
  7850. // DIRECTIONNAV:
  7851. if (slider.vars.directionNav) methods.directionNav.setup();
  7852. // KEYBOARD:
  7853. if (slider.vars.keyboard && ($(slider.containerSelector).length === 1 || slider.vars.multipleKeyboard)) {
  7854. $(document).bind("keyup", function(event) {
  7855. var keycode = event.keyCode;
  7856. if (!slider.animating && (keycode === 39 || keycode === 37)) {
  7857. var target = keycode === 39 ? slider.getTarget("next") : keycode === 37 ? slider.getTarget("prev") : false;
  7858. slider.flexAnimate(target, slider.vars.pauseOnAction);
  7859. }
  7860. });
  7861. }
  7862. // MOUSEWHEEL:
  7863. if (slider.vars.mousewheel) {
  7864. slider.bind("mousewheel", function(event, delta, deltaX, deltaY) {
  7865. event.preventDefault();
  7866. var target = delta < 0 ? slider.getTarget("next") : slider.getTarget("prev");
  7867. slider.flexAnimate(target, slider.vars.pauseOnAction);
  7868. });
  7869. }
  7870. // PAUSEPLAY
  7871. if (slider.vars.pausePlay) methods.pausePlay.setup();
  7872. //PAUSE WHEN INVISIBLE
  7873. if (slider.vars.slideshow && slider.vars.pauseInvisible) methods.pauseInvisible.init();
  7874. // SLIDSESHOW
  7875. if (slider.vars.slideshow) {
  7876. if (slider.vars.pauseOnHover) {
  7877. /*slider.hover(function() {
  7878. if (!slider.manualPlay && !slider.manualPause) slider.pause();
  7879. }, function() {
  7880. if (!slider.manualPause && !slider.manualPlay && !slider.stopped) slider.play();
  7881. });*/
  7882. slider.on("mouseover", function() {
  7883. if (!slider.manualPlay && !slider.manualPause) slider.pause();
  7884. });
  7885. slider.on("mouseout", function() {
  7886. if (!slider.manualPause && !slider.manualPlay && !slider.stopped) slider.play();
  7887. });
  7888. }
  7889. // initialize animation
  7890. //If we're visible, or we don't use PageVisibility API
  7891. if (!slider.vars.pauseInvisible || !methods.pauseInvisible.isHidden()) {
  7892. slider.vars.initDelay > 0 ? slider.startTimeout = setTimeout(slider.play, slider.vars.initDelay) : slider.play();
  7893. }
  7894. }
  7895. // ASNAV:
  7896. if (asNav) methods.asNav.setup();
  7897. // TOUCH
  7898. if (touch && slider.vars.touch) methods.touch();
  7899. // FADE&&SMOOTHHEIGHT || SLIDE:
  7900. if (!fade || fade && slider.vars.smoothHeight) $(window).bind("resize orientationchange focus", methods.resize);
  7901. slider.find("img").attr("draggable", "false");
  7902. // API: start() Callback
  7903. setTimeout(function() {
  7904. slider.vars.start(slider);
  7905. }, 200);
  7906. },
  7907. asNav: {
  7908. setup: function() {
  7909. slider.asNav = true;
  7910. slider.animatingTo = Math.floor(slider.currentSlide / slider.move);
  7911. slider.currentItem = slider.currentSlide;
  7912. slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide");
  7913. if (!msGesture) {
  7914. slider.slides.on(eventType, function(e) {
  7915. e.preventDefault();
  7916. var $slide = $(this), target = $slide.index();
  7917. var posFromLeft = $slide.offset().left - $(slider).scrollLeft();
  7918. // Find position of slide relative to left of slider container
  7919. if (posFromLeft <= 0 && $slide.hasClass(namespace + "active-slide")) {
  7920. slider.flexAnimate(slider.getTarget("prev"), true);
  7921. } else if (!$(slider.vars.asNavFor).data("flexslider").animating && !$slide.hasClass(namespace + "active-slide")) {
  7922. slider.direction = slider.currentItem < target ? "next" : "prev";
  7923. slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true);
  7924. }
  7925. });
  7926. } else {
  7927. el._slider = slider;
  7928. slider.slides.each(function() {
  7929. var that = this;
  7930. that._gesture = new MSGesture();
  7931. that._gesture.target = that;
  7932. that.addEventListener("MSPointerDown", function(e) {
  7933. e.preventDefault();
  7934. if (e.currentTarget._gesture) e.currentTarget._gesture.addPointer(e.pointerId);
  7935. }, false);
  7936. that.addEventListener("MSGestureTap", function(e) {
  7937. e.preventDefault();
  7938. var $slide = $(this), target = $slide.index();
  7939. if (!$(slider.vars.asNavFor).data("flexslider").animating && !$slide.hasClass("active")) {
  7940. slider.direction = slider.currentItem < target ? "next" : "prev";
  7941. slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true);
  7942. }
  7943. });
  7944. });
  7945. }
  7946. }
  7947. },
  7948. controlNav: {
  7949. setup: function() {
  7950. if (!slider.manualControls) {
  7951. methods.controlNav.setupPaging();
  7952. } else {
  7953. // MANUALCONTROLS:
  7954. methods.controlNav.setupManual();
  7955. }
  7956. },
  7957. setupPaging: function() {
  7958. var type = slider.vars.controlNav === "thumbnails" ? "control-thumbs" : "control-paging", j = 1, item, slide;
  7959. slider.controlNavScaffold = $('<ol class="' + namespace + "control-nav " + namespace + type + '"></ol>');
  7960. if (slider.pagingCount > 1) {
  7961. for (var i = 0; i < slider.pagingCount; i++) {
  7962. slide = slider.slides.eq(i);
  7963. item = slider.vars.controlNav === "thumbnails" ? '<img src="' + slide.attr("data-thumb") + '"/>' : "<a>" + j + "</a>";
  7964. if ("thumbnails" === slider.vars.controlNav && true === slider.vars.thumbCaptions) {
  7965. var captn = slide.attr("data-thumbcaption");
  7966. if ("" != captn && undefined != captn) item += '<span class="' + namespace + 'caption">' + captn + "</span>";
  7967. }
  7968. //slider.controlNavScaffold.append('<li>' + item + '</li>');
  7969. slider.controlNavScaffold.append("<li>" + item + "<i></i></li>");
  7970. j++;
  7971. }
  7972. }
  7973. // CONTROLSCONTAINER:
  7974. slider.controlsContainer ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
  7975. methods.controlNav.set();
  7976. methods.controlNav.active();
  7977. slider.controlNavScaffold.delegate("a, img", eventType, function(event) {
  7978. event.preventDefault();
  7979. if (watchedEvent === "" || watchedEvent === event.type) {
  7980. var $this = $(this), target = slider.controlNav.index($this);
  7981. if (!$this.hasClass(namespace + "active")) {
  7982. slider.direction = target > slider.currentSlide ? "next" : "prev";
  7983. slider.flexAnimate(target, slider.vars.pauseOnAction);
  7984. }
  7985. }
  7986. // setup flags to prevent event duplication
  7987. if (watchedEvent === "") {
  7988. watchedEvent = event.type;
  7989. }
  7990. methods.setToClearWatchedEvent();
  7991. });
  7992. },
  7993. setupManual: function() {
  7994. slider.controlNav = slider.manualControls;
  7995. methods.controlNav.active();
  7996. slider.controlNav.bind(eventType, function(event) {
  7997. event.preventDefault();
  7998. if (watchedEvent === "" || watchedEvent === event.type) {
  7999. var $this = $(this), target = slider.controlNav.index($this);
  8000. if (!$this.hasClass(namespace + "active")) {
  8001. target > slider.currentSlide ? slider.direction = "next" : slider.direction = "prev";
  8002. slider.flexAnimate(target, slider.vars.pauseOnAction);
  8003. }
  8004. }
  8005. // setup flags to prevent event duplication
  8006. if (watchedEvent === "") {
  8007. watchedEvent = event.type;
  8008. }
  8009. methods.setToClearWatchedEvent();
  8010. });
  8011. },
  8012. set: function() {
  8013. var selector = slider.vars.controlNav === "thumbnails" ? "img" : "a";
  8014. slider.controlNav = $("." + namespace + "control-nav li " + selector, slider.controlsContainer ? slider.controlsContainer : slider);
  8015. },
  8016. active: function() {
  8017. slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active");
  8018. },
  8019. update: function(action, pos) {
  8020. if (slider.pagingCount > 1 && action === "add") {
  8021. slider.controlNavScaffold.append($("<li><a>" + slider.count + "</a></li>"));
  8022. } else if (slider.pagingCount === 1) {
  8023. slider.controlNavScaffold.find("li").remove();
  8024. } else {
  8025. slider.controlNav.eq(pos).closest("li").remove();
  8026. }
  8027. methods.controlNav.set();
  8028. slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length ? slider.update(pos, action) : methods.controlNav.active();
  8029. }
  8030. },
  8031. directionNav: {
  8032. setup: function() {
  8033. var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + slider.vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + slider.vars.nextText + "</a></li></ul>");
  8034. // CONTROLSCONTAINER:
  8035. if (slider.controlsContainer) {
  8036. $(slider.controlsContainer).append(directionNavScaffold);
  8037. slider.directionNav = $("." + namespace + "direction-nav li a", slider.controlsContainer);
  8038. } else {
  8039. slider.append(directionNavScaffold);
  8040. slider.directionNav = $("." + namespace + "direction-nav li a", slider);
  8041. }
  8042. methods.directionNav.update();
  8043. slider.directionNav.bind(eventType, function(event) {
  8044. event.preventDefault();
  8045. var target;
  8046. if (watchedEvent === "" || watchedEvent === event.type) {
  8047. target = $(this).hasClass(namespace + "next") ? slider.getTarget("next") : slider.getTarget("prev");
  8048. slider.flexAnimate(target, slider.vars.pauseOnAction);
  8049. }
  8050. // setup flags to prevent event duplication
  8051. if (watchedEvent === "") {
  8052. watchedEvent = event.type;
  8053. }
  8054. methods.setToClearWatchedEvent();
  8055. });
  8056. },
  8057. update: function() {
  8058. var disabledClass = namespace + "disabled";
  8059. if (slider.pagingCount === 1) {
  8060. slider.directionNav.addClass(disabledClass).attr("tabindex", "-1");
  8061. } else if (!slider.vars.animationLoop) {
  8062. if (slider.animatingTo === 0) {
  8063. slider.directionNav.removeClass(disabledClass).filter("." + namespace + "prev").addClass(disabledClass).attr("tabindex", "-1");
  8064. } else if (slider.animatingTo === slider.last) {
  8065. slider.directionNav.removeClass(disabledClass).filter("." + namespace + "next").addClass(disabledClass).attr("tabindex", "-1");
  8066. } else {
  8067. slider.directionNav.removeClass(disabledClass).removeAttr("tabindex");
  8068. }
  8069. } else {
  8070. slider.directionNav.removeClass(disabledClass).removeAttr("tabindex");
  8071. }
  8072. }
  8073. },
  8074. pausePlay: {
  8075. setup: function() {
  8076. var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a></a></div>');
  8077. // CONTROLSCONTAINER:
  8078. if (slider.controlsContainer) {
  8079. slider.controlsContainer.append(pausePlayScaffold);
  8080. slider.pausePlay = $("." + namespace + "pauseplay a", slider.controlsContainer);
  8081. } else {
  8082. slider.append(pausePlayScaffold);
  8083. slider.pausePlay = $("." + namespace + "pauseplay a", slider);
  8084. }
  8085. methods.pausePlay.update(slider.vars.slideshow ? namespace + "pause" : namespace + "play");
  8086. slider.pausePlay.bind(eventType, function(event) {
  8087. event.preventDefault();
  8088. if (watchedEvent === "" || watchedEvent === event.type) {
  8089. if ($(this).hasClass(namespace + "pause")) {
  8090. slider.manualPause = true;
  8091. slider.manualPlay = false;
  8092. slider.pause();
  8093. } else {
  8094. slider.manualPause = false;
  8095. slider.manualPlay = true;
  8096. slider.play();
  8097. }
  8098. }
  8099. // setup flags to prevent event duplication
  8100. if (watchedEvent === "") {
  8101. watchedEvent = event.type;
  8102. }
  8103. methods.setToClearWatchedEvent();
  8104. });
  8105. },
  8106. update: function(state) {
  8107. state === "play" ? slider.pausePlay.removeClass(namespace + "pause").addClass(namespace + "play").html(slider.vars.playText) : slider.pausePlay.removeClass(namespace + "play").addClass(namespace + "pause").html(slider.vars.pauseText);
  8108. }
  8109. },
  8110. touch: function() {
  8111. var startX, startY, offset, cwidth, dx, startT, scrolling = false, localX = 0, localY = 0, accDx = 0;
  8112. if (!msGesture) {
  8113. el.addEventListener("touchstart", onTouchStart, false);
  8114. function onTouchStart(e) {
  8115. if (slider.animating) {
  8116. e.preventDefault();
  8117. } else if (window.navigator.msPointerEnabled || e.touches.length === 1) {
  8118. slider.pause();
  8119. // CAROUSEL:
  8120. cwidth = vertical ? slider.h : slider.w;
  8121. startT = Number(new Date());
  8122. // CAROUSEL:
  8123. // Local vars for X and Y points.
  8124. localX = e.touches[0].pageX;
  8125. localY = e.touches[0].pageY;
  8126. offset = carousel && reverse && slider.animatingTo === slider.last ? 0 : carousel && reverse ? slider.limit - (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo : carousel && slider.currentSlide === slider.last ? slider.limit : carousel ? (slider.itemW + slider.vars.itemMargin) * slider.move * slider.currentSlide : reverse ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
  8127. startX = vertical ? localY : localX;
  8128. startY = vertical ? localX : localY;
  8129. el.addEventListener("touchmove", onTouchMove, false);
  8130. el.addEventListener("touchend", onTouchEnd, false);
  8131. }
  8132. }
  8133. function onTouchMove(e) {
  8134. // Local vars for X and Y points.
  8135. localX = e.touches[0].pageX;
  8136. localY = e.touches[0].pageY;
  8137. dx = vertical ? startX - localY : startX - localX;
  8138. scrolling = vertical ? Math.abs(dx) < Math.abs(localX - startY) : Math.abs(dx) < Math.abs(localY - startY);
  8139. var fxms = 500;
  8140. if (!scrolling || Number(new Date()) - startT > fxms) {
  8141. e.preventDefault();
  8142. if (!fade && slider.transitions) {
  8143. if (!slider.vars.animationLoop) {
  8144. dx = dx / (slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0 ? Math.abs(dx) / cwidth + 2 : 1);
  8145. }
  8146. slider.setProps(offset + dx, "setTouch");
  8147. }
  8148. }
  8149. }
  8150. function onTouchEnd(e) {
  8151. // finish the touch by undoing the touch session
  8152. el.removeEventListener("touchmove", onTouchMove, false);
  8153. if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
  8154. var updateDx = reverse ? -dx : dx, target = updateDx > 0 ? slider.getTarget("next") : slider.getTarget("prev");
  8155. if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth / 2)) {
  8156. slider.flexAnimate(target, slider.vars.pauseOnAction);
  8157. } else {
  8158. if (!fade) slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true);
  8159. }
  8160. }
  8161. el.removeEventListener("touchend", onTouchEnd, false);
  8162. startX = null;
  8163. startY = null;
  8164. dx = null;
  8165. offset = null;
  8166. }
  8167. } else {
  8168. el.style.msTouchAction = "none";
  8169. el._gesture = new MSGesture();
  8170. el._gesture.target = el;
  8171. el.addEventListener("MSPointerDown", onMSPointerDown, false);
  8172. el._slider = slider;
  8173. el.addEventListener("MSGestureChange", onMSGestureChange, false);
  8174. el.addEventListener("MSGestureEnd", onMSGestureEnd, false);
  8175. function onMSPointerDown(e) {
  8176. e.stopPropagation();
  8177. if (slider.animating) {
  8178. e.preventDefault();
  8179. } else {
  8180. slider.pause();
  8181. el._gesture.addPointer(e.pointerId);
  8182. accDx = 0;
  8183. cwidth = vertical ? slider.h : slider.w;
  8184. startT = Number(new Date());
  8185. // CAROUSEL:
  8186. offset = carousel && reverse && slider.animatingTo === slider.last ? 0 : carousel && reverse ? slider.limit - (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo : carousel && slider.currentSlide === slider.last ? slider.limit : carousel ? (slider.itemW + slider.vars.itemMargin) * slider.move * slider.currentSlide : reverse ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
  8187. }
  8188. }
  8189. function onMSGestureChange(e) {
  8190. e.stopPropagation();
  8191. var slider = e.target._slider;
  8192. if (!slider) {
  8193. return;
  8194. }
  8195. var transX = -e.translationX, transY = -e.translationY;
  8196. //Accumulate translations.
  8197. accDx = accDx + (vertical ? transY : transX);
  8198. dx = accDx;
  8199. scrolling = vertical ? Math.abs(accDx) < Math.abs(-transX) : Math.abs(accDx) < Math.abs(-transY);
  8200. if (e.detail === e.MSGESTURE_FLAG_INERTIA) {
  8201. setImmediate(function() {
  8202. el._gesture.stop();
  8203. });
  8204. return;
  8205. }
  8206. if (!scrolling || Number(new Date()) - startT > 500) {
  8207. e.preventDefault();
  8208. if (!fade && slider.transitions) {
  8209. if (!slider.vars.animationLoop) {
  8210. dx = accDx / (slider.currentSlide === 0 && accDx < 0 || slider.currentSlide === slider.last && accDx > 0 ? Math.abs(accDx) / cwidth + 2 : 1);
  8211. }
  8212. slider.setProps(offset + dx, "setTouch");
  8213. }
  8214. }
  8215. }
  8216. function onMSGestureEnd(e) {
  8217. e.stopPropagation();
  8218. var slider = e.target._slider;
  8219. if (!slider) {
  8220. return;
  8221. }
  8222. if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
  8223. var updateDx = reverse ? -dx : dx, target = updateDx > 0 ? slider.getTarget("next") : slider.getTarget("prev");
  8224. if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth / 2)) {
  8225. slider.flexAnimate(target, slider.vars.pauseOnAction);
  8226. } else {
  8227. if (!fade) slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true);
  8228. }
  8229. }
  8230. startX = null;
  8231. startY = null;
  8232. dx = null;
  8233. offset = null;
  8234. accDx = 0;
  8235. }
  8236. }
  8237. },
  8238. resize: function() {
  8239. if (!slider.animating && slider.is(":visible")) {
  8240. if (!carousel) slider.doMath();
  8241. if (fade) {
  8242. // SMOOTH HEIGHT:
  8243. methods.smoothHeight();
  8244. } else if (carousel) {
  8245. //CAROUSEL:
  8246. slider.slides.width(slider.computedW);
  8247. slider.update(slider.pagingCount);
  8248. slider.setProps();
  8249. } else if (vertical) {
  8250. //VERTICAL:
  8251. slider.viewport.height(slider.h);
  8252. slider.setProps(slider.h, "setTotal");
  8253. } else {
  8254. // SMOOTH HEIGHT:
  8255. if (slider.vars.smoothHeight) methods.smoothHeight();
  8256. slider.newSlides.width(slider.computedW);
  8257. slider.setProps(slider.computedW, "setTotal");
  8258. }
  8259. }
  8260. },
  8261. smoothHeight: function(dur) {
  8262. if (!vertical || fade) {
  8263. var $obj = fade ? slider : slider.viewport;
  8264. dur ? $obj.animate({
  8265. height: slider.slides.eq(slider.animatingTo).height()
  8266. }, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
  8267. }
  8268. },
  8269. sync: function(action) {
  8270. var $obj = $(slider.vars.sync).data("flexslider"), target = slider.animatingTo;
  8271. switch (action) {
  8272. case "animate":
  8273. $obj.flexAnimate(target, slider.vars.pauseOnAction, false, true);
  8274. break;
  8275. case "play":
  8276. if (!$obj.playing && !$obj.asNav) {
  8277. $obj.play();
  8278. }
  8279. break;
  8280. case "pause":
  8281. $obj.pause();
  8282. break;
  8283. }
  8284. },
  8285. uniqueID: function($clone) {
  8286. // Append _clone to current level and children elements with id attributes
  8287. $clone.filter("[id]").add($clone.find("[id]")).each(function() {
  8288. var $this = $(this);
  8289. $this.attr("id", $this.attr("id") + "_clone");
  8290. });
  8291. return $clone;
  8292. },
  8293. pauseInvisible: {
  8294. visProp: null,
  8295. init: function() {
  8296. var prefixes = [ "webkit", "moz", "ms", "o" ];
  8297. if ("hidden" in document) return "hidden";
  8298. for (var i = 0; i < prefixes.length; i++) {
  8299. if (prefixes[i] + "Hidden" in document) methods.pauseInvisible.visProp = prefixes[i] + "Hidden";
  8300. }
  8301. if (methods.pauseInvisible.visProp) {
  8302. var evtname = methods.pauseInvisible.visProp.replace(/[H|h]idden/, "") + "visibilitychange";
  8303. document.addEventListener(evtname, function() {
  8304. if (methods.pauseInvisible.isHidden()) {
  8305. if (slider.startTimeout) clearTimeout(slider.startTimeout); else slider.pause();
  8306. } else {
  8307. if (slider.started) slider.play(); else slider.vars.initDelay > 0 ? setTimeout(slider.play, slider.vars.initDelay) : slider.play();
  8308. }
  8309. });
  8310. }
  8311. },
  8312. isHidden: function() {
  8313. return document[methods.pauseInvisible.visProp] || false;
  8314. }
  8315. },
  8316. setToClearWatchedEvent: function() {
  8317. clearTimeout(watchedEventClearTimer);
  8318. watchedEventClearTimer = setTimeout(function() {
  8319. watchedEvent = "";
  8320. }, 3e3);
  8321. }
  8322. };
  8323. // public methods
  8324. slider.flexAnimate = function(target, pause, override, withSync, fromNav) {
  8325. if (!slider.vars.animationLoop && target !== slider.currentSlide) {
  8326. slider.direction = target > slider.currentSlide ? "next" : "prev";
  8327. }
  8328. if (asNav && slider.pagingCount === 1) slider.direction = slider.currentItem < target ? "next" : "prev";
  8329. if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) {
  8330. if (asNav && withSync) {
  8331. var master = $(slider.vars.asNavFor).data("flexslider");
  8332. slider.atEnd = target === 0 || target === slider.count - 1;
  8333. master.flexAnimate(target, true, false, true, fromNav);
  8334. slider.direction = slider.currentItem < target ? "next" : "prev";
  8335. master.direction = slider.direction;
  8336. if (Math.ceil((target + 1) / slider.visible) - 1 !== slider.currentSlide && target !== 0) {
  8337. slider.currentItem = target;
  8338. slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
  8339. target = Math.floor(target / slider.visible);
  8340. } else {
  8341. slider.currentItem = target;
  8342. slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
  8343. return false;
  8344. }
  8345. }
  8346. slider.animating = true;
  8347. slider.animatingTo = target;
  8348. // SLIDESHOW:
  8349. if (pause) slider.pause();
  8350. // API: before() animation Callback
  8351. slider.vars.before(slider);
  8352. // SYNC:
  8353. if (slider.syncExists && !fromNav) methods.sync("animate");
  8354. // CONTROLNAV
  8355. if (slider.vars.controlNav) methods.controlNav.active();
  8356. // !CAROUSEL:
  8357. // CANDIDATE: slide active class (for add/remove slide)
  8358. if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
  8359. // INFINITE LOOP:
  8360. // CANDIDATE: atEnd
  8361. slider.atEnd = target === 0 || target === slider.last;
  8362. // DIRECTIONNAV:
  8363. if (slider.vars.directionNav) methods.directionNav.update();
  8364. if (target === slider.last) {
  8365. // API: end() of cycle Callback
  8366. slider.vars.end(slider);
  8367. // SLIDESHOW && !INFINITE LOOP:
  8368. if (!slider.vars.animationLoop) slider.pause();
  8369. }
  8370. // SLIDE:
  8371. if (!fade) {
  8372. var dimension = vertical ? slider.slides.filter(":first").height() : slider.computedW, margin, slideString, calcNext;
  8373. // INFINITE LOOP / REVERSE:
  8374. if (carousel) {
  8375. //margin = (slider.vars.itemWidth > slider.w) ? slider.vars.itemMargin * 2 : slider.vars.itemMargin;
  8376. margin = slider.vars.itemMargin;
  8377. calcNext = (slider.itemW + margin) * slider.move * slider.animatingTo;
  8378. slideString = calcNext > slider.limit && slider.visible !== 1 ? slider.limit : calcNext;
  8379. } else if (slider.currentSlide === 0 && target === slider.count - 1 && slider.vars.animationLoop && slider.direction !== "next") {
  8380. slideString = reverse ? (slider.count + slider.cloneOffset) * dimension : 0;
  8381. } else if (slider.currentSlide === slider.last && target === 0 && slider.vars.animationLoop && slider.direction !== "prev") {
  8382. slideString = reverse ? 0 : (slider.count + 1) * dimension;
  8383. } else {
  8384. slideString = reverse ? (slider.count - 1 - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension;
  8385. }
  8386. slider.setProps(slideString, "", slider.vars.animationSpeed);
  8387. if (slider.transitions) {
  8388. if (!slider.vars.animationLoop || !slider.atEnd) {
  8389. slider.animating = false;
  8390. slider.currentSlide = slider.animatingTo;
  8391. }
  8392. // Unbind previous transitionEnd events and re-bind new transitionEnd event
  8393. slider.container.unbind("webkitTransitionEnd transitionend");
  8394. slider.container.bind("webkitTransitionEnd transitionend", function() {
  8395. clearTimeout(slider.ensureAnimationEnd);
  8396. slider.wrapup(dimension);
  8397. });
  8398. // Insurance for the ever-so-fickle transitionEnd event
  8399. clearTimeout(slider.ensureAnimationEnd);
  8400. slider.ensureAnimationEnd = setTimeout(function() {
  8401. slider.wrapup(dimension);
  8402. }, slider.vars.animationSpeed + 100);
  8403. } else {
  8404. slider.container.animate(slider.args, slider.vars.animationSpeed, slider.vars.easing, function() {
  8405. slider.wrapup(dimension);
  8406. });
  8407. }
  8408. } else {
  8409. // FADE:
  8410. if (!touch) {
  8411. //slider.slides.eq(slider.currentSlide).fadeOut(slider.vars.animationSpeed, slider.vars.easing);
  8412. //slider.slides.eq(target).fadeIn(slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
  8413. slider.slides.eq(slider.currentSlide).css({
  8414. zIndex: 1
  8415. }).animate({
  8416. opacity: 0
  8417. }, slider.vars.animationSpeed, slider.vars.easing);
  8418. slider.slides.eq(target).css({
  8419. zIndex: 2
  8420. }).animate({
  8421. opacity: 1
  8422. }, slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
  8423. } else {
  8424. slider.slides.eq(slider.currentSlide).css({
  8425. opacity: 0,
  8426. zIndex: 1
  8427. });
  8428. slider.slides.eq(target).css({
  8429. opacity: 1,
  8430. zIndex: 2
  8431. });
  8432. slider.wrapup(dimension);
  8433. }
  8434. }
  8435. // SMOOTH HEIGHT:
  8436. if (slider.vars.smoothHeight) methods.smoothHeight(slider.vars.animationSpeed);
  8437. }
  8438. };
  8439. slider.wrapup = function(dimension) {
  8440. // SLIDE:
  8441. if (!fade && !carousel) {
  8442. if (slider.currentSlide === 0 && slider.animatingTo === slider.last && slider.vars.animationLoop) {
  8443. slider.setProps(dimension, "jumpEnd");
  8444. } else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && slider.vars.animationLoop) {
  8445. slider.setProps(dimension, "jumpStart");
  8446. }
  8447. }
  8448. slider.animating = false;
  8449. slider.currentSlide = slider.animatingTo;
  8450. // API: after() animation Callback
  8451. slider.vars.after(slider);
  8452. };
  8453. // SLIDESHOW:
  8454. slider.animateSlides = function() {
  8455. if (!slider.animating && focused) slider.flexAnimate(slider.getTarget("next"));
  8456. };
  8457. // SLIDESHOW:
  8458. slider.pause = function() {
  8459. clearInterval(slider.animatedSlides);
  8460. slider.animatedSlides = null;
  8461. slider.playing = false;
  8462. // PAUSEPLAY:
  8463. if (slider.vars.pausePlay) methods.pausePlay.update("play");
  8464. // SYNC:
  8465. if (slider.syncExists) methods.sync("pause");
  8466. };
  8467. // SLIDESHOW:
  8468. slider.play = function() {
  8469. if (slider.playing) clearInterval(slider.animatedSlides);
  8470. slider.animatedSlides = slider.animatedSlides || setInterval(slider.animateSlides, slider.vars.slideshowSpeed);
  8471. slider.started = slider.playing = true;
  8472. // PAUSEPLAY:
  8473. if (slider.vars.pausePlay) methods.pausePlay.update("pause");
  8474. // SYNC:
  8475. if (slider.syncExists) methods.sync("play");
  8476. };
  8477. // STOP:
  8478. slider.stop = function() {
  8479. slider.pause();
  8480. slider.stopped = true;
  8481. };
  8482. slider.canAdvance = function(target, fromNav) {
  8483. // ASNAV:
  8484. var last = asNav ? slider.pagingCount - 1 : slider.last;
  8485. return fromNav ? true : asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev" ? true : asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next" ? false : target === slider.currentSlide && !asNav ? false : slider.vars.animationLoop ? true : slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next" ? false : slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next" ? false : true;
  8486. };
  8487. slider.getTarget = function(dir) {
  8488. slider.direction = dir;
  8489. if (dir === "next") {
  8490. return slider.currentSlide === slider.last ? 0 : slider.currentSlide + 1;
  8491. } else {
  8492. return slider.currentSlide === 0 ? slider.last : slider.currentSlide - 1;
  8493. }
  8494. };
  8495. // SLIDE:
  8496. slider.setProps = function(pos, special, dur) {
  8497. var target = function() {
  8498. var posCheck = pos ? pos : (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo, posCalc = function() {
  8499. if (carousel) {
  8500. return special === "setTouch" ? pos : reverse && slider.animatingTo === slider.last ? 0 : reverse ? slider.limit - (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo : slider.animatingTo === slider.last ? slider.limit : posCheck;
  8501. } else {
  8502. switch (special) {
  8503. case "setTotal":
  8504. return reverse ? (slider.count - 1 - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos;
  8505. case "setTouch":
  8506. return reverse ? pos : pos;
  8507. case "jumpEnd":
  8508. return reverse ? pos : slider.count * pos;
  8509. case "jumpStart":
  8510. return reverse ? slider.count * pos : pos;
  8511. default:
  8512. return pos;
  8513. }
  8514. }
  8515. }();
  8516. return posCalc * -1 + "px";
  8517. }();
  8518. if (slider.transitions) {
  8519. target = vertical ? "translate3d(0," + target + ",0)" : "translate3d(" + target + ",0,0)";
  8520. dur = dur !== undefined ? dur / 1e3 + "s" : "0s";
  8521. slider.container.css("-" + slider.pfx + "-transition-duration", dur);
  8522. slider.container.css("transition-duration", dur);
  8523. }
  8524. slider.args[slider.prop] = target;
  8525. if (slider.transitions || dur === undefined) slider.container.css(slider.args);
  8526. slider.container.css("transform", target);
  8527. };
  8528. slider.setup = function(type) {
  8529. // SLIDE:
  8530. if (!fade) {
  8531. var sliderOffset, arr;
  8532. if (type === "init") {
  8533. slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({
  8534. overflow: "hidden",
  8535. position: "relative"
  8536. }).appendTo(slider).append(slider.container);
  8537. // INFINITE LOOP:
  8538. slider.cloneCount = 0;
  8539. slider.cloneOffset = 0;
  8540. // REVERSE:
  8541. if (reverse) {
  8542. arr = $.makeArray(slider.slides).reverse();
  8543. slider.slides = $(arr);
  8544. slider.container.empty().append(slider.slides);
  8545. }
  8546. }
  8547. // INFINITE LOOP && !CAROUSEL:
  8548. if (slider.vars.animationLoop && !carousel) {
  8549. slider.cloneCount = 2;
  8550. slider.cloneOffset = 1;
  8551. // clear out old clones
  8552. if (type !== "init") slider.container.find(".clone").remove();
  8553. slider.container.append(methods.uniqueID(slider.slides.first().clone().addClass("clone")).attr("aria-hidden", "true")).prepend(methods.uniqueID(slider.slides.last().clone().addClass("clone")).attr("aria-hidden", "true"));
  8554. }
  8555. slider.newSlides = $(slider.vars.selector, slider);
  8556. sliderOffset = reverse ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
  8557. // VERTICAL:
  8558. if (vertical && !carousel) {
  8559. slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
  8560. setTimeout(function() {
  8561. slider.newSlides.css({
  8562. display: "block"
  8563. });
  8564. slider.doMath();
  8565. slider.viewport.height(slider.h);
  8566. slider.setProps(sliderOffset * slider.h, "init");
  8567. }, type === "init" ? 100 : 0);
  8568. } else {
  8569. slider.container.width((slider.count + slider.cloneCount) * 200 + "%");
  8570. slider.setProps(sliderOffset * slider.computedW, "init");
  8571. setTimeout(function() {
  8572. slider.doMath();
  8573. slider.newSlides.css({
  8574. width: slider.computedW,
  8575. "float": "left",
  8576. display: "block"
  8577. });
  8578. // SMOOTH HEIGHT:
  8579. if (slider.vars.smoothHeight) methods.smoothHeight();
  8580. }, type === "init" ? 100 : 0);
  8581. }
  8582. } else {
  8583. // FADE:
  8584. slider.slides.css({
  8585. width: "100%",
  8586. "float": "left",
  8587. marginRight: "-100%",
  8588. position: "relative"
  8589. });
  8590. if (type === "init") {
  8591. if (!touch) {
  8592. //slider.slides.eq(slider.currentSlide).fadeIn(slider.vars.animationSpeed, slider.vars.easing);
  8593. if (slider.vars.fadeFirstSlide == false) {
  8594. slider.slides.css({
  8595. opacity: 0,
  8596. display: "block",
  8597. zIndex: 1
  8598. }).eq(slider.currentSlide).css({
  8599. zIndex: 2
  8600. }).css({
  8601. opacity: 1
  8602. });
  8603. } else {
  8604. slider.slides.css({
  8605. opacity: 0,
  8606. display: "block",
  8607. zIndex: 1
  8608. }).eq(slider.currentSlide).css({
  8609. zIndex: 2
  8610. }).animate({
  8611. opacity: 1
  8612. }, slider.vars.animationSpeed, slider.vars.easing);
  8613. }
  8614. } else {
  8615. slider.slides.css({
  8616. opacity: 0,
  8617. display: "block",
  8618. webkitTransition: "opacity " + slider.vars.animationSpeed / 1e3 + "s ease",
  8619. zIndex: 1
  8620. }).eq(slider.currentSlide).css({
  8621. opacity: 1,
  8622. zIndex: 2
  8623. });
  8624. }
  8625. }
  8626. // SMOOTH HEIGHT:
  8627. if (slider.vars.smoothHeight) methods.smoothHeight();
  8628. }
  8629. // !CAROUSEL:
  8630. // CANDIDATE: active slide
  8631. if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide");
  8632. //FlexSlider: init() Callback
  8633. slider.vars.init(slider);
  8634. };
  8635. slider.doMath = function() {
  8636. var slide = slider.slides.first(), slideMargin = slider.vars.itemMargin, minItems = slider.vars.minItems, maxItems = slider.vars.maxItems;
  8637. slider.w = slider.viewport === undefined ? slider.width() : slider.viewport.width();
  8638. slider.h = slide.height();
  8639. slider.boxPadding = slide.outerWidth() - slide.width();
  8640. // CAROUSEL:
  8641. if (carousel) {
  8642. slider.itemT = slider.vars.itemWidth + slideMargin;
  8643. slider.minW = minItems ? minItems * slider.itemT : slider.w;
  8644. slider.maxW = maxItems ? maxItems * slider.itemT - slideMargin : slider.w;
  8645. slider.itemW = slider.minW > slider.w ? (slider.w - slideMargin * (minItems - 1)) / minItems : slider.maxW < slider.w ? (slider.w - slideMargin * (maxItems - 1)) / maxItems : slider.vars.itemWidth > slider.w ? slider.w : slider.vars.itemWidth;
  8646. slider.visible = Math.floor(slider.w / slider.itemW);
  8647. slider.move = slider.vars.move > 0 && slider.vars.move < slider.visible ? slider.vars.move : slider.visible;
  8648. slider.pagingCount = Math.ceil((slider.count - slider.visible) / slider.move + 1);
  8649. slider.last = slider.pagingCount - 1;
  8650. slider.limit = slider.pagingCount === 1 ? 0 : slider.vars.itemWidth > slider.w ? slider.itemW * (slider.count - 1) + slideMargin * (slider.count - 1) : (slider.itemW + slideMargin) * slider.count - slider.w - slideMargin;
  8651. } else {
  8652. slider.itemW = slider.w;
  8653. slider.pagingCount = slider.count;
  8654. slider.last = slider.count - 1;
  8655. }
  8656. slider.computedW = slider.itemW - slider.boxPadding;
  8657. };
  8658. slider.update = function(pos, action) {
  8659. slider.doMath();
  8660. // update currentSlide and slider.animatingTo if necessary
  8661. if (!carousel) {
  8662. if (pos < slider.currentSlide) {
  8663. slider.currentSlide += 1;
  8664. } else if (pos <= slider.currentSlide && pos !== 0) {
  8665. slider.currentSlide -= 1;
  8666. }
  8667. slider.animatingTo = slider.currentSlide;
  8668. }
  8669. // update controlNav
  8670. if (slider.vars.controlNav && !slider.manualControls) {
  8671. if (action === "add" && !carousel || slider.pagingCount > slider.controlNav.length) {
  8672. methods.controlNav.update("add");
  8673. } else if (action === "remove" && !carousel || slider.pagingCount < slider.controlNav.length) {
  8674. if (carousel && slider.currentSlide > slider.last) {
  8675. slider.currentSlide -= 1;
  8676. slider.animatingTo -= 1;
  8677. }
  8678. methods.controlNav.update("remove", slider.last);
  8679. }
  8680. }
  8681. // update directionNav
  8682. if (slider.vars.directionNav) methods.directionNav.update();
  8683. };
  8684. slider.addSlide = function(obj, pos) {
  8685. var $obj = $(obj);
  8686. slider.count += 1;
  8687. slider.last = slider.count - 1;
  8688. // append new slide
  8689. if (vertical && reverse) {
  8690. pos !== undefined ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj);
  8691. } else {
  8692. pos !== undefined ? slider.slides.eq(pos).before($obj) : slider.container.append($obj);
  8693. }
  8694. // update currentSlide, animatingTo, controlNav, and directionNav
  8695. slider.update(pos, "add");
  8696. // update slider.slides
  8697. slider.slides = $(slider.vars.selector + ":not(.clone)", slider);
  8698. // re-setup the slider to accomdate new slide
  8699. slider.setup();
  8700. //FlexSlider: added() Callback
  8701. slider.vars.added(slider);
  8702. };
  8703. slider.removeSlide = function(obj) {
  8704. var pos = isNaN(obj) ? slider.slides.index($(obj)) : obj;
  8705. // update count
  8706. slider.count -= 1;
  8707. slider.last = slider.count - 1;
  8708. // remove slide
  8709. if (isNaN(obj)) {
  8710. $(obj, slider.slides).remove();
  8711. } else {
  8712. vertical && reverse ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove();
  8713. }
  8714. // update currentSlide, animatingTo, controlNav, and directionNav
  8715. slider.doMath();
  8716. slider.update(pos, "remove");
  8717. // update slider.slides
  8718. slider.slides = $(slider.vars.selector + ":not(.clone)", slider);
  8719. // re-setup the slider to accomdate new slide
  8720. slider.setup();
  8721. // FlexSlider: removed() Callback
  8722. slider.vars.removed(slider);
  8723. };
  8724. //FlexSlider: Initialize
  8725. methods.init();
  8726. };
  8727. // Ensure the slider isn't focussed if the window loses focus.
  8728. $(window).blur(function(e) {
  8729. focused = false;
  8730. }).focus(function(e) {
  8731. focused = true;
  8732. });
  8733. //FlexSlider: Default Settings
  8734. $.flexslider.defaults = {
  8735. namespace: "am-",
  8736. //{NEW} String: Prefix string attached to the class of every element generated by the plugin
  8737. selector: ".am-slides > li",
  8738. //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
  8739. animation: "slide",
  8740. //String: Select your animation type, "fade" or "slide"
  8741. easing: "swing",
  8742. //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
  8743. direction: "horizontal",
  8744. //String: Select the sliding direction, "horizontal" or "vertical"
  8745. reverse: false,
  8746. //{NEW} Boolean: Reverse the animation direction
  8747. animationLoop: true,
  8748. //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
  8749. smoothHeight: false,
  8750. //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
  8751. startAt: 0,
  8752. //Integer: The slide that the slider should start on. Array notation (0 = first slide)
  8753. slideshow: true,
  8754. //Boolean: Animate slider automatically
  8755. slideshowSpeed: 5e3,
  8756. //Integer: Set the speed of the slideshow cycling, in milliseconds
  8757. animationSpeed: 600,
  8758. //Integer: Set the speed of animations, in milliseconds
  8759. initDelay: 0,
  8760. //{NEW} Integer: Set an initialization delay, in milliseconds
  8761. randomize: false,
  8762. //Boolean: Randomize slide order
  8763. thumbCaptions: false,
  8764. //Boolean: Whether or not to put captions on thumbnails when using the "thumbnails" controlNav.
  8765. // Usability features
  8766. pauseOnAction: true,
  8767. //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
  8768. pauseOnHover: false,
  8769. //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
  8770. pauseInvisible: true,
  8771. //{NEW} Boolean: Pause the slideshow when tab is invisible, resume when visible. Provides better UX, lower CPU usage.
  8772. useCSS: true,
  8773. //{NEW} Boolean: Slider will use CSS3 transitions if available
  8774. touch: true,
  8775. //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
  8776. video: false,
  8777. //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches
  8778. // Primary Controls
  8779. controlNav: true,
  8780. //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
  8781. directionNav: true,
  8782. //Boolean: Create navigation for previous/next navigation? (true/false)
  8783. prevText: "Previous",
  8784. //String: Set the text for the "previous" directionNav item
  8785. nextText: "Next",
  8786. //String: Set the text for the "next" directionNav item
  8787. // Secondary Navigation
  8788. keyboard: true,
  8789. //Boolean: Allow slider navigating via keyboard left/right keys
  8790. multipleKeyboard: false,
  8791. //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
  8792. mousewheel: false,
  8793. //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
  8794. pausePlay: false,
  8795. //Boolean: Create pause/play dynamic element
  8796. pauseText: "Pause",
  8797. //String: Set the text for the "pause" pausePlay item
  8798. playText: "Play",
  8799. //String: Set the text for the "play" pausePlay item
  8800. // Special properties
  8801. controlsContainer: "",
  8802. //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
  8803. manualControls: "",
  8804. //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
  8805. sync: "",
  8806. //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
  8807. asNavFor: "",
  8808. //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider
  8809. // Carousel Options
  8810. itemWidth: 0,
  8811. //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
  8812. itemMargin: 0,
  8813. //{NEW} Integer: Margin between carousel items.
  8814. minItems: 1,
  8815. //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
  8816. maxItems: 0,
  8817. //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
  8818. move: 0,
  8819. //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.
  8820. allowOneSlide: true,
  8821. //{NEW} Boolean: Whether or not to allow a slider comprised of a single slide
  8822. // Callback API
  8823. start: function() {},
  8824. //Callback: function(slider) - Fires when the slider loads the first slide
  8825. before: function() {},
  8826. //Callback: function(slider) - Fires asynchronously with each slider animation
  8827. after: function() {},
  8828. //Callback: function(slider) - Fires after each slider animation completes
  8829. end: function() {},
  8830. //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
  8831. added: function() {},
  8832. //{NEW} Callback: function(slider) - Fires after a slide is added
  8833. removed: function() {},
  8834. //{NEW} Callback: function(slider) - Fires after a slide is removed
  8835. init: function() {}
  8836. };
  8837. //FlexSlider: Plugin Function
  8838. $.fn.flexslider = function(options) {
  8839. if (options === undefined) options = {};
  8840. if (typeof options === "object") {
  8841. return this.each(function() {
  8842. var $this = $(this), selector = options.selector ? options.selector : ".am-slides > li", $slides = $this.find(selector);
  8843. if ($slides.length === 1 && options.allowOneSlide === true || $slides.length === 0) {
  8844. $slides.animate({
  8845. opacity: 1
  8846. }, 400);
  8847. if (options.start) options.start($this);
  8848. } else if ($this.data("flexslider") === undefined) {
  8849. new $.flexslider(this, options);
  8850. }
  8851. });
  8852. } else {
  8853. // Helper strings to quickly perform functions on the slider
  8854. var $slider = $(this).data("flexslider");
  8855. switch (options) {
  8856. case "play":
  8857. $slider.play();
  8858. break;
  8859. case "pause":
  8860. $slider.pause();
  8861. break;
  8862. case "stop":
  8863. $slider.stop();
  8864. break;
  8865. case "next":
  8866. $slider.flexAnimate($slider.getTarget("next"), true);
  8867. break;
  8868. case "prev":
  8869. case "previous":
  8870. $slider.flexAnimate($slider.getTarget("prev"), true);
  8871. break;
  8872. default:
  8873. if (typeof options === "number") $slider.flexAnimate(options, true);
  8874. }
  8875. }
  8876. };
  8877. });
  8878. define("zepto.pinchzoom", [], function(require, exports, module) {
  8879. "use strict";
  8880. /**
  8881. * @via https://github.com/manuelstofer/pinchzoom/blob/master/src/pinchzoom.js
  8882. * @license the MIT License.
  8883. */
  8884. var definePinchZoom = function($) {
  8885. /**
  8886. * Pinch zoom using jQuery
  8887. * @version 0.0.2
  8888. * @author Manuel Stofer <mst@rtp.ch>
  8889. * @param el
  8890. * @param options
  8891. * @constructor
  8892. */
  8893. var PinchZoom = function(el, options) {
  8894. this.el = $(el);
  8895. this.zoomFactor = 1;
  8896. this.lastScale = 1;
  8897. this.offset = {
  8898. x: 0,
  8899. y: 0
  8900. };
  8901. this.options = $.extend({}, this.defaults, options);
  8902. this.setupMarkup();
  8903. this.bindEvents();
  8904. this.update();
  8905. // default enable.
  8906. this.enable();
  8907. }, sum = function(a, b) {
  8908. return a + b;
  8909. }, isCloseTo = function(value, expected) {
  8910. return value > expected - .01 && value < expected + .01;
  8911. };
  8912. PinchZoom.prototype = {
  8913. defaults: {
  8914. tapZoomFactor: 2,
  8915. zoomOutFactor: 1.3,
  8916. animationDuration: 300,
  8917. animationInterval: 5,
  8918. maxZoom: 5,
  8919. minZoom: .5,
  8920. lockDragAxis: false,
  8921. use2d: false,
  8922. zoomStartEventName: "pz_zoomstart",
  8923. zoomEndEventName: "pz_zoomend",
  8924. dragStartEventName: "pz_dragstart",
  8925. dragEndEventName: "pz_dragend",
  8926. doubleTapEventName: "pz_doubletap"
  8927. },
  8928. /**
  8929. * Event handler for 'dragstart'
  8930. * @param event
  8931. */
  8932. handleDragStart: function(event) {
  8933. this.el.trigger(this.options.dragStartEventName);
  8934. this.stopAnimation();
  8935. this.lastDragPosition = false;
  8936. this.hasInteraction = true;
  8937. this.handleDrag(event);
  8938. },
  8939. /**
  8940. * Event handler for 'drag'
  8941. * @param event
  8942. */
  8943. handleDrag: function(event) {
  8944. if (this.zoomFactor > 1) {
  8945. var touch = this.getTouches(event)[0];
  8946. this.drag(touch, this.lastDragPosition);
  8947. this.offset = this.sanitizeOffset(this.offset);
  8948. this.lastDragPosition = touch;
  8949. }
  8950. },
  8951. handleDragEnd: function() {
  8952. this.el.trigger(this.options.dragEndEventName);
  8953. this.end();
  8954. },
  8955. /**
  8956. * Event handler for 'zoomstart'
  8957. * @param event
  8958. */
  8959. handleZoomStart: function(event) {
  8960. this.el.trigger(this.options.zoomStartEventName);
  8961. this.stopAnimation();
  8962. this.lastScale = 1;
  8963. this.nthZoom = 0;
  8964. this.lastZoomCenter = false;
  8965. this.hasInteraction = true;
  8966. },
  8967. /**
  8968. * Event handler for 'zoom'
  8969. * @param event
  8970. */
  8971. handleZoom: function(event, newScale) {
  8972. // a relative scale factor is used
  8973. var touchCenter = this.getTouchCenter(this.getTouches(event)), scale = newScale / this.lastScale;
  8974. this.lastScale = newScale;
  8975. // the first touch events are thrown away since they are not precise
  8976. this.nthZoom += 1;
  8977. if (this.nthZoom > 3) {
  8978. this.scale(scale, touchCenter);
  8979. this.drag(touchCenter, this.lastZoomCenter);
  8980. }
  8981. this.lastZoomCenter = touchCenter;
  8982. },
  8983. handleZoomEnd: function() {
  8984. this.el.trigger(this.options.zoomEndEventName);
  8985. this.end();
  8986. },
  8987. /**
  8988. * Event handler for 'doubletap'
  8989. * @param event
  8990. */
  8991. handleDoubleTap: function(event) {
  8992. var center = this.getTouches(event)[0], zoomFactor = this.zoomFactor > 1 ? 1 : this.options.tapZoomFactor, startZoomFactor = this.zoomFactor, updateProgress = function(progress) {
  8993. this.scaleTo(startZoomFactor + progress * (zoomFactor - startZoomFactor), center);
  8994. }.bind(this);
  8995. if (this.hasInteraction) {
  8996. return;
  8997. }
  8998. if (startZoomFactor > zoomFactor) {
  8999. center = this.getCurrentZoomCenter();
  9000. }
  9001. this.animate(this.options.animationDuration, this.options.animationInterval, updateProgress, this.swing);
  9002. this.el.trigger(this.options.doubleTapEventName);
  9003. },
  9004. /**
  9005. * Max / min values for the offset
  9006. * @param offset
  9007. * @return {Object} the sanitized offset
  9008. */
  9009. sanitizeOffset: function(offset) {
  9010. var maxX = (this.zoomFactor - 1) * this.getContainerX(), maxY = (this.zoomFactor - 1) * this.getContainerY(), maxOffsetX = Math.max(maxX, 0), maxOffsetY = Math.max(maxY, 0), minOffsetX = Math.min(maxX, 0), minOffsetY = Math.min(maxY, 0);
  9011. return {
  9012. x: Math.min(Math.max(offset.x, minOffsetX), maxOffsetX),
  9013. y: Math.min(Math.max(offset.y, minOffsetY), maxOffsetY)
  9014. };
  9015. },
  9016. /**
  9017. * Scale to a specific zoom factor (not relative)
  9018. * @param zoomFactor
  9019. * @param center
  9020. */
  9021. scaleTo: function(zoomFactor, center) {
  9022. this.scale(zoomFactor / this.zoomFactor, center);
  9023. },
  9024. /**
  9025. * Scales the element from specified center
  9026. * @param scale
  9027. * @param center
  9028. */
  9029. scale: function(scale, center) {
  9030. scale = this.scaleZoomFactor(scale);
  9031. this.addOffset({
  9032. x: (scale - 1) * (center.x + this.offset.x),
  9033. y: (scale - 1) * (center.y + this.offset.y)
  9034. });
  9035. },
  9036. /**
  9037. * Scales the zoom factor relative to current state
  9038. * @param scale
  9039. * @return the actual scale (can differ because of max min zoom factor)
  9040. */
  9041. scaleZoomFactor: function(scale) {
  9042. var originalZoomFactor = this.zoomFactor;
  9043. this.zoomFactor *= scale;
  9044. this.zoomFactor = Math.min(this.options.maxZoom, Math.max(this.zoomFactor, this.options.minZoom));
  9045. return this.zoomFactor / originalZoomFactor;
  9046. },
  9047. /**
  9048. * Drags the element
  9049. * @param center
  9050. * @param lastCenter
  9051. */
  9052. drag: function(center, lastCenter) {
  9053. if (lastCenter) {
  9054. if (this.options.lockDragAxis) {
  9055. // lock scroll to position that was changed the most
  9056. if (Math.abs(center.x - lastCenter.x) > Math.abs(center.y - lastCenter.y)) {
  9057. this.addOffset({
  9058. x: -(center.x - lastCenter.x),
  9059. y: 0
  9060. });
  9061. } else {
  9062. this.addOffset({
  9063. y: -(center.y - lastCenter.y),
  9064. x: 0
  9065. });
  9066. }
  9067. } else {
  9068. this.addOffset({
  9069. y: -(center.y - lastCenter.y),
  9070. x: -(center.x - lastCenter.x)
  9071. });
  9072. }
  9073. }
  9074. },
  9075. /**
  9076. * Calculates the touch center of multiple touches
  9077. * @param touches
  9078. * @return {Object}
  9079. */
  9080. getTouchCenter: function(touches) {
  9081. return this.getVectorAvg(touches);
  9082. },
  9083. /**
  9084. * Calculates the average of multiple vectors (x, y values)
  9085. */
  9086. getVectorAvg: function(vectors) {
  9087. return {
  9088. x: vectors.map(function(v) {
  9089. return v.x;
  9090. }).reduce(sum) / vectors.length,
  9091. y: vectors.map(function(v) {
  9092. return v.y;
  9093. }).reduce(sum) / vectors.length
  9094. };
  9095. },
  9096. /**
  9097. * Adds an offset
  9098. * @param offset the offset to add
  9099. * @return return true when the offset change was accepted
  9100. */
  9101. addOffset: function(offset) {
  9102. this.offset = {
  9103. x: this.offset.x + offset.x,
  9104. y: this.offset.y + offset.y
  9105. };
  9106. },
  9107. sanitize: function() {
  9108. if (this.zoomFactor < this.options.zoomOutFactor) {
  9109. this.zoomOutAnimation();
  9110. } else if (this.isInsaneOffset(this.offset)) {
  9111. this.sanitizeOffsetAnimation();
  9112. }
  9113. },
  9114. /**
  9115. * Checks if the offset is ok with the current zoom factor
  9116. * @param offset
  9117. * @return {Boolean}
  9118. */
  9119. isInsaneOffset: function(offset) {
  9120. var sanitizedOffset = this.sanitizeOffset(offset);
  9121. return sanitizedOffset.x !== offset.x || sanitizedOffset.y !== offset.y;
  9122. },
  9123. /**
  9124. * Creates an animation moving to a sane offset
  9125. */
  9126. sanitizeOffsetAnimation: function() {
  9127. var targetOffset = this.sanitizeOffset(this.offset), startOffset = {
  9128. x: this.offset.x,
  9129. y: this.offset.y
  9130. }, updateProgress = function(progress) {
  9131. this.offset.x = startOffset.x + progress * (targetOffset.x - startOffset.x);
  9132. this.offset.y = startOffset.y + progress * (targetOffset.y - startOffset.y);
  9133. this.update();
  9134. }.bind(this);
  9135. this.animate(this.options.animationDuration, this.options.animationInterval, updateProgress, this.swing);
  9136. },
  9137. /**
  9138. * Zooms back to the original position,
  9139. * (no offset and zoom factor 1)
  9140. */
  9141. zoomOutAnimation: function() {
  9142. var startZoomFactor = this.zoomFactor, zoomFactor = 1, center = this.getCurrentZoomCenter(), updateProgress = function(progress) {
  9143. this.scaleTo(startZoomFactor + progress * (zoomFactor - startZoomFactor), center);
  9144. }.bind(this);
  9145. this.animate(this.options.animationDuration, this.options.animationInterval, updateProgress, this.swing);
  9146. },
  9147. /**
  9148. * Updates the aspect ratio
  9149. */
  9150. updateAspectRatio: function() {
  9151. // this.setContainerY(this.getContainerX() / this.getAspectRatio());
  9152. // @modified
  9153. this.setContainerY();
  9154. },
  9155. /**
  9156. * Calculates the initial zoom factor (for the element to fit into the container)
  9157. * @return the initial zoom factor
  9158. */
  9159. getInitialZoomFactor: function() {
  9160. // use .offsetWidth instead of width()
  9161. // because jQuery-width() return the original width but Zepto-width() will calculate width with transform.
  9162. // the same as .height()
  9163. return this.container[0].offsetWidth / this.el[0].offsetWidth;
  9164. },
  9165. /**
  9166. * Calculates the aspect ratio of the element
  9167. * @return the aspect ratio
  9168. */
  9169. getAspectRatio: function() {
  9170. return this.el[0].offsetWidth / this.el[0].offsetHeight;
  9171. },
  9172. /**
  9173. * Calculates the virtual zoom center for the current offset and zoom factor
  9174. * (used for reverse zoom)
  9175. * @return {Object} the current zoom center
  9176. */
  9177. getCurrentZoomCenter: function() {
  9178. // uses following formula to calculate the zoom center x value
  9179. // offset_left / offset_right = zoomcenter_x / (container_x - zoomcenter_x)
  9180. var length = this.container[0].offsetWidth * this.zoomFactor, offsetLeft = this.offset.x, offsetRight = length - offsetLeft - this.container[0].offsetWidth, widthOffsetRatio = offsetLeft / offsetRight, centerX = widthOffsetRatio * this.container[0].offsetWidth / (widthOffsetRatio + 1), // the same for the zoomcenter y
  9181. height = this.container[0].offsetHeight * this.zoomFactor, offsetTop = this.offset.y, offsetBottom = height - offsetTop - this.container[0].offsetHeight, heightOffsetRatio = offsetTop / offsetBottom, centerY = heightOffsetRatio * this.container[0].offsetHeight / (heightOffsetRatio + 1);
  9182. // prevents division by zero
  9183. if (offsetRight === 0) {
  9184. centerX = this.container[0].offsetWidth;
  9185. }
  9186. if (offsetBottom === 0) {
  9187. centerY = this.container[0].offsetHeight;
  9188. }
  9189. return {
  9190. x: centerX,
  9191. y: centerY
  9192. };
  9193. },
  9194. canDrag: function() {
  9195. return !isCloseTo(this.zoomFactor, 1);
  9196. },
  9197. /**
  9198. * Returns the touches of an event relative to the container offset
  9199. * @param event
  9200. * @return array touches
  9201. */
  9202. getTouches: function(event) {
  9203. var position = this.container.offset();
  9204. return Array.prototype.slice.call(event.touches).map(function(touch) {
  9205. return {
  9206. x: touch.pageX - position.left,
  9207. y: touch.pageY - position.top
  9208. };
  9209. });
  9210. },
  9211. /**
  9212. * Animation loop
  9213. * does not support simultaneous animations
  9214. * @param duration
  9215. * @param interval
  9216. * @param framefn
  9217. * @param timefn
  9218. * @param callback
  9219. */
  9220. animate: function(duration, interval, framefn, timefn, callback) {
  9221. var startTime = new Date().getTime(), renderFrame = function() {
  9222. if (!this.inAnimation) {
  9223. return;
  9224. }
  9225. var frameTime = new Date().getTime() - startTime, progress = frameTime / duration;
  9226. if (frameTime >= duration) {
  9227. framefn(1);
  9228. if (callback) {
  9229. callback();
  9230. }
  9231. this.update();
  9232. this.stopAnimation();
  9233. this.update();
  9234. } else {
  9235. if (timefn) {
  9236. progress = timefn(progress);
  9237. }
  9238. framefn(progress);
  9239. this.update();
  9240. setTimeout(renderFrame, interval);
  9241. }
  9242. }.bind(this);
  9243. this.inAnimation = true;
  9244. renderFrame();
  9245. },
  9246. /**
  9247. * Stops the animation
  9248. */
  9249. stopAnimation: function() {
  9250. this.inAnimation = false;
  9251. },
  9252. /**
  9253. * Swing timing function for animations
  9254. * @param p
  9255. * @return {Number}
  9256. */
  9257. swing: function(p) {
  9258. return -Math.cos(p * Math.PI) / 2 + .5;
  9259. },
  9260. getContainerX: function() {
  9261. // return this.container[0].offsetWidth;
  9262. // @modified
  9263. return window.innerWidth;
  9264. },
  9265. getContainerY: function() {
  9266. // return this.container[0].offsetHeight;
  9267. // @modified
  9268. return window.innerHeight;
  9269. },
  9270. setContainerY: function(y) {
  9271. // return this.container.height(y);
  9272. // @modified
  9273. var t = window.innerHeight;
  9274. return this.el.css({
  9275. height: t
  9276. }), this.container.height(t);
  9277. },
  9278. /**
  9279. * Creates the expected html structure
  9280. */
  9281. setupMarkup: function() {
  9282. this.container = $('<div class="pinch-zoom-container"></div>');
  9283. this.el.before(this.container);
  9284. this.container.append(this.el);
  9285. this.container.css({
  9286. overflow: "hidden",
  9287. position: "relative"
  9288. });
  9289. // Zepto doesn't recognize `webkitTransform..` style
  9290. this.el.css({
  9291. "-webkit-transform-origin": "0% 0%",
  9292. "-moz-transform-origin": "0% 0%",
  9293. "-ms-transform-origin": "0% 0%",
  9294. "-o-transform-origin": "0% 0%",
  9295. "transform-origin": "0% 0%",
  9296. position: "absolute"
  9297. });
  9298. },
  9299. end: function() {
  9300. this.hasInteraction = false;
  9301. this.sanitize();
  9302. this.update();
  9303. },
  9304. /**
  9305. * Binds all required event listeners
  9306. */
  9307. bindEvents: function() {
  9308. detectGestures(this.container.get(0), this);
  9309. // Zepto and jQuery both know about `on`
  9310. $(window).on("resize", this.update.bind(this));
  9311. $(this.el).find("img").on("load", this.update.bind(this));
  9312. },
  9313. /**
  9314. * Updates the css values according to the current zoom factor and offset
  9315. */
  9316. update: function() {
  9317. if (this.updatePlaned) {
  9318. return;
  9319. }
  9320. this.updatePlaned = true;
  9321. setTimeout(function() {
  9322. this.updatePlaned = false;
  9323. this.updateAspectRatio();
  9324. var zoomFactor = this.getInitialZoomFactor() * this.zoomFactor, offsetX = -this.offset.x / zoomFactor, offsetY = -this.offset.y / zoomFactor, transform3d = "scale3d(" + zoomFactor + ", " + zoomFactor + ",1) " + "translate3d(" + offsetX + "px," + offsetY + "px,0px)", transform2d = "scale(" + zoomFactor + ", " + zoomFactor + ") " + "translate(" + offsetX + "px," + offsetY + "px)", removeClone = function() {
  9325. if (this.clone) {
  9326. this.clone.remove();
  9327. delete this.clone;
  9328. }
  9329. }.bind(this);
  9330. // Scale 3d and translate3d are faster (at least on ios)
  9331. // but they also reduce the quality.
  9332. // PinchZoom uses the 3d transformations during interactions
  9333. // after interactions it falls back to 2d transformations
  9334. if (!this.options.use2d || this.hasInteraction || this.inAnimation) {
  9335. this.is3d = true;
  9336. removeClone();
  9337. this.el.css({
  9338. "-webkit-transform": transform3d,
  9339. "-o-transform": transform2d,
  9340. "-ms-transform": transform2d,
  9341. "-moz-transform": transform2d,
  9342. transform: transform3d
  9343. });
  9344. } else {
  9345. // When changing from 3d to 2d transform webkit has some glitches.
  9346. // To avoid this, a copy of the 3d transformed element is displayed in the
  9347. // foreground while the element is converted from 3d to 2d transform
  9348. if (this.is3d) {
  9349. this.clone = this.el.clone();
  9350. this.clone.css("pointer-events", "none");
  9351. this.clone.appendTo(this.container);
  9352. setTimeout(removeClone, 200);
  9353. }
  9354. this.el.css({
  9355. "-webkit-transform": transform2d,
  9356. "-o-transform": transform2d,
  9357. "-ms-transform": transform2d,
  9358. "-moz-transform": transform2d,
  9359. transform: transform2d
  9360. });
  9361. this.is3d = false;
  9362. }
  9363. }.bind(this), 0);
  9364. },
  9365. /**
  9366. * Enables event handling for gestures
  9367. */
  9368. enable: function() {
  9369. this.enabled = true;
  9370. },
  9371. /**
  9372. * Disables event handling for gestures
  9373. */
  9374. disable: function() {
  9375. this.enabled = false;
  9376. }
  9377. };
  9378. var detectGestures = function(el, target) {
  9379. var interaction = null, fingers = 0, lastTouchStart = null, startTouches = null, setInteraction = function(newInteraction, event) {
  9380. if (interaction !== newInteraction) {
  9381. if (interaction && !newInteraction) {
  9382. switch (interaction) {
  9383. case "zoom":
  9384. target.handleZoomEnd(event);
  9385. break;
  9386. case "drag":
  9387. target.handleDragEnd(event);
  9388. break;
  9389. }
  9390. }
  9391. switch (newInteraction) {
  9392. case "zoom":
  9393. target.handleZoomStart(event);
  9394. break;
  9395. case "drag":
  9396. target.handleDragStart(event);
  9397. break;
  9398. }
  9399. }
  9400. interaction = newInteraction;
  9401. }, updateInteraction = function(event) {
  9402. if (fingers === 2) {
  9403. setInteraction("zoom");
  9404. } else if (fingers === 1 && target.canDrag()) {
  9405. setInteraction("drag", event);
  9406. } else {
  9407. setInteraction(null, event);
  9408. }
  9409. }, targetTouches = function(touches) {
  9410. return Array.prototype.slice.call(touches).map(function(touch) {
  9411. return {
  9412. x: touch.pageX,
  9413. y: touch.pageY
  9414. };
  9415. });
  9416. }, getDistance = function(a, b) {
  9417. var x, y;
  9418. x = a.x - b.x;
  9419. y = a.y - b.y;
  9420. return Math.sqrt(x * x + y * y);
  9421. }, calculateScale = function(startTouches, endTouches) {
  9422. var startDistance = getDistance(startTouches[0], startTouches[1]), endDistance = getDistance(endTouches[0], endTouches[1]);
  9423. return endDistance / startDistance;
  9424. }, cancelEvent = function(event) {
  9425. event.stopPropagation();
  9426. event.preventDefault();
  9427. }, detectDoubleTap = function(event) {
  9428. var time = new Date().getTime();
  9429. if (fingers > 1) {
  9430. lastTouchStart = null;
  9431. }
  9432. if (time - lastTouchStart < 300) {
  9433. cancelEvent(event);
  9434. target.handleDoubleTap(event);
  9435. switch (interaction) {
  9436. case "zoom":
  9437. target.handleZoomEnd(event);
  9438. break;
  9439. case "drag":
  9440. target.handleDragEnd(event);
  9441. break;
  9442. }
  9443. }
  9444. if (fingers === 1) {
  9445. lastTouchStart = time;
  9446. }
  9447. }, firstMove = true;
  9448. el.addEventListener("touchstart", function(event) {
  9449. if (target.enabled) {
  9450. firstMove = true;
  9451. fingers = event.touches.length;
  9452. detectDoubleTap(event);
  9453. }
  9454. });
  9455. el.addEventListener("touchmove", function(event) {
  9456. if (target.enabled) {
  9457. if (firstMove) {
  9458. updateInteraction(event);
  9459. if (interaction) {
  9460. cancelEvent(event);
  9461. }
  9462. startTouches = targetTouches(event.touches);
  9463. } else {
  9464. switch (interaction) {
  9465. case "zoom":
  9466. target.handleZoom(event, calculateScale(startTouches, targetTouches(event.touches)));
  9467. break;
  9468. case "drag":
  9469. target.handleDrag(event);
  9470. break;
  9471. }
  9472. if (interaction) {
  9473. cancelEvent(event);
  9474. target.update();
  9475. }
  9476. }
  9477. firstMove = false;
  9478. }
  9479. });
  9480. el.addEventListener("touchend", function(event) {
  9481. if (target.enabled) {
  9482. fingers = event.touches.length;
  9483. updateInteraction(event);
  9484. }
  9485. });
  9486. };
  9487. return PinchZoom;
  9488. };
  9489. module.exports = definePinchZoom(window.Zepto);
  9490. });
  9491. define("accordion", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.collapse" ], function(require, exports, module) {
  9492. "use strict";
  9493. require("core");
  9494. require("ui.collapse");
  9495. var $ = window.Zepto;
  9496. var UI = $.AMUI;
  9497. function accordionInit() {
  9498. var $accordion = $('[data-am-widget="accordion"]');
  9499. var selector = {
  9500. item: ".am-accordion-item",
  9501. title: ".am-accordion-title",
  9502. content: ".am-accordion-content"
  9503. };
  9504. $accordion.each(function(i, item) {
  9505. var options = UI.utils.parseOptions($(item).attr("data-am-accordion"));
  9506. var $title = $(item).find(selector.title);
  9507. $title.on("click.accordion.amui", function() {
  9508. var $content = $(this).next(selector.content);
  9509. var $parent = $(this).parent(selector.item);
  9510. var data = $content.data("amui.collapse");
  9511. $parent.toggleClass("am-active");
  9512. if (!data) {
  9513. $content.collapse();
  9514. } else {
  9515. $content.collapse("toggle");
  9516. }
  9517. !options.multiple && $(item).children(".am-active").not($parent).removeClass("am-active").find(".am-accordion-content.am-in").collapse("close");
  9518. });
  9519. });
  9520. }
  9521. // Init on DOM ready
  9522. $(function() {
  9523. accordionInit();
  9524. });
  9525. exports.init = accordionInit;
  9526. });
  9527. define("divider", [], function(require, exports, module) {});
  9528. define("duoshuo", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  9529. "use strict";
  9530. require("core");
  9531. var $ = window.Zepto;
  9532. function duoshuoInit() {
  9533. var $dsThread = $(".ds-thread");
  9534. var dsShortName = $dsThread.parent('[data-am-widget="duoshuo"]').attr("data-ds-short-name");
  9535. var dsSrc = (document.location.protocol == "https:" ? "https:" : "http:") + "//static.duoshuo.com/embed.js";
  9536. if (!$dsThread.length || !dsShortName) {
  9537. return;
  9538. }
  9539. window.duoshuoQuery = {
  9540. short_name: dsShortName
  9541. };
  9542. // 已经有多说脚本
  9543. if ($('script[src="' + dsSrc + '"]').length) {
  9544. return;
  9545. }
  9546. var $dsJS = $("<script>", {
  9547. async: true,
  9548. type: "text/javascript",
  9549. src: dsSrc,
  9550. charset: "utf-8"
  9551. });
  9552. $("body").append($dsJS);
  9553. }
  9554. $(window).on("load", duoshuoInit);
  9555. exports.init = duoshuoInit;
  9556. });
  9557. define("figure", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.pureview", "zepto.pinchzoom", "util.hammer" ], function(require, exports, module) {
  9558. "use strict";
  9559. require("core");
  9560. require("ui.pureview");
  9561. var $ = window.Zepto;
  9562. var UI = $.AMUI;
  9563. /**
  9564. * Is Images zoomable
  9565. * @return {Boolean}
  9566. */
  9567. $.isImgZoomAble = function(element) {
  9568. var t = new Image();
  9569. t.src = element.src;
  9570. var zoomAble = $(element).width() < t.width;
  9571. if (zoomAble) {
  9572. $(element).closest(".am-figure").addClass("am-figure-zoomable");
  9573. }
  9574. return zoomAble;
  9575. };
  9576. function figureInit() {
  9577. $(".am-figure").each(function(i, item) {
  9578. var options = UI.utils.parseOptions($(item).attr("data-am-figure"));
  9579. if (options.pureview) {
  9580. $(item).addClass("am-figure-zoomable").pureview();
  9581. } else if (!!options.autoZoom) {
  9582. var zoomAble = $.isImgZoomAble($(item).find("img")[0]);
  9583. zoomAble && $(item).pureview();
  9584. }
  9585. });
  9586. }
  9587. $(window).on("load", function() {
  9588. figureInit();
  9589. });
  9590. exports.init = figureInit;
  9591. });
  9592. define("footer", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.modal", "ui.dimmer", "ui.add2home", "util.cookie" ], function(require, exports, module) {
  9593. "use strict";
  9594. require("core");
  9595. require("ui.modal");
  9596. var addToHS = require("ui.add2home");
  9597. var cookie = require("util.cookie");
  9598. var $ = window.Zepto;
  9599. function footerInit() {
  9600. // modal mode
  9601. $(".am-footer-ysp").on("click", function() {
  9602. $("#am-footer-mode").modal();
  9603. });
  9604. !window.AMUI_NO_ADD2HS && addToHS();
  9605. // switch mode
  9606. // switch to desktop
  9607. $('[data-rel="desktop"]').on("click", function(e) {
  9608. e.preventDefault();
  9609. if (window.AMPlatform) {
  9610. // front end
  9611. window.AMPlatform.util.goDesktop();
  9612. } else {
  9613. // back end
  9614. cookie.set("allmobilize", "desktop", "", "/");
  9615. window.location = window.location;
  9616. }
  9617. });
  9618. }
  9619. $(window).on("load", function() {
  9620. // make sure `window.AMPlatform` is usable
  9621. footerInit();
  9622. });
  9623. exports.init = footerInit;
  9624. });
  9625. define("gallery", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.pureview", "zepto.pinchzoom", "util.hammer" ], function(require, exports, module) {
  9626. "use strict";
  9627. require("core");
  9628. require("ui.pureview");
  9629. var $ = window.Zepto;
  9630. var UI = $.AMUI;
  9631. function galleryInit() {
  9632. var $gallery = $('[data-am-widget="gallery"]');
  9633. var $galleryOne = $gallery.filter(".am-gallery-one");
  9634. $gallery.each(function() {
  9635. var options = UI.utils.parseOptions($(this).attr("data-am-gallery"));
  9636. if (options.pureview) {
  9637. typeof options.pureview === "object" ? $(this).pureview(options.pureview) : $(this).pureview();
  9638. }
  9639. });
  9640. $galleryOne.each(function() {
  9641. galleryMore($(this));
  9642. });
  9643. }
  9644. function galleryMore($elements) {
  9645. var moreData = $("<li class='am-gallery-more'>" + '<a href="javascript:;">更多 &gt;&gt;</a></li>');
  9646. if ($elements.children().length > 6) {
  9647. $elements.children().each(function(index) {
  9648. if (index > 5) {
  9649. $(this).hide();
  9650. }
  9651. });
  9652. $elements.find(".am-gallery-more").remove();
  9653. $elements.append(moreData);
  9654. }
  9655. $elements.find(".am-gallery-more").on("click", function() {
  9656. $elements.children().show();
  9657. $(this).hide();
  9658. });
  9659. }
  9660. $(function() {
  9661. galleryInit();
  9662. });
  9663. exports.init = galleryInit;
  9664. });
  9665. define("gotop", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.smooth-scroll" ], function(require, exports, module) {
  9666. "use strict";
  9667. require("core");
  9668. require("ui.smooth-scroll");
  9669. var $ = window.Zepto;
  9670. function goTopInit() {
  9671. var $goTop = $('[data-am-widget="gotop"]');
  9672. var $fixed = $goTop.filter(".am-gotop-fixed");
  9673. var $win = $(window);
  9674. $goTop.find("a").on("click", function(e) {
  9675. e.preventDefault();
  9676. $win.smoothScroll();
  9677. });
  9678. function checkPosition() {
  9679. $fixed[($win.scrollTop() > 50 ? "add" : "remove") + "Class"]("am-active");
  9680. }
  9681. checkPosition();
  9682. $win.on("scroll.gotop.amui", $.AMUI.utils.debounce(checkPosition, 100));
  9683. }
  9684. $(function() {
  9685. goTopInit();
  9686. });
  9687. exports.init = goTopInit;
  9688. });
  9689. define("header", [], function(require, exports, module) {
  9690. "use strict";
  9691. var $ = window.Zepto;
  9692. function headerInit() {
  9693. $('[data-am-widget="header"]').each(function() {
  9694. if ($(this).hasClass("am-header-fixed")) {
  9695. $("body").addClass("am-with-fixed-header");
  9696. return false;
  9697. }
  9698. });
  9699. }
  9700. $(function() {
  9701. headerInit();
  9702. });
  9703. exports.init = headerInit;
  9704. });
  9705. define("intro", [], function(require, exports, module) {
  9706. "use strict";
  9707. });
  9708. define("list_news", [], function(require, exports, module) {
  9709. "use strict";
  9710. var $ = window.Zepto;
  9711. function listNewsInit() {
  9712. $(".am-list-news-one").each(function() {
  9713. amListNewsMore($(this));
  9714. });
  9715. }
  9716. function amListNewsMore($element) {
  9717. var $amList = $element.find(".am-list");
  9718. var $listMore = '<a class="am-list-news-more am-btn am-btn-default" ' + 'href="javascript:;">更多 &gt;&gt;</a>';
  9719. if ($amList.children().length > 6) {
  9720. $amList.children().each(function(index) {
  9721. if (index > 5) {
  9722. $(this).hide();
  9723. }
  9724. });
  9725. $element.find(".am-list-news-more").remove();
  9726. $element.append($listMore);
  9727. }
  9728. $element.find(".am-list-news-more").on("click", function() {
  9729. $amList.children().show();
  9730. $(this).hide();
  9731. });
  9732. }
  9733. $(function() {
  9734. listNewsInit();
  9735. });
  9736. exports.init = listNewsInit;
  9737. });
  9738. define("map", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  9739. /* jshint strict: false, maxlen: 200 */
  9740. /* global BMap */
  9741. require("core");
  9742. var $ = window.Zepto;
  9743. function addMapApi(callback) {
  9744. var $mapApi0 = $("<script/>", {
  9745. src: "http://api.map.baidu.com/getscript" + "?type=quick&file=api&ak=WVAXZ05oyNRXS5egLImmentg&t=20140109092002"
  9746. });
  9747. $("body").append($mapApi0);
  9748. $mapApi0.on("load", function() {
  9749. var $mapApi1 = $("<script/>", {
  9750. src: "http://api.map.baidu.com/getscript" + "?type=quick&file=feature" + "&ak=WVAXZ05oyNRXS5egLImmentg&t=20140109092002"
  9751. });
  9752. $("body").append($mapApi1);
  9753. $mapApi1.on("load", function() {
  9754. var script = document.createElement("script");
  9755. script.textContent = "(" + callback.toString() + ")();";
  9756. $("body")[0].appendChild(script);
  9757. });
  9758. });
  9759. }
  9760. function addBdMap() {
  9761. // 如果使用 $ 选择符,minify 以后会报错: $ is undefined
  9762. // 即使传入 $ 也无效,改为使用原生方法
  9763. // 这个函数作为 callback 会插入到 body 以后才执行,应该是 $ 引用错误导致
  9764. var content = document.querySelector(".am-map");
  9765. var defaultLng = 116.331398;
  9766. // 经度默认值
  9767. var defaultLat = 39.897445;
  9768. // 纬度默认值
  9769. var name = content.getAttribute("data-name");
  9770. var address = content.getAttribute("data-address");
  9771. var lng = content.getAttribute("data-longitude") || defaultLng;
  9772. var lat = content.getAttribute("data-latitude") || defaultLat;
  9773. var map = new BMap.Map("bd-map");
  9774. // 实例化一个地理坐标点
  9775. var point = new BMap.Point(lng, lat);
  9776. // 设初始化地图, options: 3-18
  9777. map.centerAndZoom(point, 18);
  9778. // 添加地图缩放控件
  9779. map.addControl(new BMap.ZoomControl());
  9780. var opts = {
  9781. width: 200,
  9782. // 信息窗口宽度
  9783. // height: 'auto', // 信息窗口高度
  9784. title: name
  9785. };
  9786. // 创建信息窗口对象
  9787. var infoWindow = new BMap.InfoWindow("地址:" + address, opts);
  9788. // 创建地址解析器实例
  9789. var myGeo = new BMap.Geocoder();
  9790. // 判断有没有使用经纬度
  9791. if (lng == defaultLng && lat == defaultLat) {
  9792. // 使用地址反解析来设置地图
  9793. // 将地址解析结果显示在地图上,并调整地图视野
  9794. myGeo.getPoint(address, function(point) {
  9795. if (point) {
  9796. map.centerAndZoom(point, 17);
  9797. map.addOverlay(new BMap.Marker(point));
  9798. map.openInfoWindow(infoWindow, point);
  9799. }
  9800. }, "");
  9801. } else {
  9802. // 使用经纬度来设置地图
  9803. myGeo.getLocation(point, function(result) {
  9804. map.centerAndZoom(point, 17);
  9805. map.addOverlay(new BMap.Marker(point));
  9806. if (address) {
  9807. map.openInfoWindow(infoWindow, point);
  9808. } else {
  9809. map.openInfoWindow(new BMap.InfoWindow(address, opts), point);
  9810. }
  9811. });
  9812. }
  9813. }
  9814. var mapInit = function() {
  9815. $(".am-map").length && addMapApi(addBdMap);
  9816. };
  9817. $(document).on("ready", mapInit);
  9818. exports.init = mapInit;
  9819. });
  9820. define("mechat", [], function(require, exports, module) {
  9821. "use strict";
  9822. var $ = window.Zepto;
  9823. function mechatInit() {
  9824. if (!$("#mechat").length) {
  9825. return;
  9826. }
  9827. var $mechat = $('[data-am-widget="mechat"]');
  9828. var unitid = $mechat.data("am-mechat-unitid");
  9829. var $mechatData = $("<script>", {
  9830. charset: "utf-8",
  9831. src: "http://mechatim.com/js/unit/button.js?id=" + unitid
  9832. });
  9833. $("body").append($mechatData);
  9834. }
  9835. // Lazy load
  9836. $(window).on("load", mechatInit);
  9837. exports.init = mechatInit;
  9838. });
  9839. define("menu", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.offcanvas", "zepto.outerdemension", "ui.collapse", "ui.iscroll-lite" ], function(require, exports, module) {
  9840. "use strict";
  9841. require("core");
  9842. require("ui.offcanvas");
  9843. require("ui.collapse");
  9844. var IScroll = require("ui.iscroll-lite");
  9845. var $ = window.Zepto;
  9846. var menuInit = function() {
  9847. var $menus = $('[data-am-widget="menu"]');
  9848. $menus.find(".am-menu-nav .am-parent > a").on("click", function(e) {
  9849. e.preventDefault();
  9850. var $clicked = $(this);
  9851. var $parent = $clicked.parent();
  9852. var $subMenu = $clicked.next(".am-menu-sub");
  9853. $parent.toggleClass("am-open");
  9854. $subMenu.collapse("toggle");
  9855. $parent.siblings(".am-parent").removeClass("am-open").children(".am-menu-sub.am-in").collapse("close");
  9856. });
  9857. // Dropdown/slideDown menu
  9858. $menus.filter("[data-am-menu-collapse]").find("> .am-menu-toggle").on("click", function(e) {
  9859. e.preventDefault();
  9860. var $this = $(this);
  9861. var $nav = $this.next(".am-menu-nav");
  9862. $this.toggleClass("am-active");
  9863. $nav.collapse("toggle");
  9864. });
  9865. // OffCanvas menu
  9866. $menus.filter("[data-am-menu-offcanvas]").find("> .am-menu-toggle").on("click", function(e) {
  9867. e.preventDefault();
  9868. var $this = $(this);
  9869. var $nav = $this.next(".am-offcanvas");
  9870. $this.toggleClass("am-active");
  9871. $nav.offCanvas("open");
  9872. });
  9873. // Close offCanvas when link clicked
  9874. var autoCloseOffCanvas = '.am-offcanvas[data-dismiss-on="click"]';
  9875. var $autoCloseOffCanvas = $(autoCloseOffCanvas);
  9876. $autoCloseOffCanvas.find("a").not(".am-parent>a").on("click", function(e) {
  9877. $(this).parents(autoCloseOffCanvas).offCanvas("close");
  9878. });
  9879. // one theme
  9880. $menus.filter(".am-menu-one").each(function(index) {
  9881. var $this = $(this);
  9882. var $wrap = $('<div class="am-menu-nav-sub-wrap"></div>');
  9883. var allWidth = 0;
  9884. var $nav = $this.find(".am-menu-nav");
  9885. var $navTopItem = $nav.children("li");
  9886. var prevIndex;
  9887. $navTopItem.filter(".am-parent").each(function(index) {
  9888. $(this).attr("data-rel", "#am-menu-sub-" + index);
  9889. $(this).find(".am-menu-sub").attr("id", "am-menu-sub-" + index).appendTo($wrap);
  9890. });
  9891. $this.append($wrap);
  9892. $nav.wrap('<div class="am-menu-nav-wrap" id="am-menu-' + index + '">');
  9893. // $navTopItem.eq(0).addClass('am-active');
  9894. // 计算出所有 li 宽度
  9895. $navTopItem.each(function(i) {
  9896. allWidth += parseFloat($(this).css("width"));
  9897. });
  9898. $nav.width(allWidth);
  9899. var menuScroll = new IScroll("#am-menu-" + index, {
  9900. eventPassthrough: true,
  9901. scrollX: true,
  9902. scrollY: false,
  9903. preventDefault: false
  9904. });
  9905. $navTopItem.on("click", function() {
  9906. var $clicked = $(this);
  9907. $clicked.addClass("am-active").siblings().removeClass("am-active");
  9908. $wrap.find(".am-menu-sub.am-in").collapse("close");
  9909. if ($clicked.is(".am-parent")) {
  9910. !$clicked.hasClass(".am-open") && $wrap.find($clicked.attr("data-rel")).collapse("open");
  9911. } else {
  9912. $clicked.siblings().removeClass("am-open");
  9913. }
  9914. // 第一次调用,没有prevIndex
  9915. if (prevIndex === undefined) {
  9916. prevIndex = $(this).index() ? 0 : 1;
  9917. }
  9918. // 判断方向
  9919. var dir = $(this).index() > prevIndex;
  9920. var target = $(this)[dir ? "next" : "prev"]();
  9921. // 点击的按钮,显示一半
  9922. var offset = target.offset() || $(this).offset();
  9923. var within = $this.offset();
  9924. // 父类左边距
  9925. var listOffset;
  9926. var parentLeft = parseInt($this.css("padding-left"));
  9927. if (dir ? offset.left + offset.width > within.left + within.width : offset.left < within.left) {
  9928. listOffset = $nav.offset();
  9929. menuScroll.scrollTo(dir ? within.width - offset.left + listOffset.left - offset.width - parentLeft : listOffset.left - offset.left, 0, 400);
  9930. }
  9931. prevIndex = $(this).index();
  9932. });
  9933. $this.on("touchmove", function(event) {
  9934. event.preventDefault();
  9935. });
  9936. });
  9937. };
  9938. $(function() {
  9939. menuInit();
  9940. });
  9941. exports.init = menuInit;
  9942. });
  9943. define("navbar", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.modal", "ui.dimmer", "util.qrcode", "ui.share" ], function(require, exports, module) {
  9944. "use strict";
  9945. require("core");
  9946. require("ui.modal");
  9947. var $ = window.Zepto;
  9948. var UI = $.AMUI;
  9949. var QRCode = require("util.qrcode");
  9950. var share = require("ui.share");
  9951. function navbarInit() {
  9952. var $navBar = $('[data-am-widget="navbar"]');
  9953. if (!$navBar.length) {
  9954. return;
  9955. }
  9956. var $win = $(window);
  9957. var $body = $("body");
  9958. var $navBarNav = $navBar.find(".am-navbar-nav");
  9959. var $navItems = $navBar.find("li");
  9960. var navItemsCounter = $navItems.length;
  9961. var configItems = $navBarNav.attr("class") && parseInt($navBarNav.attr("class").match(/sm-block-grid-(\d+)/)[1]) || 3;
  9962. var navMinWidth = 60;
  9963. // 每个 li 最小宽度
  9964. var offsetWidth = 16;
  9965. var $share = $navItems.filter("[data-am-navbar-share]");
  9966. var $qrcode = $navItems.filter("[data-am-navbar-qrcode]");
  9967. var activeStatus = "am-active";
  9968. var $moreActions = $('<ul class="am-navbar-actions"></ul>', {
  9969. id: UI.utils.generateGUID("am-navbar-actions")
  9970. });
  9971. var $moreLink = $('<li class="am-navbar-labels am-navbar-more">' + '<a href="javascript: void(0);">' + '<span class="am-icon-angle-up"></span>' + '<span class="am-navbar-label">更多</span></a></li>');
  9972. // 如果有 Fix 的工具栏则设置 body 的 padding-bottom
  9973. if ($navBar.css("position") == "fixed") {
  9974. $body.addClass("am-with-fixed-navbar");
  9975. }
  9976. if ($qrcode.length) {
  9977. var qrId = "am-navbar-qrcode";
  9978. $qrModal = $("#" + qrId);
  9979. if (!$qrModal.length) {
  9980. var qrImg = $qrcode.attr("data-am-navbar-qrcode");
  9981. var $qrModal = $('<div class="am-modal am-modal-no-btn" id="">' + '<div class="am-modal-dialog">' + '<div class="am-modal-bd"></div></div>' + "</div>", {
  9982. id: qrId
  9983. });
  9984. var $qrContainer = $qrModal.find(".am-modal-bd");
  9985. // 判断上传自定义的二维码没有,否则生成二维码
  9986. if (qrImg) {
  9987. $qrContainer.html('<img src="' + qrImg + '"/>');
  9988. } else {
  9989. var qrnode = new QRCode({
  9990. render: "canvas",
  9991. correctLevel: 0,
  9992. text: window.location.href,
  9993. width: 200,
  9994. height: 200,
  9995. background: "#fff",
  9996. foreground: "#000"
  9997. });
  9998. $qrContainer.html(qrnode);
  9999. }
  10000. $body.append($qrModal);
  10001. }
  10002. $qrcode.on("click", function(e) {
  10003. e.preventDefault();
  10004. $qrModal.modal();
  10005. });
  10006. }
  10007. if (navItemsCounter > configItems && navItemsCounter > calcSuiteItems()) {
  10008. initActions();
  10009. }
  10010. // console.log('NavItems: %d, config: %d, best: %d',
  10011. // navItemsCounter, configItems, calcSuiteItems());
  10012. function initActions() {
  10013. $navBarNav.append($moreLink);
  10014. $navBarNav.find("li").not(".am-navbar-more").slice(calcSuiteItems() - 1).appendTo($moreActions);
  10015. // Append more actions
  10016. $navBar.append($moreActions);
  10017. }
  10018. function checkNavBarItems() {
  10019. if (calcSuiteItems() >= navItemsCounter) {
  10020. // 显示所有链接,隐藏 more
  10021. $moreLink.hide();
  10022. $moreActions.find("li").insertBefore($moreLink);
  10023. return;
  10024. }
  10025. !$navBar.find(".am-navbar-actions").length && initActions();
  10026. $moreLink.show();
  10027. if ($navBarNav.find("li").length < calcSuiteItems()) {
  10028. $moreActions.find("li").slice(0, calcSuiteItems() - $navBarNav.find("li").length).insertBefore($moreLink);
  10029. } else if ($navBarNav.find("li").length > calcSuiteItems()) {
  10030. if ($moreActions.find("li").length) {
  10031. $navBarNav.find("li").not($moreLink).slice(calcSuiteItems() - 1).insertBefore($moreActions.find("li").first());
  10032. } else {
  10033. $navBarNav.find("li").not($moreLink).slice(calcSuiteItems() - 1).appendTo($moreActions);
  10034. }
  10035. }
  10036. }
  10037. /**
  10038. * 计算最适合显示的条目个数
  10039. * @returns {number}
  10040. */
  10041. function calcSuiteItems() {
  10042. return Math.floor(($win.width() - offsetWidth) / navMinWidth);
  10043. }
  10044. $navBar.on("click.navbar.amui", ".am-navbar-more", function(e) {
  10045. e.preventDefault();
  10046. $moreLink[$moreActions.hasClass(activeStatus) ? "removeClass" : "addClass"](activeStatus);
  10047. $moreActions.toggleClass(activeStatus);
  10048. });
  10049. if ($share.length) {
  10050. $share.on("click.navbar.amui", function(e) {
  10051. e.preventDefault();
  10052. share.toggle();
  10053. });
  10054. }
  10055. $win.on("resize.navbar.amui orientationchange.navbar.amui", UI.utils.debounce(checkNavBarItems, 150));
  10056. }
  10057. // DOMContent ready
  10058. $(function() {
  10059. navbarInit();
  10060. });
  10061. exports.init = navbarInit;
  10062. });
  10063. define("pagination", [], function(require, exports, module) {});
  10064. define("paragraph", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.pureview", "zepto.pinchzoom", "util.hammer", "ui.iscroll-lite" ], function(require, exports, module) {
  10065. "use strict";
  10066. require("core");
  10067. require("ui.pureview");
  10068. var $ = window.Zepto;
  10069. var UI = $.AMUI;
  10070. var IScroll = require("ui.iscroll-lite");
  10071. /**
  10072. * 表格滚动
  10073. * @param index ID 标识,多个 paragraph 里面多个 table
  10074. */
  10075. $.fn.scrollTable = function(index) {
  10076. var $this = $(this);
  10077. var $parent;
  10078. $this.wrap('<div class="am-paragraph-table-container" ' + 'id="am-paragraph-table-' + index + '">' + '<div class="am-paragraph-table-scroller"></div></div>');
  10079. $parent = $this.parent();
  10080. $parent.width($this.width());
  10081. $parent.height($this.height());
  10082. new IScroll("#am-paragraph-table-" + index, {
  10083. eventPassthrough: true,
  10084. scrollX: true,
  10085. scrollY: false,
  10086. preventDefault: false
  10087. });
  10088. };
  10089. function paragraphInit() {
  10090. var $paragraph = $('[data-am-widget="paragraph"]');
  10091. $paragraph.each(function(index) {
  10092. var $this = $(this);
  10093. var options = UI.utils.parseOptions($this.attr("data-am-paragraph"));
  10094. var $index = index;
  10095. if (options.pureview) {
  10096. $this.pureview();
  10097. }
  10098. if (options.tableScrollable) {
  10099. $this.find("table").each(function(index) {
  10100. if ($(this).width() > $(window).width()) {
  10101. $(this).scrollTable($index + "-" + index);
  10102. }
  10103. });
  10104. }
  10105. });
  10106. }
  10107. $(window).on("load", function() {
  10108. paragraphInit();
  10109. });
  10110. exports.init = paragraphInit;
  10111. });
  10112. define("slider", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "zepto.flexslider" ], function(require, exports, module) {
  10113. "use strict";
  10114. require("core");
  10115. require("zepto.flexslider");
  10116. var $ = window.Zepto;
  10117. var UI = $.AMUI;
  10118. function sliderInit() {
  10119. var $sliders = $('[data-am-widget="slider"]');
  10120. $sliders.not(".am-slider-manual").each(function(i, item) {
  10121. var options = UI.utils.parseOptions($(item).attr("data-am-slider"));
  10122. $(item).flexslider(options);
  10123. });
  10124. }
  10125. $(document).on("ready", sliderInit);
  10126. exports.init = sliderInit;
  10127. });
  10128. define("sohucs", [], function(require, exports, module) {
  10129. "use strict";
  10130. var $ = window.Zepto;
  10131. function sohuCSInit() {
  10132. if (!$("#SOHUCS").length) {
  10133. return;
  10134. }
  10135. var $sohucs = $('[data-am-widget="sohucs"]');
  10136. var appid = $sohucs.attr("data-am-sohucs-appid");
  10137. var conf = $sohucs.attr("data-am-sohucs-conf");
  10138. var $cy = $("<script></script>", {
  10139. charset: "utf-8",
  10140. id: "changyan_mobile_js",
  10141. src: "http://changyan.sohu.com/upload/mobile/wap-js/" + "changyan_mobile.js?client_id=" + appid + "&conf=" + conf
  10142. });
  10143. $("body").append($cy);
  10144. }
  10145. // Lazy load
  10146. $(window).on("load", sohuCSInit);
  10147. exports.init = sohuCSInit;
  10148. });
  10149. define("tabs", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.tabs", "util.hammer" ], function(require, exports, module) {
  10150. "use strict";
  10151. require("core");
  10152. require("ui.tabs");
  10153. var $ = window.Zepto;
  10154. function tabsInit() {
  10155. $('[data-am-widget="tabs"]').each(function() {
  10156. var options = $(this).data("amTabsNoswipe") ? {
  10157. noSwipe: 1
  10158. } : {};
  10159. $(this).tabs(options);
  10160. });
  10161. }
  10162. $(function() {
  10163. tabsInit();
  10164. });
  10165. exports.init = tabsInit;
  10166. });
  10167. define("titlebar", [], function(require, exports, module) {});
  10168. seajs.use(["core","util.fastclick","util.hammer","zepto.outerdemension","zepto.extend.data","zepto.extend.fx","zepto.extend.selector","ui.add2home","ui.collapse","ui.dimmer","ui.iscroll-lite","ui.modal","ui.offcanvas","ui.pureview","ui.share","ui.smooth-scroll","ui.tabs","util.cookie","util.qrcode","zepto.flexslider","zepto.pinchzoom","accordion","divider","duoshuo","figure","footer","gallery","gotop","header","intro","list_news","map","mechat","menu","navbar","pagination","paragraph","slider","sohucs","tabs","titlebar"]);