// Copyright (C) 2007-2008 Stephane Lavergne <http://www.imars.com/>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.

// Network I/O library
imars.net = {

	// FIXME: encodeURIComponent() appeared in JavaScript 1.5, implemented on
	// MSIE's side in version 5.5. Old enough for our use.  See YUI for
	// crawling a form safely to transform into POST. Not needed for now...

	// Async GET/POST via XMLHttpRequest.
	// If specified, callback_obj may provide net_response() and/or net_error().
	// Returns true on success, false on any error.
	post: function(url, body, bodymime, callback_obj, callback_cookie) {
		var req = false;
		if (typeof(XMLHttpRequest) != 'undefined') req = new XMLHttpRequest();
		else {
			// Try the old MSIE ways...
			try { req = new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {
				try { req = new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {
					try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {
						try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {
							req = false;
						};
					};
				};
			};
		};
		if (!req) {
			return false;
		};

		if (body) {
			req.open("POST", url, true);
			req.setRequestHeader("Content-Type", bodymime ? bodymime : "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-Length", body.length);
			req.setRequestHeader("Connection", "close");
			req.send(body);
		} else {
			req.open("GET", url, true);
			req.send(null);
		};
		done = false;
		req.onreadystatechange = function () {
			if ((req.readyState == 4) && (done == false)) {
				// Some browsers erroneously call this twice.
				done = true;
				if (req.status == 200) {
					if (callback_obj.net_response) {
						// FIXME: Remove anything starting at ';' from Content-Type.
						callback_obj.net_response(callback_cookie, req.responseText, req.getResponseHeader('Content-Type'));
					};
				} else {
					if (callback_obj.net_error) {
						callback_obj.net_error(callback_cookie);
					};
				};
				return true;
			};
		};

		return false;
	},

	// Shortcut for post() without a body.
	get: function(url, callback_obj, callback_cookie) {
		return imars.net.post(url, null, null, callback_obj, callback_cookie);
	}

};
