PageRenderTime 33ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/socket.io.js

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