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

/mobileapp/joshfire/vendor/socket.io.js

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