PageRenderTime 59ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/public/socket.io.js

https://github.com/christianhager/redisio
JavaScript | 2155 lines | 1558 code | 279 blank | 318 comment | 350 complexity | caec90fef733b5eff9d90f211117da4b MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /** Socket.IO 0.7pre - Built with build.js */
  2. /**
  3. * Socket.IO client
  4. *
  5. * @author Guillermo Rauch <guillermo@learnboost.com>
  6. * @license The MIT license.
  7. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  8. */
  9. this.io = {
  10. version: '0.7pre',
  11. setPath: function(path){
  12. if (window.console && console.error) console.error('io.setPath will be removed. Please set the variable WEB_SOCKET_SWF_LOCATION pointing to WebSocketMain.swf');
  13. this.path = /\/$/.test(path) ? path : path + '/';
  14. WEB_SOCKET_SWF_LOCATION = path + 'lib/vendor/web-socket-js/WebSocketMain.swf';
  15. }
  16. };
  17. if ('jQuery' in this) jQuery.io = this.io;
  18. if (typeof window != 'undefined'){
  19. // WEB_SOCKET_SWF_LOCATION = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cdn.socket.io/' + this.io.version + '/WebSocketMain.swf';
  20. WEB_SOCKET_SWF_LOCATION = '/Socket.IO/lib/vendor/web-socket-js/WebSocketMain.swf';
  21. }
  22. /**
  23. * Socket.IO client
  24. *
  25. * @author Guillermo Rauch <guillermo@learnboost.com>
  26. * @license The MIT license.
  27. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  28. */
  29. (function(){
  30. var _pageLoaded = false;
  31. io.util = {
  32. ios: false,
  33. load: function(fn){
  34. if (document.readyState == 'complete' || _pageLoaded) return fn();
  35. if ('attachEvent' in window){
  36. window.attachEvent('onload', fn);
  37. } else {
  38. window.addEventListener('load', fn, false);
  39. }
  40. },
  41. inherit: function(ctor, superCtor){
  42. // no support for `instanceof` for now
  43. for (var i in superCtor.prototype){
  44. ctor.prototype[i] = superCtor.prototype[i];
  45. }
  46. },
  47. indexOf: function(arr, item, from){
  48. for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){
  49. if (arr[i] === item) return i;
  50. }
  51. return -1;
  52. },
  53. isArray: function(obj){
  54. return Object.prototype.toString.call(obj) === '[object Array]';
  55. },
  56. merge: function(target, additional){
  57. for (var i in additional)
  58. if (additional.hasOwnProperty(i))
  59. target[i] = additional[i];
  60. }
  61. };
  62. io.util.ios = /iphone|ipad/i.test(navigator.userAgent);
  63. io.util.android = /android/i.test(navigator.userAgent);
  64. io.util.opera = /opera/i.test(navigator.userAgent);
  65. io.util.load(function(){
  66. _pageLoaded = true;
  67. });
  68. })();
  69. /**
  70. * Socket.IO client
  71. *
  72. * @author Guillermo Rauch <guillermo@learnboost.com>
  73. * @license The MIT license.
  74. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  75. */
  76. io.data = {};
  77. /**
  78. * Data decoder class
  79. *
  80. * @api public
  81. */
  82. io.data.Decoder = function(){
  83. this.reset();
  84. this.buffer = '';
  85. this.events = {};
  86. };
  87. io.data.Decoder.prototype = {
  88. /**
  89. * Add data to the buffer for parsing
  90. *
  91. * @param {String} data
  92. * @api public
  93. */
  94. add: function(data){
  95. this.buffer += data;
  96. this.parse();
  97. },
  98. /**
  99. * Parse the current buffer
  100. *
  101. * @api private
  102. */
  103. parse: function(){
  104. for (var l = this.buffer.length; this.i < l; this.i++){
  105. var chr = this.buffer[this.i];
  106. if (this.type === undefined){
  107. if (chr == ':') return this.error('Data type not specified');
  108. this.type = '' + chr;
  109. continue;
  110. }
  111. if (this.length === undefined && chr == ':'){
  112. this.length = '';
  113. continue;
  114. }
  115. if (this.data === undefined){
  116. if (chr != ':'){
  117. this.length += chr;
  118. } else {
  119. if (this.length.length === 0)
  120. return this.error('Data length not specified');
  121. this.length = Number(this.length);
  122. this.data = '';
  123. }
  124. continue;
  125. }
  126. if (this.data.length === this.length){
  127. if (chr == ','){
  128. this.emit('data', this.type, this.data);
  129. this.buffer = this.buffer.substr(this.i + 1);
  130. this.reset();
  131. return this.parse();
  132. } else {
  133. return this.error('Termination character "," expected');
  134. }
  135. } else {
  136. this.data += chr;
  137. }
  138. }
  139. },
  140. /**
  141. * Reset the parser state
  142. *
  143. * @api private
  144. */
  145. reset: function(){
  146. this.i = 0;
  147. this.type = this.data = this.length = undefined;
  148. },
  149. /**
  150. * Error handling functions
  151. *
  152. * @param {String} reason to report
  153. * @api private
  154. */
  155. error: function(reason){
  156. this.reset();
  157. this.emit('error', reason);
  158. },
  159. /**
  160. * Emits an event
  161. *
  162. * @param {String} ev name
  163. * @api public
  164. */
  165. emit: function(ev){
  166. if (!(ev in this.events))
  167. return this;
  168. for (var i = 0, l = this.events[ev].length; i < l; i++)
  169. if (this.events[ev][i])
  170. this.events[ev][i].apply(this, Array.prototype.slice.call(arguments).slice(1));
  171. return this;
  172. },
  173. /**
  174. * Adds an event listener
  175. *
  176. * @param {String} ev name
  177. * @param {Function} callback
  178. * @api public
  179. */
  180. on: function(ev, fn){
  181. if (!(ev in this.events))
  182. this.events[ev] = [];
  183. this.events[ev].push(fn);
  184. return this;
  185. },
  186. /**
  187. * Removes an event listener
  188. *
  189. * @param {String} ev name
  190. * @param {Function} callback
  191. * @api public
  192. */
  193. removeListener: function(ev, fn){
  194. if (!(ev in this.events))
  195. return this;
  196. for (var i = 0, l = this.events[ev].length; i < l; i++)
  197. if (this.events[ev][i] == fn)
  198. this.events[ev].splice(i, 1);
  199. return this;
  200. }
  201. };
  202. /**
  203. * Encode function
  204. *
  205. * Examples:
  206. * encode([3, 'Message of type 3']);
  207. * encode([[1, 'Message of type 1], [2, 'Message of type 2]]);
  208. *
  209. * @param {Array} list of messages
  210. * @api public
  211. */
  212. io.data.encode = function(messages){
  213. messages = io.util.isArray(messages[0]) ? messages : [messages];
  214. var ret = '';
  215. for (var i = 0, str; i < messages.length; i++){
  216. str = String(messages[i][1]);
  217. if (str === undefined || str === null) str = '';
  218. ret += messages[i][0] + ':' + str.length + ':' + str + ',';
  219. }
  220. return ret;
  221. };
  222. /**
  223. * Encode message function
  224. *
  225. * @param {String} message
  226. * @param {Object} annotations
  227. * @api public
  228. */
  229. io.data.encodeMessage = function(msg, annotations){
  230. var data = ''
  231. , anns = annotations || {};
  232. for (var k in anns){
  233. v = anns[k];
  234. data += k + (v !== null && v !== undefined ? ':' + v : '') + "\n";
  235. }
  236. data += ':' + (msg === undefined || msg === null ? '' : msg);
  237. return data;
  238. };
  239. /**
  240. * Decode message function
  241. *
  242. * @param {String} message
  243. * @api public
  244. */
  245. io.data.decodeMessage = function(msg){
  246. var anns = {}
  247. , data;
  248. for (var i = 0, chr, key, value, l = msg.length; i < l; i++){
  249. chr = msg[i];
  250. if (i === 0 && chr === ':'){
  251. data = msg.substr(1);
  252. break;
  253. }
  254. if (key == null && value == null && chr == ':'){
  255. data = msg.substr(i + 1);
  256. break;
  257. }
  258. if (chr === "\n"){
  259. anns[key] = value;
  260. key = value = undefined;
  261. continue;
  262. }
  263. if (key === undefined){
  264. key = chr;
  265. continue;
  266. }
  267. if (value === undefined && chr == ':'){
  268. value = '';
  269. continue;
  270. }
  271. if (value !== undefined)
  272. value += chr;
  273. else
  274. key += chr;
  275. }
  276. return [data, anns];
  277. };
  278. /**
  279. * Socket.IO client
  280. *
  281. * @author Guillermo Rauch <guillermo@learnboost.com>
  282. * @license The MIT license.
  283. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  284. */
  285. // abstract
  286. (function(){
  287. Transport = io.Transport = function(base, options){
  288. var self = this;
  289. this.base = base;
  290. this.options = {
  291. timeout: 15000 // based on heartbeat interval default
  292. };
  293. io.util.merge(this.options, options);
  294. this._decoder = new io.data.Decoder();
  295. this._decoder.on('data', function(type, message){
  296. self._onMessage(type, message);
  297. });
  298. };
  299. Transport.prototype.write = function(){
  300. throw new Error('Missing write() implementation');
  301. };
  302. Transport.prototype.connect = function(){
  303. throw new Error('Missing connect() implementation');
  304. };
  305. Transport.prototype.disconnect = function(){
  306. throw new Error('Missing disconnect() implementation');
  307. };
  308. Transport.prototype._onData = function(data){
  309. this._setTimeout();
  310. this._decoder.add(data);
  311. };
  312. Transport.prototype._setTimeout = function(){
  313. var self = this;
  314. if (this._timeout) clearTimeout(this._timeout);
  315. this._timeout = setTimeout(function(){
  316. self._onTimeout();
  317. }, this.options.timeout);
  318. };
  319. Transport.prototype._onTimeout = function(){
  320. this._onDisconnect();
  321. };
  322. Transport.prototype._onMessage = function(type, message){
  323. switch (type){
  324. case '0':
  325. this.disconnect();
  326. break;
  327. case '1':
  328. var msg = io.data.decodeMessage(message);
  329. // handle json decoding
  330. if ('j' in msg[1]){
  331. if (!window.JSON || !JSON.parse)
  332. alert('`JSON.parse` is not available, but Socket.IO is trying to parse'
  333. + 'JSON. Please include json2.js in your <head>');
  334. msg[0] = JSON.parse(msg[0]);
  335. }
  336. this.base._onMessage(msg[0], msg[1]);
  337. break;
  338. case '2':
  339. this._onHeartbeat(message);
  340. break;
  341. case '3':
  342. this.sessionid = message;
  343. this._onConnect();
  344. break;
  345. }
  346. },
  347. Transport.prototype._onHeartbeat = function(heartbeat){
  348. this.write('2', heartbeat); // echo
  349. };
  350. Transport.prototype._onConnect = function(){
  351. this.connected = true;
  352. this.connecting = false;
  353. this.base._onConnect();
  354. this._setTimeout();
  355. };
  356. Transport.prototype._onDisconnect = function(){
  357. this.connecting = false;
  358. this.connected = false;
  359. this.sessionid = null;
  360. this.base._onDisconnect();
  361. };
  362. Transport.prototype._prepareUrl = function(){
  363. return (this.base.options.secure ? 'https' : 'http')
  364. + '://' + this.base.host
  365. + ':' + this.base.options.port
  366. + '/' + this.base.options.resource
  367. + '/' + this.type
  368. + (this.sessionid ? ('/' + this.sessionid) : '/');
  369. };
  370. })();
  371. /**
  372. * Socket.IO client
  373. *
  374. * @author Guillermo Rauch <guillermo@learnboost.com>
  375. * @license The MIT license.
  376. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  377. */
  378. (function(){
  379. var empty = new Function,
  380. XMLHttpRequestCORS = (function(){
  381. if (!('XMLHttpRequest' in window)) return false;
  382. // CORS feature detection
  383. var a = new XMLHttpRequest();
  384. return a.withCredentials != undefined;
  385. })(),
  386. request = function(xdomain){
  387. if ('XDomainRequest' in window && xdomain) return new XDomainRequest();
  388. if ('XMLHttpRequest' in window && (!xdomain || XMLHttpRequestCORS)) return new XMLHttpRequest();
  389. if (!xdomain){
  390. try {
  391. var a = new ActiveXObject('MSXML2.XMLHTTP');
  392. return a;
  393. } catch(e){}
  394. try {
  395. var b = new ActiveXObject('Microsoft.XMLHTTP');
  396. return b;
  397. } catch(e){}
  398. }
  399. return false;
  400. },
  401. XHR = io.Transport.XHR = function(){
  402. io.Transport.apply(this, arguments);
  403. this._sendBuffer = [];
  404. };
  405. io.util.inherit(XHR, io.Transport);
  406. XHR.prototype.connect = function(){
  407. this._get();
  408. return this;
  409. };
  410. XHR.prototype._checkSend = function(){
  411. if (!this._posting && this._sendBuffer.length){
  412. var encoded = io.data.encode(this._sendBuffer);
  413. this._sendBuffer = [];
  414. this._send(encoded);
  415. }
  416. };
  417. XHR.prototype.write = function(type, data){
  418. if (io.util.isArray(type))
  419. this._sendBuffer.push.apply(this._sendBuffer, type);
  420. else
  421. this._sendBuffer.push([type, data]);
  422. this._checkSend();
  423. return this;
  424. };
  425. XHR.prototype._send = function(data){
  426. var self = this;
  427. this._posting = true;
  428. this._sendXhr = this._request('send', 'POST');
  429. this._sendXhr.onreadystatechange = function(){
  430. var status;
  431. if (self._sendXhr.readyState == 4){
  432. self._sendXhr.onreadystatechange = empty;
  433. try { status = self._sendXhr.status; } catch(e){}
  434. self._posting = false;
  435. if (status == 200){
  436. self._checkSend();
  437. } else {
  438. self._onDisconnect();
  439. }
  440. }
  441. };
  442. this._sendXhr.send('data=' + encodeURIComponent(data));
  443. };
  444. XHR.prototype.disconnect = function(){
  445. // send disconnection signal
  446. this._onDisconnect();
  447. return this;
  448. };
  449. XHR.prototype._onDisconnect = function(){
  450. if (this._xhr){
  451. this._xhr.onreadystatechange = this._xhr.onload = empty;
  452. this._xhr.abort();
  453. this._xhr = null;
  454. }
  455. if (this._sendXhr){
  456. this._sendXhr.onreadystatechange = this._sendXhr.onload = empty;
  457. this._sendXhr.abort();
  458. this._sendXhr = null;
  459. }
  460. this._sendBuffer = [];
  461. io.Transport.prototype._onDisconnect.call(this);
  462. };
  463. XHR.prototype._request = function(url, method, multipart){
  464. var req = request(this.base._isXDomain());
  465. if (multipart) req.multipart = true;
  466. req.open(method || 'GET', this._prepareUrl() + (url ? '/' + url : ''));
  467. if (method == 'POST' && 'setRequestHeader' in req){
  468. req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
  469. }
  470. return req;
  471. };
  472. XHR.check = function(xdomain){
  473. try {
  474. if (request(xdomain)) return true;
  475. } catch(e){}
  476. return false;
  477. };
  478. XHR.xdomainCheck = function(){
  479. return XHR.check(true);
  480. };
  481. XHR.request = request;
  482. })();
  483. /**
  484. * Socket.IO client
  485. *
  486. * @author Guillermo Rauch <guillermo@learnboost.com>
  487. * @license The MIT license.
  488. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  489. */
  490. (function(){
  491. var WS = io.Transport.websocket = function(){
  492. io.Transport.apply(this, arguments);
  493. };
  494. io.util.inherit(WS, io.Transport);
  495. WS.prototype.type = 'websocket';
  496. WS.prototype.connect = function(){
  497. var self = this;
  498. this.socket = new WebSocket(this._prepareUrl());
  499. this.socket.onmessage = function(ev){ self._onData(ev.data); };
  500. this.socket.onclose = function(ev){ self._onClose(); };
  501. return this;
  502. };
  503. WS.prototype.write = function(type, data){
  504. if (this.socket)
  505. this.socket.send(io.data.encode(io.util.isArray(type) ? type : [type, data]));
  506. return this;
  507. };
  508. WS.prototype.disconnect = function(){
  509. if (this.socket) this.socket.close();
  510. this._onDisconnect();
  511. return this;
  512. };
  513. WS.prototype._onClose = function(){
  514. this._onDisconnect();
  515. return this;
  516. };
  517. WS.prototype._prepareUrl = function(){
  518. return (this.base.options.secure ? 'wss' : 'ws')
  519. + '://' + this.base.host
  520. + ':' + this.base.options.port
  521. + '/' + this.base.options.resource
  522. + '/' + this.type
  523. + (this.sessionid ? ('/' + this.sessionid) : '');
  524. };
  525. WS.check = function(){
  526. // we make sure WebSocket is not confounded with a previously loaded flash WebSocket
  527. return 'WebSocket' in window && WebSocket.prototype && ( WebSocket.prototype.send && !!WebSocket.prototype.send.toString().match(/native/i)) && typeof WebSocket !== "undefined";
  528. };
  529. WS.xdomainCheck = function(){
  530. return true;
  531. };
  532. })();
  533. /**
  534. * Socket.IO client
  535. *
  536. * @author Guillermo Rauch <guillermo@learnboost.com>
  537. * @license The MIT license.
  538. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  539. */
  540. (function(){
  541. var Flashsocket = io.Transport.flashsocket = function(){
  542. io.Transport.websocket.apply(this, arguments);
  543. };
  544. io.util.inherit(Flashsocket, io.Transport.websocket);
  545. Flashsocket.prototype.type = 'flashsocket';
  546. Flashsocket.prototype.connect = function(){
  547. var self = this, args = arguments;
  548. WebSocket.__addTask(function(){
  549. io.Transport.websocket.prototype.connect.apply(self, args);
  550. });
  551. return this;
  552. };
  553. Flashsocket.prototype.send = function(){
  554. var self = this, args = arguments;
  555. WebSocket.__addTask(function(){
  556. io.Transport.websocket.prototype.send.apply(self, args);
  557. });
  558. return this;
  559. };
  560. Flashsocket.check = function(){
  561. if (typeof WebSocket == 'undefined' || !('__addTask' in WebSocket)) return false;
  562. if (io.util.opera) return false; // opera is buggy with this transport
  563. if ('navigator' in window && 'plugins' in navigator && navigator.plugins['Shockwave Flash']){
  564. return !!navigator.plugins['Shockwave Flash'].description;
  565. }
  566. if ('ActiveXObject' in window) {
  567. try {
  568. return !!new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  569. } catch (e) {}
  570. }
  571. return false;
  572. };
  573. Flashsocket.xdomainCheck = function(){
  574. return true;
  575. };
  576. })();
  577. /**
  578. * Socket.IO client
  579. *
  580. * @author Guillermo Rauch <guillermo@learnboost.com>
  581. * @license The MIT license.
  582. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  583. */
  584. (function(){
  585. var HTMLFile = io.Transport.htmlfile = function(){
  586. io.Transport.XHR.apply(this, arguments);
  587. };
  588. io.util.inherit(HTMLFile, io.Transport.XHR);
  589. HTMLFile.prototype.type = 'htmlfile';
  590. HTMLFile.prototype._get = function(){
  591. var self = this;
  592. this._open();
  593. window.attachEvent('onunload', function(){ self._destroy(); });
  594. };
  595. HTMLFile.prototype._open = function(){
  596. this._doc = new ActiveXObject('htmlfile');
  597. this._doc.open();
  598. this._doc.write('<html></html>');
  599. this._doc.parentWindow.s = this;
  600. this._doc.close();
  601. var _iframeC = this._doc.createElement('div');
  602. this._doc.body.appendChild(_iframeC);
  603. this._iframe = this._doc.createElement('iframe');
  604. _iframeC.appendChild(this._iframe);
  605. this._iframe.src = this._prepareUrl() + '/' + (+ new Date);
  606. };
  607. HTMLFile.prototype._ = function(data, doc){
  608. this._onData(data);
  609. var script = doc.getElementsByTagName('script')[0];
  610. script.parentNode.removeChild(script);
  611. };
  612. HTMLFile.prototype._destroy = function(){
  613. if (this._iframe){
  614. this._iframe.src = 'about:blank';
  615. this._doc = null;
  616. CollectGarbage();
  617. }
  618. };
  619. HTMLFile.prototype.disconnect = function(){
  620. this._destroy();
  621. return io.Transport.XHR.prototype.disconnect.call(this);
  622. };
  623. HTMLFile.check = function(){
  624. if ('ActiveXObject' in window){
  625. try {
  626. var a = new ActiveXObject('htmlfile');
  627. return a && io.Transport.XHR.check();
  628. } catch(e){}
  629. }
  630. return false;
  631. };
  632. HTMLFile.xdomainCheck = function(){
  633. // we can probably do handling for sub-domains, we should test that it's cross domain but a subdomain here
  634. return false;
  635. };
  636. })();
  637. /**
  638. * Socket.IO client
  639. *
  640. * @author Guillermo Rauch <guillermo@learnboost.com>
  641. * @license The MIT license.
  642. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  643. */
  644. (function(){
  645. var XHRMultipart = io.Transport['xhr-multipart'] = function(){
  646. io.Transport.XHR.apply(this, arguments);
  647. };
  648. io.util.inherit(XHRMultipart, io.Transport.XHR);
  649. XHRMultipart.prototype.type = 'xhr-multipart';
  650. XHRMultipart.prototype._get = function(){
  651. var self = this;
  652. this._xhr = this._request('', 'GET', true);
  653. this._xhr.onreadystatechange = function(){
  654. if (self._xhr.readyState == 3) self._onData(self._xhr.responseText);
  655. };
  656. this._xhr.send();
  657. };
  658. XHRMultipart.check = function(){
  659. return 'XMLHttpRequest' in window && 'prototype' in XMLHttpRequest && 'multipart' in XMLHttpRequest.prototype;
  660. };
  661. XHRMultipart.xdomainCheck = function(){
  662. return true;
  663. };
  664. })();
  665. /**
  666. * Socket.IO client
  667. *
  668. * @author Guillermo Rauch <guillermo@learnboost.com>
  669. * @license The MIT license.
  670. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  671. */
  672. (function(){
  673. var empty = new Function(),
  674. XHRPolling = io.Transport['xhr-polling'] = function(){
  675. io.Transport.XHR.apply(this, arguments);
  676. };
  677. io.util.inherit(XHRPolling, io.Transport.XHR);
  678. XHRPolling.prototype.type = 'xhr-polling';
  679. XHRPolling.prototype.connect = function(){
  680. if (io.util.ios || io.util.android){
  681. var self = this;
  682. io.util.load(function(){
  683. setTimeout(function(){
  684. io.Transport.XHR.prototype.connect.call(self);
  685. }, 10);
  686. });
  687. } else {
  688. io.Transport.XHR.prototype.connect.call(this);
  689. }
  690. };
  691. XHRPolling.prototype._get = function(){
  692. var self = this;
  693. this._xhr = this._request(+ new Date, 'GET');
  694. if ('onload' in this._xhr){
  695. this._xhr.onload = function(){
  696. self._onData(this.responseText);
  697. self._get();
  698. };
  699. } else {
  700. this._xhr.onreadystatechange = function(){
  701. var status;
  702. if (self._xhr.readyState == 4){
  703. self._xhr.onreadystatechange = empty;
  704. try { status = self._xhr.status; } catch(e){}
  705. if (status == 200){
  706. self._onData(self._xhr.responseText);
  707. self._get();
  708. } else {
  709. self._onDisconnect();
  710. }
  711. }
  712. };
  713. }
  714. this._xhr.send();
  715. };
  716. XHRPolling.check = function(){
  717. return io.Transport.XHR.check();
  718. };
  719. XHRPolling.xdomainCheck = function(){
  720. return io.Transport.XHR.xdomainCheck();
  721. };
  722. })();
  723. /**
  724. * Socket.IO client
  725. *
  726. * @author Guillermo Rauch <guillermo@learnboost.com>
  727. * @license The MIT license.
  728. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  729. */
  730. io.JSONP = [];
  731. JSONPPolling = io.Transport['jsonp-polling'] = function(){
  732. io.Transport.XHR.apply(this, arguments);
  733. this._insertAt = document.getElementsByTagName('script')[0];
  734. this._index = io.JSONP.length;
  735. io.JSONP.push(this);
  736. };
  737. io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
  738. JSONPPolling.prototype.type = 'jsonp-polling';
  739. JSONPPolling.prototype._send = function(data){
  740. var self = this;
  741. if (!('_form' in this)){
  742. var form = document.createElement('FORM'),
  743. area = document.createElement('TEXTAREA'),
  744. id = this._iframeId = 'socket_io_iframe_' + this._index,
  745. iframe;
  746. form.style.position = 'absolute';
  747. form.style.top = '-1000px';
  748. form.style.left = '-1000px';
  749. form.target = id;
  750. form.method = 'POST';
  751. form.action = this._prepareUrl() + '/' + (+new Date) + '/' + this._index;
  752. area.name = 'data';
  753. form.appendChild(area);
  754. this._insertAt.parentNode.insertBefore(form, this._insertAt);
  755. document.body.appendChild(form);
  756. this._form = form;
  757. this._area = area;
  758. }
  759. function complete(){
  760. initIframe();
  761. self._posting = false;
  762. self._checkSend();
  763. };
  764. function initIframe(){
  765. if (self._iframe){
  766. self._form.removeChild(self._iframe);
  767. }
  768. try {
  769. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  770. iframe = document.createElement('<iframe name="'+ self._iframeId +'">');
  771. } catch(e){
  772. iframe = document.createElement('iframe');
  773. iframe.name = self._iframeId;
  774. }
  775. iframe.id = self._iframeId;
  776. self._form.appendChild(iframe);
  777. self._iframe = iframe;
  778. };
  779. initIframe();
  780. this._posting = true;
  781. this._area.value = data;
  782. try {
  783. this._form.submit();
  784. } catch(e){}
  785. if (this._iframe.attachEvent){
  786. iframe.onreadystatechange = function(){
  787. if (self._iframe.readyState == 'complete') complete();
  788. };
  789. } else {
  790. this._iframe.onload = complete;
  791. }
  792. };
  793. JSONPPolling.prototype._get = function(){
  794. var self = this,
  795. script = document.createElement('SCRIPT');
  796. if (this._script){
  797. this._script.parentNode.removeChild(this._script);
  798. this._script = null;
  799. }
  800. script.async = true;
  801. script.src = this._prepareUrl() + '/' + (+new Date) + '/' + this._index;
  802. script.onerror = function(){
  803. self._onDisconnect();
  804. };
  805. this._insertAt.parentNode.insertBefore(script, this._insertAt);
  806. this._script = script;
  807. };
  808. JSONPPolling.prototype.disconnect = function(){
  809. if (this._script){
  810. this._script.parentNode.removeChild(this._script);
  811. this._script = null;
  812. }
  813. io.Transport['xhr-polling'].prototype.disconnect.call(this);
  814. return this;
  815. };
  816. JSONPPolling.prototype._ = function(){
  817. this._onData.apply(this, arguments);
  818. this._get();
  819. return this;
  820. };
  821. JSONPPolling.check = function(){
  822. return true;
  823. };
  824. JSONPPolling.xdomainCheck = function(){
  825. return true;
  826. };
  827. /**
  828. * Socket.IO client
  829. *
  830. * @author Guillermo Rauch <guillermo@learnboost.com>
  831. * @license The MIT license.
  832. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  833. */
  834. (function(){
  835. var Socket = io.Socket = function(host, options){
  836. this.host = host || document.domain;
  837. this.options = {
  838. secure: false,
  839. document: document,
  840. port: document.location.port || 80,
  841. resource: 'socket.io',
  842. transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
  843. transportOptions: {
  844. 'xhr-polling': {
  845. timeout: 25000 // based on polling duration default
  846. },
  847. 'jsonp-polling': {
  848. timeout: 25000
  849. }
  850. },
  851. connectTimeout: 5000,
  852. tryTransportsOnConnectTimeout: true,
  853. rememberTransport: true
  854. };
  855. io.util.merge(this.options, options);
  856. this.connected = false;
  857. this.connecting = false;
  858. this._events = {};
  859. this.transport = this.getTransport();
  860. if (!this.transport && 'console' in window) console.error('No transport available');
  861. };
  862. Socket.prototype.getTransport = function(override){
  863. var transports = override || this.options.transports, match;
  864. if (this.options.rememberTransport && !override){
  865. match = this.options.document.cookie.match('(?:^|;)\\s*socketio=([^;]*)');
  866. if (match){
  867. this._rememberedTransport = true;
  868. transports = [decodeURIComponent(match[1])];
  869. }
  870. }
  871. for (var i = 0, transport; transport = transports[i]; i++){
  872. if (io.Transport[transport]
  873. && io.Transport[transport].check()
  874. && (!this._isXDomain() || io.Transport[transport].xdomainCheck())){
  875. return new io.Transport[transport](this, this.options.transportOptions[transport] || {});
  876. }
  877. }
  878. return null;
  879. };
  880. Socket.prototype.connect = function(){
  881. if (this.transport && !this.connected){
  882. if (this.connecting) this.disconnect();
  883. this.connecting = true;
  884. this.transport.connect();
  885. if (this.options.connectTimeout){
  886. var self = this;
  887. setTimeout(function(){
  888. if (!self.connected){
  889. self.disconnect();
  890. if (self.options.tryTransportsOnConnectTimeout && !self._rememberedTransport){
  891. var remainingTransports = [], transports = self.options.transports;
  892. for (var i = 0, transport; transport = transports[i]; i++){
  893. if (transport != self.transport.type) remainingTransports.push(transport);
  894. }
  895. if (remainingTransports.length){
  896. self.transport = self.getTransport(remainingTransports);
  897. self.connect();
  898. }
  899. }
  900. }
  901. }, this.options.connectTimeout);
  902. }
  903. }
  904. return this;
  905. };
  906. Socket.prototype.write = function(message, atts){
  907. if (!this.transport || !this.transport.connected) return this._queue(message, atts);
  908. this.transport.write(message, atts);
  909. return this;
  910. };
  911. Socket.prototype.send = function(message, atts){
  912. atts = atts || {};
  913. if (typeof message == 'object'){
  914. atts['j'] = null;
  915. message = JSON.stringify(message);
  916. }
  917. this.write('1', io.data.encodeMessage(message, atts));
  918. return this;
  919. };
  920. Socket.prototype.json = function(obj, atts){
  921. atts = atts || {};
  922. atts['j'] = null
  923. return this.send(JSON.stringify(obj), atts);
  924. }
  925. Socket.prototype.disconnect = function(){
  926. this.transport.disconnect();
  927. return this;
  928. };
  929. Socket.prototype.on = function(name, fn){
  930. if (!(name in this._events)) this._events[name] = [];
  931. this._events[name].push(fn);
  932. return this;
  933. };
  934. Socket.prototype.emit = function(name, args){
  935. if (name in this._events){
  936. for (var i = 0, ii = this._events[name].length; i < ii; i++)
  937. this._events[name][i].apply(this, args === undefined ? [] : args);
  938. }
  939. return this;
  940. };
  941. Socket.prototype.removeEvent = function(name, fn){
  942. if (name in this._events){
  943. for (var a = 0, l = this._events[name].length; a < l; a++)
  944. if (this._events[name][a] == fn) this._events[name].splice(a, 1);
  945. }
  946. return this;
  947. };
  948. Socket.prototype._queue = function(message, atts){
  949. if (!('_queueStack' in this)) this._queueStack = [];
  950. this._queueStack.push([message, atts]);
  951. return this;
  952. };
  953. Socket.prototype._doQueue = function(){
  954. if (!('_queueStack' in this) || !this._queueStack.length) return this;
  955. this.transport.write(this._queueStack);
  956. this._queueStack = [];
  957. return this;
  958. };
  959. Socket.prototype._isXDomain = function(){
  960. return this.host !== document.domain;
  961. };
  962. Socket.prototype._onConnect = function(){
  963. this.connected = true;
  964. this.connecting = false;
  965. this._doQueue();
  966. if (this.options.rememberTransport) this.options.document.cookie = 'socketio=' + encodeURIComponent(this.transport.type);
  967. this.emit('connect');
  968. };
  969. Socket.prototype._onMessage = function(data){
  970. this.emit('message', [data]);
  971. };
  972. Socket.prototype._onDisconnect = function(){
  973. var wasConnected = this.connected;
  974. this.connected = false;
  975. this.connecting = false;
  976. this._queueStack = [];
  977. if (wasConnected) this.emit('disconnect');
  978. };
  979. Socket.prototype.addListener = Socket.prototype.addEvent = Socket.prototype.addEventListener = Socket.prototype.on;
  980. Socket.prototype.fire = Socket.prototype.emit;
  981. })();
  982. /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
  983. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  984. */
  985. 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}}}}();
  986. /*
  987. /*
  988. Copyright 2006 Adobe Systems Incorporated
  989. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
  990. to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  991. and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  992. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  993. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  994. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  995. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  996. OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  997. */
  998. /*
  999. * The Bridge class, responsible for navigating AS instances
  1000. */
  1001. function FABridge(target,bridgeName)
  1002. {
  1003. this.target = target;
  1004. this.remoteTypeCache = {};
  1005. this.remoteInstanceCache = {};
  1006. this.remoteFunctionCache = {};
  1007. this.localFunctionCache = {};
  1008. this.bridgeID = FABridge.nextBridgeID++;
  1009. this.name = bridgeName;
  1010. this.nextLocalFuncID = 0;
  1011. FABridge.instances[this.name] = this;
  1012. FABridge.idMap[this.bridgeID] = this;
  1013. return this;
  1014. }
  1015. // type codes for packed values
  1016. FABridge.TYPE_ASINSTANCE = 1;
  1017. FABridge.TYPE_ASFUNCTION = 2;
  1018. FABridge.TYPE_JSFUNCTION = 3;
  1019. FABridge.TYPE_ANONYMOUS = 4;
  1020. FABridge.initCallbacks = {};
  1021. FABridge.userTypes = {};
  1022. FABridge.addToUserTypes = function()
  1023. {
  1024. for (var i = 0; i < arguments.length; i++)
  1025. {
  1026. FABridge.userTypes[arguments[i]] = {
  1027. 'typeName': arguments[i],
  1028. 'enriched': false
  1029. };
  1030. }
  1031. }
  1032. FABridge.argsToArray = function(args)
  1033. {
  1034. var result = [];
  1035. for (var i = 0; i < args.length; i++)
  1036. {
  1037. result[i] = args[i];
  1038. }
  1039. return result;
  1040. }
  1041. function instanceFactory(objID)
  1042. {
  1043. this.fb_instance_id = objID;
  1044. return this;
  1045. }
  1046. function FABridge__invokeJSFunction(args)
  1047. {
  1048. var funcID = args[0];
  1049. var throughArgs = args.concat();//FABridge.argsToArray(arguments);
  1050. throughArgs.shift();
  1051. var bridge = FABridge.extractBridgeFromID(funcID);
  1052. return bridge.invokeLocalFunction(funcID, throughArgs);
  1053. }
  1054. FABridge.addInitializationCallback = function(bridgeName, callback)
  1055. {
  1056. var inst = FABridge.instances[bridgeName];
  1057. if (inst != undefined)
  1058. {
  1059. callback.call(inst);
  1060. return;
  1061. }
  1062. var callbackList = FABridge.initCallbacks[bridgeName];
  1063. if(callbackList == null)
  1064. {
  1065. FABridge.initCallbacks[bridgeName] = callbackList = [];
  1066. }
  1067. callbackList.push(callback);
  1068. }
  1069. // updated for changes to SWFObject2
  1070. function FABridge__bridgeInitialized(bridgeName) {
  1071. var objects = document.getElementsByTagName("object");
  1072. var ol = objects.length;
  1073. var activeObjects = [];
  1074. if (ol > 0) {
  1075. for (var i = 0; i < ol; i++) {
  1076. if (typeof objects[i].SetVariable != "undefined") {
  1077. activeObjects[activeObjects.length] = objects[i];
  1078. }
  1079. }
  1080. }
  1081. var embeds = document.getElementsByTagName("embed");
  1082. var el = embeds.length;
  1083. var activeEmbeds = [];
  1084. if (el > 0) {
  1085. for (var j = 0; j < el; j++) {
  1086. if (typeof embeds[j].SetVariable != "undefined") {
  1087. activeEmbeds[activeEmbeds.length] = embeds[j];
  1088. }
  1089. }
  1090. }
  1091. var aol = activeObjects.length;
  1092. var ael = activeEmbeds.length;
  1093. var searchStr = "bridgeName="+ bridgeName;
  1094. if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) {
  1095. FABridge.attachBridge(activeObjects[0], bridgeName);
  1096. }
  1097. else if (ael == 1 && !aol) {
  1098. FABridge.attachBridge(activeEmbeds[0], bridgeName);
  1099. }
  1100. else {
  1101. var flash_found = false;
  1102. if (aol > 1) {
  1103. for (var k = 0; k < aol; k++) {
  1104. var params = activeObjects[k].childNodes;
  1105. for (var l = 0; l < params.length; l++) {
  1106. var param = params[l];
  1107. if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) {
  1108. FABridge.attachBridge(activeObjects[k], bridgeName);
  1109. flash_found = true;
  1110. break;
  1111. }
  1112. }
  1113. if (flash_found) {
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. if (!flash_found && ael > 1) {
  1119. for (var m = 0; m < ael; m++) {
  1120. var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;
  1121. if (flashVars.indexOf(searchStr) >= 0) {
  1122. FABridge.attachBridge(activeEmbeds[m], bridgeName);
  1123. break;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. return true;
  1129. }
  1130. // used to track multiple bridge instances, since callbacks from AS are global across the page.
  1131. FABridge.nextBridgeID = 0;
  1132. FABridge.instances = {};
  1133. FABridge.idMap = {};
  1134. FABridge.refCount = 0;
  1135. FABridge.extractBridgeFromID = function(id)
  1136. {
  1137. var bridgeID = (id >> 16);
  1138. return FABridge.idMap[bridgeID];
  1139. }
  1140. FABridge.attachBridge = function(instance, bridgeName)
  1141. {
  1142. var newBridgeInstance = new FABridge(instance, bridgeName);
  1143. FABridge[bridgeName] = newBridgeInstance;
  1144. /* FABridge[bridgeName] = function() {
  1145. return newBridgeInstance.root();
  1146. }
  1147. */
  1148. var callbacks = FABridge.initCallbacks[bridgeName];
  1149. if (callbacks == null)
  1150. {
  1151. return;
  1152. }
  1153. for (var i = 0; i < callbacks.length; i++)
  1154. {
  1155. callbacks[i].call(newBridgeInstance);
  1156. }
  1157. delete FABridge.initCallbacks[bridgeName]
  1158. }
  1159. // some methods can't be proxied. You can use the explicit get,set, and call methods if necessary.
  1160. FABridge.blockedMethods =
  1161. {
  1162. toString: true,
  1163. get: true,
  1164. set: true,
  1165. call: true
  1166. };
  1167. FABridge.prototype =
  1168. {
  1169. // bootstrapping
  1170. root: function()
  1171. {
  1172. return this.deserialize(this.target.getRoot());
  1173. },
  1174. //clears all of the AS objects in the cache maps
  1175. releaseASObjects: function()
  1176. {
  1177. return this.target.releaseASObjects();
  1178. },
  1179. //clears a specific object in AS from the type maps
  1180. releaseNamedASObject: function(value)
  1181. {
  1182. if(typeof(value) != "object")
  1183. {
  1184. return false;
  1185. }
  1186. else
  1187. {
  1188. var ret = this.target.releaseNamedASObject(value.fb_instance_id);
  1189. return ret;
  1190. }
  1191. },
  1192. //create a new AS Object
  1193. create: function(className)
  1194. {
  1195. return this.deserialize(this.target.create(className));
  1196. },
  1197. // utilities
  1198. makeID: function(token)
  1199. {
  1200. return (this.bridgeID << 16) + token;
  1201. },
  1202. // low level access to the flash object
  1203. //get a named property from an AS object
  1204. getPropertyFromAS: function(objRef, propName)
  1205. {
  1206. if (FABridge.refCount > 0)
  1207. {
  1208. throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
  1209. }
  1210. else
  1211. {
  1212. FABridge.refCount++;
  1213. retVal = this.target.getPropFromAS(objRef, propName);
  1214. retVal = this.handleError(retVal);
  1215. FABridge.refCount--;
  1216. return retVal;
  1217. }
  1218. },
  1219. //set a named property on an AS object
  1220. setPropertyInAS: function(objRef,propName, value)
  1221. {
  1222. if (FABridge.refCount > 0)
  1223. {
  1224. throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
  1225. }
  1226. else
  1227. {
  1228. FABridge.refCount++;
  1229. retVal = this.target.setPropInAS(objRef,propName, this.serialize(value));
  1230. retVal = this.handleError(retVal);
  1231. FABridge.refCount--;
  1232. return retVal;
  1233. }
  1234. },
  1235. //call an AS function
  1236. callASFunction: function(funcID, args)
  1237. {
  1238. if (FABridge.refCount > 0)
  1239. {
  1240. throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
  1241. }
  1242. else
  1243. {
  1244. FABridge.refCount++;
  1245. retVal = this.target.invokeASFunction(funcID, this.serialize(args));
  1246. retVal = this.handleError(retVal);
  1247. FABridge.refCount--;
  1248. return retVal;
  1249. }
  1250. },
  1251. //call a method on an AS object
  1252. callASMethod: function(objID, funcName, args)
  1253. {
  1254. if (FABridge.refCount > 0)
  1255. {
  1256. throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
  1257. }
  1258. else
  1259. {
  1260. FABridge.refCount++;
  1261. args = this.serialize(args);
  1262. retVal = this.target.invokeASMethod(objID, funcName, args);
  1263. retVal = this.handleError(retVal);
  1264. FABridge.refCount--;
  1265. return retVal;
  1266. }
  1267. },
  1268. // responders to remote calls from flash
  1269. //callback from flash that executes a local JS function
  1270. //used mostly when setting js functions as callbacks on events
  1271. invokeLocalFunction: function(funcID, args)
  1272. {
  1273. var result;
  1274. var func = this.localFunctionCache[funcID];
  1275. if(func != undefined)
  1276. {
  1277. result = this.serialize(func.apply(null, this.deserialize(args)));
  1278. }
  1279. return result;
  1280. },
  1281. // Object Types and Proxies
  1282. // accepts an object reference, returns a type object matching the obj reference.
  1283. getTypeFromName: function(objTypeName)
  1284. {
  1285. return this.remoteTypeCache[objTypeName];
  1286. },
  1287. //create an AS proxy for the given object ID and type
  1288. createProxy: function(objID, typeName)
  1289. {
  1290. var objType = this.getTypeFromName(typeName);
  1291. instanceFactory.prototype = objType;
  1292. var instance = new instanceFactory(objID);
  1293. this.remoteInstanceCache[objID] = instance;
  1294. return instance;
  1295. },
  1296. //return the proxy associated with the given object ID
  1297. getProxy: function(objID)
  1298. {
  1299. return this.remoteInstanceCache[objID];
  1300. },
  1301. // accepts a type structure, returns a constructed type
  1302. addTypeDataToCache: function(typeData)
  1303. {
  1304. var newType = new ASProxy(this, typeData.name);
  1305. var accessors = typeData.accessors;
  1306. for (var i = 0; i < accessors.length; i++)
  1307. {
  1308. this.addPropertyToType(newType, accessors[i]);
  1309. }
  1310. var methods = typeData.methods;
  1311. for (var i = 0; i < methods.length; i++)
  1312. {
  1313. if (FABridge.blockedMethods[methods[i]] == undefined)
  1314. {
  1315. this.addMethodToType(newType, methods[i]);
  1316. }
  1317. }
  1318. this.remoteTypeCache[newType.typeName] = newType;
  1319. return newType;
  1320. },
  1321. //add a property to a typename; used to define the properties that can be called on an AS proxied object
  1322. addPropertyToType: function(ty, propName)
  1323. {
  1324. var c = propName.charAt(0);
  1325. var setterName;
  1326. var getterName;
  1327. if(c >= "a" && c <= "z")
  1328. {
  1329. getterName = "get" + c.toUpperCase() + propName.substr(1);
  1330. setterName = "set" + c.toUpperCase() + propName.substr(1);
  1331. }
  1332. else
  1333. {
  1334. getterName = "get" + propName;

Large files files are truncated, but you can click here to view the full file