PageRenderTime 77ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/core/src/main/resources/com/glines/socketio/socket.io.js

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