﻿function RequestHandler(requestPath) {
	var _this = this;
	var _httpRequest = null;
	var _currentCommand = null;	
	var _requestPath = requestPath;
	var _timeoutId = null;
	
	if(_requestPath == null || _requestPath == "") {
		throw "RequestHandler requestPath cannot be null or empty";
	}
	
	// Try create the XMLHttpRequest object
	_httpRequest = createRequest();
	
	if(_httpRequest == null) {
		// Browser doesn't support XMLHttpRequest, bail out.
		throw "Browser does not support XMLHttpRequest";
	}
	_httpRequest = null;
	
	this.doCommand = function(command) {
		if(_this.isProcessing()) {
			throw "RequestHandler is already processing a request for command: " + _currentCommand.name;
		}
		if(command == null || typeof command == "undefined") throw "RequestHandler command cannot be null";
		_currentCommand = command;
		
		var requestPath = _requestPath + "?c=" + command.name;	
		for(var i = 0; i < command.args.length; i++) {
			requestPath += "&" + i + "=" + escape(command.args[i]);
		}
		
		_httpRequest = createRequest(); 				
		_httpRequest.onreadystatechange = onReadyStateChange;
		_httpRequest.open("GET", requestPath, true);
		_httpRequest.send(null);		
	}
	
	this.getResponse = function(onResponse, xmlResponse) {
		var command = new Command("GetResponse", onResponse, xmlResponse);
		this.doCommand(command);
	}
	
	this.abort = function() {
		if(!this.isProcessing()) throw "RequestHandler cannot abort because it is not processing";
		
		_httpRequest.abort();
		_currentCommand = null;
		_httpRequest = null;
	}
	
	this.isProcessing = function() {
		return _currentCommand != null;
	}
	
	function createRequest() {
		var request = null;
		if(window.XMLHttpRequest) {
			request = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		return request;
	}
	
	function onReadyStateChange() {
		if(_httpRequest != null && _httpRequest.readyState == 4) {			
			var command = _currentCommand;
			command.status = _httpRequest.status;
			
			if(_timeoutId != null) window.clearTimeout(_timeoutId);	
			_currentCommand = null;	// Reset currentCommand so new requests can be made	
		
			// Get the type of response (dependent on the expected response assigned to the command)
			var response = command.xmlResponse ? _httpRequest.responseXML : _httpRequest.responseText;
			_httpRequest = null;
			
			// Call method assigned to onResponse
			if(command.onResponse != null) command.onResponse(command, response);		
		}
	}	
}

function Command(name, onResponse, xmlResponse, args) {
	this.name = name;
	this.onResponse = onResponse;
	this.xmlResponse = xmlResponse == null ? false : xmlResponse;
	this.args = args == null ? new Array() : args;
	this.status = null;

	this.validResponse = function() {
		if(this.status == null) throw "RequestHandler has not set status"; 
		return this.status == 200; 
	}	
}
