summaryrefslogtreecommitdiffstats
path: root/test/uscxml/templates/mc-html.html
blob: 33eac77e3c2fca21d7bef51cb53afb5b9c7542a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
		<script type="text/javascript">
			// see http://stackoverflow.com/questions/1206937/javascript-domready
			var domLoaded = function(callback) {
				/* Internet Explorer */
				/*@cc_on
				@if (@_win32 || @_win64)
					document.write('<script id="ieScriptLoad" defer src="//:"><\/script>');
					document.getElementById('ieScriptLoad').onreadystatechange = function() {
						if (this.readyState == 'complete') {
							callback();
						}
					};
				@end @*/
				/* Mozilla, Chrome, Opera */
				if (document.addEventListener) {
					document.addEventListener('DOMContentLoaded', callback, false);
					return;
				}
				/* Safari, iCab, Konqueror */
				if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
					var DOMLoadTimer = setInterval(function () {
						if (/loaded|complete/i.test(document.readyState)) {
							callback();
							clearInterval(DOMLoadTimer);
						}
					}, 10);
					return;
				}
				/* Other web browsers */
				window.onload = callback;
			};
		
		</script>
		<script type="text/javascript">
			
			function CometSession(options) {
				/**
				 * Support for two-channel asynchronous http communication
				 */
				for (var key in options) {
				  if (options.hasOwnProperty(key)) {
				    this[key] = options[key];
				  }
				}
				var self = this;
				
				this.xhr       = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0"));
				this.cometPoll = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0"));
				
				this.createUUID = function() {
					// http://www.ietf.org/rfc/rfc4122.txt
					var s = [];
					var hexDigits = "0123456789abcdef";
					for (var i = 0; i < 36; i++) {
						s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
					}
					s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
					s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
					s[8] = s[13] = s[18] = s[23] = "-";
					var uuid = s.join("");
					return uuid;
				}
				
				this.longpoll = function() {
					self.cometPoll.onreadystatechange = function() {
						if (self.cometPoll.readyState === 4) {
							if (self.cometPoll.status !== 200) {
								self.longpoll();
								return;
							}
							self.onRcvd(self.cometPoll);
							self.longpoll();
						}
					};
					// use token until we have a context
					self.cometPoll.open("GET", self.server + (self.query ? "?" + self.query : ""));
					self.cometPoll.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
					self.cometPoll.send(null);
				};
				
				this.post = function(data) {
					self.xhr.open("POST", self.server + (self.query ? "?" + self.query : ""));
					self.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
					self.xhr.send(data);
				}
			}
		
		</script>
		<script type="text/javascript">

			function MMISession(element, imURL, params) {
				// copy all attributes passe as params
				for (var key in params) {
				  if (params.hasOwnProperty(key)) {
				    this[key] = params[key];
				  }
				}
				var self = this;
				
				// initialize base class with onData handler
				this.__proto__ = new CometSession({
					server: imURL,
					onRcvd: function(data) {
						var mmiEvent = data.responseXML.documentElement.firstChild;
						var handler;
						var replier;
						switch (mmiEvent.localName) {
							case "NewContextResponse":
								self.context = mmiEvent.getAttribute("Context");
								self.comet.query = "context=" + self.context;
								break;
							case "PrepareRequest":
								handler = self.onPrepare;
								replier = function(attrs) { sendMMIEvent("DoneNotification", attrs) };
								break;
							case "StartRequest":
								handler = self.onStart;
								replier = function(attrs) { sendMMIEvent("StartResponse", attrs) };
								break;
							case "CancelRequest":
								handler = self.onCancel;
								replier = function(attrs) { sendMMIEvent("CancelResponse", attrs) };
								break;
							case "PauseRequest":
								handler = self.onPause;
								replier = function(attrs) { sendMMIEvent("PauseResponse", attrs) };
								break;
							case "ResumeRequest":
								handler = self.onResume;
								replier = function(attrs) { sendMMIEvent("ResumeResponse", attrs) };
								break;
							case "ClearContextRequest":
								handler = self.onClearContext;
								replier = function(attrs) { sendMMIEvent("ClearContextResponse", attrs) };
								break;
							case "StatusRequest":
								handler = self.onStatus;
								replier = function(attrs) { sendMMIEvent("StatusResponse", attrs) };
								break;
							case "ExtensionNotification":
								handler = self.onExtension;
								break;
						}
						if (typeof handler === "function") {
							var rc = handler(mmiEvent);
							if (typeof replier === "function") {
								if (rc === false) {
									replier({ Status: "Failure"});
								} else if (typeof rc === "object") {
									replier(rc);
								} else {
									replier({ Status: "Success"});
								}
							}
						}
					}
				});
				this.comet = this.__proto__;

				// get element as an HTML Node
				if (typeof(element) === 'string') {
					element = document.getElementById(element);
				}
				
				// assign attributes
				this.mmiNS        = "http://www.w3.org/2008/04/mmi-arch";
				this.comet.query  = "token=" + this.createUUID();
				this.element      = element;

				this.init = function() {
					sendMMIEvent("NewContextRequest");
					self.longpoll();
				}
				
				// helper function to determine whether something is a html node
				var isNode = function(o){
				  return (
				    typeof Node === "object" ? o instanceof Node : 
				    o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
				  );
				}

				// helper function to determine whether something is a window
				var isWindow = function(o){
				  return (
				    typeof Window === "object" ? o instanceof Window : 
				    o && typeof o === "object" && typeof o.menubar === "object"
				  );
				}
				
				// serialize an object to be send
				this.send = function(attr) {
					// see also: https://raw.github.com/douglascrockford/JSON-js/master/cycle.js
					var data = attr.Data;
					// dispatch over thingy type here
					if (typeof data === "object") {
						var seen = [];
						data = JSON.stringify(attr.Data, function(key, val) {
							if (isNode(val)) {
								// return a selection of attributes
								return {
									id: val.id,
									tagName: val.tagName,
									localName: val.localName,
								};

/*
								// return everything that is atomic - this is a lot with all the HTML inside
								var nodeAttr = {};
								for (var key in val) {
									if (
										key !== "outerHTML" &&
										val.hasOwnProperty(key) && 
										typeof val[key] !== "object" && 
										typeof val[key] !== "function"
									) {
										nodeAttr[key] = val[key];
									}
								}
								return nodeAttr;
*/
							}
							if (isWindow(val)) {
								return;
							}
							if (typeof val === "object") {
								if (seen.indexOf(val) >= 0)
									return;
								seen.push(val)
							}
							return val
						});
						
					}
					attr.Data = data;
					sendMMIEvent("ExtensionNotification", attr);
				}
				
				// register event handler if not given per constructor
				if(typeof this.onStart !== "function") {
					this.onStart = function(mmiEvent) {
						var content = mmiEvent.firstChild;
						var fromStartRequest = document.importNode(content.firstChild, true);
						self.element.appendChild(fromStartRequest);
					}
				}
				if(typeof this.onStatus !== "function") {
					this.onStatus = function(mmiEvent) {
						return true;
					}
				}
				if(typeof this.onPrepare !== "function") {
					this.onPrepare = function(mmiEvent) {
						return true;
					}
				}
				if(typeof this.onCancel !== "function") {
					this.onCancel = function(mmiEvent) {
						return true;
					}
				}
				if(typeof this.onPause !== "function") {
					this.onPause = function(mmiEvent) {
						return true;
					}
				}
				if(typeof this.onResume !== "function") {
					this.onResume = function(mmiEvent) {
						return true;
					}
				}
				if(typeof this.onExtension !== "function") {
					this.onExtension = function(mmiEvent) {
						return true;
					}
				}
				if(typeof this.onClearContext !== "function") {
					this.onClearContext = function(mmiEvent) {
						return true;
					}
				}

				if(typeof this.onDone !== "function") {
					this.onDone = function(mmiEvent) {
						return true;
					}
				}

				window.onbeforeunload=function(){
					this.onDone();
					sendMMIEvent("DoneNotification", attrs);
				};
				
				var sendMMIEvent = function(type, attrs) {
					if (!attrs)
						attrs = {};
					if (!attrs["Source"]) // default for Source
						attrs["Source"] = "HTML";
					if (!attrs["Target"]) // default for Target
						attrs["Target"] = self.imURL;
					if (!attrs["RequestID"]) // default for RequestID
						attrs["RequestID"] = self.createUUID();
					var mmiDocument = '<mmi:mmi xmlns:mmi="' + self.mmiNS + '" version="1.0">' +
						'<mmi:' + type + ' ';
					if (self.context)
						mmiDocument += 'mmi:Context="' + self.context + '" ';
					for (attr in attrs) {
						if (attr === "Data")
							continue;
						if (attr === "Content")
							continue;
						mmiDocument += 'mmi:' + attr + '="' + attrs[attr] + '" ';
					}
					mmiDocument += '>';
					
					if (attrs["Data"])
						mmiDocument += '<mmi:Data>' + "\n<![CDATA[\n" + attrs["Data"] + "\n]]>\n" + '</mmi:Data>';
					if (attrs["Content"])
						mmiDocument += '<mmi:Content>' + "\n<![CDATA[\n" + attrs["Content"] + "\n]]>\n" + '</mmi:Content>';

					mmiDocument += '</mmi:' + type +'></mmi:mmi>',
					self.post(mmiDocument);
				}

			};

		</script>
		
		<script type="text/javascript">
			var mmiSession;
			domLoaded(function () {
				mmiSession = new MMISession("foo", "${im.url}", {
					onExtension : function(mmiEvent) {
						console.log(mmiEvent);
					}
				});
				mmiSession.init();
			});
		</script>

	</head>
	<body class="tundra">
		<div id="foo"></div>
	</body>
</html>