function AjaxRequest() {
	Ajax = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		Ajax = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		try {
			Ajax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				Ajax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return Ajax;
}

function extraiScript(texto){
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);

            novo = document.createElement("script");
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

function ajax(pagina, parametros, div, callback) {
	//document.getElementById('load_page').innerHTML = '<div align="center"><img src="../imagens/load.gif" vspace="0" /></div>';

	var req = AjaxRequest();
	if(!req) {
		//document.getElementById(pagina).innerHTML = '[Erro na Chamada]';
		return;
	}
	
	req.onreadystatechange = function resultado() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				var response = req.responseText;
				document.getElementById('load_page').innerHTML = '';
				
				if	(response.substring(0,7) == '<script') {
					extraiScript(response);
				} else {
					document.getElementById(div).innerHTML = response;
					extraiScript(response);
					
				}
				if(callback != '' || callback != 'undefined'){
					eval(callback);
				} 	
			} else {
				//alert('[Erro no Servidor]');
			}
		}
	}
	
	req.open('GET', pagina + '?' + parametros + '&z=' + Math.ceil(Math.random() * 100000), true);
	req.send(null);
}

function processa(parametros,div,pagina) {
	var req = AjaxRequest();
	if(!req) {
		document.getElementById(div).innerHTML = '[Erro na Chamada]';
		return;
	}
	
	req.onreadystatechange = function resultado() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				var response = req.responseText;
				
				//alert(response);
				
				if (pagina == '_valor') {
					if (response != '') {
						document.getElementById(div).innerHTML = response;
					}
				} else {
					document.getElementById(div).innerHTML = response;
				}
				
			} else {
				//alert('[Erro no Servidor]');
			}
		}
	}
	
	req.open('GET', pagina+'.php?v='+parametros+'&z='+Math.ceil(Math.random() * 100000), true);
	req.send(null);
}
