// Copyright (c) 2007 - Insite Solucoes Internet - www.insite.com.br
// Exemple:
// <SCRIPT src="sendrequest.js" type=text/javascript></SCRIPT>
// <script>
//
//   var body = SendRequest("tmp.txt", 'sync', 'GET');
//   alert(body);
//
//// POST form without leaving the page
// 
//  var body = AjaxPost(FORM);
//
// OR:
//
//   var QUERY_STRING = ParseForm(document.forms[0]);
//   var body2 = SendRequest("/cgi-bin/ambiente.pl?"+QUERY_STRING, 'sync', 'POST')
//   alert(body2);
//
// </script>

var agt = navigator.userAgent.toLowerCase();
var is_ie  = (agt.indexOf('msie')   != -1);
var is_ie5 = (agt.indexOf('msie 5') != -1);

function AjaxPost(Form) {
	Form.style.cursor = "wait"; // Fake cursor style
	
	var QUERY_STRING = ParseForm(Form);
	QUERY_STRING = "is_ajax=1&" + QUERY_STRING;
// TODO: Do not work if <input name=action>. Conflicts with Form.action.value
	var resp_body = SendRequest(Form.action + "?" + QUERY_STRING, 'sync', Form.method)
	
	Form.style.cursor = "default";
	
	return resp_body;
}

function CreateXmlHttpReq(handler) { // TODO: Nao funciona no IE 5 do MAC
	var xmlhttp = null;
	if (is_ie) {
		var control = (is_ie5) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";
		try {
			xmlhttp = new ActiveXObject(control);
			xmlhttp.onreadystatechange = handler;
		} catch(e) {
			alert("Enable active scripting and ActiveX controls or change browser: "+e);
		}
	} else { // Firefox
		xmlhttp = new XMLHttpRequest();
		xmlhttp.onload  = handler;
		xmlhttp.onerror = handler;
	}
	return xmlhttp;
}

function DummyHandler() { }

function XmlHttpGET(xmlhttp, url, Async, Method) {
	xmlhttp.onreadystatechange = function() { // Funcao executada ao terminar de fazer o load
		if (xmlhttp.readyState == 4) { // 0 = uninitializated; 1 = Loading ; 2 = Loaded ; 3 = Interactive ; 4 = Completed
// Coloca o resultado dentro de <div id="id_name"></div>
//			elem = document.getElementById(id_name);
//			elem.innerHTML = xmlhttp.responseText;
// alert("Load Finished");
		}
	}
	
	var QUERY_STRING = null;
	
	if (Method == 'POST' || Method == 'post') {
		Method = 'POST';
		var pos_sep = url.indexOf ("?");
		QUERY_STRING = url.substring (pos_sep+1, url.length);
		url = url.substring (0, pos_sep);
	} else {
		Method = 'GET';
	}
	
	xmlhttp.open(Method, url, Async); // Sync: 'true' is async (nao espera response); 'false' is sync (waits for response, blocante)
//	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") 
//	xmlhttp.setRequestHeader("Content-Type", 'text/xml; charset="ISO-8859-1"');
//	xmlhttp.setRequestHeader("Accept-Charset", "iso-8859-1");
	
	xmlhttp.send(QUERY_STRING);
	
//var xmlDoc = xmlhttp.getAllResponseHeaders();
	
	if (Async == false) { // is Sync
		if (xmlhttp.status >= 400) {
			alert("ERROR "+xmlhttp.status+" while reading URL "+url);
		}
		
		var node;
		
		try {
			node = xmlhttp.responseXML; // [object] in IE ; Empty in firefox if response is NOT xml
			
			//  FIREFOX    && IE
			if (node!=null && node.childNodes[0]!=null) {
//alert(node.nodeType); // 9 = Document
//alert(node.childNodes[0].nodeType); // 7 = ProcessInstruction

// Parse .XML files
//alert(node.childNodes[0].nodeName); // Ex: 'xml' = node 0 ; 'body' = node 1
//alert(node.childNodes[0].attributes[0].nodeName); // Ex: "version"
//alert(node.childNodes[0].attributes[0].nodeValue); // Ex: "1.0"

// alert(node.childNodes[1].childNodes[0].nodeName); // user
// alert(node.childNodes[1].childNodes[0].childNodes[0].nodeName); // name
// alert(node.childNodes[1].childNodes[0].childNodes[0].childNodes[0].nodeName);  // #text
// alert(node.childNodes[1].childNodes[0].childNodes[0].childNodes[0].nodeValue); // John Smith

//var user_length = node.getElementsByTagName("nick").length;
//for (var i = 0; i < user_length; i++) {
////  alert(node.getElementsByTagName("nick")[i].childNodes[0].nodeValue);
//}

//alert(xmlhttp.responseXML.getElementsByTagName("name")[0].childNodes[0].nodeValue);
//alert(xmlhttp.responseXML.getElementsByTagName("phone")[0].childNodes[0].nodeValue);
//var nameNode = xmlhttp.responseXML.getElementsByTagName("name")[0]; 
//var nameTextNode = nameNode.childNodes[0]; 
//var name = nameTextNode.nodeValue;

//	var cs = node.childNodes;
//	for (var i = 0; i < cs.length; i++) {
////		str += createXmlTree(cs[i], indent);
////		alert(cs[i].nodeName); // xml (nodeType=7), body (nodeType=1)
//		var attrs = cs[i].attributes;
//		for (var j = 0; j < attrs.length; j++) {
////			alert(attrs[j].);
//		}
//	}
			}
			
		} catch(e) {
			var err = "Error: " + e.message;
			alert(err);
		}
		
		// node==null ocorre no Firefox, se response nao for xml
		//  FIREFOX    || IE
		if (node==null || node.childNodes[0]==null) {
			var docBody = xmlhttp.responseText;
			return docBody;
		} else {
			var docXML = xmlhttp.responseXML;
			return docXML;
		}
		
	} else { // is Async
		return true;
	}
}

