rocket-js 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,131 @@
1
+ Pusher.allow_reconnect = false
2
+ Pusher.log = function() {
3
+ if (window.console) console.log.apply(console, arguments)
4
+ }
5
+
6
+ WebSocket.__swfLocation = "/WebSocketMain.swf"
7
+
8
+ var testTimeout = 10000
9
+ var clientID = parseInt(Math.random() * 1000000)
10
+ var pusherAsyncTimeout = 2000;
11
+ var channelCount = 0
12
+
13
+ function nextChannel() {
14
+ return "test-channel-" + clientID + '-' + channelCount++
15
+ }
16
+
17
+ function onPusherReady(pusher, callback) {
18
+ pusher.bind("connection_established", function() {
19
+ callback(pusher, nextChannel())
20
+ })
21
+ }
22
+
23
+ function trigger(channel, event, data, socket_id) {
24
+ $.post("/trigger", {
25
+ channel: channel,
26
+ event: event,
27
+ data: data,
28
+ socket_id: socket_id
29
+ })
30
+ }
31
+
32
+ function disconnect(pusher) {
33
+ setTimeout(function() {
34
+ pusher.disconnect()
35
+ }, testTimeout)
36
+ }
37
+
38
+ function pusherTest(description, expected, callback) {
39
+ test(description, function() {
40
+ stop(testTimeout)
41
+ var pusher = new Pusher(pusherKey)
42
+ onPusherReady(pusher, callback)
43
+ disconnect(pusher)
44
+ })
45
+ }
46
+
47
+ asyncTest("should subscribe to the given channel on initialization", 1, function() {
48
+ var channel = nextChannel()
49
+ var pusher = new Pusher(pusherKey, channel)
50
+
51
+ onPusherReady(pusher, function() {
52
+ pusher.channel(channel).bind("test_event", function(data) {
53
+ same(data, { some: "data" })
54
+ start()
55
+ });
56
+
57
+ trigger(channel, "test_event", { some: "data" })
58
+ })
59
+
60
+ disconnect(pusher)
61
+ })
62
+
63
+ pusherTest("should receive events from a subscribed channel", 1, function(pusher, channel) {
64
+ pusher.subscribe(channel).bind("test_event", function(data) {
65
+ same(data, { some: "data" })
66
+ start()
67
+ });
68
+
69
+ trigger(channel, "test_event", { some: "data" })
70
+ })
71
+
72
+ pusherTest("should not trigger events for channels which we aren't subscribed to", 1, function(pusher, channel) {
73
+ var eventCalled = false
74
+
75
+ pusher.subscribe(channel).bind("test_event", function() {
76
+ eventCalled = true
77
+ });
78
+
79
+ pusher.unsubscribe(channel)
80
+
81
+ trigger(channel, "test_event", { some: "data" })
82
+
83
+ setTimeout(function() {
84
+ ok(!eventCalled)
85
+ start()
86
+ }, pusherAsyncTimeout);
87
+ })
88
+
89
+ pusherTest("should only trigger events for channels which we are subscribed to", 1, function(pusher, channel) {
90
+ var anotherChannel = nextChannel()
91
+ var eventChannels = []
92
+
93
+ pusher.subscribe(channel).bind("test_event", function() {
94
+ eventChannels.push(channel)
95
+ });
96
+ pusher.subscribe(anotherChannel).bind("test_event", function() {
97
+ eventChannels.push(anotherChannel)
98
+ });
99
+
100
+ pusher.unsubscribe(channel)
101
+
102
+ trigger(channel, "test_event", { some: "data" })
103
+ trigger(anotherChannel, "test_event", { some: "data" })
104
+
105
+ setTimeout(function() {
106
+ same(eventChannels, [anotherChannel])
107
+ start()
108
+ }, pusherAsyncTimeout);
109
+ })
110
+
111
+ pusherTest("should trigger events for all channels which we are subscribed to", 2, function(pusher, channel) {
112
+ var anotherChannel = nextChannel()
113
+ var channelEventCalled = false
114
+ var anotherChannelEventCalled = false
115
+
116
+ pusher.subscribe(channel).bind("test_event", function() {
117
+ channelEventCalled = true
118
+ });
119
+ pusher.subscribe(anotherChannel).bind("test_event", function() {
120
+ anotherChannelEventCalled = true
121
+ });
122
+
123
+ trigger(channel, "test_event", { some: "data" })
124
+ trigger(anotherChannel, "test_event", { some: "data" })
125
+
126
+ setTimeout(function() {
127
+ ok(channelEventCalled)
128
+ ok(anotherChannelEventCalled)
129
+ start()
130
+ }, pusherAsyncTimeout);
131
+ })
@@ -0,0 +1,1445 @@
1
+ /**
2
+ * Rocket JavaScript Library v0.0.1
3
+ *
4
+ * Copyright 2010, Araneo Ltd. <http://www.araneo.pl>
5
+ * Released under the MIT license.
6
+ *
7
+ * Author: Chris Kowalik <chris@nu7hat.ch>
8
+ */
9
+
10
+ /**
11
+ * This code is strongly inspired by and based on the Pusher JavaScript Library.
12
+ *
13
+ * Pusher JavaScript Library:
14
+ *
15
+ * Copyright 2010, New Bamboo <http://new-bamboo.co.uk/>
16
+ * Released under the MIT licence.
17
+ * Reference: http://pusherapp.com
18
+ *
19
+ * This library contains also code with the following licences:
20
+ *
21
+ * web_socket.js:
22
+ *
23
+ * Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
24
+ * License: New BSD License
25
+ * Reference: http://dev.w3.org/html5/websockets/
26
+ * Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
27
+ *
28
+ * swfobject.js:
29
+ *
30
+ * SWFObject v2.2 <http://code.google.com/p/swfobject/>
31
+ * is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
32
+ *
33
+ * FABridge.js:
34
+ *
35
+ * Copyright 2006 Adobe Systems Incorporated
36
+ *
37
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
38
+ * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
39
+ * 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:
40
+ *
41
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
42
+ */
43
+
44
+
45
+ /* swfobject.js */
46
+ /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
47
+ is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
48
+ */
49
+ 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}}}}();
50
+
51
+ /* FABridge.js */
52
+ /*
53
+ /*
54
+ Copyright 2006 Adobe Systems Incorporated
55
+
56
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
57
+ to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
58
+ 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:
59
+
60
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
61
+
62
+
63
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
64
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
65
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
66
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
67
+
68
+ */
69
+
70
+
71
+ /*
72
+ * The Bridge class, responsible for navigating AS instances
73
+ */
74
+ function FABridge(target,bridgeName)
75
+ {
76
+ this.target = target;
77
+ this.remoteTypeCache = {};
78
+ this.remoteInstanceCache = {};
79
+ this.remoteFunctionCache = {};
80
+ this.localFunctionCache = {};
81
+ this.bridgeID = FABridge.nextBridgeID++;
82
+ this.name = bridgeName;
83
+ this.nextLocalFuncID = 0;
84
+ FABridge.instances[this.name] = this;
85
+ FABridge.idMap[this.bridgeID] = this;
86
+
87
+ return this;
88
+ }
89
+
90
+ // type codes for packed values
91
+ FABridge.TYPE_ASINSTANCE = 1;
92
+ FABridge.TYPE_ASFUNCTION = 2;
93
+
94
+ FABridge.TYPE_JSFUNCTION = 3;
95
+ FABridge.TYPE_ANONYMOUS = 4;
96
+
97
+ FABridge.initCallbacks = {};
98
+ FABridge.userTypes = {};
99
+
100
+ FABridge.addToUserTypes = function()
101
+ {
102
+ for (var i = 0; i < arguments.length; i++)
103
+ {
104
+ FABridge.userTypes[arguments[i]] = {
105
+ 'typeName': arguments[i],
106
+ 'enriched': false
107
+ };
108
+ }
109
+ }
110
+
111
+ FABridge.argsToArray = function(args)
112
+ {
113
+ var result = [];
114
+ for (var i = 0; i < args.length; i++)
115
+ {
116
+ result[i] = args[i];
117
+ }
118
+ return result;
119
+ }
120
+
121
+ function instanceFactory(objID)
122
+ {
123
+ this.fb_instance_id = objID;
124
+ return this;
125
+ }
126
+
127
+ function FABridge__invokeJSFunction(args)
128
+ {
129
+ var funcID = args[0];
130
+ var throughArgs = args.concat();//FABridge.argsToArray(arguments);
131
+ throughArgs.shift();
132
+
133
+ var bridge = FABridge.extractBridgeFromID(funcID);
134
+ return bridge.invokeLocalFunction(funcID, throughArgs);
135
+ }
136
+
137
+ FABridge.addInitializationCallback = function(bridgeName, callback)
138
+ {
139
+ var inst = FABridge.instances[bridgeName];
140
+ if (inst != undefined)
141
+ {
142
+ callback.call(inst);
143
+ return;
144
+ }
145
+
146
+ var callbackList = FABridge.initCallbacks[bridgeName];
147
+ if(callbackList == null)
148
+ {
149
+ FABridge.initCallbacks[bridgeName] = callbackList = [];
150
+ }
151
+
152
+ callbackList.push(callback);
153
+ }
154
+
155
+ // updated for changes to SWFObject2
156
+ function FABridge__bridgeInitialized(bridgeName) {
157
+ var objects = document.getElementsByTagName("object");
158
+ var ol = objects.length;
159
+ var activeObjects = [];
160
+ if (ol > 0) {
161
+ for (var i = 0; i < ol; i++) {
162
+ if (typeof objects[i].SetVariable != "undefined") {
163
+ activeObjects[activeObjects.length] = objects[i];
164
+ }
165
+ }
166
+ }
167
+ var embeds = document.getElementsByTagName("embed");
168
+ var el = embeds.length;
169
+ var activeEmbeds = [];
170
+ if (el > 0) {
171
+ for (var j = 0; j < el; j++) {
172
+ if (typeof embeds[j].SetVariable != "undefined") {
173
+ activeEmbeds[activeEmbeds.length] = embeds[j];
174
+ }
175
+ }
176
+ }
177
+ var aol = activeObjects.length;
178
+ var ael = activeEmbeds.length;
179
+ var searchStr = "bridgeName="+ bridgeName;
180
+ if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) {
181
+ FABridge.attachBridge(activeObjects[0], bridgeName);
182
+ }
183
+ else if (ael == 1 && !aol) {
184
+ FABridge.attachBridge(activeEmbeds[0], bridgeName);
185
+ }
186
+ else {
187
+ var flash_found = false;
188
+ if (aol > 1) {
189
+ for (var k = 0; k < aol; k++) {
190
+ var params = activeObjects[k].childNodes;
191
+ for (var l = 0; l < params.length; l++) {
192
+ var param = params[l];
193
+ if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) {
194
+ FABridge.attachBridge(activeObjects[k], bridgeName);
195
+ flash_found = true;
196
+ break;
197
+ }
198
+ }
199
+ if (flash_found) {
200
+ break;
201
+ }
202
+ }
203
+ }
204
+ if (!flash_found && ael > 1) {
205
+ for (var m = 0; m < ael; m++) {
206
+ var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;
207
+ if (flashVars.indexOf(searchStr) >= 0) {
208
+ FABridge.attachBridge(activeEmbeds[m], bridgeName);
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ }
214
+ return true;
215
+ }
216
+
217
+ // used to track multiple bridge instances, since callbacks from AS are global across the page.
218
+
219
+ FABridge.nextBridgeID = 0;
220
+ FABridge.instances = {};
221
+ FABridge.idMap = {};
222
+ FABridge.refCount = 0;
223
+
224
+ FABridge.extractBridgeFromID = function(id)
225
+ {
226
+ var bridgeID = (id >> 16);
227
+ return FABridge.idMap[bridgeID];
228
+ }
229
+
230
+ FABridge.attachBridge = function(instance, bridgeName)
231
+ {
232
+ var newBridgeInstance = new FABridge(instance, bridgeName);
233
+
234
+ FABridge[bridgeName] = newBridgeInstance;
235
+
236
+ /* FABridge[bridgeName] = function() {
237
+ return newBridgeInstance.root();
238
+ }
239
+ */
240
+ var callbacks = FABridge.initCallbacks[bridgeName];
241
+ if (callbacks == null)
242
+ {
243
+ return;
244
+ }
245
+ for (var i = 0; i < callbacks.length; i++)
246
+ {
247
+ callbacks[i].call(newBridgeInstance);
248
+ }
249
+ delete FABridge.initCallbacks[bridgeName]
250
+ }
251
+
252
+ // some methods can't be proxied. You can use the explicit get,set, and call methods if necessary.
253
+
254
+ FABridge.blockedMethods =
255
+ {
256
+ toString: true,
257
+ get: true,
258
+ set: true,
259
+ call: true
260
+ };
261
+
262
+ FABridge.prototype =
263
+ {
264
+
265
+
266
+ // bootstrapping
267
+
268
+ root: function()
269
+ {
270
+ return this.deserialize(this.target.getRoot());
271
+ },
272
+ //clears all of the AS objects in the cache maps
273
+ releaseASObjects: function()
274
+ {
275
+ return this.target.releaseASObjects();
276
+ },
277
+ //clears a specific object in AS from the type maps
278
+ releaseNamedASObject: function(value)
279
+ {
280
+ if(typeof(value) != "object")
281
+ {
282
+ return false;
283
+ }
284
+ else
285
+ {
286
+ var ret = this.target.releaseNamedASObject(value.fb_instance_id);
287
+ return ret;
288
+ }
289
+ },
290
+ //create a new AS Object
291
+ create: function(className)
292
+ {
293
+ return this.deserialize(this.target.create(className));
294
+ },
295
+
296
+
297
+ // utilities
298
+
299
+ makeID: function(token)
300
+ {
301
+ return (this.bridgeID << 16) + token;
302
+ },
303
+
304
+
305
+ // low level access to the flash object
306
+
307
+ //get a named property from an AS object
308
+ getPropertyFromAS: function(objRef, propName)
309
+ {
310
+ if (FABridge.refCount > 0)
311
+ {
312
+ 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.");
313
+ }
314
+ else
315
+ {
316
+ FABridge.refCount++;
317
+ retVal = this.target.getPropFromAS(objRef, propName);
318
+ retVal = this.handleError(retVal);
319
+ FABridge.refCount--;
320
+ return retVal;
321
+ }
322
+ },
323
+ //set a named property on an AS object
324
+ setPropertyInAS: function(objRef,propName, value)
325
+ {
326
+ if (FABridge.refCount > 0)
327
+ {
328
+ 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.");
329
+ }
330
+ else
331
+ {
332
+ FABridge.refCount++;
333
+ retVal = this.target.setPropInAS(objRef,propName, this.serialize(value));
334
+ retVal = this.handleError(retVal);
335
+ FABridge.refCount--;
336
+ return retVal;
337
+ }
338
+ },
339
+
340
+ //call an AS function
341
+ callASFunction: function(funcID, args)
342
+ {
343
+ if (FABridge.refCount > 0)
344
+ {
345
+ 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.");
346
+ }
347
+ else
348
+ {
349
+ FABridge.refCount++;
350
+ retVal = this.target.invokeASFunction(funcID, this.serialize(args));
351
+ retVal = this.handleError(retVal);
352
+ FABridge.refCount--;
353
+ return retVal;
354
+ }
355
+ },
356
+ //call a method on an AS object
357
+ callASMethod: function(objID, funcName, args)
358
+ {
359
+ if (FABridge.refCount > 0)
360
+ {
361
+ 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.");
362
+ }
363
+ else
364
+ {
365
+ FABridge.refCount++;
366
+ args = this.serialize(args);
367
+ retVal = this.target.invokeASMethod(objID, funcName, args);
368
+ retVal = this.handleError(retVal);
369
+ FABridge.refCount--;
370
+ return retVal;
371
+ }
372
+ },
373
+
374
+ // responders to remote calls from flash
375
+
376
+ //callback from flash that executes a local JS function
377
+ //used mostly when setting js functions as callbacks on events
378
+ invokeLocalFunction: function(funcID, args)
379
+ {
380
+ var result;
381
+ var func = this.localFunctionCache[funcID];
382
+
383
+ if(func != undefined)
384
+ {
385
+ result = this.serialize(func.apply(null, this.deserialize(args)));
386
+ }
387
+
388
+ return result;
389
+ },
390
+
391
+ // Object Types and Proxies
392
+
393
+ // accepts an object reference, returns a type object matching the obj reference.
394
+ getTypeFromName: function(objTypeName)
395
+ {
396
+ return this.remoteTypeCache[objTypeName];
397
+ },
398
+ //create an AS proxy for the given object ID and type
399
+ createProxy: function(objID, typeName)
400
+ {
401
+ var objType = this.getTypeFromName(typeName);
402
+ instanceFactory.prototype = objType;
403
+ var instance = new instanceFactory(objID);
404
+ this.remoteInstanceCache[objID] = instance;
405
+ return instance;
406
+ },
407
+ //return the proxy associated with the given object ID
408
+ getProxy: function(objID)
409
+ {
410
+ return this.remoteInstanceCache[objID];
411
+ },
412
+
413
+ // accepts a type structure, returns a constructed type
414
+ addTypeDataToCache: function(typeData)
415
+ {
416
+ var newType = new ASProxy(this, typeData.name);
417
+ var accessors = typeData.accessors;
418
+ for (var i = 0; i < accessors.length; i++)
419
+ {
420
+ this.addPropertyToType(newType, accessors[i]);
421
+ }
422
+
423
+ var methods = typeData.methods;
424
+ for (var i = 0; i < methods.length; i++)
425
+ {
426
+ if (FABridge.blockedMethods[methods[i]] == undefined)
427
+ {
428
+ this.addMethodToType(newType, methods[i]);
429
+ }
430
+ }
431
+
432
+
433
+ this.remoteTypeCache[newType.typeName] = newType;
434
+ return newType;
435
+ },
436
+
437
+ //add a property to a typename; used to define the properties that can be called on an AS proxied object
438
+ addPropertyToType: function(ty, propName)
439
+ {
440
+ var c = propName.charAt(0);
441
+ var setterName;
442
+ var getterName;
443
+ if(c >= "a" && c <= "z")
444
+ {
445
+ getterName = "get" + c.toUpperCase() + propName.substr(1);
446
+ setterName = "set" + c.toUpperCase() + propName.substr(1);
447
+ }
448
+ else
449
+ {
450
+ getterName = "get" + propName;
451
+ setterName = "set" + propName;
452
+ }
453
+ ty[setterName] = function(val)
454
+ {
455
+ this.bridge.setPropertyInAS(this.fb_instance_id, propName, val);
456
+ }
457
+ ty[getterName] = function()
458
+ {
459
+ return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
460
+ }
461
+ },
462
+
463
+ //add a method to a typename; used to define the methods that can be callefd on an AS proxied object
464
+ addMethodToType: function(ty, methodName)
465
+ {
466
+ ty[methodName] = function()
467
+ {
468
+ return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments)));
469
+ }
470
+ },
471
+
472
+ // Function Proxies
473
+
474
+ //returns the AS proxy for the specified function ID
475
+ getFunctionProxy: function(funcID)
476
+ {
477
+ var bridge = this;
478
+ if (this.remoteFunctionCache[funcID] == null)
479
+ {
480
+ this.remoteFunctionCache[funcID] = function()
481
+ {
482
+ bridge.callASFunction(funcID, FABridge.argsToArray(arguments));
483
+ }
484
+ }
485
+ return this.remoteFunctionCache[funcID];
486
+ },
487
+
488
+ //reutrns the ID of the given function; if it doesnt exist it is created and added to the local cache
489
+ getFunctionID: function(func)
490
+ {
491
+ if (func.__bridge_id__ == undefined)
492
+ {
493
+ func.__bridge_id__ = this.makeID(this.nextLocalFuncID++);
494
+ this.localFunctionCache[func.__bridge_id__] = func;
495
+ }
496
+ return func.__bridge_id__;
497
+ },
498
+
499
+ // serialization / deserialization
500
+
501
+ serialize: function(value)
502
+ {
503
+ var result = {};
504
+
505
+ var t = typeof(value);
506
+ //primitives are kept as such
507
+ if (t == "number" || t == "string" || t == "boolean" || t == null || t == undefined)
508
+ {
509
+ result = value;
510
+ }
511
+ else if (value instanceof Array)
512
+ {
513
+ //arrays are serializesd recursively
514
+ result = [];
515
+ for (var i = 0; i < value.length; i++)
516
+ {
517
+ result[i] = this.serialize(value[i]);
518
+ }
519
+ }
520
+ else if (t == "function")
521
+ {
522
+ //js functions are assigned an ID and stored in the local cache
523
+ result.type = FABridge.TYPE_JSFUNCTION;
524
+ result.value = this.getFunctionID(value);
525
+ }
526
+ else if (value instanceof ASProxy)
527
+ {
528
+ result.type = FABridge.TYPE_ASINSTANCE;
529
+ result.value = value.fb_instance_id;
530
+ }
531
+ else
532
+ {
533
+ result.type = FABridge.TYPE_ANONYMOUS;
534
+ result.value = value;
535
+ }
536
+
537
+ return result;
538
+ },
539
+
540
+ //on deserialization we always check the return for the specific error code that is used to marshall NPE's into JS errors
541
+ // the unpacking is done by returning the value on each pachet for objects/arrays
542
+ deserialize: function(packedValue)
543
+ {
544
+
545
+ var result;
546
+
547
+ var t = typeof(packedValue);
548
+ if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
549
+ {
550
+ result = this.handleError(packedValue);
551
+ }
552
+ else if (packedValue instanceof Array)
553
+ {
554
+ result = [];
555
+ for (var i = 0; i < packedValue.length; i++)
556
+ {
557
+ result[i] = this.deserialize(packedValue[i]);
558
+ }
559
+ }
560
+ else if (t == "object")
561
+ {
562
+ for(var i = 0; i < packedValue.newTypes.length; i++)
563
+ {
564
+ this.addTypeDataToCache(packedValue.newTypes[i]);
565
+ }
566
+ for (var aRefID in packedValue.newRefs)
567
+ {
568
+ this.createProxy(aRefID, packedValue.newRefs[aRefID]);
569
+ }
570
+ if (packedValue.type == FABridge.TYPE_PRIMITIVE)
571
+ {
572
+ result = packedValue.value;
573
+ }
574
+ else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
575
+ {
576
+ result = this.getFunctionProxy(packedValue.value);
577
+ }
578
+ else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
579
+ {
580
+ result = this.getProxy(packedValue.value);
581
+ }
582
+ else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
583
+ {
584
+ result = packedValue.value;
585
+ }
586
+ }
587
+ return result;
588
+ },
589
+ //increases the reference count for the given object
590
+ addRef: function(obj)
591
+ {
592
+ this.target.incRef(obj.fb_instance_id);
593
+ },
594
+ //decrease the reference count for the given object and release it if needed
595
+ release:function(obj)
596
+ {
597
+ this.target.releaseRef(obj.fb_instance_id);
598
+ },
599
+
600
+ // check the given value for the components of the hard-coded error code : __FLASHERROR
601
+ // used to marshall NPE's into flash
602
+
603
+ handleError: function(value)
604
+ {
605
+ if (typeof(value)=="string" && value.indexOf("__FLASHERROR")==0)
606
+ {
607
+ var myErrorMessage = value.split("||");
608
+ if(FABridge.refCount > 0 )
609
+ {
610
+ FABridge.refCount--;
611
+ }
612
+ throw new Error(myErrorMessage[1]);
613
+ return value;
614
+ }
615
+ else
616
+ {
617
+ return value;
618
+ }
619
+ }
620
+ };
621
+
622
+ // The root ASProxy class that facades a flash object
623
+
624
+ ASProxy = function(bridge, typeName)
625
+ {
626
+ this.bridge = bridge;
627
+ this.typeName = typeName;
628
+ return this;
629
+ };
630
+ //methods available on each ASProxy object
631
+ ASProxy.prototype =
632
+ {
633
+ get: function(propName)
634
+ {
635
+ return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
636
+ },
637
+
638
+ set: function(propName, value)
639
+ {
640
+ this.bridge.setPropertyInAS(this.fb_instance_id, propName, value);
641
+ },
642
+
643
+ call: function(funcName, args)
644
+ {
645
+ this.bridge.callASMethod(this.fb_instance_id, funcName, args);
646
+ },
647
+
648
+ addRef: function() {
649
+ this.bridge.addRef(this);
650
+ },
651
+
652
+ release: function() {
653
+ this.bridge.release(this);
654
+ }
655
+ };
656
+
657
+
658
+ /* web_socket.js */
659
+ // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
660
+ // License: New BSD License
661
+ // Reference: http://dev.w3.org/html5/websockets/
662
+ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
663
+
664
+ (function() {
665
+
666
+ if (window.WebSocket) return;
667
+
668
+ var console = window.console;
669
+ if (!console) console = {log: function(){ }, error: function(){ }};
670
+
671
+ if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
672
+ console.error("Flash Player is not installed.");
673
+ return;
674
+ }
675
+ if (location.protocol == "file:") {
676
+ console.error(
677
+ "WARNING: web-socket-js doesn't work in file:///... URL " +
678
+ "unless you set Flash Security Settings properly. " +
679
+ "Open the page via Web server i.e. http://...");
680
+ }
681
+
682
+ WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
683
+ var self = this;
684
+ self.readyState = WebSocket.CONNECTING;
685
+ self.bufferedAmount = 0;
686
+ // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
687
+ // Otherwise, when onopen fires immediately, onopen is called before it is set.
688
+ setTimeout(function() {
689
+ WebSocket.__addTask(function() {
690
+ self.__createFlash(url, protocol, proxyHost, proxyPort, headers);
691
+ });
692
+ }, 1);
693
+ }
694
+
695
+ WebSocket.prototype.__createFlash = function(url, protocol, proxyHost, proxyPort, headers) {
696
+ var self = this;
697
+ self.__flash =
698
+ WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);
699
+
700
+ self.__flash.addEventListener("open", function(fe) {
701
+ try {
702
+ self.readyState = self.__flash.getReadyState();
703
+ if (self.__timer) clearInterval(self.__timer);
704
+ if (window.opera) {
705
+ // Workaround for weird behavior of Opera which sometimes drops events.
706
+ self.__timer = setInterval(function () {
707
+ self.__handleMessages();
708
+ }, 500);
709
+ }
710
+ if (self.onopen) self.onopen();
711
+ } catch (e) {
712
+ console.error(e.toString());
713
+ }
714
+ });
715
+
716
+ self.__flash.addEventListener("close", function(fe) {
717
+ try {
718
+ self.readyState = self.__flash.getReadyState();
719
+ if (self.__timer) clearInterval(self.__timer);
720
+ if (self.onclose) self.onclose();
721
+ } catch (e) {
722
+ console.error(e.toString());
723
+ }
724
+ });
725
+
726
+ self.__flash.addEventListener("message", function() {
727
+ try {
728
+ self.__handleMessages();
729
+ } catch (e) {
730
+ console.error(e.toString());
731
+ }
732
+ });
733
+
734
+ self.__flash.addEventListener("error", function(fe) {
735
+ try {
736
+ if (self.__timer) clearInterval(self.__timer);
737
+ if (self.onerror) self.onerror();
738
+ } catch (e) {
739
+ console.error(e.toString());
740
+ }
741
+ });
742
+
743
+ self.__flash.addEventListener("stateChange", function(fe) {
744
+ try {
745
+ self.readyState = self.__flash.getReadyState();
746
+ self.bufferedAmount = fe.getBufferedAmount();
747
+ } catch (e) {
748
+ console.error(e.toString());
749
+ }
750
+ });
751
+
752
+ //console.log("[WebSocket] Flash object is ready");
753
+ };
754
+
755
+ WebSocket.prototype.send = function(data) {
756
+ if (this.__flash) {
757
+ this.readyState = this.__flash.getReadyState();
758
+ }
759
+ if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
760
+ throw "INVALID_STATE_ERR: Web Socket connection has not been established";
761
+ }
762
+ // We use encodeURIComponent() here, because FABridge doesn't work if
763
+ // the argument includes some characters. We don't use escape() here
764
+ // because of this:
765
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
766
+ // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
767
+ // preserve all Unicode characters either e.g. "\uffff" in Firefox.
768
+ var result = this.__flash.send(encodeURIComponent(data));
769
+ if (result < 0) { // success
770
+ return true;
771
+ } else {
772
+ this.bufferedAmount = result;
773
+ return false;
774
+ }
775
+ };
776
+
777
+ WebSocket.prototype.close = function() {
778
+ var self = this;
779
+ if (!self.__flash) return;
780
+ self.readyState = self.__flash.getReadyState();
781
+ if (self.readyState == WebSocket.CLOSED || self.readyState == WebSocket.CLOSING) return;
782
+ self.__flash.close();
783
+ // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
784
+ // which causes weird error:
785
+ // > You are trying to call recursively into the Flash Player which is not allowed.
786
+ self.readyState = WebSocket.CLOSED;
787
+ if (self.__timer) clearInterval(self.__timer);
788
+ if (self.onclose) {
789
+ // Make it asynchronous so that it looks more like an actual
790
+ // close event
791
+ setTimeout(self.onclose, 1);
792
+ }
793
+ };
794
+
795
+ /**
796
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
797
+ *
798
+ * @param {string} type
799
+ * @param {function} listener
800
+ * @param {boolean} useCapture !NB Not implemented yet
801
+ * @return void
802
+ */
803
+ WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
804
+ if (!('__events' in this)) {
805
+ this.__events = {};
806
+ }
807
+ if (!(type in this.__events)) {
808
+ this.__events[type] = [];
809
+ if ('function' == typeof this['on' + type]) {
810
+ this.__events[type].defaultHandler = this['on' + type];
811
+ this['on' + type] = this.__createEventHandler(this, type);
812
+ }
813
+ }
814
+ this.__events[type].push(listener);
815
+ };
816
+
817
+ /**
818
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
819
+ *
820
+ * @param {string} type
821
+ * @param {function} listener
822
+ * @param {boolean} useCapture NB! Not implemented yet
823
+ * @return void
824
+ */
825
+ WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
826
+ if (!('__events' in this)) {
827
+ this.__events = {};
828
+ }
829
+ if (!(type in this.__events)) return;
830
+ for (var i = this.__events.length; i > -1; --i) {
831
+ if (listener === this.__events[type][i]) {
832
+ this.__events[type].splice(i, 1);
833
+ break;
834
+ }
835
+ }
836
+ };
837
+
838
+ /**
839
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
840
+ *
841
+ * @param {WebSocketEvent} event
842
+ * @return void
843
+ */
844
+ WebSocket.prototype.dispatchEvent = function(event) {
845
+ if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
846
+ if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
847
+
848
+ for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
849
+ this.__events[event.type][i](event);
850
+ if (event.cancelBubble) break;
851
+ }
852
+
853
+ if (false !== event.returnValue &&
854
+ 'function' == typeof this.__events[event.type].defaultHandler)
855
+ {
856
+ this.__events[event.type].defaultHandler(event);
857
+ }
858
+ };
859
+
860
+ WebSocket.prototype.__handleMessages = function() {
861
+ // Gets data using readSocketData() instead of getting it from event object
862
+ // of Flash event. This is to make sure to keep message order.
863
+ // It seems sometimes Flash events don't arrive in the same order as they are sent.
864
+ var arr = this.__flash.readSocketData();
865
+ for (var i = 0; i < arr.length; i++) {
866
+ var data = decodeURIComponent(arr[i]);
867
+ try {
868
+ if (this.onmessage) {
869
+ var e;
870
+ if (window.MessageEvent && !window.opera) {
871
+ e = document.createEvent("MessageEvent");
872
+ e.initMessageEvent("message", false, false, data, null, null, window, null);
873
+ } else { // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes
874
+ e = {data: data};
875
+ }
876
+ this.onmessage(e);
877
+ }
878
+ } catch (e) {
879
+ console.error(e.toString());
880
+ }
881
+ }
882
+ };
883
+
884
+ /**
885
+ * @param {object} object
886
+ * @param {string} type
887
+ */
888
+ WebSocket.prototype.__createEventHandler = function(object, type) {
889
+ return function(data) {
890
+ var event = new WebSocketEvent();
891
+ event.initEvent(type, true, true);
892
+ event.target = event.currentTarget = object;
893
+ for (var key in data) {
894
+ event[key] = data[key];
895
+ }
896
+ object.dispatchEvent(event, arguments);
897
+ };
898
+ }
899
+
900
+ /**
901
+ * Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
902
+ *
903
+ * @class
904
+ * @constructor
905
+ */
906
+ function WebSocketEvent(){}
907
+
908
+ /**
909
+ *
910
+ * @type boolean
911
+ */
912
+ WebSocketEvent.prototype.cancelable = true;
913
+
914
+ /**
915
+ *
916
+ * @type boolean
917
+ */
918
+ WebSocketEvent.prototype.cancelBubble = false;
919
+
920
+ /**
921
+ *
922
+ * @return void
923
+ */
924
+ WebSocketEvent.prototype.preventDefault = function() {
925
+ if (this.cancelable) {
926
+ this.returnValue = false;
927
+ }
928
+ };
929
+
930
+ /**
931
+ *
932
+ * @return void
933
+ */
934
+ WebSocketEvent.prototype.stopPropagation = function() {
935
+ this.cancelBubble = true;
936
+ };
937
+
938
+ /**
939
+ *
940
+ * @param {string} eventTypeArg
941
+ * @param {boolean} canBubbleArg
942
+ * @param {boolean} cancelableArg
943
+ * @return void
944
+ */
945
+ WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
946
+ this.type = eventTypeArg;
947
+ this.cancelable = cancelableArg;
948
+ this.timeStamp = new Date();
949
+ };
950
+
951
+
952
+ WebSocket.CONNECTING = 0;
953
+ WebSocket.OPEN = 1;
954
+ WebSocket.CLOSING = 2;
955
+ WebSocket.CLOSED = 3;
956
+
957
+ WebSocket.__tasks = [];
958
+
959
+ WebSocket.__initialize = function() {
960
+ if (WebSocket.__swfLocation) {
961
+ // For backword compatibility.
962
+ window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
963
+ }
964
+ if (!window.WEB_SOCKET_SWF_LOCATION) {
965
+ console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
966
+ return;
967
+ }
968
+ var container = document.createElement("div");
969
+ container.id = "webSocketContainer";
970
+ // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
971
+ // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
972
+ // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
973
+ // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
974
+ // the best we can do as far as we know now.
975
+ container.style.position = "absolute";
976
+ if (WebSocket.__isFlashLite()) {
977
+ container.style.left = "0px";
978
+ container.style.top = "0px";
979
+ } else {
980
+ container.style.left = "-100px";
981
+ container.style.top = "-100px";
982
+ }
983
+ var holder = document.createElement("div");
984
+ holder.id = "webSocketFlash";
985
+ container.appendChild(holder);
986
+ document.body.appendChild(container);
987
+ // See this article for hasPriority:
988
+ // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
989
+ swfobject.embedSWF(
990
+ WEB_SOCKET_SWF_LOCATION, "webSocketFlash",
991
+ "1" /* width */, "1" /* height */, "9.0.0" /* SWF version */,
992
+ null, {bridgeName: "webSocket"}, {hasPriority: true, allowScriptAccess: "always"}, null,
993
+ function(e) {
994
+ if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
995
+ }
996
+ );
997
+ FABridge.addInitializationCallback("webSocket", function() {
998
+ try {
999
+ //console.log("[WebSocket] FABridge initializad");
1000
+ WebSocket.__flash = FABridge.webSocket.root();
1001
+ WebSocket.__flash.setCallerUrl(location.href);
1002
+ WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
1003
+ for (var i = 0; i < WebSocket.__tasks.length; ++i) {
1004
+ WebSocket.__tasks[i]();
1005
+ }
1006
+ WebSocket.__tasks = [];
1007
+ } catch (e) {
1008
+ console.error("[WebSocket] " + e.toString());
1009
+ }
1010
+ });
1011
+ };
1012
+
1013
+ WebSocket.__addTask = function(task) {
1014
+ if (WebSocket.__flash) {
1015
+ task();
1016
+ } else {
1017
+ WebSocket.__tasks.push(task);
1018
+ }
1019
+ };
1020
+
1021
+ WebSocket.__isFlashLite = function() {
1022
+ if (!window.navigator || !window.navigator.mimeTypes) return false;
1023
+ var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
1024
+ if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) return false;
1025
+ return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
1026
+ };
1027
+
1028
+ // called from Flash
1029
+ window.webSocketLog = function(message) {
1030
+ console.log(decodeURIComponent(message));
1031
+ };
1032
+
1033
+ // called from Flash
1034
+ window.webSocketError = function(message) {
1035
+ console.error(decodeURIComponent(message));
1036
+ };
1037
+
1038
+ if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
1039
+ if (window.addEventListener) {
1040
+ window.addEventListener("load", WebSocket.__initialize, false);
1041
+ } else {
1042
+ window.attachEvent("onload", WebSocket.__initialize);
1043
+ }
1044
+ }
1045
+
1046
+ })();
1047
+
1048
+
1049
+ /* rocket.core.js */
1050
+ /**
1051
+ * Rocket base class. Examples:
1052
+ *
1053
+ * rocket = new Rocket('ws://host.com:8080', 'my-app'); // no trailing slash in url!
1054
+ * rocket = new Rocket('wss://host.com:433', 'my-secured-app');
1055
+ *
1056
+ * @class
1057
+ * @constructor
1058
+ */
1059
+ var Rocket = function(url, appID) {
1060
+ this.socketId;
1061
+ this.url = url + '/app/' + appID;
1062
+ this.appID = appID;
1063
+ this.channels = new Rocket.Channels();
1064
+ this.retryCounter = 0;
1065
+ this.isConnected = false;
1066
+ this.globalChannel = new Rocket.Channel();
1067
+ this.globalChannel.isGlobal = true
1068
+ this.connect();
1069
+
1070
+ var self = this;
1071
+
1072
+ this.globalChannel.bind('rocket:connected', function(data) {
1073
+ self.isConnected = true;
1074
+ self.retryCounter = 0;
1075
+ self.socketId = data.socket_id;
1076
+ self.subscribeAll();
1077
+ });
1078
+
1079
+ this.globalChannel.bind('rocket:error', function(data) {
1080
+ //self.log("Rocket : error : " + data.message);
1081
+ });
1082
+ };
1083
+
1084
+ Rocket.prototype = {
1085
+ /**
1086
+ * Establish connection with specified web socket server.
1087
+ *
1088
+ * @return self
1089
+ */
1090
+ connect: function() {
1091
+ Rocket.log('Rocket : connecting with ' + this.url);
1092
+ this.allowReconnect = true
1093
+ var self = this;
1094
+
1095
+ if (window["WebSocket"]) {
1096
+ this.connection = new WebSocket(this.url);
1097
+ this.connection.onmessage = function(msg) { self.onmessage(msg); };
1098
+ this.connection.onclose = function() { self.onclose(); };
1099
+ this.connection.onopen = function() { self.onopen(); };
1100
+ } else {
1101
+ Rocket.log("Rocket : can't establish connection")
1102
+ this.connection = {};
1103
+ this.onclose();
1104
+ }
1105
+ return this;
1106
+ },
1107
+
1108
+ /**
1109
+ * Close connection with web socket server and cleanup configuration.
1110
+ *
1111
+ * @return self
1112
+ */
1113
+ disconnect: function() {
1114
+ Rocket.log('Rocket : disconnecting');
1115
+ this.allowReconnect = false;
1116
+ this.isConnected = false;
1117
+ this.retryCount = 0;
1118
+ this.connection.close();
1119
+ return this;
1120
+ },
1121
+
1122
+ /**
1123
+ * Trying reconnect to socket after specified time.
1124
+ *
1125
+ * @param {integer} delay
1126
+ * @return self
1127
+ */
1128
+ reconnect: function(delay) {
1129
+ var self = this;
1130
+ setTimeout(function(){ self.connect(); }, delay);
1131
+ return this;
1132
+ },
1133
+
1134
+ /**
1135
+ * Searches for given channel and return it when exists.
1136
+ *
1137
+ * @param {string} channelName
1138
+ * @return Rocket.Channel
1139
+ */
1140
+ channel: function(channelName) {
1141
+ return this.channels.find(channelName)
1142
+ },
1143
+
1144
+ /**
1145
+ * Trigger given event by sending specified data.
1146
+ *
1147
+ * rocket.trigger('rocket:unsubscribe', { channel: 'my-channel' });
1148
+ *
1149
+ * @param {string} eventName
1150
+ * @param {Object} data
1151
+ * @return self
1152
+ */
1153
+ trigger: function(eventName, data) {
1154
+ if (this.isConnected) {
1155
+ var payload = JSON.stringify({ event: eventName, data: data });
1156
+ Rocket.log("Rocket : triggering event : " + payload);
1157
+ this.connection.send(payload);
1158
+ } else {
1159
+ Rocket.log("Rocket : not connected : can't trigger event " + eventName);
1160
+ }
1161
+ return this;
1162
+ },
1163
+
1164
+ /**
1165
+ * Subscribes specified channel and returns it.
1166
+ *
1167
+ * myChannel = rocket.subscribe('my-channel');
1168
+ * myChannel.bind('my-event', function(data) {
1169
+ * // do something with received data...
1170
+ * });
1171
+ *
1172
+ * @param {string} channelName
1173
+ * @return Rocket.Channel
1174
+ */
1175
+ subscribe: function(channelName) {
1176
+ var channel = this.channels.add(channelName);
1177
+ this.trigger('rocket:subscribe', { channel: channelName });
1178
+ return channel;
1179
+ },
1180
+
1181
+ /**
1182
+ * Unsubscribes specified channel.
1183
+ *
1184
+ * myChannel = rocket.subscribe('my-channel');
1185
+ * myChannel.bind('unsubscribe', function(data) {
1186
+ * rocket.unsubscribe('my-channel');
1187
+ * });
1188
+ *
1189
+ * @param {string} channelName
1190
+ * @return self
1191
+ */
1192
+ unsubscribe: function(channelName) {
1193
+ this.channels.remove(channelName);
1194
+ this.trigger('rocket:unsubscribe', { channel: channelName });
1195
+ return this;
1196
+ },
1197
+
1198
+ /**
1199
+ * Subscribe all registered channels. It's usualy used to subscribe all
1200
+ * registered just after open connetion (or to re-subscribe after reconnect).
1201
+ *
1202
+ * @return void
1203
+ */
1204
+ subscribeAll: function() {
1205
+ for (var channel in this.channels.all) {
1206
+ if (this.channels.all.hasOwnProperty(channel)) {
1207
+ this.subscribe(channel);
1208
+ }
1209
+ };
1210
+ },
1211
+
1212
+ /**
1213
+ * Callback invoked when conneciton is closed.
1214
+ *
1215
+ * @return void
1216
+ */
1217
+ onclose: function() {
1218
+ Rocket.log("Rocket : socket closed");
1219
+ this.globalChannel.dispatch('rocket:close', null);
1220
+ var time = Rocket.reconnectDelay;
1221
+
1222
+ if (!(this.isConnected)) {
1223
+ this.globalChannel.dispatch("rocket:disconnected", {});
1224
+
1225
+ if (Rocket.allowReconnect) {
1226
+ Rocket.log('Pusher : reconnecting in 5 seconds...');
1227
+ this.reconnect(time);
1228
+ }
1229
+ } else {
1230
+ this.globalChannel("rocket:connection_failed", {});
1231
+
1232
+ if (this.retryCounter == 0){
1233
+ time = 100;
1234
+ }
1235
+ this.retryCounter = this.retryCounter + 1
1236
+ this.reconnect(time);
1237
+ }
1238
+ this.connected = false;
1239
+ },
1240
+
1241
+ /**
1242
+ * Callback invoked when connection is established.
1243
+ *
1244
+ * @return void
1245
+ */
1246
+ onopen: function() {
1247
+ this.globalChannel.dispatch('rocket:open', null);
1248
+ },
1249
+
1250
+ /**
1251
+ * Callback invoked when message is received.
1252
+ *
1253
+ * @param {string} msg
1254
+ * @return void
1255
+ */
1256
+ onmessage: function(msg) {
1257
+ Rocket.log("Rocket : received message : " + msg.data)
1258
+ var params = JSON.parse(msg.data);
1259
+ var channel = params.channel ? this.channel(params.channel) : this.globalChannel;
1260
+ channel.dispatch(params.event, params.data);
1261
+ },
1262
+ };
1263
+
1264
+
1265
+ /* rocket.channels.js */
1266
+ /**
1267
+ * This object helps with channels management. Examples:
1268
+ *
1269
+ * channels = new Rocket.Channels();
1270
+ * channels.add('test');
1271
+ * channels.find('test');
1272
+ * channels.remove('test');
1273
+ * // ...
1274
+ *
1275
+ * @class
1276
+ * @constructor
1277
+ */
1278
+ Rocket.Channels = function() {
1279
+ this.all = {};
1280
+ };
1281
+
1282
+ Rocket.Channels.prototype = {
1283
+ /**
1284
+ * Append new channel to the list of registered.
1285
+ *
1286
+ * @param {string} channelName
1287
+ * @return Rocket.Channel
1288
+ */
1289
+ add: function(channelName) {
1290
+ existingChannel = this.find(channelName)
1291
+ if (!existingChannel) {
1292
+ return (this.all[channelName] = new Rocket.Channel());
1293
+ } else {
1294
+ return existingChannel;
1295
+ }
1296
+ },
1297
+
1298
+ /**
1299
+ * Returns channel with specified name when it exists.
1300
+ *
1301
+ * @param {string} channelName
1302
+ * @return Rocket.Channel
1303
+ */
1304
+ find: function(channelName) {
1305
+ return this.all[channelName];
1306
+ },
1307
+
1308
+ /**
1309
+ * Remove specified channel from the list.
1310
+ *
1311
+ * @param {string} channelName
1312
+ * @return void
1313
+ */
1314
+ remove: function(channelName) {
1315
+ delete this.all[channelName];
1316
+ }
1317
+ };
1318
+
1319
+ /**
1320
+ * Single channel. It keeps eg. list of callbacks for all binded events,
1321
+ * and helps with events dispatching.
1322
+ *
1323
+ * channel = new Rocket.Channel();
1324
+ * channel.bind('my-event', function(data) {
1325
+ * // do something with given data ...
1326
+ * })
1327
+ *
1328
+ * @class
1329
+ * @constructor
1330
+ */
1331
+ Rocket.Channel = function() {
1332
+ this.callbacks = {};
1333
+ this.globalCallbacks = [];
1334
+ };
1335
+
1336
+ Rocket.Channel.prototype = {
1337
+ /**
1338
+ * Assign callback to given event. More than one callback can be assigned
1339
+ * to one event, eg:
1340
+ *
1341
+ * channel.bind('my-event', function(data){ alert('first one!') });
1342
+ * channel.bind('my-event', function(data){ alert('second one!') });
1343
+ *
1344
+ * @param {string} eventName
1345
+ * @param {function} callback
1346
+ * @return self
1347
+ */
1348
+ bind: function(eventName, callback) {
1349
+ this.callbacks[eventName] = this.callbacks[eventName] || [];
1350
+ this.callbacks[eventName].push(callback);
1351
+ return this;
1352
+ },
1353
+
1354
+ /**
1355
+ * Creates global callback which will be invoked on all events just after
1356
+ * processing callbacks assigned to it.
1357
+ *
1358
+ * channel.bindAll(function(event, data){ alert(event) });
1359
+ *
1360
+ * @param {function} callback
1361
+ * @return self
1362
+ */
1363
+ bindAll: function(callback) {
1364
+ this.globalCallbacks.push(callback);
1365
+ return this;
1366
+ },
1367
+
1368
+ /**
1369
+ * Dispatch given event with passing data to all registered callbacks.
1370
+ * All global callbacks will be called here too.
1371
+ *
1372
+ * channel.dispatch('my-event', {'hello': 'world'});
1373
+ *
1374
+ * @param {string} eventName
1375
+ * @param {Object} eventData
1376
+ * @return void
1377
+ */
1378
+ dispatch: function(eventName, eventData) {
1379
+ var callbacks = this.callbacks[eventName]
1380
+ if (callbacks) {
1381
+ Rocket.log('Rocket : Executing callbacks for ' + eventName)
1382
+ for (var i = 0; i < callbacks.length; i++) {
1383
+ callbacks[i](eventData);
1384
+ }
1385
+ } else if (!this.isGlobal) {
1386
+ Rocket.log('Rocket : No callbacks for ' + eventName)
1387
+ }
1388
+ for (var i = 0; i < this.globalCallbacks.length; i++) {
1389
+ this.globalCallbacks[i](eventName, eventData);
1390
+ }
1391
+ }
1392
+ };
1393
+
1394
+
1395
+ /* rocket.defaults.js */
1396
+ // The web-socket-js default configuration.
1397
+
1398
+ // Where your WebSocketMain.swf is located?
1399
+ var WEB_SOCKET_SWF_LOCATION = 'WebSocketMain.swf';
1400
+ // Run web socket in debug mode?
1401
+ var WEB_SOCKET_DEBUG = false;
1402
+
1403
+ // Rocket defaults.
1404
+
1405
+ /**
1406
+ * How many miliseconds system will wait until next reconnect try.
1407
+ *
1408
+ * @type integer
1409
+ */
1410
+ Rocket.reconnectDelay = 5000;
1411
+
1412
+ /**
1413
+ * Allow socket reconnect?
1414
+ *
1415
+ * @type boolean
1416
+ */
1417
+ Rocket.allowReconnect = true;
1418
+
1419
+ /**
1420
+ * Default logger. You can replace it with your own, eg.
1421
+ *
1422
+ * Rocket.log = function(msg) { console.log(msg) };
1423
+ *
1424
+ * @param {string} msg
1425
+ * @return void
1426
+ */
1427
+ Rocket.log = function(msg) {
1428
+ // nothing to do...
1429
+ };
1430
+
1431
+ /**
1432
+ * Default data parser. By default received data is treated as JSON. You
1433
+ * can change this behaviour by replacing this parser.
1434
+ *
1435
+ * @param {string} data
1436
+ * @return Object or string
1437
+ */
1438
+ Rocket.parser = function(data) {
1439
+ try {
1440
+ return JSON.parse(data);
1441
+ } catch(e) {
1442
+ Pusher.log("Rocket : data attribute not valid JSON - you may wish to implement your own Rocket.parser");
1443
+ return data;
1444
+ }
1445
+ };