﻿function getXmlHttpObject()
{
    var xmlHttp = null;
    
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (e)
        {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
    
    if (xmlHttp == null)
    {
        window.alert('AJAX not supported!');
        return null;
    }
    
    return xmlHttp;
}

function doAJAX(url, params, source, destination)
{
    //document.getElementById(destination).innerHTML = '<div class="spinnerContainer"><div class="spinner">&nbsp;</div></div>';
    showSpinner(document.getElementById(destination));
    
    var xmlHttp = getXmlHttpObject();
    
    xmlHttp.onreadystatechange = function ()
    {
        if (xmlHttp.readyState == 4)
        {
            if (xmlHttp.status == 200)
            {
                document.getElementById(destination).innerHTML = xmlHttp.responseText;
            }
            else
            {
                // *** Raise an error here ***
                window.alert('An error has occurred - ' + source);
            }                
        }
    }

    xmlHttp.open('POST', url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);
}

function showSpinner(container)
{
    // *** fiddle for IE7, which doesn't return the right offsetTop value :@ ***
    var oElement = container;
    if (typeof(oElement.offsetParent) != 'undefined')
    {
        for (var posX=0, posY=0; oElement; oElement=oElement.offsetParent)
        {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
        }
    }
    else
    {
        var posX = oElement.offsetLeft;
        var posY = oElement.offsetTop; 
    }

// *** Remove the innerHTML call because of rumoured memory leak in IE7, do it properly using the DOM ***    
//    var positioning = 'top: ' + posY + 'px; width: ' + container.offsetWidth + 'px; height: ' + container.offsetHeight + 'px; ';
//    container.innerHTML += '<div class="spinner" style="position: absolute; ' + positioning + '"></div>';

    var spinnerDiv = document.createElement('div');
    
    spinnerDiv.style.position = 'absolute';
    spinnerDiv.style.top = posY + 'px';
    spinnerDiv.style.width = container.offsetWidth + 'px';
    spinnerDiv.style.height = container.offsetHeight + 'px';
    
    spinnerDiv.className = 'spinner';
    
    container.appendChild(spinnerDiv);
}


