// JavaScript Document
xmlConnection = function() {

	// Variáveis utilizadas no objeto
	var strNav = new String('');
	var objAjax = null;
	var strMethod = new String('GET');
	var strParams = new String('');
	var strURL = new String('');
	var strChildName = new String('');
	var arrParamName = new Array();
	var arrParamValue = new Array();
	var numTotalParams = new Number(0);
	var xmlReturn = null;
	var textReturn = new String('');
	var thisObj = this;
	
	// Evento executado quando o xml é lido comsucesso
	this.onComplete = function () { };
	// Evento executado quando o xml acabou de ser lido | Retorna o código do resultado Ex.: 200, 401...
	this.onLoad = function () { };
	// Evento executado quando o xml troca de status | Retorna o status atual
	this.onStateChange = function () { };
	// Evento executado quando o xml não foi lido | Retorna o código do erro
	this.onError = function() { alert('Erro ao ler o xml!'); }
	
	// Adiciona itens as array de parâmetros (variáveis que serão passadas)
	this.addParameters = function() {	
		arrParamName[numTotalParams] = arguments[0];
		arrParamValue[numTotalParams] = arguments[1];
		numTotalParams++;
	}

	// Limpa o array de parâmetros
	this.emptyParameters = function() {
		numTotalParams = new Number(0);
		arrParamName = new Array();
		arrParamValue = new Array();
	}
	
	// Informa para o objeto a URL do xml
	this.setURL = function() {
		strURL = arguments[0];
	}

	// Informa para o objeto o método utilizado para os envios dos dados
	this.setMethod = function() {
		if ((arguments[0].toUpperCase() == 'POST') || (arguments[0].toUpperCase() == 'GET')) {
			strMethod = arguments[0].toUpperCase();
		}
	}
	
	// Informa para o objeto o nome da tag padrão para retorno dos dados
	this.setChildName = function() {
		strChildName = arguments[0];
	}

	// Retorna o status da leitura do xml
	this.getStatus = function() {
		return objAjax.statusText;
	}

	// Retorna o browser do usuário ('ie' ou 'ff')
	this.getBrowser = function() {
		return strNav;
	}

	// Retorna o XML recebido
	this.getXML = function() {
		return xmlReturn;
	}

	// Retorna o texto recebido
	this.getText = function() {
		return textReturn;
	}
	
	// Retorna a quantidade de itens da tag especificada pela função setChildName
	this.getCountItens = function() {
		return xmlReturn.getElementsByTagName(strChildName).length;
	}
	
	// Retorna o atributo da tag especificada pela função setChildName
	this.getAttByName = function() {
		try { return xmlReturn.getElementsByTagName(strChildName)[arguments[1]].getAttribute(arguments[0]); } catch(e) { return null; }
	}
	
	// Retorna o CDATA da tag especificada pela função setChildName
	this.getDataByName = function() {
		try { return xmlReturn.getElementsByTagName(strChildName)[arguments[0]].firstChild.data; } catch(e) { return null; }
	}
	
	// Faz o envio de dados e aguarda o retorno
	this.execute = function() {
		strParams = '';
		for (var i = 0; i < arrParamName.length; i++) {
			if (i > 0) strParams += '&';
			strParams += arrParamName[i]+'='+arrParamValue[i];
		}
		if (strMethod == 'GET') {
			objAjax.open(strMethod, strURL+'?'+strParams, true);
		} else {
			objAjax.open(strMethod, strURL, true);
		}
		objAjax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//; iso-8859-1
		objAjax.setRequestHeader("CharSet", "UTF-8");
		objAjax.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate");
		objAjax.setRequestHeader("Cache-Control","post-check=0, pre-check=0");
		objAjax.setRequestHeader("Pragma", "no-cache");
		objAjax.onreadystatechange = function() {
			thisObj.onStateChange(objAjax.readyState);
			if (objAjax.readyState == 4){
				thisObj.onLoad(objAjax.status);
				if (objAjax.status == 200){
					xmlReturn = objAjax.responseXML;
					textReturn = objAjax.responseText;
					thisObj.onComplete();
				} else {
					thisObj.onError(objAjax.statusText, objAjax.status);
				}
			}
		}
		if (strMethod == 'GET') {
			objAjax.send(null);
		} else {
			objAjax.send(strParams);
		}
	}

	// Cria o objeto AJAX (utilizado para envio e recebimento dos dados)
	this.create = function() {
		if (window.ActiveXObject) {
			strNav = 'ie';
			try {
				objAjax = new ActiveXObject("Msxml2.XMLHTTP.4.0");
			} catch(e) {
				try {
					objAjax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
				} catch(e) {
					try {
						objAjax = new ActiveXObject("Msxml2.XMLHTTP");
					} catch(e) {
						try {
							objAjax = new ActiveXObject("Microsoft.XMLHTTP");
						} catch(e) {
							objAjax = null;
							return false;
						}
					}
				}
			}
		} else if (window.XMLHttpRequest) {
			objAjax = new XMLHttpRequest();
			strNav = 'ff';
		}
		return true;
	}

}
