var selecting = false;
var defaultTimeout = 60;
var timeout = defaultTimeout;

function getUA () {
    var ua;
    try {
        // Firefox, Opera 8.0+, Safari
        ua = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            ua = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
              ua = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    return ua;
}

function synch_call_rpc (url, action, params, failback) {
    var ua = getUA();

    if (ua) {
        ua.open('GET', prepare_url(url, action, params), false);

        timeout = 5; // Never longer for synchronous. Stalls browser.
        var t_o = setTimeout(function() {
            ua.abort();
            alert("There was a problem communicating with the server");
        }, timeout * 1000);
        timeout = defaultTimeout;

        ua.send(null);
        clearTimeout(t_o);

        if (ua.responseText.match(/^FAIL:.*/)) {
            alert(/^FAIL:(.*)/.exec(ua.responseText)[1]);
            ua.responseText.replace(/<!-- .* -->/gm, '');
            if (failback) failback(ua.responseText);
            return false;
        }

        ua.responseText.replace(/<!-- .* -->/gm, '');
        return ua.responseText;
    }
    else return false;
}

function asynch_call_rpc(url, action, callback, params, failback) {
    var ua = getUA();

    if (ua) {
        ua.open('GET', prepare_url(url, action, params), true);
        ua.callback = callback;
        if (failback) ua.failback = failback;

        ua.onreadystatechange = function() {
            if (ua.readyState == 4) {
                if (ua.status == 200) {
                    if (ua.responseText.match(/^FAIL:.*/)) {
                        alert(/^FAIL:(.*)/.exec(ua.responseText)[1]);
                        ua.responseText.replace(/<!-- .* -->/gm, '');
                        if (ua.failback) ua.failback(ua.responseText);
                        return false;
                    }
                    ua.responseText.replace(/<!-- .* -->/gm, '');
                    ua.callback(ua.responseText);
                }
                else if (ua.failback) {
                    ua.responseText.replace(/<!-- .* -->/gm, '');
                    ua.failback(ua.responseText);
                }
                else alert("AJAX RPC Call failed with status code " + ua.status +
                           "\n" +
                           "Please try again later.");
            }
        }

        if (!timeout)  timeout = 60;
        var t_o = setTimeout(function() {
            ua.abort();
        }, timeout * 1000);
        ua.send(null);
    }
    else return false;
}

function prepare_url(url, action, params) {
    var qs = '?action=' + encodeURIComponent(action);

    if (params) {
        for (key in params) {
            qs = qs + '&' + key + '=' + encodeURIComponent(params[key]);
        }
    }

    qs = qs + '&x=' + new Date().getTime() + ':' + Math.floor(Math.random() * 1000000);

    return url + qs;
}

function get_suggestions(which, what) {
    var suggestion_box = document.getElementById(which + '_suggestions');
    if (!suggestion_box) return false;
    var input = document.getElementById(which);
    if (!input) return false;

    var search = input.value;
    if (!search) return false;

    document.getElementById('status_readout').innerHTML = 'getting suggestions for ' + search;

    var callback;
    eval("callback=function(response){var box=document.getElementById('"+suggestion_box.id+"');var input=document.getElementById('"+input.id+"');if(response){box.innerHTML=response;box.style.display='block';input.style.backgroundColor=''}else{box.innerHTML=''; box.style.display='none';input.style.backgroundColor='red';return false}};");

    asynch_call_rpc('/get_suggestions.ez', 'get_' + what + '_suggestions', callback, {'id' : which, 'q' : search});

}

function set_suggestion(which, what) {
    var el = document.getElementById(which);
    if (!el) return false;
    el.value = what;
    var suggestions = document.getElementById(which + '_suggestions');
    if (!suggestions) return false;
    suggestions.innerHTML = '';
    suggestions.style.display = 'none';
}

function hide_suggestions(which) {
    if (selecting) return false;
    var suggestions = document.getElementById(which + '_suggestions');
    if (!suggestions) return false;
    suggestions.style.display = 'none';
}

function show_suggestions(which) {
    var suggestions = document.getElementById(which + '_suggestions');
    if (!suggestions) return false;
    if (!suggestions.innerHTML) return false;
    suggestions.style.display = 'block';
}
