//http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest - the rules

/**
*    XHR is the global XHR object
**/
var XHR;

/**
*	returnResults is the method that will be envoked after the server replies
**/
var returnResults;  //must be typeof function
var statusNotification //must be typeof function

/**
*	returnType will be either domString or xml to tell the wrapper which to pass to the returnResults method.
*	the default is domString.
**/
var returnType;

/**
*    Define the ajaxWrapper object
**/
function ajaxWrapper(defaultUrl){

/**
*    create the XHR object
**/
    try {
        XHR = new XMLHttpRequest();
    }catch(e){
        try {
            XHR = new ActiveXObject("Microsoft.XMLHTTP");
        }catch (e){
        	this.handleError('Browser not supported!');
        }
    }

/**
*    envoke setReplyProcess (passing a method name as a parameter) to tell the wrapper which method to call
*    on completion of the server call
**/
    this.setReplyProcess = function(method){
        if(typeof method != 'function'){
            this.handleError(method + " must be typeof function not typeof" + typeof method);
        }else {
            returnResults = method;
        }
    };

/**
*	envoke setErrorProcess (passing a method name parameter) to tell the wrapper which method to call when 
*	an error is encountered
**/
	this.setErrorProcess = function(){
		
	}

/**
*	envoke setCancelProcess to tell the wrapper which method will be called to terminate the server request
**/

	this.setCancelProcess = function(){
		return this.cancelProcess;
	}

/**
*	this process will cancel the thread to the server...use setCancelProcess to assing a method to do this
*
**/
	this.cancelProcess = function(){
		XHR.abort();
	}
	
/**
*	envoke setStatusProcess (passing a method name parameter) to get handle ready state change status notification
**/

	this.setStatusProcess = function(method){
		if(typeof method != 'function'){
			this.handleError("Status Process method must be typeof 'function' not " + typeof method);
		} else {
			statusNotification = method;
		}
	}

/**
*	envoke setReturnType (passing 'DOM' or 'XML') to reset the default parameter passed to returnResults from DOM to XML.
**/

	this.setReturnType = function(type){
		if(type.toUpperCase() != 'DOM' && type.toUpperCase() != 'XML'){
			this.handleError("Return Type must be 'DOM' or 'XML'");
		} else {
			returnType = type.toUpperCase();
		}
	}

/**
*    this method will handle waiting for a reply from the server
**/
    XHR.onreadystatechange = function(){
    	if(typeof statusNotification == 'function'){
    		statusNotification(XHR.readyState);
    	}

        if(XHR.readyState == 4){
            if(typeof returnResults == 'function'){
                if(returnType == 'XML'){
                	returnResults(XHR.responseXML);
                }else {
                	returnResults(XHR.responseText);
                }
            }else {
            	this.handleError("ReplyProcess not a function, make sure you pass a function parameter to setReplyProcess");
            }
        }
    };

/**
*    Base URL.  Edit here or use the setURL method.
**/
	if(defaultUrl){
		this.URL = defaultUrl;
	} else {
		this.URL = '';
	}

	this.setURL = function(url){
        this.URL = url;
    };

/**
*    URL Query String
**/
    this.queryName = new Array;
    this.queryValue = new Array;

/**
*    envoke the addQueryVar passing it a querystring variable name and value to be strung onto
*    the XHR url that will be sent to the server
**/
    this.addQueryVar = function(name, value){
        this.queryName.push(name);
        this.queryValue.push(value);
    };

/**
*    Setup and Send request to server
**/
    this.sendURL = function() {
		//alert(this.URL);

        //makes sure that the querystring variables names match up to the querystring values
        if(this.queryName.length != this.queryValue.length){
        	this.handleError('Error!  Name and Var out of sync!');
        }

        //makes sure that a querystring is present
        if(this.queryName.length <= 0){
        	this.handleError("Querystring missing!");
        }

        //create the query string
        var queryString = new Array;
        for(var x=0;x<this.queryName.length + x;x++) {
            queryString.push(this.queryName.pop() + '=' + this.queryValue.pop());
        }

        //add the querystring to the url
        this.URL += queryString.join('&');

        //open the URL
        XHR.open("GET", this.URL, true);

        //send the reqest to the server
        XHR.send(null);
    };

	this.cancel = function(){
		this.abort();
	}
    
/**
*	this will handle any errors that are encountered
**/
	this.handleError = function(errorMessage){
		alert(errorMessage);
		return false;
	}
}
/*

executable non-class related code
*/

function showUserDetails(user_id){
	document.getElementById('results').innerHTML = '';
	showStatus(1);

    var details = new ajaxWrapper();
    details.addQueryVar('field1', 'matt');
    details.addQueryVar('field2', 'rules');
    details.setReturnType('DOM');
    details.setStatusProcess(showStatus);
    details.setReplyProcess(showResults);
	stopRequest = details.setCancelProcess();
    //details.setErrorProcess(showErrorMessage);
    details.sendURL();
}

function showResults(reply){
    document.getElementById('results').innerHTML = reply;
}

function showStatus(status_cd){
	var color;
	var text = 'Loading...';
	switch (status_cd) {
		case 1:
			color = '#DDDD55';
			break;
		case 2:
			color = '#EEEE66';
			break;
		case 3:
			color = '#FFFF77';
			break;
		case 4:
			color = '#CCCCCC';
			text = 'Click';
			break;
	}
	document.getElementById('button').style.background = color;
	document.getElementById('button').value = text;
}

function showErrorMessage(reply){
	alert(reply);
}