﻿/*
Dyma'r prif ffeil Javascript ar gyfer Cysill Ar-lein. Mae'n gyfrifol yn bennaf am yrru darnau o'r 
testun i'r gweinydd er mwyn ei brawf ddarllen ac i gyflwyno canlyniadau canfod gwallau ac awgrymiadau 
mewn dull hwylus i'r defnyddiwr. 

Er bod y cod Javascript yn hollol ddibynnol ar weinydd am swyddogaethau prawf ddarllen, mae croeso 
i chi i'w defnyddio at unrhyw ddiben gan gynnwys diben masnachol. Trwyddedir y cod Javascript yn ôl 
trwydded meddalwedd tebyg i BSD.

Cynhyrchwyd y wefan yma gyda nawdd o werthiant y pecyn Cysgliad. Os hoffwch ddefnyddio'r cod Javascript 
gyda swyddogaethau Cysill ac/neu Cysgliad o fewn eich darpariaeth ar-lein chi, yna cysylltwch â'r Uned 
Technolegau Iaith drwy'r botwm 'Cysylltu â Ni' ar y wefan.

                                               ****

This is the main Javascript file for Cysill Ar-lein. It mainly sends texts to the server for proof 
reading and presents the results of any errors and suggestions back to the user. 

Although the Javascript is totally dependent on a server for its proof reading capability, you are
welcome to use this code for any purpose including commercail purposes. The code is licensed according
to a BSD-like type software license. 

This website was produced with funding from sales of the Cysgliad package. If you would like to use
the Javascript with the functionalities in Cysill and/or Cysgliad within your website offering, then 
please contact us by using the 'Contact Us' button on the website. 

                                               ****
Hawlfraint Prifysgol Bangor 2009.
Copyright Bangor University 2009.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided 
that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions 
      and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
      and the following disclaimer in the documentation and/or other materials provided with the 
      distribution.
 
    * Neither the name of the Bangor University nor the names of its contributors may be used to endorse 
      or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED 
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
                                                                                                                                                                                          
*/

// Globals
var maxTextLength = 1072;
var startLoc = 0;
var endLoc = 0;

var s_id = '';

var grammarStartLoc = 0;
var grammarEndLoc = 0;

var segmentStartLoc = 0;
var segmentEndLoc = 0;

var isSpellingMode = true;

var textintrodisplayed = true;

var proofingStatus = '';

function initialisePage()
{    
    var textarea = document.getElementById("text");
    textarea.style.color = '#AAAAAA';  
    
    checkButton = document.getElementById("btnCheck");
    checkButton.disabled = true;
    
    // register the dialog for moving
    document.documentElement.onmousemove = moveWindow;
    document.documentElement.onmouseup = stopMove;        
}

function checkText()
{
    document.getElementById("txtCompleted").style.display='none';

    var text = document.getElementById("text");

    var proceed = isTextProofingViable(text,false);

    if (proceed == true) {
        ret = org.egymraeg.cyslib.simplechecker.WebService.StartProofing(OnStartProofingComplete, OnTimeout, OnError);        
    }
    else {
        // let's chop the text.
        text.value = text.value.substring(0, maxTextLength);
    }
}

function isTextProofingViable(field,silent) {
    var c = 0;
    var strTextToMeasure = field.value;
    var strTextToMeasureArray = new Array();
    strTextToMeasureArray = strTextToMeasure.split("\n");

    var ny = findNumOfRows(strTextToMeasureArray);

    c = ny * field.cols;
        
    if (c > maxTextLength) {
        if (silent==false) {
            document.getElementById('infodialog').style.display = 'block';
        }
        
        return false;
    }
    else
        return true;
}

function confirm() {
    document.getElementById('infodialog').style.display = 'none';
    chopText();
}

