PageRenderTime 74ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/core/static/3rd/socket.io.js

https://bitbucket.org/ggerrietts/pnad
JavaScript | 3818 lines | 2872 code | 331 blank | 615 comment | 227 complexity | c0d95498ff96d63b2cbf520a5033d220 MD5 | raw file
  1. /*! Socket.IO.js build:0.9.6, development. Copyright(c) 2011 LearnBoost <dev@learnboost.com> MIT Licensed */
  2. var io = ('undefined' === typeof module ? {} : module.exports);
  3. (function() {
  4. /**
  5. * socket.io
  6. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  7. * MIT Licensed
  8. */
  9. (function (exports, global) {
  10. /**
  11. * IO namespace.
  12. *
  13. * @namespace
  14. */
  15. var io = exports;
  16. /**
  17. * Socket.IO version
  18. *
  19. * @api public
  20. */
  21. io.version = '0.9.6';
  22. /**
  23. * Protocol implemented.
  24. *
  25. * @api public
  26. */
  27. io.protocol = 1;
  28. /**
  29. * Available transports, these will be populated with the available transports
  30. *
  31. * @api public
  32. */
  33. io.transports = [];
  34. /**
  35. * Keep track of jsonp callbacks.
  36. *
  37. * @api private
  38. */
  39. io.j = [];
  40. /**
  41. * Keep track of our io.Sockets
  42. *
  43. * @api private
  44. */
  45. io.sockets = {};
  46. /**
  47. * Manages connections to hosts.
  48. *
  49. * @param {String} uri
  50. * @Param {Boolean} force creation of new socket (defaults to false)
  51. * @api public
  52. */
  53. io.connect = function (host, details) {
  54. var uri = io.util.parseUri(host)
  55. , uuri
  56. , socket;
  57. if (global && global.location) {
  58. uri.protocol = uri.protocol || global.location.protocol.slice(0, -1);
  59. uri.host = uri.host || (global.document
  60. ? global.document.domain : global.location.hostname);
  61. uri.port = uri.port || global.location.port;
  62. }
  63. uuri = io.util.uniqueUri(uri);
  64. var options = {
  65. host: uri.host
  66. , secure: 'https' == uri.protocol
  67. , port: uri.port || ('https' == uri.protocol ? 443 : 80)
  68. , query: uri.query || ''
  69. };
  70. io.util.merge(options, details);
  71. if (options['force new connection'] || !io.sockets[uuri]) {
  72. socket = new io.Socket(options);
  73. }
  74. if (!options['force new connection'] && socket) {
  75. io.sockets[uuri] = socket;
  76. }
  77. socket = socket || io.sockets[uuri];
  78. // if path is different from '' or /
  79. return socket.of(uri.path.length > 1 ? uri.path : '');
  80. };
  81. })('object' === typeof module ? module.exports : (this.io = {}), this);
  82. /**
  83. * socket.io
  84. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  85. * MIT Licensed
  86. */
  87. (function (exports, global) {
  88. /**
  89. * Utilities namespace.
  90. *
  91. * @namespace
  92. */
  93. var util = exports.util = {};
  94. /**
  95. * Parses an URI
  96. *
  97. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  98. * @api public
  99. */
  100. var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  101. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
  102. 'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
  103. 'anchor'];
  104. util.parseUri = function (str) {
  105. var m = re.exec(str || '')
  106. , uri = {}
  107. , i = 14;
  108. while (i--) {
  109. uri[parts[i]] = m[i] || '';
  110. }
  111. return uri;
  112. };
  113. /**
  114. * Produces a unique url that identifies a Socket.IO connection.
  115. *
  116. * @param {Object} uri
  117. * @api public
  118. */
  119. util.uniqueUri = function (uri) {
  120. var protocol = uri.protocol
  121. , host = uri.host
  122. , port = uri.port;
  123. if ('document' in global) {
  124. host = host || document.domain;
  125. port = port || (protocol == 'https'
  126. && document.location.protocol !== 'https:' ? 443 : document.location.port);
  127. } else {
  128. host = host || 'localhost';
  129. if (!port && protocol == 'https') {
  130. port = 443;
  131. }
  132. }
  133. return (protocol || 'http') + '://' + host + ':' + (port || 80);
  134. };
  135. /**
  136. * Mergest 2 query strings in to once unique query string
  137. *
  138. * @param {String} base
  139. * @param {String} addition
  140. * @api public
  141. */
  142. util.query = function (base, addition) {
  143. var query = util.chunkQuery(base || '')
  144. , components = [];
  145. util.merge(query, util.chunkQuery(addition || ''));
  146. for (var part in query) {
  147. if (query.hasOwnProperty(part)) {
  148. components.push(part + '=' + query[part]);
  149. }
  150. }
  151. return components.length ? '?' + components.join('&') : '';
  152. };
  153. /**
  154. * Transforms a querystring in to an object
  155. *
  156. * @param {String} qs
  157. * @api public
  158. */
  159. util.chunkQuery = function (qs) {
  160. var query = {}
  161. , params = qs.split('&')
  162. , i = 0
  163. , l = params.length
  164. , kv;
  165. for (; i < l; ++i) {
  166. kv = params[i].split('=');
  167. if (kv[0]) {
  168. query[kv[0]] = kv[1];
  169. }
  170. }
  171. return query;
  172. };
  173. /**
  174. * Executes the given function when the page is loaded.
  175. *
  176. * io.util.load(function () { console.log('page loaded'); });
  177. *
  178. * @param {Function} fn
  179. * @api public
  180. */
  181. var pageLoaded = false;
  182. util.load = function (fn) {
  183. if ('document' in global && document.readyState === 'complete' || pageLoaded) {
  184. return fn();
  185. }
  186. util.on(global, 'load', fn, false);
  187. };
  188. /**
  189. * Adds an event.
  190. *
  191. * @api private
  192. */
  193. util.on = function (element, event, fn, capture) {
  194. if (element.attachEvent) {
  195. element.attachEvent('on' + event, fn);
  196. } else if (element.addEventListener) {
  197. element.addEventListener(event, fn, capture);
  198. }
  199. };
  200. /**
  201. * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
  202. *
  203. * @param {Boolean} [xdomain] Create a request that can be used cross domain.
  204. * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
  205. * @api private
  206. */
  207. util.request = function (xdomain) {
  208. if (xdomain && 'undefined' != typeof XDomainRequest) {
  209. return new XDomainRequest();
  210. }
  211. if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
  212. return new XMLHttpRequest();
  213. }
  214. if (!xdomain) {
  215. try {
  216. return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
  217. } catch(e) { }
  218. }
  219. return null;
  220. };
  221. /**
  222. * XHR based transport constructor.
  223. *
  224. * @constructor
  225. * @api public
  226. */
  227. /**
  228. * Change the internal pageLoaded value.
  229. */
  230. if ('undefined' != typeof window) {
  231. util.load(function () {
  232. pageLoaded = true;
  233. });
  234. }
  235. /**
  236. * Defers a function to ensure a spinner is not displayed by the browser
  237. *
  238. * @param {Function} fn
  239. * @api public
  240. */
  241. util.defer = function (fn) {
  242. if (!util.ua.webkit || 'undefined' != typeof importScripts) {
  243. return fn();
  244. }
  245. util.load(function () {
  246. setTimeout(fn, 100);
  247. });
  248. };
  249. /**
  250. * Merges two objects.
  251. *
  252. * @api public
  253. */
  254. util.merge = function merge (target, additional, deep, lastseen) {
  255. var seen = lastseen || []
  256. , depth = typeof deep == 'undefined' ? 2 : deep
  257. , prop;
  258. for (prop in additional) {
  259. if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
  260. if (typeof target[prop] !== 'object' || !depth) {
  261. target[prop] = additional[prop];
  262. seen.push(additional[prop]);
  263. } else {
  264. util.merge(target[prop], additional[prop], depth - 1, seen);
  265. }
  266. }
  267. }
  268. return target;
  269. };
  270. /**
  271. * Merges prototypes from objects
  272. *
  273. * @api public
  274. */
  275. util.mixin = function (ctor, ctor2) {
  276. util.merge(ctor.prototype, ctor2.prototype);
  277. };
  278. /**
  279. * Shortcut for prototypical and static inheritance.
  280. *
  281. * @api private
  282. */
  283. util.inherit = function (ctor, ctor2) {
  284. function f() {};
  285. f.prototype = ctor2.prototype;
  286. ctor.prototype = new f;
  287. };
  288. /**
  289. * Checks if the given object is an Array.
  290. *
  291. * io.util.isArray([]); // true
  292. * io.util.isArray({}); // false
  293. *
  294. * @param Object obj
  295. * @api public
  296. */
  297. util.isArray = Array.isArray || function (obj) {
  298. return Object.prototype.toString.call(obj) === '[object Array]';
  299. };
  300. /**
  301. * Intersects values of two arrays into a third
  302. *
  303. * @api public
  304. */
  305. util.intersect = function (arr, arr2) {
  306. var ret = []
  307. , longest = arr.length > arr2.length ? arr : arr2
  308. , shortest = arr.length > arr2.length ? arr2 : arr;
  309. for (var i = 0, l = shortest.length; i < l; i++) {
  310. if (~util.indexOf(longest, shortest[i]))
  311. ret.push(shortest[i]);
  312. }
  313. return ret;
  314. }
  315. /**
  316. * Array indexOf compatibility.
  317. *
  318. * @see bit.ly/a5Dxa2
  319. * @api public
  320. */
  321. util.indexOf = function (arr, o, i) {
  322. for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
  323. i < j && arr[i] !== o; i++) {}
  324. return j <= i ? -1 : i;
  325. };
  326. /**
  327. * Converts enumerables to array.
  328. *
  329. * @api public
  330. */
  331. util.toArray = function (enu) {
  332. var arr = [];
  333. for (var i = 0, l = enu.length; i < l; i++)
  334. arr.push(enu[i]);
  335. return arr;
  336. };
  337. /**
  338. * UA / engines detection namespace.
  339. *
  340. * @namespace
  341. */
  342. util.ua = {};
  343. /**
  344. * Whether the UA supports CORS for XHR.
  345. *
  346. * @api public
  347. */
  348. util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
  349. try {
  350. var a = new XMLHttpRequest();
  351. } catch (e) {
  352. return false;
  353. }
  354. return a.withCredentials != undefined;
  355. })();
  356. /**
  357. * Detect webkit.
  358. *
  359. * @api public
  360. */
  361. util.ua.webkit = 'undefined' != typeof navigator
  362. && /webkit/i.test(navigator.userAgent);
  363. /**
  364. * Detect iPad/iPhone/iPod.
  365. *
  366. * @api public
  367. */
  368. util.ua.iDevice = 'undefined' != typeof navigator
  369. && /iPad|iPhone|iPod/i.test(navigator.userAgent);
  370. })('undefined' != typeof io ? io : module.exports, this);
  371. /**
  372. * socket.io
  373. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  374. * MIT Licensed
  375. */
  376. (function (exports, io) {
  377. /**
  378. * Expose constructor.
  379. */
  380. exports.EventEmitter = EventEmitter;
  381. /**
  382. * Event emitter constructor.
  383. *
  384. * @api public.
  385. */
  386. function EventEmitter () {};
  387. /**
  388. * Adds a listener
  389. *
  390. * @api public
  391. */
  392. EventEmitter.prototype.on = function (name, fn) {
  393. if (!this.$events) {
  394. this.$events = {};
  395. }
  396. if (!this.$events[name]) {
  397. this.$events[name] = fn;
  398. } else if (io.util.isArray(this.$events[name])) {
  399. this.$events[name].push(fn);
  400. } else {
  401. this.$events[name] = [this.$events[name], fn];
  402. }
  403. return this;
  404. };
  405. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  406. /**
  407. * Adds a volatile listener.
  408. *
  409. * @api public
  410. */
  411. EventEmitter.prototype.once = function (name, fn) {
  412. var self = this;
  413. function on () {
  414. self.removeListener(name, on);
  415. fn.apply(this, arguments);
  416. };
  417. on.listener = fn;
  418. this.on(name, on);
  419. return this;
  420. };
  421. /**
  422. * Removes a listener.
  423. *
  424. * @api public
  425. */
  426. EventEmitter.prototype.removeListener = function (name, fn) {
  427. if (this.$events && this.$events[name]) {
  428. var list = this.$events[name];
  429. if (io.util.isArray(list)) {
  430. var pos = -1;
  431. for (var i = 0, l = list.length; i < l; i++) {
  432. if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
  433. pos = i;
  434. break;
  435. }
  436. }
  437. if (pos < 0) {
  438. return this;
  439. }
  440. list.splice(pos, 1);
  441. if (!list.length) {
  442. delete this.$events[name];
  443. }
  444. } else if (list === fn || (list.listener && list.listener === fn)) {
  445. delete this.$events[name];
  446. }
  447. }
  448. return this;
  449. };
  450. /**
  451. * Removes all listeners for an event.
  452. *
  453. * @api public
  454. */
  455. EventEmitter.prototype.removeAllListeners = function (name) {
  456. // TODO: enable this when node 0.5 is stable
  457. //if (name === undefined) {
  458. //this.$events = {};
  459. //return this;
  460. //}
  461. if (this.$events && this.$events[name]) {
  462. this.$events[name] = null;
  463. }
  464. return this;
  465. };
  466. /**
  467. * Gets all listeners for a certain event.
  468. *
  469. * @api publci
  470. */
  471. EventEmitter.prototype.listeners = function (name) {
  472. if (!this.$events) {
  473. this.$events = {};
  474. }
  475. if (!this.$events[name]) {
  476. this.$events[name] = [];
  477. }
  478. if (!io.util.isArray(this.$events[name])) {
  479. this.$events[name] = [this.$events[name]];
  480. }
  481. return this.$events[name];
  482. };
  483. /**
  484. * Emits an event.
  485. *
  486. * @api public
  487. */
  488. EventEmitter.prototype.emit = function (name) {
  489. if (!this.$events) {
  490. return false;
  491. }
  492. var handler = this.$events[name];
  493. if (!handler) {
  494. return false;
  495. }
  496. var args = Array.prototype.slice.call(arguments, 1);
  497. if ('function' == typeof handler) {
  498. handler.apply(this, args);
  499. } else if (io.util.isArray(handler)) {
  500. var listeners = handler.slice();
  501. for (var i = 0, l = listeners.length; i < l; i++) {
  502. listeners[i].apply(this, args);
  503. }
  504. } else {
  505. return false;
  506. }
  507. return true;
  508. };
  509. })(
  510. 'undefined' != typeof io ? io : module.exports
  511. , 'undefined' != typeof io ? io : module.parent.exports
  512. );
  513. /**
  514. * socket.io
  515. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  516. * MIT Licensed
  517. */
  518. /**
  519. * Based on JSON2 (http://www.JSON.org/js.html).
  520. */
  521. (function (exports, nativeJSON) {
  522. "use strict";
  523. // use native JSON if it's available
  524. if (nativeJSON && nativeJSON.parse){
  525. return exports.JSON = {
  526. parse: nativeJSON.parse
  527. , stringify: nativeJSON.stringify
  528. }
  529. }
  530. var JSON = exports.JSON = {};
  531. function f(n) {
  532. // Format integers to have at least two digits.
  533. return n < 10 ? '0' + n : n;
  534. }
  535. function date(d, key) {
  536. return isFinite(d.valueOf()) ?
  537. d.getUTCFullYear() + '-' +
  538. f(d.getUTCMonth() + 1) + '-' +
  539. f(d.getUTCDate()) + 'T' +
  540. f(d.getUTCHours()) + ':' +
  541. f(d.getUTCMinutes()) + ':' +
  542. f(d.getUTCSeconds()) + 'Z' : null;
  543. };
  544. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  545. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  546. gap,
  547. indent,
  548. meta = { // table of character substitutions
  549. '\b': '\\b',
  550. '\t': '\\t',
  551. '\n': '\\n',
  552. '\f': '\\f',
  553. '\r': '\\r',
  554. '"' : '\\"',
  555. '\\': '\\\\'
  556. },
  557. rep;
  558. function quote(string) {
  559. // If the string contains no control characters, no quote characters, and no
  560. // backslash characters, then we can safely slap some quotes around it.
  561. // Otherwise we must also replace the offending characters with safe escape
  562. // sequences.
  563. escapable.lastIndex = 0;
  564. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  565. var c = meta[a];
  566. return typeof c === 'string' ? c :
  567. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  568. }) + '"' : '"' + string + '"';
  569. }
  570. function str(key, holder) {
  571. // Produce a string from holder[key].
  572. var i, // The loop counter.
  573. k, // The member key.
  574. v, // The member value.
  575. length,
  576. mind = gap,
  577. partial,
  578. value = holder[key];
  579. // If the value has a toJSON method, call it to obtain a replacement value.
  580. if (value instanceof Date) {
  581. value = date(key);
  582. }
  583. // If we were called with a replacer function, then call the replacer to
  584. // obtain a replacement value.
  585. if (typeof rep === 'function') {
  586. value = rep.call(holder, key, value);
  587. }
  588. // What happens next depends on the value's type.
  589. switch (typeof value) {
  590. case 'string':
  591. return quote(value);
  592. case 'number':
  593. // JSON numbers must be finite. Encode non-finite numbers as null.
  594. return isFinite(value) ? String(value) : 'null';
  595. case 'boolean':
  596. case 'null':
  597. // If the value is a boolean or null, convert it to a string. Note:
  598. // typeof null does not produce 'null'. The case is included here in
  599. // the remote chance that this gets fixed someday.
  600. return String(value);
  601. // If the type is 'object', we might be dealing with an object or an array or
  602. // null.
  603. case 'object':
  604. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  605. // so watch out for that case.
  606. if (!value) {
  607. return 'null';
  608. }
  609. // Make an array to hold the partial results of stringifying this object value.
  610. gap += indent;
  611. partial = [];
  612. // Is the value an array?
  613. if (Object.prototype.toString.apply(value) === '[object Array]') {
  614. // The value is an array. Stringify every element. Use null as a placeholder
  615. // for non-JSON values.
  616. length = value.length;
  617. for (i = 0; i < length; i += 1) {
  618. partial[i] = str(i, value) || 'null';
  619. }
  620. // Join all of the elements together, separated with commas, and wrap them in
  621. // brackets.
  622. v = partial.length === 0 ? '[]' : gap ?
  623. '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
  624. '[' + partial.join(',') + ']';
  625. gap = mind;
  626. return v;
  627. }
  628. // If the replacer is an array, use it to select the members to be stringified.
  629. if (rep && typeof rep === 'object') {
  630. length = rep.length;
  631. for (i = 0; i < length; i += 1) {
  632. if (typeof rep[i] === 'string') {
  633. k = rep[i];
  634. v = str(k, value);
  635. if (v) {
  636. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  637. }
  638. }
  639. }
  640. } else {
  641. // Otherwise, iterate through all of the keys in the object.
  642. for (k in value) {
  643. if (Object.prototype.hasOwnProperty.call(value, k)) {
  644. v = str(k, value);
  645. if (v) {
  646. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  647. }
  648. }
  649. }
  650. }
  651. // Join all of the member texts together, separated with commas,
  652. // and wrap them in braces.
  653. v = partial.length === 0 ? '{}' : gap ?
  654. '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
  655. '{' + partial.join(',') + '}';
  656. gap = mind;
  657. return v;
  658. }
  659. }
  660. // If the JSON object does not yet have a stringify method, give it one.
  661. JSON.stringify = function (value, replacer, space) {
  662. // The stringify method takes a value and an optional replacer, and an optional
  663. // space parameter, and returns a JSON text. The replacer can be a function
  664. // that can replace values, or an array of strings that will select the keys.
  665. // A default replacer method can be provided. Use of the space parameter can
  666. // produce text that is more easily readable.
  667. var i;
  668. gap = '';
  669. indent = '';
  670. // If the space parameter is a number, make an indent string containing that
  671. // many spaces.
  672. if (typeof space === 'number') {
  673. for (i = 0; i < space; i += 1) {
  674. indent += ' ';
  675. }
  676. // If the space parameter is a string, it will be used as the indent string.
  677. } else if (typeof space === 'string') {
  678. indent = space;
  679. }
  680. // If there is a replacer, it must be a function or an array.
  681. // Otherwise, throw an error.
  682. rep = replacer;
  683. if (replacer && typeof replacer !== 'function' &&
  684. (typeof replacer !== 'object' ||
  685. typeof replacer.length !== 'number')) {
  686. throw new Error('JSON.stringify');
  687. }
  688. // Make a fake root object containing our value under the key of ''.
  689. // Return the result of stringifying the value.
  690. return str('', {'': value});
  691. };
  692. // If the JSON object does not yet have a parse method, give it one.
  693. JSON.parse = function (text, reviver) {
  694. // The parse method takes a text and an optional reviver function, and returns
  695. // a JavaScript value if the text is a valid JSON text.
  696. var j;
  697. function walk(holder, key) {
  698. // The walk method is used to recursively walk the resulting structure so
  699. // that modifications can be made.
  700. var k, v, value = holder[key];
  701. if (value && typeof value === 'object') {
  702. for (k in value) {
  703. if (Object.prototype.hasOwnProperty.call(value, k)) {
  704. v = walk(value, k);
  705. if (v !== undefined) {
  706. value[k] = v;
  707. } else {
  708. delete value[k];
  709. }
  710. }
  711. }
  712. }
  713. return reviver.call(holder, key, value);
  714. }
  715. // Parsing happens in four stages. In the first stage, we replace certain
  716. // Unicode characters with escape sequences. JavaScript handles many characters
  717. // incorrectly, either silently deleting them, or treating them as line endings.
  718. text = String(text);
  719. cx.lastIndex = 0;
  720. if (cx.test(text)) {
  721. text = text.replace(cx, function (a) {
  722. return '\\u' +
  723. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  724. });
  725. }
  726. // In the second stage, we run the text against regular expressions that look
  727. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  728. // because they can cause invocation, and '=' because it can cause mutation.
  729. // But just to be safe, we want to reject all unexpected forms.
  730. // We split the second stage into 4 regexp operations in order to work around
  731. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  732. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  733. // replace all simple value tokens with ']' characters. Third, we delete all
  734. // open brackets that follow a colon or comma or that begin the text. Finally,
  735. // we look to see that the remaining characters are only whitespace or ']' or
  736. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  737. if (/^[\],:{}\s]*$/
  738. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  739. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  740. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  741. // In the third stage we use the eval function to compile the text into a
  742. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  743. // in JavaScript: it can begin a block or an object literal. We wrap the text
  744. // in parens to eliminate the ambiguity.
  745. j = eval('(' + text + ')');
  746. // In the optional fourth stage, we recursively walk the new structure, passing
  747. // each name/value pair to a reviver function for possible transformation.
  748. return typeof reviver === 'function' ?
  749. walk({'': j}, '') : j;
  750. }
  751. // If the text is not JSON parseable, then a SyntaxError is thrown.
  752. throw new SyntaxError('JSON.parse');
  753. };
  754. })(
  755. 'undefined' != typeof io ? io : module.exports
  756. , typeof JSON !== 'undefined' ? JSON : undefined
  757. );
  758. /**
  759. * socket.io
  760. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  761. * MIT Licensed
  762. */
  763. (function (exports, io) {
  764. /**
  765. * Parser namespace.
  766. *
  767. * @namespace
  768. */
  769. var parser = exports.parser = {};
  770. /**
  771. * Packet types.
  772. */
  773. var packets = parser.packets = [
  774. 'disconnect'
  775. , 'connect'
  776. , 'heartbeat'
  777. , 'message'
  778. , 'json'
  779. , 'event'
  780. , 'ack'
  781. , 'error'
  782. , 'noop'
  783. ];
  784. /**
  785. * Errors reasons.
  786. */
  787. var reasons = parser.reasons = [
  788. 'transport not supported'
  789. , 'client not handshaken'
  790. , 'unauthorized'
  791. ];
  792. /**
  793. * Errors advice.
  794. */
  795. var advice = parser.advice = [
  796. 'reconnect'
  797. ];
  798. /**
  799. * Shortcuts.
  800. */
  801. var JSON = io.JSON
  802. , indexOf = io.util.indexOf;
  803. /**
  804. * Encodes a packet.
  805. *
  806. * @api private
  807. */
  808. parser.encodePacket = function (packet) {
  809. var type = indexOf(packets, packet.type)
  810. , id = packet.id || ''
  811. , endpoint = packet.endpoint || ''
  812. , ack = packet.ack
  813. , data = null;
  814. switch (packet.type) {
  815. case 'error':
  816. var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
  817. , adv = packet.advice ? indexOf(advice, packet.advice) : '';
  818. if (reason !== '' || adv !== '')
  819. data = reason + (adv !== '' ? ('+' + adv) : '');
  820. break;
  821. case 'message':
  822. if (packet.data !== '')
  823. data = packet.data;
  824. break;
  825. case 'event':
  826. var ev = { name: packet.name };
  827. if (packet.args && packet.args.length) {
  828. ev.args = packet.args;
  829. }
  830. data = JSON.stringify(ev);
  831. break;
  832. case 'json':
  833. data = JSON.stringify(packet.data);
  834. break;
  835. case 'connect':
  836. if (packet.qs)
  837. data = packet.qs;
  838. break;
  839. case 'ack':
  840. data = packet.ackId
  841. + (packet.args && packet.args.length
  842. ? '+' + JSON.stringify(packet.args) : '');
  843. break;
  844. }
  845. // construct packet with required fragments
  846. var encoded = [
  847. type
  848. , id + (ack == 'data' ? '+' : '')
  849. , endpoint
  850. ];
  851. // data fragment is optional
  852. if (data !== null && data !== undefined)
  853. encoded.push(data);
  854. return encoded.join(':');
  855. };
  856. /**
  857. * Encodes multiple messages (payload).
  858. *
  859. * @param {Array} messages
  860. * @api private
  861. */
  862. parser.encodePayload = function (packets) {
  863. var decoded = '';
  864. if (packets.length == 1)
  865. return packets[0];
  866. for (var i = 0, l = packets.length; i < l; i++) {
  867. var packet = packets[i];
  868. decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
  869. }
  870. return decoded;
  871. };
  872. /**
  873. * Decodes a packet
  874. *
  875. * @api private
  876. */
  877. var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
  878. parser.decodePacket = function (data) {
  879. var pieces = data.match(regexp);
  880. if (!pieces) return {};
  881. var id = pieces[2] || ''
  882. , data = pieces[5] || ''
  883. , packet = {
  884. type: packets[pieces[1]]
  885. , endpoint: pieces[4] || ''
  886. };
  887. // whether we need to acknowledge the packet
  888. if (id) {
  889. packet.id = id;
  890. if (pieces[3])
  891. packet.ack = 'data';
  892. else
  893. packet.ack = true;
  894. }
  895. // handle different packet types
  896. switch (packet.type) {
  897. case 'error':
  898. var pieces = data.split('+');
  899. packet.reason = reasons[pieces[0]] || '';
  900. packet.advice = advice[pieces[1]] || '';
  901. break;
  902. case 'message':
  903. packet.data = data || '';
  904. break;
  905. case 'event':
  906. try {
  907. var opts = JSON.parse(data);
  908. packet.name = opts.name;
  909. packet.args = opts.args;
  910. } catch (e) { }
  911. packet.args = packet.args || [];
  912. break;
  913. case 'json':
  914. try {
  915. packet.data = JSON.parse(data);
  916. } catch (e) { }
  917. break;
  918. case 'connect':
  919. packet.qs = data || '';
  920. break;
  921. case 'ack':
  922. var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
  923. if (pieces) {
  924. packet.ackId = pieces[1];
  925. packet.args = [];
  926. if (pieces[3]) {
  927. try {
  928. packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
  929. } catch (e) { }
  930. }
  931. }
  932. break;
  933. case 'disconnect':
  934. case 'heartbeat':
  935. break;
  936. };
  937. return packet;
  938. };
  939. /**
  940. * Decodes data payload. Detects multiple messages
  941. *
  942. * @return {Array} messages
  943. * @api public
  944. */
  945. parser.decodePayload = function (data) {
  946. // IE doesn't like data[i] for unicode chars, charAt works fine
  947. if (data.charAt(0) == '\ufffd') {
  948. var ret = [];
  949. for (var i = 1, length = ''; i < data.length; i++) {
  950. if (data.charAt(i) == '\ufffd') {
  951. ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
  952. i += Number(length) + 1;
  953. length = '';
  954. } else {
  955. length += data.charAt(i);
  956. }
  957. }
  958. return ret;
  959. } else {
  960. return [parser.decodePacket(data)];
  961. }
  962. };
  963. })(
  964. 'undefined' != typeof io ? io : module.exports
  965. , 'undefined' != typeof io ? io : module.parent.exports
  966. );
  967. /**
  968. * socket.io
  969. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  970. * MIT Licensed
  971. */
  972. (function (exports, io) {
  973. /**
  974. * Expose constructor.
  975. */
  976. exports.Transport = Transport;
  977. /**
  978. * This is the transport template for all supported transport methods.
  979. *
  980. * @constructor
  981. * @api public
  982. */
  983. function Transport (socket, sessid) {
  984. this.socket = socket;
  985. this.sessid = sessid;
  986. };
  987. /**
  988. * Apply EventEmitter mixin.
  989. */
  990. io.util.mixin(Transport, io.EventEmitter);
  991. /**
  992. * Handles the response from the server. When a new response is received
  993. * it will automatically update the timeout, decode the message and
  994. * forwards the response to the onMessage function for further processing.
  995. *
  996. * @param {String} data Response from the server.
  997. * @api private
  998. */
  999. Transport.prototype.onData = function (data) {
  1000. this.clearCloseTimeout();
  1001. // If the connection in currently open (or in a reopening state) reset the close
  1002. // timeout since we have just received data. This check is necessary so
  1003. // that we don't reset the timeout on an explicitly disconnected connection.
  1004. if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) {
  1005. this.setCloseTimeout();
  1006. }
  1007. if (data !== '') {
  1008. // todo: we should only do decodePayload for xhr transports
  1009. var msgs = io.parser.decodePayload(data);
  1010. if (msgs && msgs.length) {
  1011. for (var i = 0, l = msgs.length; i < l; i++) {
  1012. this.onPacket(msgs[i]);
  1013. }
  1014. }
  1015. }
  1016. return this;
  1017. };
  1018. /**
  1019. * Handles packets.
  1020. *
  1021. * @api private
  1022. */
  1023. Transport.prototype.onPacket = function (packet) {
  1024. this.socket.setHeartbeatTimeout();
  1025. if (packet.type == 'heartbeat') {
  1026. return this.onHeartbeat();
  1027. }
  1028. if (packet.type == 'connect' && packet.endpoint == '') {
  1029. this.onConnect();
  1030. }
  1031. if (packet.type == 'error' && packet.advice == 'reconnect') {
  1032. this.open = false;
  1033. }
  1034. this.socket.onPacket(packet);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets close timeout
  1039. *
  1040. * @api private
  1041. */
  1042. Transport.prototype.setCloseTimeout = function () {
  1043. if (!this.closeTimeout) {
  1044. var self = this;
  1045. this.closeTimeout = setTimeout(function () {
  1046. self.onDisconnect();
  1047. }, this.socket.closeTimeout);
  1048. }
  1049. };
  1050. /**
  1051. * Called when transport disconnects.
  1052. *
  1053. * @api private
  1054. */
  1055. Transport.prototype.onDisconnect = function () {
  1056. if (this.close && this.open) this.close();
  1057. this.clearTimeouts();
  1058. this.socket.onDisconnect();
  1059. return this;
  1060. };
  1061. /**
  1062. * Called when transport connects
  1063. *
  1064. * @api private
  1065. */
  1066. Transport.prototype.onConnect = function () {
  1067. this.socket.onConnect();
  1068. return this;
  1069. }
  1070. /**
  1071. * Clears close timeout
  1072. *
  1073. * @api private
  1074. */
  1075. Transport.prototype.clearCloseTimeout = function () {
  1076. if (this.closeTimeout) {
  1077. clearTimeout(this.closeTimeout);
  1078. this.closeTimeout = null;
  1079. }
  1080. };
  1081. /**
  1082. * Clear timeouts
  1083. *
  1084. * @api private
  1085. */
  1086. Transport.prototype.clearTimeouts = function () {
  1087. this.clearCloseTimeout();
  1088. if (this.reopenTimeout) {
  1089. clearTimeout(this.reopenTimeout);
  1090. }
  1091. };
  1092. /**
  1093. * Sends a packet
  1094. *
  1095. * @param {Object} packet object.
  1096. * @api private
  1097. */
  1098. Transport.prototype.packet = function (packet) {
  1099. this.send(io.parser.encodePacket(packet));
  1100. };
  1101. /**
  1102. * Send the received heartbeat message back to server. So the server
  1103. * knows we are still connected.
  1104. *
  1105. * @param {String} heartbeat Heartbeat response from the server.
  1106. * @api private
  1107. */
  1108. Transport.prototype.onHeartbeat = function (heartbeat) {
  1109. this.packet({ type: 'heartbeat' });
  1110. };
  1111. /**
  1112. * Called when the transport opens.
  1113. *
  1114. * @api private
  1115. */
  1116. Transport.prototype.onOpen = function () {
  1117. this.open = true;
  1118. this.clearCloseTimeout();
  1119. this.socket.onOpen();
  1120. };
  1121. /**
  1122. * Notifies the base when the connection with the Socket.IO server
  1123. * has been disconnected.
  1124. *
  1125. * @api private
  1126. */
  1127. Transport.prototype.onClose = function () {
  1128. var self = this;
  1129. /* FIXME: reopen delay causing a infinit loop
  1130. this.reopenTimeout = setTimeout(function () {
  1131. self.open();
  1132. }, this.socket.options['reopen delay']);*/
  1133. this.open = false;
  1134. this.socket.onClose();
  1135. this.onDisconnect();
  1136. };
  1137. /**
  1138. * Generates a connection url based on the Socket.IO URL Protocol.
  1139. * See <https://github.com/learnboost/socket.io-node/> for more details.
  1140. *
  1141. * @returns {String} Connection url
  1142. * @api private
  1143. */
  1144. Transport.prototype.prepareUrl = function () {
  1145. var options = this.socket.options;
  1146. return this.scheme() + '://'
  1147. + options.host + ':' + options.port + '/'
  1148. + options.resource + '/' + io.protocol
  1149. + '/' + this.name + '/' + this.sessid;
  1150. };
  1151. /**
  1152. * Checks if the transport is ready to start a connection.
  1153. *
  1154. * @param {Socket} socket The socket instance that needs a transport
  1155. * @param {Function} fn The callback
  1156. * @api private
  1157. */
  1158. Transport.prototype.ready = function (socket, fn) {
  1159. fn.call(this);
  1160. };
  1161. })(
  1162. 'undefined' != typeof io ? io : module.exports
  1163. , 'undefined' != typeof io ? io : module.parent.exports
  1164. );
  1165. /**
  1166. * socket.io
  1167. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1168. * MIT Licensed
  1169. */
  1170. (function (exports, io, global) {
  1171. /**
  1172. * Expose constructor.
  1173. */
  1174. exports.Socket = Socket;
  1175. /**
  1176. * Create a new `Socket.IO client` which can establish a persistent
  1177. * connection with a Socket.IO enabled server.
  1178. *
  1179. * @api public
  1180. */
  1181. function Socket (options) {
  1182. this.options = {
  1183. port: 80
  1184. , secure: false
  1185. , document: 'document' in global ? document : false
  1186. , resource: 'socket.io'
  1187. , transports: io.transports
  1188. , 'connect timeout': 10000
  1189. , 'try multiple transports': true
  1190. , 'reconnect': true
  1191. , 'reconnection delay': 500
  1192. , 'reconnection limit': Infinity
  1193. , 'reopen delay': 3000
  1194. , 'max reconnection attempts': 10
  1195. , 'sync disconnect on unload': true
  1196. , 'auto connect': true
  1197. , 'flash policy port': 10843
  1198. };
  1199. io.util.merge(this.options, options);
  1200. this.connected = false;
  1201. this.open = false;
  1202. this.connecting = false;
  1203. this.reconnecting = false;
  1204. this.namespaces = {};
  1205. this.buffer = [];
  1206. this.doBuffer = false;
  1207. if (this.options['sync disconnect on unload'] &&
  1208. (!this.isXDomain() || io.util.ua.hasCORS)) {
  1209. var self = this;
  1210. io.util.on(global, 'unload', function () {
  1211. self.disconnectSync();
  1212. }, false);
  1213. }
  1214. if (this.options['auto connect']) {
  1215. this.connect();
  1216. }
  1217. };
  1218. /**
  1219. * Apply EventEmitter mixin.
  1220. */
  1221. io.util.mixin(Socket, io.EventEmitter);
  1222. /**
  1223. * Returns a namespace listener/emitter for this socket
  1224. *
  1225. * @api public
  1226. */
  1227. Socket.prototype.of = function (name) {
  1228. if (!this.namespaces[name]) {
  1229. this.namespaces[name] = new io.SocketNamespace(this, name);
  1230. if (name !== '') {
  1231. this.namespaces[name].packet({ type: 'connect' });
  1232. }
  1233. }
  1234. return this.namespaces[name];
  1235. };
  1236. /**
  1237. * Emits the given event to the Socket and all namespaces
  1238. *
  1239. * @api private
  1240. */
  1241. Socket.prototype.publish = function () {
  1242. this.emit.apply(this, arguments);
  1243. var nsp;
  1244. for (var i in this.namespaces) {
  1245. if (this.namespaces.hasOwnProperty(i)) {
  1246. nsp = this.of(i);
  1247. nsp.$emit.apply(nsp, arguments);
  1248. }
  1249. }
  1250. };
  1251. /**
  1252. * Performs the handshake
  1253. *
  1254. * @api private
  1255. */
  1256. function empty () { };
  1257. Socket.prototype.handshake = function (fn) {
  1258. var self = this
  1259. , options = this.options;
  1260. function complete (data) {
  1261. if (data instanceof Error) {
  1262. self.connecting = false;
  1263. self.onError(data.message);
  1264. } else {
  1265. fn.apply(null, data.split(':'));
  1266. }
  1267. };
  1268. var url = [
  1269. 'http' + (options.secure ? 's' : '') + ':/'
  1270. , options.host + ':' + options.port
  1271. , options.resource
  1272. , io.protocol
  1273. , io.util.query(this.options.query, 't=' + +new Date)
  1274. ].join('/');
  1275. if (this.isXDomain() && !io.util.ua.hasCORS) {
  1276. var insertAt = document.getElementsByTagName('script')[0]
  1277. , script = document.createElement('script');
  1278. script.src = url + '&jsonp=' + io.j.length;
  1279. insertAt.parentNode.insertBefore(script, insertAt);
  1280. io.j.push(function (data) {
  1281. complete(data);
  1282. script.parentNode.removeChild(script);
  1283. });
  1284. } else {
  1285. var xhr = io.util.request();
  1286. xhr.open('GET', url, true);
  1287. xhr.withCredentials = true;
  1288. xhr.onreadystatechange = function () {
  1289. if (xhr.readyState == 4) {
  1290. xhr.onreadystatechange = empty;
  1291. if (xhr.status == 200) {
  1292. complete(xhr.responseText);
  1293. } else {
  1294. self.connecting = false;
  1295. !self.reconnecting && self.onError(xhr.responseText);
  1296. }
  1297. }
  1298. };
  1299. xhr.send(null);
  1300. }
  1301. };
  1302. /**
  1303. * Find an available transport based on the options supplied in the constructor.
  1304. *
  1305. * @api private
  1306. */
  1307. Socket.prototype.getTransport = function (override) {
  1308. var transports = override || this.transports, match;
  1309. for (var i = 0, transport; transport = transports[i]; i++) {
  1310. if (io.Transport[transport]
  1311. && io.Transport[transport].check(this)
  1312. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
  1313. return new io.Transport[transport](this, this.sessionid);
  1314. }
  1315. }
  1316. return null;
  1317. };
  1318. /**
  1319. * Connects to the server.
  1320. *
  1321. * @param {Function} [fn] Callback.
  1322. * @returns {io.Socket}
  1323. * @api public
  1324. */
  1325. Socket.prototype.connect = function (fn) {
  1326. if (this.connecting) {
  1327. return this;
  1328. }
  1329. var self = this;
  1330. self.connecting = true;
  1331. this.handshake(function (sid, heartbeat, close, transports) {
  1332. self.sessionid = sid;
  1333. self.closeTimeout = close * 1000;
  1334. self.heartbeatTimeout = heartbeat * 1000;
  1335. self.transports = transports ? io.util.intersect(
  1336. transports.split(',')
  1337. , self.options.transports
  1338. ) : self.options.transports;
  1339. self.setHeartbeatTimeout();
  1340. function connect (transports){
  1341. if (self.transport) self.transport.clearTimeouts();
  1342. self.transport = self.getTransport(transports);
  1343. if (!self.transport) return self.publish('connect_failed');
  1344. // once the transport is ready
  1345. self.transport.ready(self, function () {
  1346. self.connecting = true;
  1347. self.publish('connecting', self.transport.name);
  1348. self.transport.open();
  1349. if (self.options['connect timeout']) {
  1350. self.connectTimeoutTimer = setTimeout(function () {
  1351. if (!self.connected) {
  1352. self.connecting = false;
  1353. if (self.options['try multiple transports']) {
  1354. if (!self.remainingTransports) {
  1355. self.remainingTransports = self.transports.slice(0);
  1356. }
  1357. var remaining = self.remainingTransports;
  1358. while (remaining.length > 0 && remaining.splice(0,1)[0] !=
  1359. self.transport.name) {}
  1360. if (remaining.length){
  1361. connect(remaining);
  1362. } else {
  1363. self.publish('connect_failed');
  1364. }
  1365. }
  1366. }
  1367. }, self.options['connect timeout']);
  1368. }
  1369. });
  1370. }
  1371. connect(self.transports);
  1372. self.once('connect', function (){
  1373. clearTimeout(self.connectTimeoutTimer);
  1374. fn && typeof fn == 'function' && fn();
  1375. });
  1376. });
  1377. return this;
  1378. };
  1379. /**
  1380. * Clears and sets a new heartbeat timeout using the value given by the
  1381. * server during the handshake.
  1382. *
  1383. * @api private
  1384. */
  1385. Socket.prototype.setHeartbeatTimeout = function () {
  1386. clearTimeout(this.heartbeatTimeoutTimer);
  1387. var self = this;
  1388. this.heartbeatTimeoutTimer = setTimeout(function () {
  1389. self.transport.onClose();
  1390. }, this.heartbeatTimeout);
  1391. };
  1392. /**
  1393. * Sends a message.
  1394. *
  1395. * @param {Object} data packet.
  1396. * @returns {io.Socket}
  1397. * @api public
  1398. */
  1399. Socket.prototype.packet = function (data) {
  1400. if (this.connected && !this.doBuffer) {
  1401. this.transport.packet(data);
  1402. } else {
  1403. this.buffer.push(data);
  1404. }
  1405. return this;
  1406. };
  1407. /**
  1408. * Sets buffer state
  1409. *
  1410. * @api private
  1411. */
  1412. Socket.prototype.setBuffer = function (v) {
  1413. this.doBuffer = v;
  1414. if (!v && this.connected && this.buffer.length) {
  1415. this.transport.payload(this.buffer);
  1416. this.buffer = [];
  1417. }
  1418. };
  1419. /**
  1420. * Disconnect the established connect.
  1421. *
  1422. * @returns {io.Socket}
  1423. * @api public
  1424. */
  1425. Socket.prototype.disconnect = function () {
  1426. if (this.connected || this.connecting) {
  1427. if (this.open) {
  1428. this.of('').packet({ type: 'disconnect' });
  1429. }
  1430. // handle disconnection immediately
  1431. this.onDisconnect('booted');
  1432. }
  1433. return this;
  1434. };
  1435. /**
  1436. * Disconnects the socket with a sync XHR.
  1437. *
  1438. * @api private
  1439. */
  1440. Socket.prototype.disconnectSync = function () {
  1441. // ensure disconnection
  1442. var xhr = io.util.request()
  1443. , uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
  1444. xhr.open('GET', uri, true);
  1445. // handle disconnection immediately
  1446. this.onDisconnect('booted');
  1447. };
  1448. /**
  1449. * Check if we need to use cross domain enabled transports. Cross domain would
  1450. * be a different port or different domain name.
  1451. *
  1452. * @returns {Boolean}
  1453. * @api private
  1454. */
  1455. Socket.prototype.isXDomain = function () {
  1456. var port = global.location.port ||
  1457. ('https:' == global.location.protocol ? 443 : 80);
  1458. return this.options.host !== global.location.hostname
  1459. || this.options.port != port;
  1460. };
  1461. /**
  1462. * Called upon handshake.
  1463. *
  1464. * @api private
  1465. */
  1466. Socket.prototype.onConnect = function () {
  1467. if (!this.connected) {
  1468. this.connected = true;
  1469. this.connecting = false;
  1470. if (!this.doBuffer) {
  1471. // make sure to flush the buffer
  1472. this.setBuffer(false);
  1473. }
  1474. this.emit('connect');
  1475. }
  1476. };
  1477. /**
  1478. * Called when the transport opens
  1479. *
  1480. * @api private
  1481. */
  1482. Socket.prototype.onOpen = function () {
  1483. this.open = true;
  1484. };
  1485. /**
  1486. * Called when the transport closes.
  1487. *
  1488. * @api private
  1489. */
  1490. Socket.prototype.onClose = function () {
  1491. this.open = false;
  1492. clearTimeout(this.heartbeatTimeoutTimer);
  1493. };
  1494. /**
  1495. * Called when the transport first opens a connection
  1496. *
  1497. * @param text
  1498. */
  1499. Socket.prototype.onPacket = function (packet) {
  1500. this.of(packet.endpoint).onPacket(packet);
  1501. };
  1502. /**
  1503. * Handles an error.
  1504. *
  1505. * @api private
  1506. */
  1507. Socket.prototype.onError = function (err) {
  1508. if (err && err.advice) {
  1509. if (err.advice === 'reconnect' && (this.connected || this.connecting)) {
  1510. this.disconnect();
  1511. if (this.options.reconnect) {
  1512. this.reconnect();
  1513. }
  1514. }
  1515. }
  1516. this.publish('error', err && err.reason ? err.reason : err);
  1517. };
  1518. /**
  1519. * Called when the transport disconnects.
  1520. *
  1521. * @api private
  1522. */
  1523. Socket.prototype.onDisconnect = function (reason) {
  1524. var wasConnected = this.connected
  1525. , wasConnecting = this.connecting;
  1526. this.connected = false;
  1527. this.connecting = false;
  1528. this.open = false;
  1529. if (wasConnected || wasConnecting) {
  1530. this.transport.close();
  1531. this.transport.clearTimeouts();
  1532. if (wasConnected) {
  1533. this.publish('disconnect', reason);
  1534. if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
  1535. this.reconnect();
  1536. }
  1537. }
  1538. }
  1539. };
  1540. /**
  1541. * Called upon reconnection.
  1542. *
  1543. * @api private
  1544. */
  1545. Socket.prototype.reconnect = function () {
  1546. this.reconnecting = true;
  1547. this.reconnectionAttempts = 0;
  1548. this.reconnectionDelay = this.options['reconnection delay'];
  1549. var self = this
  1550. , maxAttempts = this.options['max reconnection attempts']
  1551. , tryMultiple = this.options['try multiple transports']
  1552. , limit = this.options['reconnection limit'];
  1553. function reset () {
  1554. if (self.connected) {
  1555. for (var i in self.namespaces) {
  1556. if (self.namespaces.hasOwnProperty(i) && '' !== i) {
  1557. self.namespaces[i].packet({ type: 'connect' });
  1558. }
  1559. }
  1560. self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
  1561. }
  1562. clearTimeout(self.reconnectionTimer);
  1563. self.removeListener('connect_failed', maybeReconnect);
  1564. self.removeListener('connect', maybeReconnect);
  1565. self.reconnecting = false;
  1566. delete self.reconnectionAttempts;
  1567. delete self.reconnectionDelay;
  1568. delete self.reconnectionTimer;
  1569. delete self.redoTransports;
  1570. self.options['try multiple transports'] = tryMultiple;
  1571. };
  1572. function maybeReconnect () {
  1573. if (!self.reconnecting) {
  1574. return;
  1575. }
  1576. if (self.connected) {
  1577. return reset();
  1578. };
  1579. if (self.connecting && self.reconnecting) {
  1580. return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1581. }
  1582. if (self.reconnectionAttempts++ >= maxAttempts) {
  1583. if (!self.redoTransports) {
  1584. self.on('connect_failed', maybeReconnect);
  1585. self.options['try multiple transports'] = true;
  1586. self.transport = self.getTransport();
  1587. self.redoTransports = true;
  1588. self.connect();
  1589. } else {
  1590. self.publish('reconnect_failed');
  1591. reset();
  1592. }
  1593. } else {
  1594. if (self.reconnectionDelay < limit) {
  1595. self.reconnectionDelay *= 2; // exponential back off
  1596. }
  1597. self.connect();
  1598. self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
  1599. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1600. }
  1601. };
  1602. this.options['try multiple transports'] = false;
  1603. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1604. this.on('connect', maybeReconnect);
  1605. };
  1606. })(
  1607. 'undefined' != typeof io ? io : module.exports
  1608. , 'undefined' != typeof io ? io : module.parent.exports
  1609. , this
  1610. );
  1611. /**
  1612. * socket.io
  1613. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1614. * MIT Licensed
  1615. */
  1616. (function (exports, io) {
  1617. /**
  1618. * Expose constructor.
  1619. */
  1620. exports.SocketNamespace = SocketNamespace;
  1621. /**
  1622. * Socket namespace constructor.
  1623. *
  1624. * @constructor
  1625. * @api public
  1626. */
  1627. function SocketNamespace (socket, name) {
  1628. this.socket = socket;
  1629. this.name = name || '';
  1630. this.flags = {};
  1631. this.json = new Flag(this, 'json');
  1632. this.ackPackets = 0;
  1633. this.acks = {};
  1634. };
  1635. /**
  1636. * Apply EventEmitter mixin.
  1637. */
  1638. io.util.mixin(SocketNamespace, io.EventEmitter);
  1639. /**
  1640. * Copies emit since we override it
  1641. *
  1642. * @api private
  1643. */
  1644. SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
  1645. /**
  1646. * Creates a new namespace, by proxying the request to the socket. This
  1647. * allows us to use the synax as we do on the server.
  1648. *
  1649. * @api public
  1650. */
  1651. SocketNamespace.prototype.of = function () {
  1652. return this.socket.of.apply(this.socket, arguments);
  1653. };
  1654. /**
  1655. * Sends a packet.
  1656. *
  1657. * @api private
  1658. */
  1659. SocketNamespace.prototype.packet = function (packet) {
  1660. packet.endpoint = this.name;
  1661. this.socket.packet(packet);
  1662. this.flags = {};
  1663. return this;
  1664. };
  1665. /**
  1666. * Sends a message
  1667. *
  1668. * @api public
  1669. */
  1670. SocketNamespace.prototype.send = function (data, fn) {
  1671. var packet = {
  1672. type: this.flags.json ? 'json' : 'message'
  1673. , data: data
  1674. };
  1675. if ('function' == typeof fn) {
  1676. packet.id = ++this.ackPackets;
  1677. packet.ack = true;
  1678. this.acks[packet.id] = fn;
  1679. }
  1680. return this.packet(packet);
  1681. };
  1682. /**
  1683. * Emits an event
  1684. *
  1685. * @api public
  1686. */
  1687. SocketNamespace.prototype.emit = function (name) {
  1688. var args = Array.prototype.slice.call(arguments, 1)
  1689. , lastArg = args[args.length - 1]
  1690. , packet = {
  1691. type: 'event'
  1692. , name: name
  1693. };
  1694. if ('function' == typeof lastArg) {
  1695. packet.id = ++this.ackPackets;
  1696. packet.ack = 'data';
  1697. this.acks[packet.id] = lastArg;
  1698. args = args.slice(0, args.length - 1);
  1699. }
  1700. packet.args = args;
  1701. return this.packet(packet);
  1702. };
  1703. /**
  1704. * Disconnects the namespace
  1705. *
  1706. * @api private
  1707. */
  1708. SocketNamespace.prototype.disconnect = function () {
  1709. if (this.name === '') {
  1710. this.socket.disconnect();
  1711. } else {
  1712. this.packet({ type: 'disconnect' });
  1713. this.$emit('disconnect');
  1714. }
  1715. return this;
  1716. };
  1717. /**
  1718. * Handles a packet
  1719. *
  1720. * @api private
  1721. */
  1722. SocketNamespace.prototype.onPacket = function (packet) {
  1723. var self = this;
  1724. function ack () {
  1725. self.packet({
  1726. type: 'ack'
  1727. , args: io.util.toArray(arguments)
  1728. , ackId: packet.id
  1729. });
  1730. };
  1731. switch (packet.type) {
  1732. case 'connect':
  1733. this.$emit('connect');
  1734. break;
  1735. case 'disconnect':
  1736. if (this.name === '') {
  1737. this.socket.onDisconnect(packet.reason || 'booted');
  1738. } else {
  1739. this.$emit('disconnect', packet.reason);
  1740. }
  1741. break;
  1742. case 'message':
  1743. case 'json':
  1744. var params = ['message', packet.data];
  1745. if (packet.ack == 'data') {
  1746. params.push(ack);
  1747. } else if (packet.ack) {
  1748. this.packet({ type: 'ack', ackId: packet.id });
  1749. }
  1750. this.$emit.apply(this, params);
  1751. break;
  1752. case 'event':
  1753. var params = [packet.name].concat(packet.args);
  1754. if (packet.ack == 'data')
  1755. params.push(ack);
  1756. this.$emit.apply(this, params);
  1757. break;
  1758. case 'ack':
  1759. if (this.acks[packet.ackId]) {
  1760. this.acks[packet.ackId].apply(this, packet.args);
  1761. delete this.acks[packet.ackId];
  1762. }
  1763. break;
  1764. case 'error':
  1765. if (packet.advice){
  1766. this.socket.onError(packet);
  1767. } else {
  1768. if (packet.reason == 'unauthorized') {
  1769. this.$emit('connect_failed', packet.reason);
  1770. } else {
  1771. this.$emit('error', packet.reason);
  1772. }
  1773. }
  1774. break;
  1775. }
  1776. };
  1777. /**
  1778. * Flag interface.
  1779. *
  1780. * @api private
  1781. */
  1782. function Flag (nsp, name) {
  1783. this.namespace = nsp;
  1784. this.name = name;
  1785. };
  1786. /**
  1787. * Send a message
  1788. *
  1789. * @api public
  1790. */
  1791. Flag.prototype.send = function () {
  1792. this.namespace.flags[this.name] = true;
  1793. this.namespace.send.apply(this.namespace, arguments);
  1794. };
  1795. /**
  1796. * Emit an event
  1797. *
  1798. * @api public
  1799. */
  1800. Flag.prototype.emit = function () {
  1801. this.namespace.flags[this.name] = true;
  1802. this.namespace.emit.apply(this.namespace, arguments);
  1803. };
  1804. })(
  1805. 'undefined' != typeof io ? io : module.exports
  1806. , 'undefined' != typeof io ? io : module.parent.exports
  1807. );
  1808. /**
  1809. * socket.io
  1810. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1811. * MIT Licensed
  1812. */
  1813. (function (exports, io, global) {
  1814. /**
  1815. * Expose constructor.
  1816. */
  1817. exports.websocket = WS;
  1818. /**
  1819. * The WebSocket transport uses the HTML5 WebSocket API to establish an
  1820. * persistent connection with the Socket.IO server. This transport will also
  1821. * be inherited by the FlashSocket fallback as it provides a API compatible
  1822. * polyfill for the WebSockets.
  1823. *
  1824. * @constructor
  1825. * @extends {io.Transport}
  1826. * @api public
  1827. */
  1828. function WS (socket) {
  1829. io.Transport.apply(this, arguments);
  1830. };
  1831. /**
  1832. * Inherits from Transport.
  1833. */
  1834. io.util.inherit(WS, io.Transport);
  1835. /**
  1836. * Transport name
  1837. *
  1838. * @api public
  1839. */
  1840. WS.prototype.name = 'websocket';
  1841. /**
  1842. * Initializes a new `WebSocket` connection with the Socket.IO server. We attach
  1843. * all the appropriate listeners to handle the responses from the server.
  1844. *
  1845. * @returns {Transport}
  1846. * @api public
  1847. */
  1848. WS.prototype.open = function () {
  1849. var query = io.util.query(this.socket.options.query)
  1850. , self = this
  1851. , Socket
  1852. if (!Socket) {
  1853. Socket = global.MozWebSocket || global.WebSocket;
  1854. }
  1855. this.websocket = new Socket(this.prepareUrl() + query);
  1856. this.websocket.onopen = function () {
  1857. self.onOpen();
  1858. self.socket.setBuffer(false);
  1859. };
  1860. this.websocket.onmessage = function (ev) {
  1861. self.onData(ev.data);
  1862. };
  1863. this.websocket.onclose = function () {
  1864. self.onClose();
  1865. self.socket.setBuffer(true);
  1866. };
  1867. this.websocket.onerror = function (e) {
  1868. self.onError(e);
  1869. };
  1870. return this;
  1871. };
  1872. /**
  1873. * Send a message to the Socket.IO server. The message will automatically be
  1874. * encoded in the correct message format.
  1875. *
  1876. * @returns {Transport}
  1877. * @api public
  1878. */
  1879. // Do to a bug in the current IDevices browser, we need to wrap the send in a
  1880. // setTimeout, when they resume from sleeping the browser will crash if
  1881. // we don't allow the browser time to detect the socket has been closed
  1882. if (io.util.ua.iDevice) {
  1883. WS.prototype.send = function (data) {
  1884. var self = this;
  1885. setTimeout(function() {
  1886. self.websocket.send(data);
  1887. },0);
  1888. return this;
  1889. };
  1890. } else {
  1891. WS.prototype.send = function (data) {
  1892. this.websocket.send(data);
  1893. return this;
  1894. };
  1895. }
  1896. /**
  1897. * Payload
  1898. *
  1899. * @api private
  1900. */
  1901. WS.prototype.payload = function (arr) {
  1902. for (var i = 0, l = arr.length; i < l; i++) {
  1903. this.packet(arr[i]);
  1904. }
  1905. return this;
  1906. };
  1907. /**
  1908. * Disconnect the established `WebSocket` connection.
  1909. *
  1910. * @returns {Transport}
  1911. * @api public
  1912. */
  1913. WS.prototype.close = function () {
  1914. this.websocket.close();
  1915. return this;
  1916. };
  1917. /**
  1918. * Handle the errors that `WebSocket` might be giving when we
  1919. * are attempting to connect or send messages.
  1920. *
  1921. * @param {Error} e The error.
  1922. * @api private
  1923. */
  1924. WS.prototype.onError = function (e) {
  1925. this.socket.onError(e);
  1926. };
  1927. /**
  1928. * Returns the appropriate scheme for the URI generation.
  1929. *
  1930. * @api private
  1931. */
  1932. WS.prototype.scheme = function () {
  1933. return this.socket.options.secure ? 'wss' : 'ws';
  1934. };
  1935. /**
  1936. * Checks if the browser has support for native `WebSockets` and that
  1937. * it's not the polyfill created for the FlashSocket transport.
  1938. *
  1939. * @return {Boolean}
  1940. * @api public
  1941. */
  1942. WS.check = function () {
  1943. return ('WebSocket' in global && !('__addTask' in WebSocket))
  1944. || 'MozWebSocket' in global;
  1945. };
  1946. /**
  1947. * Check if the `WebSocket` transport support cross domain communications.
  1948. *
  1949. * @returns {Boolean}
  1950. * @api public
  1951. */
  1952. WS.xdomainCheck = function () {
  1953. return true;
  1954. };
  1955. /**
  1956. * Add the transport to your public io.transports array.
  1957. *
  1958. * @api private
  1959. */
  1960. io.transports.push('websocket');
  1961. })(
  1962. 'undefined' != typeof io ? io.Transport : module.exports
  1963. , 'undefined' != typeof io ? io : module.parent.exports
  1964. , this
  1965. );
  1966. /**
  1967. * socket.io
  1968. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1969. * MIT Licensed
  1970. */
  1971. (function (exports, io) {
  1972. /**
  1973. * Expose constructor.
  1974. */
  1975. exports.flashsocket = Flashsocket;
  1976. /**
  1977. * The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket
  1978. * specification. It uses a .swf file to communicate with the server. If you want
  1979. * to serve the .swf file from a other server than where the Socket.IO script is
  1980. * coming from you need to use the insecure version of the .swf. More information
  1981. * about this can be found on the github page.
  1982. *
  1983. * @constructor
  1984. * @extends {io.Transport.websocket}
  1985. * @api public
  1986. */
  1987. function Flashsocket () {
  1988. io.Transport.websocket.apply(this, arguments);
  1989. };
  1990. /**
  1991. * Inherits from Transport.
  1992. */
  1993. io.util.inherit(Flashsocket, io.Transport.websocket);
  1994. /**
  1995. * Transport name
  1996. *
  1997. * @api public
  1998. */
  1999. Flashsocket.prototype.name = 'flashsocket';
  2000. /**
  2001. * Disconnect the established `FlashSocket` connection. This is done by adding a
  2002. * new task to the FlashSocket. The rest will be handled off by the `WebSocket`
  2003. * transport.
  2004. *
  2005. * @returns {Transport}
  2006. * @api public
  2007. */
  2008. Flashsocket.prototype.open = function () {
  2009. var self = this
  2010. , args = arguments;
  2011. WebSocket.__addTask(function () {
  2012. io.Transport.websocket.prototype.open.apply(self, args);
  2013. });
  2014. return this;
  2015. };
  2016. /**
  2017. * Sends a message to the Socket.IO server. This is done by adding a new
  2018. * task to the FlashSocket. The rest will be handled off by the `WebSocket`
  2019. * transport.
  2020. *
  2021. * @returns {Transport}
  2022. * @api public
  2023. */
  2024. Flashsocket.prototype.send = function () {
  2025. var self = this, args = arguments;
  2026. WebSocket.__addTask(function () {
  2027. io.Transport.websocket.prototype.send.apply(self, args);
  2028. });
  2029. return this;
  2030. };
  2031. /**
  2032. * Disconnects the established `FlashSocket` connection.
  2033. *
  2034. * @returns {Transport}
  2035. * @api public
  2036. */
  2037. Flashsocket.prototype.close = function () {
  2038. WebSocket.__tasks.length = 0;
  2039. io.Transport.websocket.prototype.close.call(this);
  2040. return this;
  2041. };
  2042. /**
  2043. * The WebSocket fall back needs to append the flash container to the body
  2044. * element, so we need to make sure we have access to it. Or defer the call
  2045. * until we are sure there is a body element.
  2046. *
  2047. * @param {Socket} socket The socket instance that needs a transport
  2048. * @param {Function} fn The callback
  2049. * @api private
  2050. */
  2051. Flashsocket.prototype.ready = function (socket, fn) {
  2052. function init () {
  2053. var options = socket.options
  2054. , port = options['flash policy port']
  2055. , path = [
  2056. 'http' + (options.secure ? 's' : '') + ':/'
  2057. , options.host + ':' + options.port
  2058. , options.resource
  2059. , 'static/flashsocket'
  2060. , 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf'
  2061. ];
  2062. // Only start downloading the swf file when the checked that this browser
  2063. // actually supports it
  2064. if (!Flashsocket.loaded) {
  2065. if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined') {
  2066. // Set the correct file based on the XDomain settings
  2067. WEB_SOCKET_SWF_LOCATION = path.join('/');
  2068. }
  2069. if (port !== 843) {
  2070. WebSocket.loadFlashPolicyFile('xmlsocket://' + options.host + ':' + port);
  2071. }
  2072. WebSocket.__initialize();
  2073. Flashsocket.loaded = true;
  2074. }
  2075. fn.call(self);
  2076. }
  2077. var self = this;
  2078. if (document.body) return init();
  2079. io.util.load(init);
  2080. };
  2081. /**
  2082. * Check if the FlashSocket transport is supported as it requires that the Adobe
  2083. * Flash Player plug-in version `10.0.0` or greater is installed. And also check if
  2084. * the polyfill is correctly loaded.
  2085. *
  2086. * @returns {Boolean}
  2087. * @api public
  2088. */
  2089. Flashsocket.check = function () {
  2090. if (
  2091. typeof WebSocket == 'undefined'
  2092. || !('__initialize' in WebSocket) || !swfobject
  2093. ) return false;
  2094. return swfobject.getFlashPlayerVersion().major >= 10;
  2095. };
  2096. /**
  2097. * Check if the FlashSocket transport can be used as cross domain / cross origin
  2098. * transport. Because we can't see which type (secure or insecure) of .swf is used
  2099. * we will just return true.
  2100. *
  2101. * @returns {Boolean}
  2102. * @api public
  2103. */
  2104. Flashsocket.xdomainCheck = function () {
  2105. return true;
  2106. };
  2107. /**
  2108. * Disable AUTO_INITIALIZATION
  2109. */
  2110. if (typeof window != 'undefined') {
  2111. WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true;
  2112. }
  2113. /**
  2114. * Add the transport to your public io.transports array.
  2115. *
  2116. * @api private
  2117. */
  2118. io.transports.push('flashsocket');
  2119. })(
  2120. 'undefined' != typeof io ? io.Transport : module.exports
  2121. , 'undefined' != typeof io ? io : module.parent.exports
  2122. );
  2123. /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
  2124. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  2125. */
  2126. if ('undefined' != typeof window) {
  2127. var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O[(['Active'].concat('Object').join('X'))]!=D){try{var ad=new window[(['Active'].concat('Object').join('X'))](W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?(['Active'].concat('').join('X')):"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
  2128. }
  2129. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  2130. // License: New BSD License
  2131. // Reference: http://dev.w3.org/html5/websockets/
  2132. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
  2133. (function() {
  2134. if ('undefined' == typeof window || window.WebSocket) return;
  2135. var console = window.console;
  2136. if (!console || !console.log || !console.error) {
  2137. console = {log: function(){ }, error: function(){ }};
  2138. }
  2139. if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
  2140. console.error("Flash Player >= 10.0.0 is required.");
  2141. return;
  2142. }
  2143. if (location.protocol == "file:") {
  2144. console.error(
  2145. "WARNING: web-socket-js doesn't work in file:///... URL " +
  2146. "unless you set Flash Security Settings properly. " +
  2147. "Open the page via Web server i.e. http://...");
  2148. }
  2149. /**
  2150. * This class represents a faux web socket.
  2151. * @param {string} url
  2152. * @param {array or string} protocols
  2153. * @param {string} proxyHost
  2154. * @param {int} proxyPort
  2155. * @param {string} headers
  2156. */
  2157. WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
  2158. var self = this;
  2159. self.__id = WebSocket.__nextId++;
  2160. WebSocket.__instances[self.__id] = self;
  2161. self.readyState = WebSocket.CONNECTING;
  2162. self.bufferedAmount = 0;
  2163. self.__events = {};
  2164. if (!protocols) {
  2165. protocols = [];
  2166. } else if (typeof protocols == "string") {
  2167. protocols = [protocols];
  2168. }
  2169. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  2170. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  2171. setTimeout(function() {
  2172. WebSocket.__addTask(function() {
  2173. WebSocket.__flash.create(
  2174. self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
  2175. });
  2176. }, 0);
  2177. };
  2178. /**
  2179. * Send data to the web socket.
  2180. * @param {string} data The data to send to the socket.
  2181. * @return {boolean} True for success, false for failure.
  2182. */
  2183. WebSocket.prototype.send = function(data) {
  2184. if (this.readyState == WebSocket.CONNECTING) {
  2185. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  2186. }
  2187. // We use encodeURIComponent() here, because FABridge doesn't work if
  2188. // the argument includes some characters. We don't use escape() here
  2189. // because of this:
  2190. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  2191. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  2192. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  2193. // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
  2194. // additional testing.
  2195. var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
  2196. if (result < 0) { // success
  2197. return true;
  2198. } else {
  2199. this.bufferedAmount += result;
  2200. return false;
  2201. }
  2202. };
  2203. /**
  2204. * Close this web socket gracefully.
  2205. */
  2206. WebSocket.prototype.close = function() {
  2207. if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
  2208. return;
  2209. }
  2210. this.readyState = WebSocket.CLOSING;
  2211. WebSocket.__flash.close(this.__id);
  2212. };
  2213. /**
  2214. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  2215. *
  2216. * @param {string} type
  2217. * @param {function} listener
  2218. * @param {boolean} useCapture
  2219. * @return void
  2220. */
  2221. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  2222. if (!(type in this.__events)) {
  2223. this.__events[type] = [];
  2224. }
  2225. this.__events[type].push(listener);
  2226. };
  2227. /**
  2228. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  2229. *
  2230. * @param {string} type
  2231. * @param {function} listener
  2232. * @param {boolean} useCapture
  2233. * @return void
  2234. */
  2235. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  2236. if (!(type in this.__events)) return;
  2237. var events = this.__events[type];
  2238. for (var i = events.length - 1; i >= 0; --i) {
  2239. if (events[i] === listener) {
  2240. events.splice(i, 1);
  2241. break;
  2242. }
  2243. }
  2244. };
  2245. /**
  2246. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  2247. *
  2248. * @param {Event} event
  2249. * @return void
  2250. */
  2251. WebSocket.prototype.dispatchEvent = function(event) {
  2252. var events = this.__events[event.type] || [];
  2253. for (var i = 0; i < events.length; ++i) {
  2254. events[i](event);
  2255. }
  2256. var handler = this["on" + event.type];
  2257. if (handler) handler(event);
  2258. };
  2259. /**
  2260. * Handles an event from Flash.
  2261. * @param {Object} flashEvent
  2262. */
  2263. WebSocket.prototype.__handleEvent = function(flashEvent) {
  2264. if ("readyState" in flashEvent) {
  2265. this.readyState = flashEvent.readyState;
  2266. }
  2267. if ("protocol" in flashEvent) {
  2268. this.protocol = flashEvent.protocol;
  2269. }
  2270. var jsEvent;
  2271. if (flashEvent.type == "open" || flashEvent.type == "error") {
  2272. jsEvent = this.__createSimpleEvent(flashEvent.type);
  2273. } else if (flashEvent.type == "close") {
  2274. // TODO implement jsEvent.wasClean
  2275. jsEvent = this.__createSimpleEvent("close");
  2276. } else if (flashEvent.type == "message") {
  2277. var data = decodeURIComponent(flashEvent.message);
  2278. jsEvent = this.__createMessageEvent("message", data);
  2279. } else {
  2280. throw "unknown event type: " + flashEvent.type;
  2281. }
  2282. this.dispatchEvent(jsEvent);
  2283. };
  2284. WebSocket.prototype.__createSimpleEvent = function(type) {
  2285. if (document.createEvent && window.Event) {
  2286. var event = document.createEvent("Event");
  2287. event.initEvent(type, false, false);
  2288. return event;
  2289. } else {
  2290. return {type: type, bubbles: false, cancelable: false};
  2291. }
  2292. };
  2293. WebSocket.prototype.__createMessageEvent = function(type, data) {
  2294. if (document.createEvent && window.MessageEvent && !window.opera) {
  2295. var event = document.createEvent("MessageEvent");
  2296. event.initMessageEvent("message", false, false, data, null, null, window, null);
  2297. return event;
  2298. } else {
  2299. // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
  2300. return {type: type, data: data, bubbles: false, cancelable: false};
  2301. }
  2302. };
  2303. /**
  2304. * Define the WebSocket readyState enumeration.
  2305. */
  2306. WebSocket.CONNECTING = 0;
  2307. WebSocket.OPEN = 1;
  2308. WebSocket.CLOSING = 2;
  2309. WebSocket.CLOSED = 3;
  2310. WebSocket.__flash = null;
  2311. WebSocket.__instances = {};
  2312. WebSocket.__tasks = [];
  2313. WebSocket.__nextId = 0;
  2314. /**
  2315. * Load a new flash security policy file.
  2316. * @param {string} url
  2317. */
  2318. WebSocket.loadFlashPolicyFile = function(url){
  2319. WebSocket.__addTask(function() {
  2320. WebSocket.__flash.loadManualPolicyFile(url);
  2321. });
  2322. };
  2323. /**
  2324. * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
  2325. */
  2326. WebSocket.__initialize = function() {
  2327. if (WebSocket.__flash) return;
  2328. if (WebSocket.__swfLocation) {
  2329. // For backword compatibility.
  2330. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  2331. }
  2332. if (!window.WEB_SOCKET_SWF_LOCATION) {
  2333. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  2334. return;
  2335. }
  2336. var container = document.createElement("div");
  2337. container.id = "webSocketContainer";
  2338. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  2339. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  2340. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  2341. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  2342. // the best we can do as far as we know now.
  2343. container.style.position = "absolute";
  2344. if (WebSocket.__isFlashLite()) {
  2345. container.style.left = "0px";
  2346. container.style.top = "0px";
  2347. } else {
  2348. container.style.left = "-100px";
  2349. container.style.top = "-100px";
  2350. }
  2351. var holder = document.createElement("div");
  2352. holder.id = "webSocketFlash";
  2353. container.appendChild(holder);
  2354. document.body.appendChild(container);
  2355. // See this article for hasPriority:
  2356. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  2357. swfobject.embedSWF(
  2358. WEB_SOCKET_SWF_LOCATION,
  2359. "webSocketFlash",
  2360. "1" /* width */,
  2361. "1" /* height */,
  2362. "10.0.0" /* SWF version */,
  2363. null,
  2364. null,
  2365. {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
  2366. null,
  2367. function(e) {
  2368. if (!e.success) {
  2369. console.error("[WebSocket] swfobject.embedSWF failed");
  2370. }
  2371. });
  2372. };
  2373. /**
  2374. * Called by Flash to notify JS that it's fully loaded and ready
  2375. * for communication.
  2376. */
  2377. WebSocket.__onFlashInitialized = function() {
  2378. // We need to set a timeout here to avoid round-trip calls
  2379. // to flash during the initialization process.
  2380. setTimeout(function() {
  2381. WebSocket.__flash = document.getElementById("webSocketFlash");
  2382. WebSocket.__flash.setCallerUrl(location.href);
  2383. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  2384. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  2385. WebSocket.__tasks[i]();
  2386. }
  2387. WebSocket.__tasks = [];
  2388. }, 0);
  2389. };
  2390. /**
  2391. * Called by Flash to notify WebSockets events are fired.
  2392. */
  2393. WebSocket.__onFlashEvent = function() {
  2394. setTimeout(function() {
  2395. try {
  2396. // Gets events using receiveEvents() instead of getting it from event object
  2397. // of Flash event. This is to make sure to keep message order.
  2398. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  2399. var events = WebSocket.__flash.receiveEvents();
  2400. for (var i = 0; i < events.length; ++i) {
  2401. WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
  2402. }
  2403. } catch (e) {
  2404. console.error(e);
  2405. }
  2406. }, 0);
  2407. return true;
  2408. };
  2409. // Called by Flash.
  2410. WebSocket.__log = function(message) {
  2411. console.log(decodeURIComponent(message));
  2412. };
  2413. // Called by Flash.
  2414. WebSocket.__error = function(message) {
  2415. console.error(decodeURIComponent(message));
  2416. };
  2417. WebSocket.__addTask = function(task) {
  2418. if (WebSocket.__flash) {
  2419. task();
  2420. } else {
  2421. WebSocket.__tasks.push(task);
  2422. }
  2423. };
  2424. /**
  2425. * Test if the browser is running flash lite.
  2426. * @return {boolean} True if flash lite is running, false otherwise.
  2427. */
  2428. WebSocket.__isFlashLite = function() {
  2429. if (!window.navigator || !window.navigator.mimeTypes) {
  2430. return false;
  2431. }
  2432. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  2433. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
  2434. return false;
  2435. }
  2436. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  2437. };
  2438. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  2439. if (window.addEventListener) {
  2440. window.addEventListener("load", function(){
  2441. WebSocket.__initialize();
  2442. }, false);
  2443. } else {
  2444. window.attachEvent("onload", function(){
  2445. WebSocket.__initialize();
  2446. });
  2447. }
  2448. }
  2449. })();
  2450. /**
  2451. * socket.io
  2452. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2453. * MIT Licensed
  2454. */
  2455. (function (exports, io, global) {
  2456. /**
  2457. * Expose constructor.
  2458. *
  2459. * @api public
  2460. */
  2461. exports.XHR = XHR;
  2462. /**
  2463. * XHR constructor
  2464. *
  2465. * @costructor
  2466. * @api public
  2467. */
  2468. function XHR (socket) {
  2469. if (!socket) return;
  2470. io.Transport.apply(this, arguments);
  2471. this.sendBuffer = [];
  2472. };
  2473. /**
  2474. * Inherits from Transport.
  2475. */
  2476. io.util.inherit(XHR, io.Transport);
  2477. /**
  2478. * Establish a connection
  2479. *
  2480. * @returns {Transport}
  2481. * @api public
  2482. */
  2483. XHR.prototype.open = function () {
  2484. this.socket.setBuffer(false);
  2485. this.onOpen();
  2486. this.get();
  2487. // we need to make sure the request succeeds since we have no indication
  2488. // whether the request opened or not until it succeeded.
  2489. this.setCloseTimeout();
  2490. return this;
  2491. };
  2492. /**
  2493. * Check if we need to send data to the Socket.IO server, if we have data in our
  2494. * buffer we encode it and forward it to the `post` method.
  2495. *
  2496. * @api private
  2497. */
  2498. XHR.prototype.payload = function (payload) {
  2499. var msgs = [];
  2500. for (var i = 0, l = payload.length; i < l; i++) {
  2501. msgs.push(io.parser.encodePacket(payload[i]));
  2502. }
  2503. this.send(io.parser.encodePayload(msgs));
  2504. };
  2505. /**
  2506. * Send data to the Socket.IO server.
  2507. *
  2508. * @param data The message
  2509. * @returns {Transport}
  2510. * @api public
  2511. */
  2512. XHR.prototype.send = function (data) {
  2513. this.post(data);
  2514. return this;
  2515. };
  2516. /**
  2517. * Posts a encoded message to the Socket.IO server.
  2518. *
  2519. * @param {String} data A encoded message.
  2520. * @api private
  2521. */
  2522. function empty () { };
  2523. XHR.prototype.post = function (data) {
  2524. var self = this;
  2525. this.socket.setBuffer(true);
  2526. function stateChange () {
  2527. if (this.readyState == 4) {
  2528. this.onreadystatechange = empty;
  2529. self.posting = false;
  2530. if (this.status == 200){
  2531. self.socket.setBuffer(false);
  2532. } else {
  2533. self.onClose();
  2534. }
  2535. }
  2536. }
  2537. function onload () {
  2538. this.onload = empty;
  2539. self.socket.setBuffer(false);
  2540. };
  2541. this.sendXHR = this.request('POST');
  2542. if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) {
  2543. this.sendXHR.onload = this.sendXHR.onerror = onload;
  2544. } else {
  2545. this.sendXHR.onreadystatechange = stateChange;
  2546. }
  2547. this.sendXHR.send(data);
  2548. };
  2549. /**
  2550. * Disconnects the established `XHR` connection.
  2551. *
  2552. * @returns {Transport}
  2553. * @api public
  2554. */
  2555. XHR.prototype.close = function () {
  2556. this.onClose();
  2557. return this;
  2558. };
  2559. /**
  2560. * Generates a configured XHR request
  2561. *
  2562. * @param {String} url The url that needs to be requested.
  2563. * @param {String} method The method the request should use.
  2564. * @returns {XMLHttpRequest}
  2565. * @api private
  2566. */
  2567. XHR.prototype.request = function (method) {
  2568. var req = io.util.request(this.socket.isXDomain())
  2569. , query = io.util.query(this.socket.options.query, 't=' + +new Date);
  2570. req.open(method || 'GET', this.prepareUrl() + query, true);
  2571. if (method == 'POST') {
  2572. try {
  2573. if (req.setRequestHeader) {
  2574. req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  2575. } else {
  2576. // XDomainRequest
  2577. req.contentType = 'text/plain';
  2578. }
  2579. } catch (e) {}
  2580. }
  2581. return req;
  2582. };
  2583. /**
  2584. * Returns the scheme to use for the transport URLs.
  2585. *
  2586. * @api private
  2587. */
  2588. XHR.prototype.scheme = function () {
  2589. return this.socket.options.secure ? 'https' : 'http';
  2590. };
  2591. /**
  2592. * Check if the XHR transports are supported
  2593. *
  2594. * @param {Boolean} xdomain Check if we support cross domain requests.
  2595. * @returns {Boolean}
  2596. * @api public
  2597. */
  2598. XHR.check = function (socket, xdomain) {
  2599. try {
  2600. var request = io.util.request(xdomain),
  2601. usesXDomReq = (global.XDomainRequest && request instanceof XDomainRequest),
  2602. socketProtocol = (socket && socket.options && socket.options.secure ? 'https:' : 'http:'),
  2603. isXProtocol = (socketProtocol != global.location.protocol);
  2604. if (request && !(usesXDomReq && isXProtocol)) {
  2605. return true;
  2606. }
  2607. } catch(e) {}
  2608. return false;
  2609. };
  2610. /**
  2611. * Check if the XHR transport supports cross domain requests.
  2612. *
  2613. * @returns {Boolean}
  2614. * @api public
  2615. */
  2616. XHR.xdomainCheck = function () {
  2617. return XHR.check(null, true);
  2618. };
  2619. })(
  2620. 'undefined' != typeof io ? io.Transport : module.exports
  2621. , 'undefined' != typeof io ? io : module.parent.exports
  2622. , this
  2623. );
  2624. /**
  2625. * socket.io
  2626. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2627. * MIT Licensed
  2628. */
  2629. (function (exports, io) {
  2630. /**
  2631. * Expose constructor.
  2632. */
  2633. exports.htmlfile = HTMLFile;
  2634. /**
  2635. * The HTMLFile transport creates a `forever iframe` based transport
  2636. * for Internet Explorer. Regular forever iframe implementations will
  2637. * continuously trigger the browsers buzy indicators. If the forever iframe
  2638. * is created inside a `htmlfile` these indicators will not be trigged.
  2639. *
  2640. * @constructor
  2641. * @extends {io.Transport.XHR}
  2642. * @api public
  2643. */
  2644. function HTMLFile (socket) {
  2645. io.Transport.XHR.apply(this, arguments);
  2646. };
  2647. /**
  2648. * Inherits from XHR transport.
  2649. */
  2650. io.util.inherit(HTMLFile, io.Transport.XHR);
  2651. /**
  2652. * Transport name
  2653. *
  2654. * @api public
  2655. */
  2656. HTMLFile.prototype.name = 'htmlfile';
  2657. /**
  2658. * Creates a new Ac...eX `htmlfile` with a forever loading iframe
  2659. * that can be used to listen to messages. Inside the generated
  2660. * `htmlfile` a reference will be made to the HTMLFile transport.
  2661. *
  2662. * @api private
  2663. */
  2664. HTMLFile.prototype.get = function () {
  2665. this.doc = new window[(['Active'].concat('Object').join('X'))]('htmlfile');
  2666. this.doc.open();
  2667. this.doc.write('<html></html>');
  2668. this.doc.close();
  2669. this.doc.parentWindow.s = this;
  2670. var iframeC = this.doc.createElement('div');
  2671. iframeC.className = 'socketio';
  2672. this.doc.body.appendChild(iframeC);
  2673. this.iframe = this.doc.createElement('iframe');
  2674. iframeC.appendChild(this.iframe);
  2675. var self = this
  2676. , query = io.util.query(this.socket.options.query, 't='+ +new Date);
  2677. this.iframe.src = this.prepareUrl() + query;
  2678. io.util.on(window, 'unload', function () {
  2679. self.destroy();
  2680. });
  2681. };
  2682. /**
  2683. * The Socket.IO server will write script tags inside the forever
  2684. * iframe, this function will be used as callback for the incoming
  2685. * information.
  2686. *
  2687. * @param {String} data The message
  2688. * @param {document} doc Reference to the context
  2689. * @api private
  2690. */
  2691. HTMLFile.prototype._ = function (data, doc) {
  2692. this.onData(data);
  2693. try {
  2694. var script = doc.getElementsByTagName('script')[0];
  2695. script.parentNode.removeChild(script);
  2696. } catch (e) { }
  2697. };
  2698. /**
  2699. * Destroy the established connection, iframe and `htmlfile`.
  2700. * And calls the `CollectGarbage` function of Internet Explorer
  2701. * to release the memory.
  2702. *
  2703. * @api private
  2704. */
  2705. HTMLFile.prototype.destroy = function () {
  2706. if (this.iframe){
  2707. try {
  2708. this.iframe.src = 'about:blank';
  2709. } catch(e){}
  2710. this.doc = null;
  2711. this.iframe.parentNode.removeChild(this.iframe);
  2712. this.iframe = null;
  2713. CollectGarbage();
  2714. }
  2715. };
  2716. /**
  2717. * Disconnects the established connection.
  2718. *
  2719. * @returns {Transport} Chaining.
  2720. * @api public
  2721. */
  2722. HTMLFile.prototype.close = function () {
  2723. this.destroy();
  2724. return io.Transport.XHR.prototype.close.call(this);
  2725. };
  2726. /**
  2727. * Checks if the browser supports this transport. The browser
  2728. * must have an `Ac...eXObject` implementation.
  2729. *
  2730. * @return {Boolean}
  2731. * @api public
  2732. */
  2733. HTMLFile.check = function () {
  2734. if (typeof window != "undefined" && (['Active'].concat('Object').join('X')) in window){
  2735. try {
  2736. var a = new window[(['Active'].concat('Object').join('X'))]('htmlfile');
  2737. return a && io.Transport.XHR.check();
  2738. } catch(e){}
  2739. }
  2740. return false;
  2741. };
  2742. /**
  2743. * Check if cross domain requests are supported.
  2744. *
  2745. * @returns {Boolean}
  2746. * @api public
  2747. */
  2748. HTMLFile.xdomainCheck = function () {
  2749. // we can probably do handling for sub-domains, we should
  2750. // test that it's cross domain but a subdomain here
  2751. return false;
  2752. };
  2753. /**
  2754. * Add the transport to your public io.transports array.
  2755. *
  2756. * @api private
  2757. */
  2758. io.transports.push('htmlfile');
  2759. })(
  2760. 'undefined' != typeof io ? io.Transport : module.exports
  2761. , 'undefined' != typeof io ? io : module.parent.exports
  2762. );
  2763. /**
  2764. * socket.io
  2765. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2766. * MIT Licensed
  2767. */
  2768. (function (exports, io, global) {
  2769. /**
  2770. * Expose constructor.
  2771. */
  2772. exports['xhr-polling'] = XHRPolling;
  2773. /**
  2774. * The XHR-polling transport uses long polling XHR requests to create a
  2775. * "persistent" connection with the server.
  2776. *
  2777. * @constructor
  2778. * @api public
  2779. */
  2780. function XHRPolling () {
  2781. io.Transport.XHR.apply(this, arguments);
  2782. };
  2783. /**
  2784. * Inherits from XHR transport.
  2785. */
  2786. io.util.inherit(XHRPolling, io.Transport.XHR);
  2787. /**
  2788. * Merge the properties from XHR transport
  2789. */
  2790. io.util.merge(XHRPolling, io.Transport.XHR);
  2791. /**
  2792. * Transport name
  2793. *
  2794. * @api public
  2795. */
  2796. XHRPolling.prototype.name = 'xhr-polling';
  2797. /**
  2798. * Establish a connection, for iPhone and Android this will be done once the page
  2799. * is loaded.
  2800. *
  2801. * @returns {Transport} Chaining.
  2802. * @api public
  2803. */
  2804. XHRPolling.prototype.open = function () {
  2805. var self = this;
  2806. io.Transport.XHR.prototype.open.call(self);
  2807. return false;
  2808. };
  2809. /**
  2810. * Starts a XHR request to wait for incoming messages.
  2811. *
  2812. * @api private
  2813. */
  2814. function empty () {};
  2815. XHRPolling.prototype.get = function () {
  2816. if (!this.open) return;
  2817. var self = this;
  2818. function stateChange () {
  2819. if (this.readyState == 4) {
  2820. this.onreadystatechange = empty;
  2821. if (this.status == 200) {
  2822. self.onData(this.responseText);
  2823. self.get();
  2824. } else {
  2825. self.onClose();
  2826. }
  2827. }
  2828. };
  2829. function onload () {
  2830. this.onload = empty;
  2831. this.onerror = empty;
  2832. self.onData(this.responseText);
  2833. self.get();
  2834. };
  2835. function onerror () {
  2836. self.onClose();
  2837. };
  2838. this.xhr = this.request();
  2839. if (global.XDomainRequest && this.xhr instanceof XDomainRequest) {
  2840. this.xhr.onload = onload;
  2841. this.xhr.onerror = onerror;
  2842. } else {
  2843. this.xhr.onreadystatechange = stateChange;
  2844. }
  2845. this.xhr.send(null);
  2846. };
  2847. /**
  2848. * Handle the unclean close behavior.
  2849. *
  2850. * @api private
  2851. */
  2852. XHRPolling.prototype.onClose = function () {
  2853. io.Transport.XHR.prototype.onClose.call(this);
  2854. if (this.xhr) {
  2855. this.xhr.onreadystatechange = this.xhr.onload = this.xhr.onerror = empty;
  2856. try {
  2857. this.xhr.abort();
  2858. } catch(e){}
  2859. this.xhr = null;
  2860. }
  2861. };
  2862. /**
  2863. * Webkit based browsers show a infinit spinner when you start a XHR request
  2864. * before the browsers onload event is called so we need to defer opening of
  2865. * the transport until the onload event is called. Wrapping the cb in our
  2866. * defer method solve this.
  2867. *
  2868. * @param {Socket} socket The socket instance that needs a transport
  2869. * @param {Function} fn The callback
  2870. * @api private
  2871. */
  2872. XHRPolling.prototype.ready = function (socket, fn) {
  2873. var self = this;
  2874. io.util.defer(function () {
  2875. fn.call(self);
  2876. });
  2877. };
  2878. /**
  2879. * Add the transport to your public io.transports array.
  2880. *
  2881. * @api private
  2882. */
  2883. io.transports.push('xhr-polling');
  2884. })(
  2885. 'undefined' != typeof io ? io.Transport : module.exports
  2886. , 'undefined' != typeof io ? io : module.parent.exports
  2887. , this
  2888. );
  2889. /**
  2890. * socket.io
  2891. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2892. * MIT Licensed
  2893. */
  2894. (function (exports, io, global) {
  2895. /**
  2896. * There is a way to hide the loading indicator in Firefox. If you create and
  2897. * remove a iframe it will stop showing the current loading indicator.
  2898. * Unfortunately we can't feature detect that and UA sniffing is evil.
  2899. *
  2900. * @api private
  2901. */
  2902. var indicator = global.document && "MozAppearance" in
  2903. global.document.documentElement.style;
  2904. /**
  2905. * Expose constructor.
  2906. */
  2907. exports['jsonp-polling'] = JSONPPolling;
  2908. /**
  2909. * The JSONP transport creates an persistent connection by dynamically
  2910. * inserting a script tag in the page. This script tag will receive the
  2911. * information of the Socket.IO server. When new information is received
  2912. * it creates a new script tag for the new data stream.
  2913. *
  2914. * @constructor
  2915. * @extends {io.Transport.xhr-polling}
  2916. * @api public
  2917. */
  2918. function JSONPPolling (socket) {
  2919. io.Transport['xhr-polling'].apply(this, arguments);
  2920. this.index = io.j.length;
  2921. var self = this;
  2922. io.j.push(function (msg) {
  2923. self._(msg);
  2924. });
  2925. };
  2926. /**
  2927. * Inherits from XHR polling transport.
  2928. */
  2929. io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
  2930. /**
  2931. * Transport name
  2932. *
  2933. * @api public
  2934. */
  2935. JSONPPolling.prototype.name = 'jsonp-polling';
  2936. /**
  2937. * Posts a encoded message to the Socket.IO server using an iframe.
  2938. * The iframe is used because script tags can create POST based requests.
  2939. * The iframe is positioned outside of the view so the user does not
  2940. * notice it's existence.
  2941. *
  2942. * @param {String} data A encoded message.
  2943. * @api private
  2944. */
  2945. JSONPPolling.prototype.post = function (data) {
  2946. var self = this
  2947. , query = io.util.query(
  2948. this.socket.options.query
  2949. , 't='+ (+new Date) + '&i=' + this.index
  2950. );
  2951. if (!this.form) {
  2952. var form = document.createElement('form')
  2953. , area = document.createElement('textarea')
  2954. , id = this.iframeId = 'socketio_iframe_' + this.index
  2955. , iframe;
  2956. form.className = 'socketio';
  2957. form.style.position = 'absolute';
  2958. form.style.top = '0px';
  2959. form.style.left = '0px';
  2960. form.style.display = 'none';
  2961. form.target = id;
  2962. form.method = 'POST';
  2963. form.setAttribute('accept-charset', 'utf-8');
  2964. area.name = 'd';
  2965. form.appendChild(area);
  2966. document.body.appendChild(form);
  2967. this.form = form;
  2968. this.area = area;
  2969. }
  2970. this.form.action = this.prepareUrl() + query;
  2971. function complete () {
  2972. initIframe();
  2973. self.socket.setBuffer(false);
  2974. };
  2975. function initIframe () {
  2976. if (self.iframe) {
  2977. self.form.removeChild(self.iframe);
  2978. }
  2979. try {
  2980. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2981. iframe = document.createElement('<iframe name="'+ self.iframeId +'">');
  2982. } catch (e) {
  2983. iframe = document.createElement('iframe');
  2984. iframe.name = self.iframeId;
  2985. }
  2986. iframe.id = self.iframeId;
  2987. self.form.appendChild(iframe);
  2988. self.iframe = iframe;
  2989. };
  2990. initIframe();
  2991. // we temporarily stringify until we figure out how to prevent
  2992. // browsers from turning `\n` into `\r\n` in form inputs
  2993. this.area.value = io.JSON.stringify(data);
  2994. try {
  2995. this.form.submit();
  2996. } catch(e) {}
  2997. if (this.iframe.attachEvent) {
  2998. iframe.onreadystatechange = function () {
  2999. if (self.iframe.readyState == 'complete') {
  3000. complete();
  3001. }
  3002. };
  3003. } else {
  3004. this.iframe.onload = complete;
  3005. }
  3006. this.socket.setBuffer(true);
  3007. };
  3008. /**
  3009. * Creates a new JSONP poll that can be used to listen
  3010. * for messages from the Socket.IO server.
  3011. *
  3012. * @api private
  3013. */
  3014. JSONPPolling.prototype.get = function () {
  3015. var self = this
  3016. , script = document.createElement('script')
  3017. , query = io.util.query(
  3018. this.socket.options.query
  3019. , 't='+ (+new Date) + '&i=' + this.index
  3020. );
  3021. if (this.script) {
  3022. this.script.parentNode.removeChild(this.script);
  3023. this.script = null;
  3024. }
  3025. script.async = true;
  3026. script.src = this.prepareUrl() + query;
  3027. script.onerror = function () {
  3028. self.onClose();
  3029. };
  3030. var insertAt = document.getElementsByTagName('script')[0]
  3031. insertAt.parentNode.insertBefore(script, insertAt);
  3032. this.script = script;
  3033. if (indicator) {
  3034. setTimeout(function () {
  3035. var iframe = document.createElement('iframe');
  3036. document.body.appendChild(iframe);
  3037. document.body.removeChild(iframe);
  3038. }, 100);
  3039. }
  3040. };
  3041. /**
  3042. * Callback function for the incoming message stream from the Socket.IO server.
  3043. *
  3044. * @param {String} data The message
  3045. * @api private
  3046. */
  3047. JSONPPolling.prototype._ = function (msg) {
  3048. this.onData(msg);
  3049. if (this.open) {
  3050. this.get();
  3051. }
  3052. return this;
  3053. };
  3054. /**
  3055. * The indicator hack only works after onload
  3056. *
  3057. * @param {Socket} socket The socket instance that needs a transport
  3058. * @param {Function} fn The callback
  3059. * @api private
  3060. */
  3061. JSONPPolling.prototype.ready = function (socket, fn) {
  3062. var self = this;
  3063. if (!indicator) return fn.call(this);
  3064. io.util.load(function () {
  3065. fn.call(self);
  3066. });
  3067. };
  3068. /**
  3069. * Checks if browser supports this transport.
  3070. *
  3071. * @return {Boolean}
  3072. * @api public
  3073. */
  3074. JSONPPolling.check = function () {
  3075. return 'document' in global;
  3076. };
  3077. /**
  3078. * Check if cross domain requests are supported
  3079. *
  3080. * @returns {Boolean}
  3081. * @api public
  3082. */
  3083. JSONPPolling.xdomainCheck = function () {
  3084. return true;
  3085. };
  3086. /**
  3087. * Add the transport to your public io.transports array.
  3088. *
  3089. * @api private
  3090. */
  3091. io.transports.push('jsonp-polling');
  3092. })(
  3093. 'undefined' != typeof io ? io.Transport : module.exports
  3094. , 'undefined' != typeof io ? io : module.parent.exports
  3095. , this
  3096. );
  3097. })();