Protocol-relative URL breaks origin checks, use location.protocol.
[webcart1000.git] / webcart1000.js
1 /* The person who associated a work with this deed has dedicated the
2 work to the public domain by waiving all of his or her rights to
3 the work worldwide under copyright law, including all related and
4 neighboring rights, to the extent allowed by law.
5
6 You can copy, modify, distribute and perform the work, even for
7 commercial purposes, all without asking permission.
8 */
9
10 (function () {
11 "use strict";
12
13 var ORIGIN = location.protocol + "//yukkurigames.com";
14 var TARGET = ORIGIN + "/webcart1000/o_o.html";
15 var wc1kFrame;
16 var wc1kWindow;
17 var saveData;
18 var _this = this;
19 this.data = scrub();
20
21 function clamp (i, hi) { return Math.max(0, Math.min(hi, +i | 0)); }
22 function force10 (i) { return clamp(i, 1023); }
23 function force16 (i) { return clamp(i, 65535); }
24 function forcebool (i) { return !!(+i || i === "true"); }
25 function forcestr (s) { return (s || "").toString().substring(0, 1023); }
26
27 var KEYS = {
28 MapX: force10, MapY: force10,
29 PlayerName: forcestr,
30 Misc0: force16, Misc1: force16, Misc2: force16, Misc3: force16,
31 Switch0: forcebool, Switch1: forcebool,
32 Switch2: forcebool, Switch3: forcebool,
33 Switch4: forcebool, Switch5: forcebool,
34 Switch6: forcebool, Switch7: forcebool
35 };
36
37 function scrub (data) {
38 if (typeof data !== "object")
39 data = {};
40 var r = {};
41 for (var k in KEYS)
42 r[k] = KEYS[k](data[k]);
43 return r;
44 }
45
46 function onMessage (event) {
47 if (event.origin !== ORIGIN)
48 return;
49 wc1kWindow = event.source;
50 _this.data = scrub(event.data);
51 }
52
53 function refresh () {
54 wc1kWindow.postMessage("refresh", ORIGIN);
55 }
56
57 function update (data) {
58 for (var k in data)
59 _this.data[k] = data[k];
60 _this.data = scrub(_this.data);
61 wc1kWindow.postMessage(data || _this.data, ORIGIN);
62 }
63
64 window.addEventListener("load", function () {
65 window.addEventListener("message", onMessage, false);
66 wc1kFrame = document.createElement('iframe');
67 wc1kFrame.style.display = "none";
68 wc1kFrame.src = TARGET;
69 document.body.appendChild(wc1kFrame);
70 }, false);
71
72 this.refresh = refresh;
73 this.update = update;
74 this.scrub = scrub;
75 }).call(window.webcart1000 = {});