client/js/save-once.js
changeset 52 e0f6f3c31150
child 67 d341117f9370
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/js/save-once.js	Thu Jan 31 18:53:08 2013 +0100
@@ -0,0 +1,75 @@
+/* Saves the Full JSON once */
+
+Rkns.jsonIO = function(_renkan, _opts) {
+    var _proj = _renkan.project,
+        _saveWarn = false,
+        _onLeave = function() {
+            return "Project not saved";
+        };
+    if (typeof _opts.http_method == "undefined") {
+        _opts.http_method = 'POST';
+    }
+    var _load = function() {
+        var getdata = {},
+            rx = /id=([^&#?=]+)/,
+            matches = document.location.hash.match(rx);
+        if (matches) {
+            getdata.id = matches[1];
+        }
+        Rkns.$.ajax({
+            url: _opts.url,
+            data: getdata,
+            success: function(_data) {
+                _proj.set(_data);
+                _renkan.renderer.autoScale();
+            }
+        });
+    }
+    var _save = function() {
+        _proj.set("saved_at", new Date());
+        var _data = _proj.toJSON();
+        Rkns.$.ajax({
+            type: _opts.http_method,
+            url: _opts.url,
+            contentType: "application/json",
+            data: JSON.stringify(_data),
+            success: function(data, textStatus, jqXHR) {
+                $(window).off("beforeunload", _onLeave);
+                _saveWarn = false;
+                document.location.hash = "#id=" + data.id;
+                $(".Rk-Notifications").text("Saved as "+document.location.href).fadeIn().delay(2000).fadeOut();
+            }
+        });
+    }
+    var _checkLeave = function() {
+        var title = _proj.get("title");
+        if (title && _proj.get("nodes").length) {
+            $(".Rk-Save-Button").removeClass("disabled");
+        } else {
+            $(".Rk-Save-Button").addClass("disabled");
+        }
+        if (title) {
+            $(".Rk-PadTitle").css("border-color","#333333");
+        }
+        if (!_saveWarn) {
+            _saveWarn = true;
+            $(window).on("beforeunload", _onLeave);
+        }
+    }
+    _load();
+    _proj.on("add:nodes add:edges add:users change", function(_model) {
+        _model.on("change remove", function(_model) {
+            _checkLeave();
+        });
+        _checkLeave();
+    });
+    $(".Rk-Save-Button").click(function() {
+        if ($(this).hasClass("disabled")) {
+            if (!_proj.get("title")) {
+                $(".Rk-PadTitle").css("border-color","#ff0000");
+            }
+        } else {
+            _save();
+        }
+    });
+}