PageRenderTime 32ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/django_socketio/static/js/socket.io.js

https://github.com/genba/django-socketio
JavaScript | 1940 lines | 1446 code | 254 blank | 240 comment | 320 complexity | 67a4484fca1258a566e0a500c4b77f26 MD5 | raw file
Possible License(s): BSD-2-Clause
  1. /** Socket.IO 0.6.1 - 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.6.1',
  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. try {
  18. if ('jQuery' in this)
  19. jQuery.io = this.io;
  20. } catch (e) {
  21. try {
  22. if ('django' in this && 'jQuery' in django)
  23. django.jQuery.io = this.io;
  24. } catch (e) {
  25. }
  26. }
  27. if (typeof window != 'undefined'){
  28. // WEB_SOCKET_SWF_LOCATION = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cdn.socket.io/' + this.io.version + '/WebSocketMain.swf';
  29. if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined')
  30. WEB_SOCKET_SWF_LOCATION = '/socket.io/lib/vendor/web-socket-js/WebSocketMain.swf';
  31. }
  32. /**
  33. * Socket.IO client
  34. *
  35. * @author Guillermo Rauch <guillermo@learnboost.com>
  36. * @license The MIT license.
  37. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  38. */
  39. (function(){
  40. var _pageLoaded = false;
  41. io.util = {
  42. ios: false,
  43. load: function(fn){
  44. if (/loaded|complete/.test(document.readyState) || _pageLoaded) return fn();
  45. if ('attachEvent' in window){
  46. window.attachEvent('onload', fn);
  47. } else {
  48. window.addEventListener('load', fn, false);
  49. }
  50. },
  51. inherit: function(ctor, superCtor){
  52. // no support for `instanceof` for now
  53. for (var i in superCtor.prototype){
  54. ctor.prototype[i] = superCtor.prototype[i];
  55. }
  56. },
  57. indexOf: function(arr, item, from){
  58. for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){
  59. if (arr[i] === item) return i;
  60. }
  61. return -1;
  62. },
  63. isArray: function(obj){
  64. return Object.prototype.toString.call(obj) === '[object Array]';
  65. },
  66. merge: function(target, additional){
  67. for (var i in additional)
  68. if (additional.hasOwnProperty(i))
  69. target[i] = additional[i];
  70. }
  71. };
  72. io.util.ios = /iphone|ipad/i.test(navigator.userAgent);
  73. io.util.android = /android/i.test(navigator.userAgent);
  74. io.util.opera = /opera/i.test(navigator.userAgent);
  75. io.util.load(function(){
  76. _pageLoaded = true;
  77. });
  78. })();
  79. /**
  80. * Socket.IO client
  81. *
  82. * @author Guillermo Rauch <guillermo@learnboost.com>
  83. * @license The MIT license.
  84. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  85. */
  86. // abstract
  87. (function(){
  88. var frame = '~m~',
  89. stringify = function(message){
  90. if (Object.prototype.toString.call(message) == '[object Object]'){
  91. if (!('JSON' in window)){
  92. if ('console' in window && console.error) console.error('Trying to encode as JSON, but JSON.stringify is missing.');
  93. return '{ "$error": "Invalid message" }';
  94. }
  95. return '~j~' + JSON.stringify(message);
  96. } else {
  97. return String(message);
  98. }
  99. };
  100. Transport = io.Transport = function(base, options){
  101. this.base = base;
  102. this.options = {
  103. timeout: 15000 // based on heartbeat interval default
  104. };
  105. io.util.merge(this.options, options);
  106. };
  107. Transport.prototype.send = function(){
  108. throw new Error('Missing send() implementation');
  109. };
  110. Transport.prototype.connect = function(){
  111. throw new Error('Missing connect() implementation');
  112. };
  113. Transport.prototype.disconnect = function(){
  114. throw new Error('Missing disconnect() implementation');
  115. };
  116. Transport.prototype._encode = function(messages){
  117. var ret = '', message,
  118. messages = io.util.isArray(messages) ? messages : [messages];
  119. for (var i = 0, l = messages.length; i < l; i++){
  120. message = messages[i] === null || messages[i] === undefined ? '' : stringify(messages[i]);
  121. ret += frame + message.length + frame + message;
  122. }
  123. return ret;
  124. };
  125. Transport.prototype._decode = function(data){
  126. var messages = [], number, n;
  127. do {
  128. if (data.substr(0, 3) !== frame) return messages;
  129. data = data.substr(3);
  130. number = '', n = '';
  131. for (var i = 0, l = data.length; i < l; i++){
  132. n = Number(data.substr(i, 1));
  133. if (data.substr(i, 1) == n){
  134. number += n;
  135. } else {
  136. data = data.substr(number.length + frame.length);
  137. number = Number(number);
  138. break;
  139. }
  140. }
  141. messages.push(data.substr(0, number)); // here
  142. data = data.substr(number);
  143. } while(data !== '');
  144. return messages;
  145. };
  146. Transport.prototype._onData = function(data){
  147. this._setTimeout();
  148. var msgs = this._decode(data);
  149. if (msgs && msgs.length){
  150. for (var i = 0, l = msgs.length; i < l; i++){
  151. this._onMessage(msgs[i]);
  152. }
  153. }
  154. };
  155. Transport.prototype._setTimeout = function(){
  156. var self = this;
  157. if (this._timeout) clearTimeout(this._timeout);
  158. this._timeout = setTimeout(function(){
  159. self._onTimeout();
  160. }, this.options.timeout);
  161. };
  162. Transport.prototype._onTimeout = function(){
  163. this._onDisconnect();
  164. };
  165. Transport.prototype._onMessage = function(message){
  166. if (!this.sessionid){
  167. this.sessionid = message;
  168. this._onConnect();
  169. } else if (message.substr(0, 3) == '~h~'){
  170. this._onHeartbeat(message.substr(3));
  171. } else if (message.substr(0, 3) == '~j~'){
  172. this.base._onMessage(JSON.parse(message.substr(3)));
  173. } else {
  174. this.base._onMessage(message);
  175. }
  176. },
  177. Transport.prototype._onHeartbeat = function(heartbeat){
  178. this.send('~h~' + heartbeat); // echo
  179. };
  180. Transport.prototype._onConnect = function(){
  181. this.connected = true;
  182. this.connecting = false;
  183. this.base._onConnect();
  184. this._setTimeout();
  185. };
  186. Transport.prototype._onDisconnect = function(){
  187. this.connecting = false;
  188. this.connected = false;
  189. this.sessionid = null;
  190. this.base._onDisconnect();
  191. };
  192. Transport.prototype._prepareUrl = function(){
  193. return (this.base.options.secure ? 'https' : 'http')
  194. + '://' + this.base.host
  195. + ':' + this.base.options.port
  196. + '/' + this.base.options.resource
  197. + '/' + this.type
  198. + (this.sessionid ? ('/' + this.sessionid) : '/');
  199. };
  200. })();
  201. /**
  202. * Socket.IO client
  203. *
  204. * @author Guillermo Rauch <guillermo@learnboost.com>
  205. * @license The MIT license.
  206. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  207. */
  208. (function(){
  209. var empty = new Function,
  210. XMLHttpRequestCORS = (function(){
  211. if (!('XMLHttpRequest' in window)) return false;
  212. // CORS feature detection
  213. var a = new XMLHttpRequest();
  214. return a.withCredentials != undefined;
  215. })(),
  216. request = function(xdomain){
  217. if ('XDomainRequest' in window && xdomain) return new XDomainRequest();
  218. if ('XMLHttpRequest' in window && (!xdomain || XMLHttpRequestCORS)) return new XMLHttpRequest();
  219. if (!xdomain){
  220. try {
  221. var a = new ActiveXObject('MSXML2.XMLHTTP');
  222. return a;
  223. } catch(e){}
  224. try {
  225. var b = new ActiveXObject('Microsoft.XMLHTTP');
  226. return b;
  227. } catch(e){}
  228. }
  229. return false;
  230. },
  231. XHR = io.Transport.XHR = function(){
  232. io.Transport.apply(this, arguments);
  233. this._sendBuffer = [];
  234. };
  235. io.util.inherit(XHR, io.Transport);
  236. XHR.prototype.connect = function(){
  237. this._get();
  238. return this;
  239. };
  240. XHR.prototype._checkSend = function(){
  241. if (!this._posting && this._sendBuffer.length){
  242. var encoded = this._encode(this._sendBuffer);
  243. this._sendBuffer = [];
  244. this._send(encoded);
  245. }
  246. };
  247. XHR.prototype.send = function(data){
  248. if (io.util.isArray(data)){
  249. this._sendBuffer.push.apply(this._sendBuffer, data);
  250. } else {
  251. this._sendBuffer.push(data);
  252. }
  253. this._checkSend();
  254. return this;
  255. };
  256. XHR.prototype._send = function(data){
  257. var self = this;
  258. this._posting = true;
  259. this._sendXhr = this._request('send', 'POST');
  260. this._sendXhr.onreadystatechange = function(){
  261. var status;
  262. if (self._sendXhr.readyState == 4){
  263. self._sendXhr.onreadystatechange = empty;
  264. try { status = self._sendXhr.status; } catch(e){}
  265. self._posting = false;
  266. if (status == 200){
  267. self._checkSend();
  268. } else {
  269. self._onDisconnect();
  270. }
  271. }
  272. };
  273. this._sendXhr.send('data=' + encodeURIComponent(data));
  274. };
  275. XHR.prototype.disconnect = function(){
  276. // send disconnection signal
  277. this._onDisconnect();
  278. return this;
  279. };
  280. XHR.prototype._onDisconnect = function(){
  281. if (this._xhr){
  282. this._xhr.onreadystatechange = empty;
  283. try {
  284. this._xhr.abort();
  285. } catch(e){}
  286. this._xhr = null;
  287. }
  288. if (this._sendXhr){
  289. this._sendXhr.onreadystatechange = empty;
  290. try {
  291. this._sendXhr.abort();
  292. } catch(e){}
  293. this._sendXhr = null;
  294. }
  295. this._sendBuffer = [];
  296. io.Transport.prototype._onDisconnect.call(this);
  297. };
  298. XHR.prototype._request = function(url, method, multipart){
  299. var req = request(this.base._isXDomain());
  300. if (multipart) req.multipart = true;
  301. req.open(method || 'GET', this._prepareUrl() + (url ? '/' + url : ''));
  302. if (method == 'POST' && 'setRequestHeader' in req){
  303. req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
  304. }
  305. return req;
  306. };
  307. XHR.check = function(xdomain){
  308. try {
  309. if (request(xdomain)) return true;
  310. } catch(e){}
  311. return false;
  312. };
  313. XHR.xdomainCheck = function(){
  314. return XHR.check(true);
  315. };
  316. XHR.request = request;
  317. })();
  318. /**
  319. * Socket.IO client
  320. *
  321. * @author Guillermo Rauch <guillermo@learnboost.com>
  322. * @license The MIT license.
  323. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  324. */
  325. (function(){
  326. var WS = io.Transport.websocket = function(){
  327. io.Transport.apply(this, arguments);
  328. };
  329. io.util.inherit(WS, io.Transport);
  330. WS.prototype.type = 'websocket';
  331. WS.prototype.connect = function(){
  332. var self = this;
  333. this.socket = new WebSocket(this._prepareUrl());
  334. this.socket.onmessage = function(ev){ self._onData(ev.data); };
  335. this.socket.onclose = function(ev){ self._onClose(); };
  336. this.socket.onerror = function(e){ self._onError(e); };
  337. return this;
  338. };
  339. WS.prototype.send = function(data){
  340. if (this.socket) this.socket.send(this._encode(data));
  341. return this;
  342. };
  343. WS.prototype.disconnect = function(){
  344. if (this.socket) this.socket.close();
  345. return this;
  346. };
  347. WS.prototype._onClose = function(){
  348. this._onDisconnect();
  349. return this;
  350. };
  351. WS.prototype._onError = function(e){
  352. this.base.emit('error', [e]);
  353. };
  354. WS.prototype._prepareUrl = function(){
  355. return (this.base.options.secure ? 'wss' : 'ws')
  356. + '://' + this.base.host
  357. + ':' + this.base.options.port
  358. + '/' + this.base.options.resource
  359. + '/' + this.type
  360. + (this.sessionid ? ('/' + this.sessionid) : '');
  361. };
  362. WS.check = function(){
  363. // we make sure WebSocket is not confounded with a previously loaded flash WebSocket
  364. return 'WebSocket' in window && WebSocket.prototype && ( WebSocket.prototype.send && !!WebSocket.prototype.send.toString().match(/native/i)) && typeof WebSocket !== "undefined";
  365. };
  366. WS.xdomainCheck = function(){
  367. return true;
  368. };
  369. })();
  370. /**
  371. * Socket.IO client
  372. *
  373. * @author Guillermo Rauch <guillermo@learnboost.com>
  374. * @license The MIT license.
  375. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  376. */
  377. (function(){
  378. var Flashsocket = io.Transport.flashsocket = function(){
  379. io.Transport.websocket.apply(this, arguments);
  380. };
  381. io.util.inherit(Flashsocket, io.Transport.websocket);
  382. Flashsocket.prototype.type = 'flashsocket';
  383. Flashsocket.prototype.connect = function(){
  384. var self = this, args = arguments;
  385. WebSocket.__addTask(function(){
  386. io.Transport.websocket.prototype.connect.apply(self, args);
  387. });
  388. return this;
  389. };
  390. Flashsocket.prototype.send = function(){
  391. var self = this, args = arguments;
  392. WebSocket.__addTask(function(){
  393. io.Transport.websocket.prototype.send.apply(self, args);
  394. });
  395. return this;
  396. };
  397. Flashsocket.check = function(){
  398. if (typeof WebSocket == 'undefined' || !('__addTask' in WebSocket)) return false;
  399. if (io.util.opera) return false; // opera is buggy with this transport
  400. if ('navigator' in window && 'plugins' in navigator && navigator.plugins['Shockwave Flash']){
  401. return !!navigator.plugins['Shockwave Flash'].description;
  402. }
  403. if ('ActiveXObject' in window) {
  404. try {
  405. return !!new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  406. } catch (e) {}
  407. }
  408. return false;
  409. };
  410. Flashsocket.xdomainCheck = function(){
  411. return true;
  412. };
  413. })();
  414. /**
  415. * Socket.IO client
  416. *
  417. * @author Guillermo Rauch <guillermo@learnboost.com>
  418. * @license The MIT license.
  419. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  420. */
  421. (function(){
  422. var HTMLFile = io.Transport.htmlfile = function(){
  423. io.Transport.XHR.apply(this, arguments);
  424. };
  425. io.util.inherit(HTMLFile, io.Transport.XHR);
  426. HTMLFile.prototype.type = 'htmlfile';
  427. HTMLFile.prototype._get = function(){
  428. var self = this;
  429. this._open();
  430. window.attachEvent('onunload', function(){ self._destroy(); });
  431. };
  432. HTMLFile.prototype._open = function(){
  433. this._doc = new ActiveXObject('htmlfile');
  434. this._doc.open();
  435. this._doc.write('<html></html>');
  436. this._doc.parentWindow.s = this;
  437. this._doc.close();
  438. var _iframeC = this._doc.createElement('div');
  439. this._doc.body.appendChild(_iframeC);
  440. this._iframe = this._doc.createElement('iframe');
  441. _iframeC.appendChild(this._iframe);
  442. this._iframe.src = this._prepareUrl() + '/' + (+ new Date);
  443. };
  444. HTMLFile.prototype._ = function(data, doc){
  445. this._onData(data);
  446. var script = doc.getElementsByTagName('script')[0];
  447. script.parentNode.removeChild(script);
  448. };
  449. HTMLFile.prototype._destroy = function(){
  450. if (this._iframe){
  451. this._iframe.src = 'about:blank';
  452. this._doc = null;
  453. CollectGarbage();
  454. }
  455. };
  456. HTMLFile.prototype.disconnect = function(){
  457. this._destroy();
  458. return io.Transport.XHR.prototype.disconnect.call(this);
  459. };
  460. HTMLFile.check = function(){
  461. if ('ActiveXObject' in window){
  462. try {
  463. var a = new ActiveXObject('htmlfile');
  464. return a && io.Transport.XHR.check();
  465. } catch(e){}
  466. }
  467. return false;
  468. };
  469. HTMLFile.xdomainCheck = function(){
  470. // we can probably do handling for sub-domains, we should test that it's cross domain but a subdomain here
  471. return false;
  472. };
  473. })();
  474. /**
  475. * Socket.IO client
  476. *
  477. * @author Guillermo Rauch <guillermo@learnboost.com>
  478. * @license The MIT license.
  479. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  480. */
  481. (function(){
  482. var XHRMultipart = io.Transport['xhr-multipart'] = function(){
  483. io.Transport.XHR.apply(this, arguments);
  484. };
  485. io.util.inherit(XHRMultipart, io.Transport.XHR);
  486. XHRMultipart.prototype.type = 'xhr-multipart';
  487. XHRMultipart.prototype._get = function(){
  488. var self = this;
  489. this._xhr = this._request('', 'GET', true);
  490. this._xhr.onreadystatechange = function(){
  491. if (self._xhr.readyState == 3) self._onData(self._xhr.responseText);
  492. };
  493. this._xhr.send(null);
  494. };
  495. XHRMultipart.check = function(){
  496. return 'XMLHttpRequest' in window && 'prototype' in XMLHttpRequest && 'multipart' in XMLHttpRequest.prototype;
  497. };
  498. XHRMultipart.xdomainCheck = function(){
  499. return true;
  500. };
  501. })();
  502. /**
  503. * Socket.IO client
  504. *
  505. * @author Guillermo Rauch <guillermo@learnboost.com>
  506. * @license The MIT license.
  507. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  508. */
  509. (function(){
  510. var empty = new Function(),
  511. XHRPolling = io.Transport['xhr-polling'] = function(){
  512. io.Transport.XHR.apply(this, arguments);
  513. };
  514. io.util.inherit(XHRPolling, io.Transport.XHR);
  515. XHRPolling.prototype.type = 'xhr-polling';
  516. XHRPolling.prototype.connect = function(){
  517. if (io.util.ios || io.util.android){
  518. var self = this;
  519. io.util.load(function(){
  520. setTimeout(function(){
  521. io.Transport.XHR.prototype.connect.call(self);
  522. }, 10);
  523. });
  524. } else {
  525. io.Transport.XHR.prototype.connect.call(this);
  526. }
  527. };
  528. XHRPolling.prototype._get = function(){
  529. var self = this;
  530. this._xhr = this._request(+ new Date, 'GET');
  531. this._xhr.onreadystatechange = function(){
  532. var status;
  533. if (self._xhr.readyState == 4){
  534. self._xhr.onreadystatechange = empty;
  535. try { status = self._xhr.status; } catch(e){}
  536. if (status == 200){
  537. self._onData(self._xhr.responseText);
  538. self._get();
  539. } else {
  540. self._onDisconnect();
  541. }
  542. }
  543. };
  544. this._xhr.send(null);
  545. };
  546. XHRPolling.check = function(){
  547. return io.Transport.XHR.check();
  548. };
  549. XHRPolling.xdomainCheck = function(){
  550. return io.Transport.XHR.xdomainCheck();
  551. };
  552. })();
  553. /**
  554. * Socket.IO client
  555. *
  556. * @author Guillermo Rauch <guillermo@learnboost.com>
  557. * @license The MIT license.
  558. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  559. */
  560. io.JSONP = [];
  561. JSONPPolling = io.Transport['jsonp-polling'] = function(){
  562. io.Transport.XHR.apply(this, arguments);
  563. this._insertAt = document.getElementsByTagName('script')[0];
  564. this._index = io.JSONP.length;
  565. io.JSONP.push(this);
  566. };
  567. io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
  568. JSONPPolling.prototype.type = 'jsonp-polling';
  569. JSONPPolling.prototype._send = function(data){
  570. var self = this;
  571. if (!('_form' in this)){
  572. var form = document.createElement('FORM'),
  573. area = document.createElement('TEXTAREA'),
  574. id = this._iframeId = 'socket_io_iframe_' + this._index,
  575. iframe;
  576. form.style.position = 'absolute';
  577. form.style.top = '-1000px';
  578. form.style.left = '-1000px';
  579. form.target = id;
  580. form.method = 'POST';
  581. form.action = this._prepareUrl() + '/' + (+new Date) + '/' + this._index;
  582. area.name = 'data';
  583. form.appendChild(area);
  584. this._insertAt.parentNode.insertBefore(form, this._insertAt);
  585. document.body.appendChild(form);
  586. this._form = form;
  587. this._area = area;
  588. }
  589. function complete(){
  590. initIframe();
  591. self._posting = false;
  592. self._checkSend();
  593. };
  594. function initIframe(){
  595. if (self._iframe){
  596. self._form.removeChild(self._iframe);
  597. }
  598. try {
  599. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  600. iframe = document.createElement('<iframe name="'+ self._iframeId +'">');
  601. } catch(e){
  602. iframe = document.createElement('iframe');
  603. iframe.name = self._iframeId;
  604. }
  605. iframe.id = self._iframeId;
  606. self._form.appendChild(iframe);
  607. self._iframe = iframe;
  608. };
  609. initIframe();
  610. this._posting = true;
  611. this._area.value = data;
  612. try {
  613. this._form.submit();
  614. } catch(e){}
  615. if (this._iframe.attachEvent){
  616. iframe.onreadystatechange = function(){
  617. if (self._iframe.readyState == 'complete') complete();
  618. };
  619. } else {
  620. this._iframe.onload = complete;
  621. }
  622. };
  623. JSONPPolling.prototype._get = function(){
  624. var self = this,
  625. script = document.createElement('SCRIPT');
  626. if (this._script){
  627. this._script.parentNode.removeChild(this._script);
  628. this._script = null;
  629. }
  630. script.async = true;
  631. script.src = this._prepareUrl() + '/' + (+new Date) + '/' + this._index;
  632. script.onerror = function(){
  633. self._onDisconnect();
  634. };
  635. this._insertAt.parentNode.insertBefore(script, this._insertAt);
  636. this._script = script;
  637. };
  638. JSONPPolling.prototype._ = function(){
  639. this._onData.apply(this, arguments);
  640. this._get();
  641. return this;
  642. };
  643. JSONPPolling.check = function(){
  644. return true;
  645. };
  646. JSONPPolling.xdomainCheck = function(){
  647. return true;
  648. };
  649. /**
  650. * Socket.IO client
  651. *
  652. * @author Guillermo Rauch <guillermo@learnboost.com>
  653. * @license The MIT license.
  654. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
  655. */
  656. (function(){
  657. var Socket = io.Socket = function(host, options){
  658. this.host = host || document.domain;
  659. this.options = {
  660. secure: false,
  661. document: document,
  662. port: document.location.port || 80,
  663. resource: 'socket.io',
  664. transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
  665. transportOptions: {
  666. 'xhr-polling': {
  667. timeout: 25000 // based on polling duration default
  668. },
  669. 'jsonp-polling': {
  670. timeout: 25000
  671. }
  672. },
  673. connectTimeout: 5000,
  674. tryTransportsOnConnectTimeout: true,
  675. rememberTransport: true
  676. };
  677. io.util.merge(this.options, options);
  678. this.connected = false;
  679. this.connecting = false;
  680. this._events = {};
  681. this.transport = this.getTransport();
  682. if (!this.transport && 'console' in window) console.error('No transport available');
  683. };
  684. Socket.prototype.getTransport = function(override){
  685. var transports = override || this.options.transports, match;
  686. if (this.options.rememberTransport && !override){
  687. match = this.options.document.cookie.match('(?:^|;)\\s*socketio=([^;]*)');
  688. if (match){
  689. this._rememberedTransport = true;
  690. transports = [decodeURIComponent(match[1])];
  691. }
  692. }
  693. for (var i = 0, transport; transport = transports[i]; i++){
  694. if (io.Transport[transport]
  695. && io.Transport[transport].check()
  696. && (!this._isXDomain() || io.Transport[transport].xdomainCheck())){
  697. return new io.Transport[transport](this, this.options.transportOptions[transport] || {});
  698. }
  699. }
  700. return null;
  701. };
  702. Socket.prototype.connect = function(){
  703. if (this.transport && !this.connected){
  704. if (this.connecting) this.disconnect();
  705. this.connecting = true;
  706. this.transport.connect();
  707. if (this.options.connectTimeout){
  708. var self = this;
  709. this.connectTimeoutTimer = setTimeout(function(){
  710. if (!self.connected){
  711. self.disconnect();
  712. if (self.options.tryTransportsOnConnectTimeout && !self._rememberedTransport){
  713. var remainingTransports = [], transports = self.options.transports;
  714. for (var i = 0, transport; transport = transports[i]; i++){
  715. if (transport != self.transport.type) remainingTransports.push(transport);
  716. }
  717. if (remainingTransports.length){
  718. self.transport = self.getTransport(remainingTransports);
  719. self.connect();
  720. }
  721. }
  722. }
  723. }, this.options.connectTimeout);
  724. }
  725. }
  726. return this;
  727. };
  728. Socket.prototype.send = function(data){
  729. if (!this.transport || !this.transport.connected) return this._queue(data);
  730. this.transport.send(data);
  731. return this;
  732. };
  733. Socket.prototype.disconnect = function(){
  734. if (this.connectTimeoutTimer) clearTimeout(this.connectTimeoutTimer);
  735. this.transport.disconnect();
  736. return this;
  737. };
  738. Socket.prototype.on = function(name, fn){
  739. if (!(name in this._events)) this._events[name] = [];
  740. this._events[name].push(fn);
  741. return this;
  742. };
  743. Socket.prototype.emit = function(name, args){
  744. if (name in this._events){
  745. var events = this._events[name].concat();
  746. for (var i = 0, ii = events.length; i < ii; i++)
  747. events[i].apply(this, args === undefined ? [] : args);
  748. }
  749. return this;
  750. };
  751. Socket.prototype.removeEvent = function(name, fn){
  752. if (name in this._events){
  753. for (var a = 0, l = this._events[name].length; a < l; a++)
  754. if (this._events[name][a] == fn) this._events[name].splice(a, 1);
  755. }
  756. return this;
  757. };
  758. Socket.prototype._queue = function(message){
  759. if (!('_queueStack' in this)) this._queueStack = [];
  760. this._queueStack.push(message);
  761. return this;
  762. };
  763. Socket.prototype._doQueue = function(){
  764. if (!('_queueStack' in this) || !this._queueStack.length) return this;
  765. this.transport.send(this._queueStack);
  766. this._queueStack = [];
  767. return this;
  768. };
  769. Socket.prototype._isXDomain = function(){
  770. return this.host !== document.domain;
  771. };
  772. Socket.prototype._onConnect = function(){
  773. this.connected = true;
  774. this.connecting = false;
  775. this._doQueue();
  776. if (this.options.rememberTransport) this.options.document.cookie = 'socketio=' + encodeURIComponent(this.transport.type);
  777. this.emit('connect');
  778. };
  779. Socket.prototype._onMessage = function(data){
  780. this.emit('message', [data]);
  781. };
  782. Socket.prototype._onDisconnect = function(){
  783. var wasConnected = this.connected;
  784. this.connected = false;
  785. this.connecting = false;
  786. this._queueStack = [];
  787. if (wasConnected) this.emit('disconnect');
  788. };
  789. Socket.prototype.fire = Socket.prototype.emit;
  790. Socket.prototype.addListener = Socket.prototype.addEvent = Socket.prototype.addEventListener = Socket.prototype.on;
  791. })();
  792. /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
  793. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  794. */
  795. 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}}}}();
  796. /*
  797. /*
  798. Copyright 2006 Adobe Systems Incorporated
  799. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
  800. to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  801. 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:
  802. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  803. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  804. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  805. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  806. OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  807. */
  808. /*
  809. * The Bridge class, responsible for navigating AS instances
  810. */
  811. function FABridge(target,bridgeName)
  812. {
  813. this.target = target;
  814. this.remoteTypeCache = {};
  815. this.remoteInstanceCache = {};
  816. this.remoteFunctionCache = {};
  817. this.localFunctionCache = {};
  818. this.bridgeID = FABridge.nextBridgeID++;
  819. this.name = bridgeName;
  820. this.nextLocalFuncID = 0;
  821. FABridge.instances[this.name] = this;
  822. FABridge.idMap[this.bridgeID] = this;
  823. return this;
  824. }
  825. // type codes for packed values
  826. FABridge.TYPE_ASINSTANCE = 1;
  827. FABridge.TYPE_ASFUNCTION = 2;
  828. FABridge.TYPE_JSFUNCTION = 3;
  829. FABridge.TYPE_ANONYMOUS = 4;
  830. FABridge.initCallbacks = {};
  831. FABridge.userTypes = {};
  832. FABridge.addToUserTypes = function()
  833. {
  834. for (var i = 0; i < arguments.length; i++)
  835. {
  836. FABridge.userTypes[arguments[i]] = {
  837. 'typeName': arguments[i],
  838. 'enriched': false
  839. };
  840. }
  841. }
  842. FABridge.argsToArray = function(args)
  843. {
  844. var result = [];
  845. for (var i = 0; i < args.length; i++)
  846. {
  847. result[i] = args[i];
  848. }
  849. return result;
  850. }
  851. function instanceFactory(objID)
  852. {
  853. this.fb_instance_id = objID;
  854. return this;
  855. }
  856. function FABridge__invokeJSFunction(args)
  857. {
  858. var funcID = args[0];
  859. var throughArgs = args.concat();//FABridge.argsToArray(arguments);
  860. throughArgs.shift();
  861. var bridge = FABridge.extractBridgeFromID(funcID);
  862. return bridge.invokeLocalFunction(funcID, throughArgs);
  863. }
  864. FABridge.addInitializationCallback = function(bridgeName, callback)
  865. {
  866. var inst = FABridge.instances[bridgeName];
  867. if (inst != undefined)
  868. {
  869. callback.call(inst);
  870. return;
  871. }
  872. var callbackList = FABridge.initCallbacks[bridgeName];
  873. if(callbackList == null)
  874. {
  875. FABridge.initCallbacks[bridgeName] = callbackList = [];
  876. }
  877. callbackList.push(callback);
  878. }
  879. // updated for changes to SWFObject2
  880. function FABridge__bridgeInitialized(bridgeName) {
  881. var objects = document.getElementsByTagName("object");
  882. var ol = objects.length;
  883. var activeObjects = [];
  884. if (ol > 0) {
  885. for (var i = 0; i < ol; i++) {
  886. if (typeof objects[i].SetVariable != "undefined") {
  887. activeObjects[activeObjects.length] = objects[i];
  888. }
  889. }
  890. }
  891. var embeds = document.getElementsByTagName("embed");
  892. var el = embeds.length;
  893. var activeEmbeds = [];
  894. if (el > 0) {
  895. for (var j = 0; j < el; j++) {
  896. if (typeof embeds[j].SetVariable != "undefined") {
  897. activeEmbeds[activeEmbeds.length] = embeds[j];
  898. }
  899. }
  900. }
  901. var aol = activeObjects.length;
  902. var ael = activeEmbeds.length;
  903. var searchStr = "bridgeName="+ bridgeName;
  904. if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) {
  905. FABridge.attachBridge(activeObjects[0], bridgeName);
  906. }
  907. else if (ael == 1 && !aol) {
  908. FABridge.attachBridge(activeEmbeds[0], bridgeName);
  909. }
  910. else {
  911. var flash_found = false;
  912. if (aol > 1) {
  913. for (var k = 0; k < aol; k++) {
  914. var params = activeObjects[k].childNodes;
  915. for (var l = 0; l < params.length; l++) {
  916. var param = params[l];
  917. if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) {
  918. FABridge.attachBridge(activeObjects[k], bridgeName);
  919. flash_found = true;
  920. break;
  921. }
  922. }
  923. if (flash_found) {
  924. break;
  925. }
  926. }
  927. }
  928. if (!flash_found && ael > 1) {
  929. for (var m = 0; m < ael; m++) {
  930. var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;
  931. if (flashVars.indexOf(searchStr) >= 0) {
  932. FABridge.attachBridge(activeEmbeds[m], bridgeName);
  933. break;
  934. }
  935. }
  936. }
  937. }
  938. return true;
  939. }
  940. // used to track multiple bridge instances, since callbacks from AS are global across the page.
  941. FABridge.nextBridgeID = 0;
  942. FABridge.instances = {};
  943. FABridge.idMap = {};
  944. FABridge.refCount = 0;
  945. FABridge.extractBridgeFromID = function(id)
  946. {
  947. var bridgeID = (id >> 16);
  948. return FABridge.idMap[bridgeID];
  949. }
  950. FABridge.attachBridge = function(instance, bridgeName)
  951. {
  952. var newBridgeInstance = new FABridge(instance, bridgeName);
  953. FABridge[bridgeName] = newBridgeInstance;
  954. /* FABridge[bridgeName] = function() {
  955. return newBridgeInstance.root();
  956. }
  957. */
  958. var callbacks = FABridge.initCallbacks[bridgeName];
  959. if (callbacks == null)
  960. {
  961. return;
  962. }
  963. for (var i = 0; i < callbacks.length; i++)
  964. {
  965. callbacks[i].call(newBridgeInstance);
  966. }
  967. delete FABridge.initCallbacks[bridgeName]
  968. }
  969. // some methods can't be proxied. You can use the explicit get,set, and call methods if necessary.
  970. FABridge.blockedMethods =
  971. {
  972. toString: true,
  973. get: true,
  974. set: true,
  975. call: true
  976. };
  977. FABridge.prototype =
  978. {
  979. // bootstrapping
  980. root: function()
  981. {
  982. return this.deserialize(this.target.getRoot());
  983. },
  984. //clears all of the AS objects in the cache maps
  985. releaseASObjects: function()
  986. {
  987. return this.target.releaseASObjects();
  988. },
  989. //clears a specific object in AS from the type maps
  990. releaseNamedASObject: function(value)
  991. {
  992. if(typeof(value) != "object")
  993. {
  994. return false;
  995. }
  996. else
  997. {
  998. var ret = this.target.releaseNamedASObject(value.fb_instance_id);
  999. return ret;
  1000. }
  1001. },
  1002. //create a new AS Object
  1003. create: function(className)
  1004. {
  1005. return this.deserialize(this.target.create(className));
  1006. },
  1007. // utilities
  1008. makeID: function(token)
  1009. {
  1010. return (this.bridgeID << 16) + token;
  1011. },
  1012. // low level access to the flash object
  1013. //get a named property from an AS object
  1014. getPropertyFromAS: function(objRef, propName)
  1015. {
  1016. if (FABridge.refCount > 0)
  1017. {
  1018. 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.");
  1019. }
  1020. else
  1021. {
  1022. FABridge.refCount++;
  1023. retVal = this.target.getPropFromAS(objRef, propName);
  1024. retVal = this.handleError(retVal);
  1025. FABridge.refCount--;
  1026. return retVal;
  1027. }
  1028. },
  1029. //set a named property on an AS object
  1030. setPropertyInAS: function(objRef,propName, value)
  1031. {
  1032. if (FABridge.refCount > 0)
  1033. {
  1034. 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.");
  1035. }
  1036. else
  1037. {
  1038. FABridge.refCount++;
  1039. retVal = this.target.setPropInAS(objRef,propName, this.serialize(value));
  1040. retVal = this.handleError(retVal);
  1041. FABridge.refCount--;
  1042. return retVal;
  1043. }
  1044. },
  1045. //call an AS function
  1046. callASFunction: function(funcID, args)
  1047. {
  1048. if (FABridge.refCount > 0)
  1049. {
  1050. 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.");
  1051. }
  1052. else
  1053. {
  1054. FABridge.refCount++;
  1055. retVal = this.target.invokeASFunction(funcID, this.serialize(args));
  1056. retVal = this.handleError(retVal);
  1057. FABridge.refCount--;
  1058. return retVal;
  1059. }
  1060. },
  1061. //call a method on an AS object
  1062. callASMethod: function(objID, funcName, args)
  1063. {
  1064. if (FABridge.refCount > 0)
  1065. {
  1066. 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.");
  1067. }
  1068. else
  1069. {
  1070. FABridge.refCount++;
  1071. args = this.serialize(args);
  1072. retVal = this.target.invokeASMethod(objID, funcName, args);
  1073. retVal = this.handleError(retVal);
  1074. FABridge.refCount--;
  1075. return retVal;
  1076. }
  1077. },
  1078. // responders to remote calls from flash
  1079. //callback from flash that executes a local JS function
  1080. //used mostly when setting js functions as callbacks on events
  1081. invokeLocalFunction: function(funcID, args)
  1082. {
  1083. var result;
  1084. var func = this.localFunctionCache[funcID];
  1085. if(func != undefined)
  1086. {
  1087. result = this.serialize(func.apply(null, this.deserialize(args)));
  1088. }
  1089. return result;
  1090. },
  1091. // Object Types and Proxies
  1092. // accepts an object reference, returns a type object matching the obj reference.
  1093. getTypeFromName: function(objTypeName)
  1094. {
  1095. return this.remoteTypeCache[objTypeName];
  1096. },
  1097. //create an AS proxy for the given object ID and type
  1098. createProxy: function(objID, typeName)
  1099. {
  1100. var objType = this.getTypeFromName(typeName);
  1101. instanceFactory.prototype = objType;
  1102. var instance = new instanceFactory(objID);
  1103. this.remoteInstanceCache[objID] = instance;
  1104. return instance;
  1105. },
  1106. //return the proxy associated with the given object ID
  1107. getProxy: function(objID)
  1108. {
  1109. return this.remoteInstanceCache[objID];
  1110. },
  1111. // accepts a type structure, returns a constructed type
  1112. addTypeDataToCache: function(typeData)
  1113. {
  1114. var newType = new ASProxy(this, typeData.name);
  1115. var accessors = typeData.accessors;
  1116. for (var i = 0; i < accessors.length; i++)
  1117. {
  1118. this.addPropertyToType(newType, accessors[i]);
  1119. }
  1120. var methods = typeData.methods;
  1121. for (var i = 0; i < methods.length; i++)
  1122. {
  1123. if (FABridge.blockedMethods[methods[i]] == undefined)
  1124. {
  1125. this.addMethodToType(newType, methods[i]);
  1126. }
  1127. }
  1128. this.remoteTypeCache[newType.typeName] = newType;
  1129. return newType;
  1130. },
  1131. //add a property to a typename; used to define the properties that can be called on an AS proxied object
  1132. addPropertyToType: function(ty, propName)
  1133. {
  1134. var c = propName.charAt(0);
  1135. var setterName;
  1136. var getterName;
  1137. if(c >= "a" && c <= "z")
  1138. {
  1139. getterName = "get" + c.toUpperCase() + propName.substr(1);
  1140. setterName = "set" + c.toUpperCase() + propName.substr(1);
  1141. }
  1142. else
  1143. {
  1144. getterName = "get" + propName;
  1145. setterName = "set" + propName;
  1146. }
  1147. ty[setterName] = function(val)
  1148. {
  1149. this.bridge.setPropertyInAS(this.fb_instance_id, propName, val);
  1150. }
  1151. ty[getterName] = function()
  1152. {
  1153. return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
  1154. }
  1155. },
  1156. //add a method to a typename; used to define the methods that can be callefd on an AS proxied object
  1157. addMethodToType: function(ty, methodName)
  1158. {
  1159. ty[methodName] = function()
  1160. {
  1161. return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments)));
  1162. }
  1163. },
  1164. // Function Proxies
  1165. //returns the AS proxy for the specified function ID
  1166. getFunctionProxy: function(funcID)
  1167. {
  1168. var bridge = this;
  1169. if (this.remoteFunctionCache[funcID] == null)
  1170. {
  1171. this.remoteFunctionCache[funcID] = function()
  1172. {
  1173. bridge.callASFunction(funcID, FABridge.argsToArray(arguments));
  1174. }
  1175. }
  1176. return this.remoteFunctionCache[funcID];
  1177. },
  1178. //reutrns the ID of the given function; if it doesnt exist it is created and added to the local cache
  1179. getFunctionID: function(func)
  1180. {
  1181. if (func.__bridge_id__ == undefined)
  1182. {
  1183. func.__bridge_id__ = this.makeID(this.nextLocalFuncID++);
  1184. this.localFunctionCache[func.__bridge_id__] = func;
  1185. }
  1186. return func.__bridge_id__;
  1187. },
  1188. // serialization / deserialization
  1189. serialize: function(value)
  1190. {
  1191. var result = {};
  1192. var t = typeof(value);
  1193. //primitives are kept as such
  1194. if (t == "number" || t == "string" || t == "boolean" || t == null || t == undefined)
  1195. {
  1196. result = value;
  1197. }
  1198. else if (value instanceof Array)
  1199. {
  1200. //arrays are serializesd recursively
  1201. result = [];
  1202. for (var i = 0; i < value.length; i++)
  1203. {
  1204. result[i] = this.serialize(value[i]);
  1205. }
  1206. }
  1207. else if (t == "function")
  1208. {
  1209. //js functions are assigned an ID and stored in the local cache
  1210. result.type = FABridge.TYPE_JSFUNCTION;
  1211. result.value = this.getFunctionID(value);
  1212. }
  1213. else if (value instanceof ASProxy)
  1214. {
  1215. result.type = FABridge.TYPE_ASINSTANCE;
  1216. result.value = value.fb_instance_id;
  1217. }
  1218. else
  1219. {
  1220. result.type = FABridge.TYPE_ANONYMOUS;
  1221. result.value = value;
  1222. }
  1223. return result;
  1224. },
  1225. //on deserialization we always check the return for the specific error code that is used to marshall NPE's into JS errors
  1226. // the unpacking is done by returning the value on each pachet for objects/arrays
  1227. deserialize: function(packedValue)
  1228. {
  1229. var result;
  1230. var t = typeof(packedValue);
  1231. if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
  1232. {
  1233. result = this.handleError(packedValue);
  1234. }
  1235. else if (packedValue instanceof Array)
  1236. {
  1237. result = [];
  1238. for (var i = 0; i < packedValue.length; i++)
  1239. {
  1240. result[i] = this.deserialize(packedValue[i]);
  1241. }
  1242. }
  1243. else if (t == "object")
  1244. {
  1245. for(var i = 0; i < packedValue.newTypes.length; i++)
  1246. {
  1247. this.addTypeDataToCache(packedValue.newTypes[i]);
  1248. }
  1249. for (var aRefID in packedValue.newRefs)
  1250. {
  1251. this.createProxy(aRefID, packedValue.newRefs[aRefID]);
  1252. }
  1253. if (packedValue.type == FABridge.TYPE_PRIMITIVE)
  1254. {
  1255. result = packedValue.value;
  1256. }
  1257. else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
  1258. {
  1259. result = this.getFunctionProxy(packedValue.value);
  1260. }
  1261. else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
  1262. {
  1263. result = this.getProxy(packedValue.value);
  1264. }
  1265. else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
  1266. {
  1267. result = packedValue.value;
  1268. }
  1269. }
  1270. return result;
  1271. },
  1272. //increases the reference count for the given object
  1273. addRef: function(obj)
  1274. {
  1275. this.target.incRef(obj.fb_instance_id);
  1276. },
  1277. //decrease the reference count for the given object and release it if needed
  1278. release:function(obj)
  1279. {
  1280. this.target.releaseRef(obj.fb_instance_id);
  1281. },
  1282. // check the given value for the components of the hard-coded error code : __FLASHERROR
  1283. // used to marshall NPE's into flash
  1284. handleError: function(value)
  1285. {
  1286. if (typeof(value)=="string" && value.indexOf("__FLASHERROR")==0)
  1287. {
  1288. var myErrorMessage = value.split("||");
  1289. if(FABridge.refCount > 0 )
  1290. {
  1291. FABridge.refCount--;
  1292. }
  1293. throw new Error(myErrorMessage[1]);
  1294. return value;
  1295. }
  1296. else
  1297. {
  1298. return value;
  1299. }
  1300. }
  1301. };
  1302. // The root ASProxy class that facades a flash object
  1303. ASProxy = function(bridge, typeName)
  1304. {
  1305. this.bridge = bridge;
  1306. this.typeName = typeName;
  1307. return this;
  1308. };
  1309. //methods available on each ASProxy object
  1310. ASProxy.prototype =
  1311. {
  1312. get: function(propName)
  1313. {
  1314. return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
  1315. },
  1316. set: function(propName, value)
  1317. {
  1318. this.bridge.setPropertyInAS(this.fb_instance_id, propName, value);
  1319. },
  1320. call: function(funcName, args)
  1321. {
  1322. this.bridge.callASMethod(this.fb_instance_id, funcName, args);
  1323. },
  1324. addRef: function() {
  1325. this.bridge.addRef(this);
  1326. },
  1327. release: function() {
  1328. this.bridge.release(this);
  1329. }
  1330. };
  1331. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  1332. // License: New BSD License
  1333. // Reference: http://dev.w3.org/html5/websockets/
  1334. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
  1335. (function() {
  1336. if (window.WebSocket) return;
  1337. var console = window.console;
  1338. if (!console) console = {log: function(){ }, error: function(){ }};
  1339. if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
  1340. console.error("Flash Player is not installed.");
  1341. return;
  1342. }
  1343. if (location.protocol == "file:") {
  1344. console.error(
  1345. "WARNING: web-socket-js doesn't work in file:///... URL " +
  1346. "unless you set Flash Security Settings properly. " +
  1347. "Open the page via Web server i.e. http://...");
  1348. }
  1349. WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
  1350. var self = this;
  1351. self.readyState = WebSocket.CONNECTING;
  1352. self.bufferedAmount = 0;
  1353. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  1354. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  1355. setTimeout(function() {
  1356. WebSocket.__addTask(function() {
  1357. self.__createFlash(url, protocol, proxyHost, proxyPort, headers);
  1358. });
  1359. }, 1);
  1360. }
  1361. WebSocket.prototype.__createFlash = function(url, protocol, proxyHost, proxyPort, headers) {
  1362. var self = this;
  1363. self.__flash =
  1364. WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);
  1365. self.__flash.addEventListener("open", function(fe) {
  1366. try {
  1367. self.readyState = self.__flash.getReadyState();
  1368. if (self.__timer) clearInterval(self.__timer);
  1369. if (window.opera) {
  1370. // Workaround for weird behavior of Opera which sometimes drops events.
  1371. self.__timer = setInterval(function () {
  1372. self.__handleMessages();
  1373. }, 500);
  1374. }
  1375. if (self.onopen) self.onopen();
  1376. } catch (e) {
  1377. console.error(e.toString());
  1378. }
  1379. });
  1380. self.__flash.addEventListener("close", function(fe) {
  1381. try {
  1382. self.readyState = self.__flash.getReadyState();
  1383. if (self.__timer) clearInterval(self.__timer);
  1384. if (self.onclose) self.onclose();
  1385. } catch (e) {
  1386. console.error(e.toString());
  1387. }
  1388. });
  1389. self.__flash.addEventListener("message", function() {
  1390. try {
  1391. self.__handleMessages();
  1392. } catch (e) {
  1393. console.error(e.toString());
  1394. }
  1395. });
  1396. self.__flash.addEventListener("error", function(fe) {
  1397. try {
  1398. if (self.__timer) clearInterval(self.__timer);
  1399. if (self.onerror) self.onerror();
  1400. } catch (e) {
  1401. console.error(e.toString());
  1402. }
  1403. });
  1404. self.__flash.addEventListener("stateChange", function(fe) {
  1405. try {
  1406. self.readyState = self.__flash.getReadyState();
  1407. self.bufferedAmount = fe.getBufferedAmount();
  1408. } catch (e) {
  1409. console.error(e.toString());
  1410. }
  1411. });
  1412. //console.log("[WebSocket] Flash object is ready");
  1413. };
  1414. WebSocket.prototype.send = function(data) {
  1415. if (this.__flash) {
  1416. this.readyState = this.__flash.getReadyState();
  1417. }
  1418. if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
  1419. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  1420. }
  1421. // We use encodeURIComponent() here, because FABridge doesn't work if
  1422. // the argument includes some characters. We don't use escape() here
  1423. // because of this:
  1424. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  1425. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  1426. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  1427. var result = this.__flash.send(encodeURIComponent(data));
  1428. if (result < 0) { // success
  1429. return true;
  1430. } else {
  1431. this.bufferedAmount = result;
  1432. return false;
  1433. }
  1434. };
  1435. WebSocket.prototype.close = function() {
  1436. var self = this;
  1437. if (!self.__flash) return;
  1438. self.readyState = self.__flash.getReadyState();
  1439. if (self.readyState == WebSocket.CLOSED || self.readyState == WebSocket.CLOSING) return;
  1440. self.__flash.close();
  1441. // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
  1442. // which causes weird error:
  1443. // > You are trying to call recursively into the Flash Player which is not allowed.
  1444. self.readyState = WebSocket.CLOSED;
  1445. if (self.__timer) clearInterval(self.__timer);
  1446. if (self.onclose) {
  1447. // Make it asynchronous so that it looks more like an actual
  1448. // close event
  1449. setTimeout(self.onclose, 1);
  1450. }
  1451. };
  1452. /**
  1453. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1454. *
  1455. * @param {string} type
  1456. * @param {function} listener
  1457. * @param {boolean} useCapture !NB Not implemented yet
  1458. * @return void
  1459. */
  1460. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  1461. if (!('__events' in this)) {
  1462. this.__events = {};
  1463. }
  1464. if (!(type in this.__events)) {
  1465. this.__events[type] = [];
  1466. if ('function' == typeof this['on' + type]) {
  1467. this.__events[type].defaultHandler = this['on' + type];
  1468. this['on' + type] = this.__createEventHandler(this, type);
  1469. }
  1470. }
  1471. this.__events[type].push(listener);
  1472. };
  1473. /**
  1474. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1475. *
  1476. * @param {string} type
  1477. * @param {function} listener
  1478. * @param {boolean} useCapture NB! Not implemented yet
  1479. * @return void
  1480. */
  1481. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  1482. if (!('__events' in this)) {
  1483. this.__events = {};
  1484. }
  1485. if (!(type in this.__events)) return;
  1486. for (var i = this.__events.length; i > -1; --i) {
  1487. if (listener === this.__events[type][i]) {
  1488. this.__events[type].splice(i, 1);
  1489. break;
  1490. }
  1491. }
  1492. };
  1493. /**
  1494. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  1495. *
  1496. * @param {WebSocketEvent} event
  1497. * @return void
  1498. */
  1499. WebSocket.prototype.dispatchEvent = function(event) {
  1500. if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  1501. if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  1502. for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
  1503. this.__events[event.type][i](event);
  1504. if (event.cancelBubble) break;
  1505. }
  1506. if (false !== event.returnValue &&
  1507. 'function' == typeof this.__events[event.type].defaultHandler)
  1508. {
  1509. this.__events[event.type].defaultHandler(event);
  1510. }
  1511. };
  1512. WebSocket.prototype.__handleMessages = function() {
  1513. // Gets data using readSocketData() instead of getting it from event object
  1514. // of Flash event. This is to make sure to keep message order.
  1515. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  1516. var arr = this.__flash.readSocketData();
  1517. for (var i = 0; i < arr.length; i++) {
  1518. var data = decodeURIComponent(arr[i]);
  1519. try {
  1520. if (this.onmessage) {
  1521. var e;
  1522. if (window.MessageEvent) {
  1523. e = document.createEvent("MessageEvent");
  1524. e.initMessageEvent("message", false, false, data, null, null, window, null);
  1525. } else { // IE
  1526. e = {data: data};
  1527. }
  1528. this.onmessage(e);
  1529. }
  1530. } catch (e) {
  1531. console.error(e.toString());
  1532. }
  1533. }
  1534. };
  1535. /**
  1536. * @param {object} object
  1537. * @param {string} type
  1538. */
  1539. WebSocket.prototype.__createEventHandler = function(object, type) {
  1540. return function(data) {
  1541. var event = new WebSocketEvent();
  1542. event.initEvent(type, true, true);
  1543. event.target = event.currentTarget = object;
  1544. for (var key in data) {
  1545. event[key] = data[key];
  1546. }
  1547. object.dispatchEvent(event, arguments);
  1548. };
  1549. }
  1550. /**
  1551. * Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
  1552. *
  1553. * @class
  1554. * @constructor
  1555. */
  1556. function WebSocketEvent(){}
  1557. /**
  1558. *
  1559. * @type boolean
  1560. */
  1561. WebSocketEvent.prototype.cancelable = true;
  1562. /**
  1563. *
  1564. * @type boolean
  1565. */
  1566. WebSocketEvent.prototype.cancelBubble = false;
  1567. /**
  1568. *
  1569. * @return void
  1570. */
  1571. WebSocketEvent.prototype.preventDefault = function() {
  1572. if (this.cancelable) {
  1573. this.returnValue = false;
  1574. }
  1575. };
  1576. /**
  1577. *
  1578. * @return void
  1579. */
  1580. WebSocketEvent.prototype.stopPropagation = function() {
  1581. this.cancelBubble = true;
  1582. };
  1583. /**
  1584. *
  1585. * @param {string} eventTypeArg
  1586. * @param {boolean} canBubbleArg
  1587. * @param {boolean} cancelableArg
  1588. * @return void
  1589. */
  1590. WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
  1591. this.type = eventTypeArg;
  1592. this.cancelable = cancelableArg;
  1593. this.timeStamp = new Date();
  1594. };
  1595. WebSocket.CONNECTING = 0;
  1596. WebSocket.OPEN = 1;
  1597. WebSocket.CLOSING = 2;
  1598. WebSocket.CLOSED = 3;
  1599. WebSocket.__tasks = [];
  1600. WebSocket.__initialize = function() {
  1601. if (WebSocket.__swfLocation) {
  1602. // For backword compatibility.
  1603. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  1604. }
  1605. if (!window.WEB_SOCKET_SWF_LOCATION) {
  1606. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  1607. return;
  1608. }
  1609. var container = document.createElement("div");
  1610. container.id = "webSocketContainer";
  1611. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  1612. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  1613. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  1614. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  1615. // the best we can do as far as we know now.
  1616. container.style.position = "absolute";
  1617. if (WebSocket.__isFlashLite()) {
  1618. container.style.left = "0px";
  1619. container.style.top = "0px";
  1620. } else {
  1621. container.style.left = "-100px";
  1622. container.style.top = "-100px";
  1623. }
  1624. var holder = document.createElement("div");
  1625. holder.id = "webSocketFlash";
  1626. container.appendChild(holder);
  1627. document.body.appendChild(container);
  1628. // See this article for hasPriority:
  1629. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  1630. swfobject.embedSWF(
  1631. WEB_SOCKET_SWF_LOCATION, "webSocketFlash",
  1632. "1" /* width */, "1" /* height */, "9.0.0" /* SWF version */,
  1633. null, {bridgeName: "webSocket"}, {hasPriority: true, allowScriptAccess: "always"}, null,
  1634. function(e) {
  1635. if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
  1636. }
  1637. );
  1638. FABridge.addInitializationCallback("webSocket", function() {
  1639. try {
  1640. //console.log("[WebSocket] FABridge initializad");
  1641. WebSocket.__flash = FABridge.webSocket.root();
  1642. WebSocket.__flash.setCallerUrl(location.href);
  1643. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  1644. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  1645. WebSocket.__tasks[i]();
  1646. }
  1647. WebSocket.__tasks = [];
  1648. } catch (e) {
  1649. console.error("[WebSocket] " + e.toString());
  1650. }
  1651. });
  1652. };
  1653. WebSocket.__addTask = function(task) {
  1654. if (WebSocket.__flash) {
  1655. task();
  1656. } else {
  1657. WebSocket.__tasks.push(task);
  1658. }
  1659. };
  1660. WebSocket.__isFlashLite = function() {
  1661. if (!window.navigator || !window.navigator.mimeTypes) return false;
  1662. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  1663. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) return false;
  1664. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  1665. };
  1666. // called from Flash
  1667. window.webSocketLog = function(message) {
  1668. console.log(decodeURIComponent(message));
  1669. };
  1670. // called from Flash
  1671. window.webSocketError = function(message) {
  1672. console.error(decodeURIComponent(message));
  1673. };
  1674. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  1675. if (window.addEventListener) {
  1676. window.addEventListener("load", WebSocket.__initialize, false);
  1677. } else {
  1678. window.attachEvent("onload", WebSocket.__initialize);
  1679. }
  1680. }
  1681. })();