const Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

function setEngine() {
    var searchEngineName = Services.prefs.getCharPref("kmeleon.general.searchEngineName");
	  var searchText = document.getElementById("searchText");
    searchText.addEventListener("blur", function searchText_onBlur() {
        searchText.removeEventListener("blur", searchText_onBlur);
        searchText.removeAttribute("autofocus");
    });
	  
    searchText.placeholder = searchEngineName;
}

window.addEventListener('pageshow', function () {
    Services.prefs.addObserver("kmeleon.general.searchEngine", setEngine, false);
    setEngine();
});
	
function onSearchSubmit(aEvent)
{
    var searchTerms = document.getElementById("searchText").value;
    var searchURL = Services.prefs.getCharPref("kmeleon.general.searchEngine");

    if (searchURL && searchTerms.length > 0) {

        const SEARCH_TOKEN = "_searchTerms_";
        let searchPostData = document.documentElement.getAttribute("searchEnginePostData");
        if (searchPostData) {
            // Check if a post form already exists. If so, remove it.
            const POST_FORM_NAME = "searchFormPost";
            let form = document.forms[POST_FORM_NAME];
            if (form) {
                form.parentNode.removeChild(form);
            }

            // Create a new post form.
            form = document.body.appendChild(document.createElement("form"));
            form.setAttribute("name", POST_FORM_NAME);
            // Set the URL to submit the form to.
            form.setAttribute("action", searchURL.replace(SEARCH_TOKEN, searchTerms));
            form.setAttribute("method", "post");

            // Create new <input type=hidden> elements for search param.
            searchPostData = searchPostData.split("&");
            for (let postVar of searchPostData) {
                let [name, value] = postVar.split("=");
                if (value == SEARCH_TOKEN) {
                    value = searchTerms;
                }
                let input = document.createElement("input");
                input.setAttribute("type", "hidden");
                input.setAttribute("name", name);
                input.setAttribute("value", value);
                form.appendChild(input);
            }
            // Submit the form.
            form.submit();
        } else {
            searchURL = searchURL + encodeURIComponent(searchTerms);//.replace(SEARCH_TOKEN, encodeURIComponent(searchTerms));
            window.location.href = searchURL;
        }
    }

    aEvent.preventDefault();
}