function doAjaxCall(func, args, callback)
{
    if (!Ajax)
    {
        alert('prototype.js is missing');
        return false;
    }

    
    queryString = 'ajax_func='+func;
    for (i=0; i<args.length; i++)
    {
        queryString += encodeURI('&args[]='+args[i]);
    }
    
    var req = new Ajax.Request(document.location, {
        method: 'post',
        parameters: queryString,
        onComplete: function(req){callback(req.responseText)}
    });
}

function getWidget(tag, elements, callback)
{
    // if elements is a string, or a lone object, then put it inside an array
    // note: a string is an array too
    if (typeof(elements) != 'object' || undefined == elements.length)
    {
        elements = [elements];
    }

    doAjaxCall('GetWidget', [tag], function(responseText)
    {
        response = getJson(responseText);
        for (e = 0; e < elements.length; e++)
        {
            element = elements[e];
            if (typeof(element) == "string")
            {
                element = document.getElementById(element);
            }
            element.innerHTML = response.content;
        }
        
        if (callback != null)
        {
            callback(response);
        }
    });
}

function getJson(json)
{
    json = json.replace(/\n/g, '\\n');
    json = json.replace(/\r/g, '\\n');

    // turn this to true to debug for strange characters in the json
    if (false)
    {
        try
        {
            var debug_start = "{content:'" . length;
            for (i = json.length - "',error:false}".length - 1; i > debug_start; i--)
            {
                if (json.charAt(i) == "'") continue;
                json_debug = json.substring(0, debug_start) + '(' + json.charAt(i) + '|' + json.charCodeAt(i) + ')' + json.substring(i, json.length);
                // this will break at the location when a strange character will appear
                // the number in parenthesis will tell you what character it is
                eval('var obj = ' + json_debug + ';');
            }
        }
        catch(e)
        {
            alert('error while evaluating JSON: ' + e.message + '\n\n' + json_debug);
        }
    }
    else
    {
        try
        {
            eval('var obj = ' + json + ';');
        }
        catch(e)
        {
            alert('error while evaluating JSON: ' + e.message + '\n\n' + json);
        }
    }

    return obj;
}

