// JavaScript Document

function RCL_KeyHandler(event)
{
    // Was the key that was pressed [ENTER]? If so, perform a web search.
    if(event.keyCode == event.DOM_VK_RETURN)
        RCL_Search(event);
}

function RCL_Search(event)
{
    // This variable will hold the URL we will browse to
    var URL = "";

    // This variable will tell us whether our search box is empty or not
    var isEmpty = false;

    // Get a handle to our search terms box (the <menulist> element)
    var searchTermsBox = document.getElementById("RCL-searchterm");
    
    // Get the value in the search terms box, trimming whitespace as necessary
    // See the RCL_TrimString() function farther down in this file for details
    // on how it works.
    var searchTerms = RCL_TrimString(searchTermsBox.value);

    if(searchTerms.length == 0) // Is the search terms box empty?
        isEmpty = true;         // If so, set the isEmpty flag to true
    else                        // If not, convert the terms to a URL-safe string
        searchTerms = RCL_ConvertTermsToURI(searchTerms);
		
	if(isEmpty) { URL = "http://reddo-translation.com/free-chinese-translation.html"; }
        else        { URL = "http://www.google.com/search?q=" + searchTerms; }
        break;
	
	RCL_LoadURL(URL);
}

function RCL_TrimString(string)
{
    // If the incoming string is invalid, or nothing was passed in, return empty
    if (!string)
        return "";

    string = string.replace(/^\s+/, ''); // Remove leading whitespace
    string = string.replace(/\s+$/, ''); // Remove trailing whitespace

    // Replace all whitespace runs with a single space
    string = string.replace(/\s+/g, ' ');

    return string; // Return the altered value
}

function RCL_ConvertTermsToURI(terms)
{
    // Create an array to hold each search term
    var termArray = new Array();

    // Split up the search term string based on the space character
    termArray = terms.split(" ");

    // Create a variable to hold our resulting URI-safe value
    var result = "";

    // Loop through the search terms
    for(var i=0; i<termArray.length; i++)
    {
        // All search terms (after the first one) are to be separated with a '+'
        if(i > 0)
            result += "+";

        // Encode each search term, using the built-in Firefox function
        // encodeURIComponent().
        result += encodeURIComponent(termArray[i]);
    }

    return result; // Return the result
}

function RCL_LoadURL(url)
{
    // Set the browser window's location to the incoming URL
    window._content.document.location = url;

    // Make sure that we get the focus
    window.content.focus();
}