/*
* Code to process ajax requests. Simply call the call function and the target div will be filled with
* whatever the server responds with. In this case we are using response text.
*
* Most of this code was originally taken from Apple's Developer Connection site
* Reference: http://developer.apple.com/internet/webcontent/xmlhttpreq.html
*
* Version: 1.0 - 29/07/2006 - Initial Version
*		   1.1 - 29/07/2006 - fixed a ton a bugs, diverged from Apple version signif
* 
* Author: Mike Quigley <mike@pandasurf.com>
*/

function call(url,target_element,method,loading_message,error_message,params) 
{
	//set some default values if some params are not passed
	if (method == undefined)
	{
		method = 'GET';
	}
	
	if (loading_message == undefined)
	{
		loading_message = 'Loading ...';
	}
	
	if (error_message == undefined)
	{
		error_message = 'Error processing request.';
	}

	document.getElementById(target_element).innerHTML = loading_message;

	//ASSERT: params will only be sent with POST method
	if (params == undefined)
	{
		params = null;
	}

	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) 
    {
    	try 
    	{
			req = new XMLHttpRequest();
        } 
        catch(e) 
        {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } 
    else if(window.ActiveXObject) 
    {
       	try 
       	{
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} 
      	catch(e) 
      	{
        	try 
        	{
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} 
        	catch(e) 
        	{
          		req = false;
        	}
		}
    }

	if(req) 
	{	
		req.onreadystatechange = function()
		{
			processReqChange(target_element,error_message);
		}				

		req.open(method, url, true);
		
		//we need to let the object know we are passing name value pairs
		if (method == 'POST')
		{
			req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 		
		}
		
		req.send(params);				
	}
	else
	{
		document.getElementById(target_element).innerHTML = error_message;
	}
}

function processReqChange(target_element,error_message) 
{
    // only if req shows "loaded"

    if (req.readyState == 4) 
    {            
        // only if "OK"
        if (req.status == 200) 
        {
            document.getElementById(target_element).innerHTML = req.responseText;
        }
        else
        {
        	document.getElementById(target_element).innerHTML = error_message;
        }
    }
}