var basePath = "/";

$(document).ready(function () {
    $("#commandSubmit").click(consoleSubmit);
    $("#consoleForm").submit(consoleSubmit);
    initUI();
    requestPrompt();
});

function initUI() {
    $(".button").button();
}

function rPath(rId) {
    return basePath + "runtime/" + rId + "/";
}
function gPath(rId, gId) {
    return rPath(rId) + "graph/" + gId + "/";
}
function nPath(rId, gId, nId) {
    return gPath(rId, gId) + "node/" + nId + "/";
}

/*** Runtime Operations ***/

function reloadGraphList(rId) {
    $.get(
        rPath(rId) + "graph/list.html",
        function (list) {
            $("#graphList").empty().append(list);
        });
}

function removeGraph(rId, gId) {
    $.ajax(gPath(rId, gId), {
        type: "DELETE",
        success: function () { reloadGraphList(rId); }
    });
}

/*** Graph Operations ***/

function reloadNodeList(rId, gId) {
    $.get(
        gPath(rId, gId) + "node/list.html",
        function (list) {
            $("#nodeList").empty().append(list);
        });
}

function activateNode(rId, gId, nId) {
    $.post(
        nPath(rId, gId, nId) + "activate",
        function() {
            window.alert('Node was activated.');
        });
}

/*** PowerShell Console ***/

function requestPrompt() {
    $.get(basePath + 'appcontext/prompt', updatePrompt);
}

function updatePrompt(prompt) {
    $("#consolePrompt").text(prompt);
}

function consoleSubmit(event) {
    var cmd = $("#commandText").val();
    $.post( 
        basePath + 'appcontext/command',
        { 'command': cmd },
        function(text) {
            printConsole(text);
            afterConsoleSubmit();
        }
    );
    event.preventDefault();
}

function printConsole(text) {
    var con = $("#console");
    con.append(normalizeNewLine(text));
    con.append('<br/>');
    var height = $("#consoleBox")[0].scrollHeight;
    $("#consoleBox").scrollTop(height);
}

function afterConsoleSubmit()
{
    requestPrompt();
    $("#commandText").focus().select();
}

function normalizeNewLine(text) {
    return text.replace(/\r\n/g, '\n');
}
