Prefix storage keys.
[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 = "http://yukkurigames.com";
14 var TARGET = ORIGIN + "/webcart1000/o_o.html";
15 var wc1kFrame;
16 var wc1kWindow;
17 var saveData;
18 var _this = this;
19
20 function clamp (i, hi) { return Math.max(0, Math.min(hi, +i | 0)); }
21 function force10 (i) { return clamp(i, 1023); }
22 function force16 (i) { return clamp(i, 65535); }
23 function forcebool (i) { return !!(+i || i === "true"); }
24 function forcestr (s) { return (s || "").toString().substring(0, 1023); }
25
26 var KEYS = {
27 MapX: force10, MapY: force10,
28 PlayerName: forcestr,
29 Misc0: force16, Misc1: force16, Misc2: force16, Misc3: force16,
30 Switch0: forcebool, Switch1: forcebool,
31 Switch2: forcebool, Switch3: forcebool,
32 Switch4: forcebool, Switch5: forcebool,
33 Switch6: forcebool, Switch7: forcebool
34 };
35
36 function scrub (data) {
37 if (typeof data !== "object")
38 data = {};
39 var r = {};
40 for (var k in KEYS)
41 r[k] = KEYS[k](data[k]);
42 return r;
43 }
44
45 function onMessage (event) {
46 if (event.origin !== ORIGIN)
47 return;
48 wc1kWindow = event.source;
49 _this.data = scrub(event.data);
50 }
51
52 function refresh () {
53 wc1kWindow.postMessage("refresh", ORIGIN);
54 }
55
56 function update (data) {
57 for (var k in data)
58 _this.data[k] = data[k];
59 _this.data = scrub(_this.data);
60 wc1kWindow.postMessage(data || _this.data, ORIGIN);
61 }
62
63 window.addEventListener("load", function () {
64 window.addEventListener("message", onMessage, false);
65 wc1kFrame = document.createElement('iframe');
66 wc1kFrame.style.display = "none";
67 wc1kFrame.src = TARGET;
68 document.body.appendChild(wc1kFrame);
69 }, false);
70
71 this.refresh = refresh;
72 this.update = update;
73 this.scrub = scrub;
74 }).call(window.webcart1000 = {});