var globalAjaxOperationsStarted = 0;
var globalAjaxOperationsEnded = 0;

function applyDefaultValues(conf, basicConf)
{
    for(key in basicConf)
    {
        if(conf[key] == undefined)
        {
            conf[key] = basicConf[key];
        }
    }
	return conf;
}

function imgToDisplay(targetDiv, img)
{
	try
	{
		document.getElementById(targetDiv).innerHTML = '<img src="' + img + '">';
	}
	catch(err)
	{
	}
}

function xmlValuesToTemplate(baseDiv, xml)
{
    for(i=0;i<xml.childNodes.length;i++)
    {
        try
        {
            document.getElementById(baseDiv + xml.childNodes[i].tagName).innerHTML = xml.childNodes[i].firstChild.nodeValue;
        }
        catch(err)
        {
            //alert(err);
        }
    }
}

function doAJAX_GET_POST_Conv(conf)
{
    for(i=0; i < conf.form_id.elements.length; i++)
    //for each (var item in id.elements)    
    {
	var item = conf.form_id.elements[i];
        try
        {
            if(item.type == "checkbox")
            {
                if(item.checked || !conf.suppress_uncheked)
                    conf.parameters +="&"+item.name+"="+item.value;
            }
            else if(item.type == "text")
            {
                if(item.value.lenght > 0 || !conf.suppress_null_length)
                   conf.parameters +="&"+item.name+"="+item.value;
            }
            else if(item.type == "select-one")
            {
                if(item.multiple == true)
                {
                    var selectedArray = new Array();
                    for (i=0; i< item.options.length; i++)
                    {
                        if (item.options[i].selected)
                        {
                            selectedArray.push(item.options[i].value);
                        }
                    }
                    if(selectedArray.length > 0)
                        conf.parameters +="&"+item.name+"="+selectedArray;
                }
                else
                {
                    conf.parameters +="&"+item.name+"="+item.value;
                }
            }
        }
        catch(err)
        {
        }
    }
}

function doAJAX(conf)
{
    var confBasic = {
            'targetString': '../',
            'targetDiv': document,
            'method': 'GET',
            'return_type': 'text',
            'form_id': null,
            'addToDiv': false,
            'errorPage': null,
            'loading_img' : null,
            'loading_text': 'Loading...',
            'loading_img_div_id': 'loadBar',
            'disable_caller': false,
            'clear_caller': false,
            'caller' : this,
            'warning_language': 'de',
            'warning_ajax_unsupported': '<strong>Ihr Browser unterstuetzt kein AJAX - Bitte verwenden Sie einen modernen Browser wie Firefox 3, Safari 4, Opera 10 oder IE8</strong>',
            'parameters': 'debug=test',
            'suppress_errors': false,
            'suppress_null_length': true,
            'suppress_unchecked': true,
            'post_function': null,
            'post_function_poll': 25
        };
    conf = applyDefaultValues(conf, confBasic);
    globalAjaxOperationsStarted++;
    var req = null;
    try
    {
        req = new XMLHttpRequest();
    }
    catch (ms)
    {
        try
        {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (nonms)
        {
            try
            {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (failed)
            {
                req = null;
            }
        }
    }
    if (req == null)
    {
        globalAjaxOperationsEnded++;
        if(conf.errorPage == null)
            document.getElementById(conf.targetDiv).innerHTML = conf.warning_ajax_unsupported;
        else
            document.getElementById(conf.targetDiv).innerHTML = conf.errorpage;
    }
    else
    {
        // Clear caller
        if(conf.clear_caller)
        {
            try
            {
                document.getElementById(conf.caller).innerHTML = "";
            }
            catch(err){}
        }
        // Display loading text or image
        var loader = '<div id="' + conf.loading_img_div_id + '">' + conf.loading_text + '</div>';
        if(conf.loading_img != null)
        {
            loader = '<img id="' + conf.loading_img_div_id + '" src="' + conf.loading_img + '">';
            
        }
		switch(conf.return_type)
		{
			case 'img':
			case 'xml':
				break;
			case 'html':
				if(conf.addToDiv)
                    document.getElementById(conf.targetDiv).innerText += loader;
				else
                    document.getElementById(conf.targetDiv).innerText = loader;
			default:
				if(conf.addToDiv)
                    document.getElementById(conf.targetDiv).innerHTML += loader;
				else
                    document.getElementById(conf.targetDiv).innerHTML = loader;
		}
    }
    req.onreadystatechange = function()
    {
        switch(req.readyState)
        {
            case 4:
				globalAjaxOperationsEnded++;
				switch(conf.return_type)
				{
					case 'img':
						imgToDisplay(conf.targetDiv, req.responseText);
						break;
					case 'xml':
						xmlValuesToTemplate(conf.targetDiv, req.responseXML.documentElement);
						break;
					default:
						if(conf.addToDiv)
							document.getElementById(conf.targetDiv).innerHTML += req.responseText;
						else
							document.getElementById(conf.targetDiv).innerHTML = req.responseText;
						break;
				}
                break;
            default:
                return false;
                break;
        }
    };
    if(conf.method == "GET")
    {
        req.open("GET", conf.targetString, true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.send(null);
    }
    else if(conf.method == "POST")
    {
        // Parse parameters first
        doAJAX_GET_POST_Conv(conf);
        req.open("POST", conf.targetString, true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.setRequestHeader("Content-length", conf.parameters.length);
        req.setRequestHeader("Connection", "close");
        req.send(conf.parameters);
    }

    // Add Loading Bar removal as delayed function
    if(conf.addToDiv && conf.loading_img != null)
        delayedFuncCall('document.getElementById(\'' + conf.targetDiv +'\').removeChild(document.getElementById(\'' + conf.loading_img_div_id + '\'))', conf.post_function_poll);
    // Add Post Function handler
    if(conf.post_function != null)
        delayedFuncCall("\"" + conf.post_function + "\"", conf.post_function_poll)
}
