window.addEventListener("DOMContentLoaded", function() {
    function encodeData(val) {
        return encodeURIComponent(val.replace(/\r\n|\r|\n/g, "\r\n"));
    }
    var body = document.body;
    body.removeChild(body.getElementsByTagName("p")[0]);
    var fresh = body.appendChild(document.createElement("a"));
    fresh.appendChild(document.createTextNode("New"));
    fresh.href = "jsuri.html";
    var raw = body.appendChild(document.createElement("textarea"));
    raw.value = "(function() {\n    code goes here\n})();";
    raw.focus();
    var loc = window.location.href;
    var q = loc.indexOf("?source=");
    if (q != -1) {
        raw.value = decodeURIComponent(loc.substr(q + 8));
    }
    var bm = document.createElement("input");
    bm.type = "text";
    bm.readOnly = true;
    bm.addEventListener("click", function(e) {
        e.target.select();
    }, false);
    bm.value = "javascript:";
    body.appendChild(bm);
    var perm = body.appendChild(document.createElement("a"));
    perm.appendChild(document.createTextNode("Permalink"))
    function update() {
        var enc = encodeData(raw.value); 
        bm.value =  "javascript:" + enc ;
        if (enc == "") {
            perm.href = "jsuri.html";
        } else {
            perm.href = "jsuri.html?source=" + enc
        }
    }
    update();
    raw.addEventListener("input", update, false);
}, false);
