
/*
03/2006
César de Moura Campos
cesar@cmcinternet.com.br
www.cmcinternet.com.br
CMC - SOLUÇÕES EM INTERNET
11 - 9774-2380
*/

//Retorna um objeto XmlHttpRequest compatível com o 
// navegador usado.
function getHttpRequestObject()
{
	var objHttpRequest = null;
	
	if (window.XMLHttpRequest) //IE 7, Mozilla, Safari,...
	{
		objHttpRequest = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) // Internet Explorer
	{
		//todos os program id's possiveis do objeto XMLHTTPREQUEST da Microsoft
		// que é de natureza ActiveX
		var progIds = [
		    'Microsoft.XMLHTTP',
		    'MSXML2.XMLHTTP.5.0',
		    'MSXML2.XMLHTTP.4.0',
		    'MSXML2.XMLHTTP.3.0',
		    'MSXML2.XMLHTTP'
		   ];
		for (var i = 0; i < progIds.length; i++)
		{
	    	try
			{
      			objHttpRequest = new ActiveXObject(progIds[i]);
				break;
			}
			catch (e)
			{
			}
    	}
	}
	return objHttpRequest;
}

var CMC_OUTPUT_TEXT = 'T';
var CMC_OUTPUT_XML  = 'X';

//Objeto que e usado para executar operacoes em AJAX
function CMCAjax(url,method,params,process,outputType)
{
	this.url = url;
	this.method = (method) ? method : 'GET';
	this.params = null;
	if (method != 'GET') this.params = params;
	this.processFunction = process;
	this.outputType = (outputType) ? outputType : 'text';
	if (this.outputType != CMC_OUTPUT_TEXT && this.outputType != CMC_OUTPUT_XML) this.outputType = CMC_OUTPUT_TEXT;
}

CMCAjax.prototype = {
	execute: function()
	{
		this.httprequest = getHttpRequestObject();
		if (this.httprequest != null && this.httprequest != undefined)
		{
			var obj = this;
			this.httprequest.onreadystatechange = function()
				{
					obj.processresponse.call(obj);
				}		
		}
		if (this.method == undefined || this.method == '') this.method = 'GET';
		
		this.httprequest.open(this.method, this.url, true)
		this.httprequest.send(this.params);
	},
	
	//
	processresponse: function()
	{
		if (this.httprequest.readyState == 4)
		{
			if (this.httprequest.status == 200)
			{
				//verifica formato da responsta (texto ou xml)
				var response = (this.outputType == CMC_OUTPUT_XML) ? this.httprequest.responseXML : this.httprequest.responseText;
				if (this.processFunction != null)
				{
					this.processFunction(response);
				}
				else
				{
					//resposta
					document.write(response);
				}
			}
			else
			{
				// erro
				this.processerror();
			}
		}
	},
	
	//
	processerror: function()
	{
		alert(this.httprequest.status + '-' + this.httprequest.statusText + ' :-> ' + this.url);
	}
}
