var page;
var initialized = false;

[].slice.call(window.top.document.getElementsByTagName("script")).forEach(function(tag) {
    tag.src.match(/\/jquery-/g) && (function(src) {
        var script = document.createElement("script");
        script.src = src;
        script.onload = function() {
            initialized || (initialized = true, Microsoft.Dynamics.NAV.InvokeExtensibilityMethod("ControlReady", []));
        };
        document.head.appendChild(script);
    })(tag.src);
});

function MethodCall(request) {
    switch (request.method) {
        case "sendScript":
            $ && $(document.body).append("<script" + (request.id && (" id=\"" + request.id + "\"")) + ">" + request.script + "</script>");
            break;
        case "sendStyle":
            $ && $(document.body).append("<style type=\"text/css\">" + request.style + "</style>");
            break;
        case "sendHtml":
            $("#controlAddIn").empty().append(request.html);
            break;
    }
};

// Navigating away behavior
(function () {
    var unloaded = false;
    function unload() {
        unloaded || (unloaded = true, Microsoft.Dynamics.NAV.InvokeExtensibilityMethod("CloseRequested", []));
    };

    window.top.onbeforeunload = unload;
    window.onbeforeunload = unload;
})();