function chopText() {
           
    var cutoff = 0;
    var noOfRows = 0;
    var chopped = false;
    var textarea = document.getElementById('text');
    var strTextToMeasure = textarea.value;
    var strTextToMeasureArray = new Array();
    strTextToMeasureArray = strTextToMeasure.split("\n");

    for (var i = 0; i < strTextToMeasureArray.length; i++) {
        noOfRows += findNumOfRows_String(strTextToMeasureArray[i]);
                                    
        if (noOfRows > textarea.rows-1) {
            textarea.value = textarea.value.substring(0, cutoff);
            chopped = true;
            break;
        }

        cutoff += strTextToMeasureArray[i].length;

        if (cutoff > maxTextLength) {
            textarea.value = textarea.value.substring(0, maxTextLength);
            chopped = true;
            break;
        }

    }

    if (chopped == false) {
        // chop one character off until isViable is true.
        while (true) {
            textarea.value = textarea.value.substring(0, textarea.value.length - 1);
            if (isTextProofingViable(textarea, true)) {
                break;
            }
        }
    }                    
}

function OnStartProofingComplete(arg)
{
    // do nothing
    s_id = arg;
    proofingStatus = getProofingStatus(0);
    getNextError();
}

function getSegment()
{
    var text = document.getElementById("text").value;
    
    for(var i = segmentStartLoc+1; i < text.length; i++) {
        nextchar = text.charCodeAt(i);
        if (nextchar==10 || nextchar==12 || nextchar==46) {
            segmentEndLoc = i;
            return;
        } 
    }
    
    segmentEndLoc=text.length;    
}

function getNextError()
{
    var text = document.getElementById("text").value;
    
    getSegment();
            
    checkButton = document.getElementById("btnCheck");
    loadingGif = document.getElementById("LoadingAnimation");
        
    loadingGif.style.display='block';
    checkButton.disabled=true;

    ret = org.egymraeg.cyslib.simplechecker.WebService.GetErrors(s_id,
                                                                 text.substring(segmentStartLoc, segmentEndLoc),
                                                                 proofingStatus,
                                                                 uiLanguage,
                                                                 OnComplete,
                                                                 OnTimeout,
                                                                 OnError);                                                       
}

function OnComplete(arg)
{
    loadingGif = document.getElementById("LoadingAnimation");
    loadingGif.style.display='none';
    
    var err = undefined;
    var textarea = document.getElementById("text");
    var json = '';

    try {
        json = eval('(' + arg + ')');
    }
    catch (Error) {
        alert("Wps. Trafferth JSON. Cysylltwch â'r Uned Technolegau Iaith gyda'r testun rydych chi'n gwirio");
        alert("Oops. JSON problems. Please contact the Language Technologies Unit with the text you're checking");
        cancel();
        return;
    }
        
    var errors = json.Errors;
    var inSegmentStartLoc = 0;
     
    if (errors.length > 0) {
        if (isSpellingMode == true) {
            inSegmentStartLoc = startLoc - segmentStartLoc;
        }
        else {
            inSegmentStartLoc = grammarStartLoc - segmentStartLoc;
        }
                        
        for (var i = 0; i < errors.length; i++) {
            if (errors[i].start < inSegmentStartLoc) {
                continue;
            }
            
            if (isSpellingMode == true) {
                if (errors[i].isSpelling == false) {
                    continue;
                }                
            } else {
                // spelling mode is false
                if (errors[i].isSpelling == true) {
                    continue;
                }
            }
            
            err = errors[i];
            break;
        }
        
        if (err == undefined) {
            finishChecking();
            return;
        }
            
        var badText = textarea.value.substring(segmentStartLoc+err.start, segmentStartLoc+err.start + err.length);
        
        document.getElementById("badText").innerHTML = quoteXML(badText);
        document.getElementById("message").innerHTML = quoteXML(err.message);
    
        clearSuggestions();
        
        //
        for(var i = 0; i < err.suggestions.length; i++) {
            var opt = document.createElement("option");
            opt.nodeValue = quoteXML(err.suggestions[i]);
            opt.innerHTML = quoteXML(err.suggestions[i]);
            
            document.getElementById('suggestionsselect').appendChild(opt);
        }

        if (isSpellingMode == true){
             startLoc = segmentStartLoc + err.start;
             endLoc = segmentStartLoc + err.start + err.length;
        } else {
            grammarStartLoc = segmentStartLoc + err.start;
            grammarEndLoc = segmentStartLoc + err.start + err.length;
        }

        initWindowLocation();
        document.getElementById('dialog').style.display = 'block';
        
        setSelectionRange();
        
    } else {
        finishChecking()
    }    
}

