
var edited = false;
var lastParseFailed = false;
var lastSubmitted = false;
function execute(scripts) {
    lastSubmitted = true;
    $("#messages").text("Please wait while the script is being submitted ... It may take a while ....")
    var url = "test/execute";
    $.ajax({
        url:url,
        type:"POST",
        data:scripts,
        contentType:false,
        processData:false,
        success:refreshResult,
        error:showError
    }).complete(function () {
            $("#submit").attr("disabled", false);
            $("#createClassLoader").attr("disabled", false);
        });
}

function refreshResult(list, status, jqXHR) {
    $("#resultText").text(list);
    $("#messages").text("Executed Successfully.");


}

//function changeLanguageResult(list, status, jqXHR) {
//
//    $("#messages").html("Script language changed to:" + $("#languages").val() );
//
//}


function refreshCreateClassLoaderResult(list, status, jqXHR) {

    var data = jQuery.parseJSON(jqXHR.responseText).data;

    if (data.length ==0) {
        $("#messages").text("No extra classpath entries are added ...");
    }  else {
        $("#messages").text(data.length +  " classpath entries found...");
        var jars = "Selected Classpath:\n";
        $.each(data, function(item) {
            jars += data[item] + '\n';
        });
        $("#resultText").text(jars);



//        var optionsValues = "";
//
//        $.each(data, function(item) {
//            optionsValues += '<option value="' + data[item] + '">' + data[item] + '</option>';
//        });
//
//        var options = $('#languages');
//        options.html(optionsValues);

    }

    setTimeout(autoFileCompile(), 5000);

}


function showError(jqXHR, status, error) {
    $("#resultText").text(jqXHR.responseText);
    $("#messages").text(jqXHR.getResponseHeader("GROOVY_SCRIPT_ERROR"));

    if (status == "timeout") {
        $("#resultText").text("timeout");
        return;
    }
    var lineNum;
    lineNum = jqXHR.getResponseHeader("GROOVY_SCRIPT_ERROR_LINE_NUMBER");

    highlightLine(lineNum - 1);
}

function highlightLine(lineNum) {
    var lines;
    var scripts = document.getElementById('scriptText');
    if (document.all) { // IE
        lines = scripts.value.split('\r\n');
    } else {
        lines = scripts.value.split('\n');
    }
    if (lineNum <= lines.length && lineNum > 0) {
        var startPos = 0;
        for (var i = 0; i < lineNum; i++) {
            startPos += lines[i].length + 1;
        }
        var endPos = startPos + lines[lineNum].length + 1;
        setSelectionRange(scripts, startPos, endPos);
    }

}

function setSelectionRange(input, selectionStart, selectionEnd) {
    var cursorPosition = $('#scriptText').prop("selectionStart");
    if (cursorPosition == selectionEnd - 1) {
        return;
    }

    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

function compile(scripts) {
    // $("#compileErrorMsg").html("Parsing ...");
    var url = "test/compile";
    $.ajax({
        url:url,
        type:"POST",
        data:scripts,
        contentType:false,
        processData:false,
        success:refreshForCompileResult,
        error:showCompileError
    }).complete(function () {
            if (edited) {
                edited = false;
                setTimeout(autoFileCompile(), 10000);
            }
        });
}

function refreshLibrary() {
     $("#messages").text("Loading current library configurations ...");
    var url = "test/libraries";
    $.ajax({
        url:url,
        type:"GET",

        contentType:false,
        processData:false,
        success:refreshLibraryResult,
        error:showCompileError
    }).complete(function () {

        });
}


function refreshForCompileResult(list, status, jqXHR) {

    if (edited) {
        edited = false;
        autoFileCompile();
    }
    $("#messages").text("Parsed Successfully...");
    lastParseFailed = false;
    lastSubmitted = false;

}


function refreshLibraryResult(list, status, jqXHR) {

    $("#messages").text("Loaded ...");
    $("#classpathText").text(list);



}




function showCompileError(jqXHR, status, error) {


    if (status == "timeout") {
        $("#resultText").text("timeout");
        return;
    }
    var lineNum;
    lineNum = jqXHR.getResponseHeader("GROOVY_SCRIPT_ERROR_LINE_NUMBER");
    $("#messages").text(jqXHR.getResponseHeader("GROOVY_SCRIPT_ERROR"));

    if (edited) {
        edited = false;
        setTimeout(autoFileCompile(), 10000);
    }
    if (lastSubmitted) {


        highlightLine(lineNum - 1);
        lastSubmitted = false;

    }
    lastParseFailed = true;

}

function clearAll() {
    $("#resultText").text("");
    $("#messages").text("");

}

function autoFileCompile() {
    var input = $("#scriptText").val();
    compile(input);

}

$(document).ready(function () {


//    setInterval(function() {compile($("#scriptText").val());}, 10000);
    $('#scriptText').change(function () {
        if (!edited) {
            edited = true;
            setTimeout(autoFileCompile(), 10000);
        }


    });

    $('#scriptText').on("keyup", function (e) {

        e = e || window.event;

        if (e.keyCode == '37' || e.keyCode == '38' || e.keyCode == '39' || e.keyCode == '40') {

        }
        else {
            setTimeout(autoFileCompile(), 0);
        }


    });


    $("#createClassLoader").live("click", function (e) {
        //disable the button until request return

        var input = $("#classpathText").val();
        if (input != "") {

            $("#createClassLoader").attr("disabled", true);
            createClassLoader(input);
        }
        return e.preventDefault();
    });


    function createClassLoader(scripts) {
        lastSubmitted = true;
        $("#messages").text("Setting up the classpath ....")
        var url = "test/createloader";
        $.ajax({
            url:url,
            type:"POST",
            headers:{
                Accept:"application/json; charset=utf-8",
                "Content-Type":"text/plain; charset=utf-8"
            },
            data:scripts,
            contentType:false,
            processData:false,
            success:refreshCreateClassLoaderResult,
            error:showError
        }).complete(function () {
                $("#submit").attr("disabled", false);
                $("#createClassLoader").attr("disabled", false);
            });
    }


//    function changeLanguage(newlanguage) {
//        lastSubmitted = true;
//        $("#messages").html("Creating Classloader ....")
//        var url = "test/changelanguage";
//        $.ajax({
//            url:url,
//            type:"POST",
//
//            data:newlanguage,
//            contentType:false,
//            processData:false,
//            success:changeLanguageResult,
//            error:showError
//        }).complete(function () {
//
//            });
//    }
//



    $("#submit").live("click", function (e) {
        //disable the button until request return

        var input = $("#scriptText").val();
        if (input != "") {
            clearAll();
            $("#submit").attr("disabled", true);
            $("#createClassLoader").attr("disabled", true);
            execute(input);
        }
        return e.preventDefault();
    });







    $("#clear").live("click", function (e) {
        $("#resultText").text("");

        $("#messages").text("");
        return e.preventDefault();
    });

    refreshLibrary();


 //   $("#createClassLoader").trigger('click');

//
//    $("#languages").change(function(){
//        changeLanguage($(this).val());
//    });



});

