PageRenderTime 86ms CodeModel.GetById 26ms RepoModel.GetById 2ms app.codeStats 0ms

/examples/javascripts/socket.io.js

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