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

/public/js/socket.io.js

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