function startTranslate() {
    // hide results if there are any
    document.getElementById('errorMsg').style.display = 'none';  
    document.getElementById('statusMsg').style.display = 'none';  
    document.getElementById('results').style.display = 'none';  
    
    // check for valid input
    if (!checkForm()) {
        return;
    }
  
    // perform some AJAX magic
    displayStatusMsg('Performing a dictionary search...');
    dictLookup(
      document.searchEntryForm.searchEntryEdit.value, 
      getRadioValue(document.searchEntryForm.dictSelectRadioGroup), 
      getRadioValue(document.searchEntryForm.searchMethodGroup)
     );
}

function checkForm() {
    // first, check if there is a search word
    if (document.searchEntryForm.searchEntryEdit.value == null || document.searchEntryForm.searchEntryEdit.value=="") {
        displayErrorMsg('Please enter a search word!');
        return false;
    }
    
    // check for search words that are too short
    // temporarily set to 3 chars, because of a  botnet which probably consumes lot of performance
    if (document.searchEntryForm.searchEntryEdit.value.length < 3) {
        displayErrorMsg('Please enter a search word of at least three characters!');
        return false;
    }
    
    return true;
}


function dictLookup(searchWord, dictID, srcTypeID) {
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        displayErrorMsg('Unfortunately your webbrowser does not support asynchronous data exchange, therefore you cannot use the online dictionary.');
        return;
    }     

    var params = "searchWord=" + searchWord.replace("", "'") + "&dictID=" + dictID + "&srcTypeID=" + srcTypeID;
    
    xmlHttp.open("POST", "inc/dictionaryLookup.php", true);
    xmlHttp.onreadystatechange = verifyLookup;
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");    
    xmlHttp.setRequestHeader("Content-length", params.length);    
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);

    timeOut = setTimeout("displayErrorMsg('A timeout occured: the server did not respond in time.')", 6000);
}   

function verifyLookup() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        clearTimeout(timeOut);

        switch (xmlHttp.responseText) {
            case "-1":
                displayStatusMsg('For some unknown reason the server did not receive your search word correctly. (-1)');
                break;
            case "-2":
                displayStatusMsg('For some unknown reason the server did not receive your language selection correctly. (-2)');
                break;
            case "-3":
                displayStatusMsg('For some unknown reason the server did not receive your search type selection correctly. (-3)');
                break;
            case "-4":
                displayStatusMsg('For some unknown reason the server could not determine the results. (-4)');
                break;
            case "-5":
                displayStatusMsg('For some unknown reason the search failed. (-5)');
                break;
            case "-6":
                displayStatusMsg('For some unknown reason the search failed. (-6)');
                break;
            case "-7":
                displayStatusMsg('For some unknown reason the search failed. (-7)');
                break;
            case "-8":
                displayStatusMsg('For some unknown reason the search failed. (-8)');
                break;
            case "-9":
                displayStatusMsg('For some unknown reason the search failed. (-9)');
                break;
            case "-10":
                displayStatusMsg('For some unknown reason the search failed. (-10)');
                break;
            case "-11":
                displayStatusMsg('For some unknown reason the search failed. (-11)');
                break;
            case "-99":
                displayStatusMsg('Access restricted due to probable abuse. Please contact us if you think this is an error. (-99)');
                break;
            default:
                try {
                    //displayStatusMsg('Server said: ' + xmlHttp.responseText);
                    hideStatusMsg();

                    var respJson = eval("(" + xmlHttp.responseText + ")");
                    
                    switch (respJson.resultType) {
                        case 1:
                            displayResults('No results found, sorry.<br /><br />Please try again by filling in only the stem or the root of your search word, i.e. remove prefixes and suffixes.');
                            break;
                        case 2:
                            var resMeaning = eval(respJson.resultValue); 
                            displayResults('<strong>' + resMeaning.entryFull + '</strong>&nbsp;' + resMeaning.meaning);
                              //'<br /><br />The Dictionary depends on sponsoring. Please consider contributing to the project. Click <a href=\'http://www.chichewadictionary.org/contact-us\'>here</a> to contact us.');
                            break;
                        case 3:
                            //var resMeaning = eval(respJson.resultValue); 
                            var resMeaning = respJson.resultValue; 
                            var resultString = 'Multiple entries (' + resMeaning.length + ') found, please select the right one:<br />';
                            
                            for (var i = 0; i < resMeaning.length; i++) {
                                //alert(resMeaning[i]['ID']);
                                resultString += '<a href="javascript:getEntryById(' + resMeaning[i]['ID'] + ')">' + resMeaning[i]['entryFull'] + '</a><br />';
                            }
                            
                            displayResults(resultString);
                            break;
                        case 4:
                            displayResults('Too many results (' + respJson.resultValue + '), please specify your search a bit more or choose another search method.');
                            break;
                        case 5:
                            displayResults('You have consulted the Dictionary ' + respJson.resultValue + ' times in the last 24 hours. Thank you for your interest. Access is limited to ' + respJson.resultValue + ' searches per 24 hours and to the first lines of an entry. Please buy a personal licence code, which provides unlimited acces. Click <a href="http://www.chichewadictionary.org/how-to-contribute">here</a> for details.');
                            break;
                        case 6:
                            displayResults('You have consulted the Dictionary extensively the last 24 hours (' + respJson.resultValue + ' times). For security reasons, your account is (temporarily) disabled. We are sorry for the inconvenience.');
                            break;
                        default:
                            displayErrorMsg('The server returned an unknown result.')
                    }
                }
                catch(err) {
                    displayErrorMsg("An error occured: " + err.description);
                }
        }  
    }
}

function getEntryById(ID) {
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        displayErrorMsg('Unfortunately your webbrowser does not support asynchronous data exchange, therefore you cannot use the online dictionary.');
        return;
    }     
    
    var params = "searchWord=" + document.searchEntryForm.searchEntryEdit.value + "&dictID=" + 
      getRadioValue(document.searchEntryForm.dictSelectRadioGroup) + 
      "&srcTypeID=" + getRadioValue(document.searchEntryForm.searchMethodGroup) + "&srcID=" + ID;
    
    xmlHttp.open("POST", "inc/dictionaryLookupId.php", true);
    xmlHttp.onreadystatechange = verifyLookup;
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");    
    xmlHttp.setRequestHeader("Content-length", params.length);    
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);

    timeOut = setTimeout("displayErrorMsg('A timeout occured: the server did not respond in time.')", 3000);
    
}

 
function displayErrorMsg(errMsg) {
    document.getElementById('errorMsg').innerHTML = errMsg;
    document.getElementById('errorMsg').style.display = 'block';
}

function displayStatusMsg(statusMsg) {
    document.getElementById('statusMsg').innerHTML = statusMsg;
    document.getElementById('statusMsg').style.display = 'block';
}

function hideStatusMsg() {
    document.getElementById('statusMsg').innerHTML = '';
    document.getElementById('statusMsg').style.display = 'none';
}

function displayResults(resMsg) {
    document.getElementById('results').innerHTML = resMsg;
    document.getElementById('results').style.display = 'block';
}

function GetXmlHttpObject() {
  xmlHttp = null;
  
  try {
    // IE7+, Firefox, Chrome, Opera, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch (e) {
    // Internet Explorer
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }

  return xmlHttp;
}

function getRadioValue(radioName) {
    for (var i = 0; i < radioName.length; i++) {
        if (radioName[i].checked)
            return radioName[i].value;
    }
}