var rnd = (new Date).getTime();

function SendRequest(url, Async, Method) { // url must be local (same-domain security policies)
	if (Async == 'sync' || Async == 'false' || Async == undefined) { // SYNC is default
		Async = false ;
	} else {
		Async = true;
	}
	
	var xmlhttp = CreateXmlHttpReq(DummyHandler);
	++rnd; // Avoid cache
	var has_param = (url.indexOf('?') != -1);
	var sep = (has_param) ? "&" : "?";
	return XmlHttpGET(xmlhttp, url + sep + "rnd=" + rnd, Async, Method);
}

function ParseForm(form) {
	// Recebe objeto "form"
	// Retorna todos os dados preenchidos no form na forma de QUERY_STRING
	var QUERY_STRING = '';
	
	// Este getElements pegaria apenas todos objetos "input"
	// var inputs = document.getElementsByTagName('input');
	for (var i=0; i<form.elements.length; i++) {
		var id    = form[i].id;
		var name  = form[i].name;
		var value = form[i].value;
		// type = text, hidden, radio, checkbox, select-one, select-multiple, file, textarea, password...
		var type  = form[i].type;
		
		// TODO: Pegar multiplos valores se for <select multiple>. Esta pegando so o primeiro valor selecionado.
		
		value = escape(value);
		value = value.replace(/\+/g, "%2B");
		
		if (type.indexOf("checkbox") != -1) { // Pega valor do(s) campo(s) <input type=checkbox> selecionado(s)
			if (form[i].checked == true) {
				QUERY_STRING += name + "=" + value + "&";
			}
		} else if (type.indexOf("radio") != -1) {
			if (form[i].checked == true) {
				QUERY_STRING += name + "=" + value + "&";
			}
		} else { // Campo generico
			QUERY_STRING += name + "=" + value + "&";
		}
		
	}
	
	QUERY_STRING = QUERY_STRING.replace(/\&$/,""); // Trim "&" final
	
	return QUERY_STRING;
}

function GetUrlParams() {
	var URL = window.location + ''; //little bug with URLs and strings (window.location is object?)
	var pos_sep = URL.indexOf ("?");
	var QUERY_STRING = URL.substring (pos_sep+1, URL.length);
	
	var params = Object;
	
	while (QUERY_STRING.length>0) {
		var pos_amp = QUERY_STRING.indexOf("&");
		if (pos_amp==-1) {
			pos_amp = QUERY_STRING.length;
		}
		var str = QUERY_STRING.substring(0,pos_amp);
		var pos_equal = str.indexOf("=");
		
		var key = str.substring(0,pos_equal);
		var val = str.substring(pos_equal+1,str.length);
		
		QUERY_STRING = QUERY_STRING.substring(pos_amp+1,QUERY_STRING.length);
		val = val.replace(/\+/g, " ");
		params[key] = unescape(val);
	}
	
	return params;
}

// params = GetUrlParams();

