var Request = {};
var nextFunctionToCall = null;
var afterCallBack = null;
Request.send = function(url, method, data, handler, acb) {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.onreadystatechange = function() {
        if (req.readyState == 4) {// only if req shows "loaded"
            if (req.status < 400) {// only if "OK"
                if(handler)
                    handler(req.responseText);
                req = null;
                if (acb) {
                    acb();
                }
                if (isIE()) runPngFix();
            } else {
                alert("There was a problem loading data :\n" + req.status + "/" + req.statusText);
            }
        }
    }
    afterCallBack = acb;
    //url = url.replace("%26", "&");
    if (method == "POST") {
        if (data != null) {
            if (url.indexOf("?") != -1) {
                url = url.substring(0, url.indexOf("?"));
            }
            req.open("POST", url, true);
            req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            req.setRequestHeader("Content-length", data.length);
        } else {
            req.open("POST", url, true);
        }
        req.setRequestHeader("Connection", "close");
        req.send("" + data);
    } else if (method == "PUT") {
        req.open("PUT", url, true);
        if (urlencoded) req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send("" + data);
    } else if (method == "DELETE") {
        req.open("DELETE", url, true);
        req.send(null);
    } else {
        req.open("GET", url, true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send(null);
    }

    return req;
}

//evaluates the value of nextFunctionToCall and sets it to null
function callNextFunction() {
    if (nextFunctionToCall != null) {
        var fcall = nextFunctionToCall;
        nextFunctionToCall = null;
        eval(fcall);
    }
}


//local deco

var doDecoQuery = false;

function doDecoDynamicCheck() {
    doDecoQuery = true;
    tsrt = new Date().getTime();
    Request.send("decoDynamicOutputCheck.jsp?t=" + tsrt, "get", null, dynamicDecoOutputCheck, null);
}


function dynamicDecoOutputCheck(response) {
    response = response.trim();
    if (doDecoQuery && response.length < 5) {
        byId("teInput").value = "processing: " + response + " done";
        setTimeout("doDecoDynamicCheck()", 1000);
    }
    else {
        byId("teInput").value = response;
    }
}

//local enco

var doEncoQuery = false;

function doEncoDynamicCheck() {
    doEncoQuery = true;
    tsrt = new Date().getTime();
    Request.send("encoDynamicOutputCheck.jsp?t=" + tsrt, "GET", null, dynamicEncoOutputCheck, null);
}

function dynamicEncoOutputCheck(response) {
    response = response.trim();
    if (doEncoQuery && response.length < 5) {
        byId("teInput").value = "processing: " + response + " done";
        setTimeout("doEncoDynamicCheck()", 1000);
    }
    else {
        byId("teInput").value = response;
    }
}


//local mora

var doMoraQuery = false;
var params = "";
function doMoraDynamicCheck(cb, paramstr) {
    doMoraQuery = true;
    if (paramstr != null) {
        params = paramstr
    }

    doMoraDynamicCheckRequest(cb)
}

function doMoraDynamicCheckRequest(cb) {
    tsrt = new Date().getTime();
    if (params == null) {
        params = "";
    }
    Request.send("moraDynamicOutputCheck.jsp?t=" + tsrt + params, "get", null, cb, null);
}

//te pro
function dynamicMoraOutputCheckForTEPro(response) {
    response = response.trim();
    if (doMoraQuery && response == ".") {
        byId("processing").innerHTML += response;
        setTimeout("doMoraDynamicCheckRequest(dynamicMoraOutputCheckForTEPro)", 1000);

    }
    else {
        byId("processing").innerHTML = response;
        //resizeArea("teInput");
    }
}

//te
function dynamicMoraOutputCheckForTE(response) {
    response = response.trim();
    if (doMoraQuery && response == ".") {
        byId("loading").innerHTML += response;
        setTimeout("doMoraDynamicCheckRequest(dynamicMoraOutputCheckForTE, 'resultcontent')", 1000);
    }
    else {
        byId("selectedText").value = response;
        byId("moraForm").submit();
    }
}

//save file content
function saveFile(filenameContainerId, contentConteinerId) {

    tsrt = new Date().getTime();
    var filename = byId(filenameContainerId).value;
    if (filename.trim() == "") {
        alert("Please insert a filename.")
        return;
    }
    if (!confirm("Saving into \"" + filename + "\". Are you sure?")) {
        return;
    }
    var content = byId(contentConteinerId).value;
    if (filename == null || filename == "") {
        alert("Please provide a name for the file.");
        return;
    }
    Request.send("saveFile.jsp", "POST", "content=" + escape(content)
            + "&filename=" + filename + "&t=" + tsrt, saveCallBack, null);

}

function saveCallBack(response) {
    response = response.trim();
    if (response != "ok") {
        alert("Failed to save the file. Special chars can be the cause.")
    }
    else {
        loadIntoContainer("fileBrowserFileList.jsp", "fileListContainer", "");
    }
}


//tranformations
var selectedSentenceCell = 0;

function loadSentence(i) {
    //returning previous selected cell's border to its normal state
    byId('s_' + selectedSentenceCell).className = "tranformSentence";

    selectedSentenceCell = i;
    tsrt = new Date().getTime();
    byId('s_' + selectedSentenceCell).className = "transformSentenceSelected";
    byId("viewFrame").src = "transformView.jsp?t=" + tsrt + "&sid=" + i;
}
function switchToView(view) {
    tsrt = new Date().getTime()
    byId("viewFrame").src = "transformView.jsp?t=" + tsrt + "&view=" + view;
}

// dynamic loading

var containerId
function loadIntoContainer(file, contId, paramStr) {

    if (contId != null && byId(contId) != null && file != null) {
        containerId = contId;
        byId(containerId).innerHTML = "loading...";
        file.replace("&amp;", "&");
        tsrt = new Date().getTime();
        Request.send(file + "?t=" + tsrt + paramStr, "get", null, loadCallBack, null);
    }
}

function loadCallBack(response) {
    if (containerId != null && byId(containerId) != null) {
        byId(containerId).innerHTML = response;
    }
}
//loading url source into input of TE
function getURLView() {
    urlStr = byId("url").value;
    if (urlStr == "") {
        alert("no url provided.");
        return;
    }
    if (urlStr.indexOf("://") == -1) {
        urlStr = "http://" + urlStr;
    }

    byId("teInput").value = "";

    byId("teFrame").src = urlStr;
}
//loading url source into input of TE
function loadURL() {

    urlStr = byId("url").value;
    if (urlStr == "") {
        alert("no url provided.");
        return;
    }
    if (urlStr.indexOf("://") == -1) {
        urlStr = "http://" + urlStr;
    }
    byId("teFrame").src = urlStr;
    byId("teInput").value = "loading..."
    tsrt = new Date().getTime();
    Request.send("utils_getURLSource.jsp?t=" + tsrt + "&url=" + escape(urlStr), "get", null, loadURLCallBack, null);
}

function getViewMode() {
    byId("teInput").style.display = "none";
    byId("teFrame").style.display = "";
}

function getEditMode() {
    byId("teInput").style.display = "";
    byId("teFrame").style.display = "none";
}

function loadURLCallBack(response) {
    byId("teInput").value = response.trim();
    callNextFunction();
}

// calling htm2uhm application for the html source
var html2uhmCallForGetURLSource = false; //to avoid loop when calling getURLSource
function html2uhm(nextFunction) {
    nextFunctionToCall = nextFunction;
    src = byId("teInput").value;
    if (src == "") {
        alert("no source provided.");
        nextFunctionToCall = null;
        return;
    }
    getEditMode();
    if (!validateHTML(src)) {

        html2uhmCallForGetURLSource = false;
        if (nextFunctionToCall != null) {
            return callNextFunction();
        }
        else {
            alert("The source is not an HTML file.");
            return;
        }
    }

    if (src.indexOf("<") != -1 && src.indexOf("{htm}") != -1) {
        return callNextFunction();
        ;
    }
    byId("teInput").value = "Converting to UHM...";
    tsrt = new Date().getTime();
    Request.send("utils_html2uhm.jsp", "POST", "t=" + tsrt + "&src=" + escape(src), html2uhmCallBack, null);
}

function html2uhmCallBack(response) {
    byId("teInput").value = response.trim();
    callNextFunction();
}

function htm2unl(nextFunction) {
    nextFunctionToCall = nextFunction;

    src = byId("teInput").value.trim();
    if (src == "") {
        alert("no data provided.");
        nextFunctionToCall = null;
        return;
    }
    else {
        getEditMode()
        if (validateUNL()) {
            callNextFunction();
        }
        else {
            tsrt = new Date().getTime();
            Request.send("utils_getUNLfromHTML.jsp", "POST", "t=" + tsrt + "&teInput=" + escape(src), html2unlCallBack, null);
        }
    }
}

function html2unlCallBack(response) {
    byId("teInput").value = response.trim();
    byId("teInput").style.display = "block"
    callNextFunction();
}

// calling content extraction application for the uhm source
function extractContent(nextFunction) {
    nextFunctionToCall = nextFunction;
    src = byId("teInput").value;
    getEditMode();
    if (src == "") {
        alert("please provide a valid UHM input.");
        nextFunctionToCall = null;
        return;
    }
    if (src.indexOf("{htm}") == -1) {
        if (nextFunctionToCall != null) {
            return callNextFunction();
        }
        else {
            alert("The source is not in UHM format.");
            return;
        }
    }

    if (src.indexOf("S[") != -1 && src.indexOf("{htm}") == -1) {
        return callNextFunction();
        ;
    }

    byId("teInput").value = "Extracting contents...";
    tsrt = new Date().getTime();
    Request.send("utils_extractContents.jsp", "POST", "t=" + tsrt + "&src=" + escape(src), extractContentCallBack, null);
}

function extractContentCallBack(response) {
    byId("teInput").value = response.trim();
    callNextFunction();
}

// splitting text into sentences 
function buildUNLDoc(nextFunction) {

    src = byId("teInput").value;
    if (src == "") {
        alert("no source provided.");
        return;
    }
    if (src.indexOf("{org}") != -1) {
        alert("the source is already a UNL Document.");
        return;
    }
    nextFunctionToCall = nextFunction;
    byId("teInput").value = "Building UNL Document...";
    tsrt = new Date().getTime();
    Request.send("utils_buildUNLDoc.jsp", "POST", "t=" + tsrt + "&src=" + escape(src), buildUNLDocCallBack, null);
}

function buildUNLDocCallBack(response) {
    byId("teInput").value = response.trim();
    callNextFunction();
}

// dstant loading parameters
var doDistantCheckQuery = true;
var currFileName = "";
var requestType = "deco"

// Sending content to server for further request to Language Server
function sendUNLDocToServer(reqtype, doEscape, layoutFN) {
    requestType = reqtype;
    src = byId("teInput").value;
    if (src == "") {
        alert("no source provided.");
        return;
    }
    src = src.trim();
    byId("teInput").value = "Preparing UNL Document...";
    var selfurl = window.location.href;
    tsrt = new Date().getTime();
    if (doEscape != null && doEscape == true) {
        src = escape(src);
    }
    var lfnStr = "";
    if (layoutFN != null) {
        lfnStr = "&lfn=" + layoutFN;
    }
    Request.send("service_unlproxy.jsp", "POST", "t=" + tsrt + "&selfURL=" + escape(selfurl) + lfnStr + "&type=" + requestType + "&teInput=" + src, doDynamicOutputCheck, null);
}

// this function receives the responce from "service_unlproxy.jsp"
// which is the relative url of the saved document. 

function doDynamicOutputCheck(response) {
    response = response.trim();
    doDistantCheckQuery = true;
    tsrt = new Date().getTime();
    currFileName = response.trim()
    if (response.indexOf("error:") != -1) {
        doDistantCheckQuery = false;
        byId("teInput").value = "language server response: " + response;
        return;
    }
    Request.send("service_unlproxy_checktask.jsp?t=" + tsrt + "&fn=" + escape(currFileName), "GET", null, dynamicOutputCheck, null);
}

function dynamicOutputCheck(response) {
    response = response.trim();
    if (doDistantCheckQuery) {
        if (response == "100%") {
            byId("teInput").value = "language server response: " + response
                    + " done, waiting for the output";
            doDistantCheckQuery = false;
            doDynamicOutputGet();

        }
        else if (response == "0%") {
            byId("teInput").value = "language server response: the processor is in use, the required operation is added to the task list. Please wait.";
            setTimeout("doDynamicOutputCheck('" + currFileName + "')", 1000);
        }
        else if (response.indexOf("error:") != -1) {
                doDistantCheckQuery = false;
                byId("teInput").value = "language server response: " + response;
            }
            else {
                byId("teInput").value = "language server response: " + response + " done";
                setTimeout("doDynamicOutputCheck('" + currFileName + "')", 1000);
            }
    }
}

var maxGetTries = 15;
var getTries = 0;
function doDynamicOutputGet() {
    tsrt = new Date().getTime();
    Request.send("service_unlproxy_gettask.jsp?t=" + tsrt
            + "&fn=" + currFileName, "get", null, dynamicOutputGet, null);
}

function dynamicOutputGet(response) {
    response = response.trim();
    if (response == "error:output file not found. please try to reload the page" && getTries < maxGetTries) {
        byId("teInput").value = "waiting for the output file to be generated."
        getTries++;
        setTimeout("doDynamicOutputGet()", 1000);
    }
    else {
        if (requestType == "x_mora") {
            byId("teInput").value = "";
            byId("teInput").style.display = "none";
            byId("moraOutTable").innerHTML = response
            intTags();
        }
        else if (requestType == "deco" && response.indexOf(".htm") >= 0) {
            var fr = byId("decohtmlframe");
            fr.style.display = "block";
            fr.src = "unl/temp/output/" + response;
            byId("teInput").style.display = "none";
        }
        else if (requestType == "mora") {
                byId("teInput").value = response;
                submitToMoraAE()
            }
            else {
                byId("teInput").value = response
            }
    }
}


// calling moraclean application for the mora nodelist
function moraClean() {
    getContent();
    src = byId("teInput").value;
    if (src == "") {
        alert("no source provided.");
        return;
    }
    else {
        src = src.trim();
    }
    src = normalateDoc(src)
    byId("teInput").value = src;
    byId("screen").value = "process";
    byId("moraaction").value = "moraclean";
    byId("teinputform").submit();
}

function checkMoraCallBack(response) {
    byId("moraOutTable").innerHTML = response.trim();
}


/* calling moracheck application for the mora nodelist
 function moraCheck() {
 getContent();
 src = byId("teInput").value;
 if(src == ""){
 alert("no source provided.");
 return;
 }
 else{
 src = src.trim();
 }
 src = normalateDoc(src)
 byId("teInput").value = src;
 byId("screen").value = "process";
 byId("moraaction").value = "moracheck";
 byId("teinputform").submit();
 }
 */


function normalateDoc(src) {
    var s = src.indexOf("[S:");
    var e = src.indexOf("[/S]");
    nSrc = "";
    while (s > -1 && e > -1 && s < e) {
        snt = src.substring(s, e + 4).trim();
        snt = normalateSnt(snt);
        src = src.substring(e + 4).trim();
        s = src.indexOf("[S:");
        e = src.indexOf("[/S]");
        nSrc += snt;
    }
    return nSrc;
}

function normalateSnt(snt) {
    var ss = snt.substring(0, snt.indexOf("]") + 1).trim();
    var org = snt.substring(snt.indexOf("{org}") + 5, snt.indexOf("{/org}")).trim();
    var seg = snt.substring(snt.indexOf("{seg}") + 5, snt.indexOf("{/seg}")).trim();
    snt = ss + "\n" + "{org}\n" + org + "\n{/org}\n{seg}\n" + normalateSeg(seg) + "{/seg}\n[/S]\n"
    return snt;
}

function normalateSeg(seg) {
    var e = seg.indexOf(";");
    var nSeg = "";
    while (e > -1) {
        entry = seg.substring(0, e + 1).trim();
        seg = seg.substring(e + 1);
        e = seg.indexOf(";");
        entry = entry.replaceAll("\n", "")
        entry = entry.replaceAll("\r", "")
        entry = entry.replaceAll("\t", "")
        entry += "\n";
        nSeg += entry;
    }
    return nSeg;
}