function finishChecking()
{
    var textarea = document.getElementById("text");
    var lastPosition=textarea.value.length;
    if (textarea.value.substring(lastPosition != '.')) lastPosition += 1;
    
    if (segmentEndLoc < lastPosition) {
        if (isSpellingMode == true) {
            isSpellingMode = false;
            grammarStartLoc = segmentStartLoc;
            grammarEndLoc = segmentStartLoc;
            proofingStatus = getProofingStatus(2);
            getNextError();
        } else {
            isSpellingMode = true;
            startLoc = segmentEndLoc;
            endLoc = segmentEndLoc;
            segmentStartLoc = segmentEndLoc;
            
            if (segmentEndLoc == lastPosition-1) {
                cancel();  
                document.getElementById("txtCompleted").style.display='block';
            } else {
                proofingStatus = getProofingStatus(1); 
                getNextError();
            }
        }
    } else {
        cancel();  
        document.getElementById("txtCompleted").style.display='block';              
    }
}

function setSelectionRange() 
{
    var textarea = document.getElementById("text");

    if (textarea == null)
        return;
    
    var start, end=0;
    
    if (isSpellingMode==true){
	    start=startLoc;
        end=endLoc;
    } else {
        start=grammarStartLoc;
        end=grammarEndLoc;
    }

    if (navigator.userAgent.indexOf("MSIE") != -1) {
        //IE
        var range = textarea.createTextRange();
        range.collapse(true);

        range.moveStart('character', parseInt(start));
        range.moveEnd('character', parseInt(end - start));

        range.select();
    } else {
        textarea.selectionStart = start;
        textarea.selectionEnd = end;

        textarea.focus();
    }
}

function clearSelectionRange() 
{
    var textarea = document.getElementById("text");
    var text = textarea.value;

    textarea.value = "";
    textarea.value = text;       
}

function clearSuggestions()
{
    var suggestions_selection = document.getElementById('suggestionsselect');
    
    while(suggestions_selection.hasChildNodes()) {
        suggestions_selection.removeChild(suggestions_selection.lastChild);
    }
}

function acceptSuggestion() 
{       
    var textarea = document.getElementById("text");
    
    var selectedIndex = document.getElementById('suggestionsselect').selectedIndex;
    var selectedSuggestion = document.getElementById('suggestionsselect').options[selectedIndex].text;
    
    if (isSpellingMode==true){
	    start=startLoc;
        end=endLoc;
    } else {
        start=grammarStartLoc;
        end=grammarEndLoc;
    }
    
    newText = textarea.value.slice(0, start);
    newText += selectedSuggestion;
    newText += textarea.value.slice(end);
    textarea.value = newText;

    hideDialog();
    proofingStatus = getProofingStatus(3);    
    getNextError();
}

function cancel() 
{
    if (textintrodisplayed == true) {
        var textarea = document.getElementById("text");
        textarea.value = "";
        textintrodisplayed = false;  
        textarea.style.color = '#000000';  
    } else {
        hideDialog();

        startLoc = endLoc = grammarStartLoc = grammarEndLoc = segmentStartLoc = segmentEndLoc = 0;

        checkButton = document.getElementById("btnCheck");
        checkButton.disabled = false;
    }
}

function ignore() 
{   
    if (isSpellingMode==true){
	    startLoc += 1;
        endLoc = -1;
    } else {
        grammarStartLoc+= 1;
        grammarEndLoc = -1
    }
    
    hideDialog();
    proofingStatus = getProofingStatus(4);
    getNextError(); 
}

function hideDialog() 
{
    document.getElementById('dialog').style.display = 'none';    
    
    document.getElementById('badText').innerHTML = '';
    document.getElementById('message').innerHTML = '';
    
    clearSuggestions();
       
}

function quoteXML(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function getProofingStatus(action) { 
    if (isSpellingMode == true) {
        return '1' + action;
    } else {
        return '2' + action;
    }    
}

function OnTimeout(arg) {
    loadingGif = document.getElementById("LoadingAnimation");
    loadingGif.style.display='none';

    alert('Timeout :' + arg);
}

function OnError(arg)
{
    loadingGif = document.getElementById("LoadingAnimation");
    loadingGif.style.display='none';

    alert('Error :' + arg);
}
