/**
* Filename................: mel.xhr.js
* Project.................: web pages SDK
* Last Modified...........: $Date: 4/7/2007 16:40:11 $
* CVS Revision............: $Revision: 0.0.2 $
* Idea and Developed by...: Maxim Bulygin (sailormax@gmail.com)
*/

if (typeof MEL == "undefined") var MEL = {};

// unicode functions
	MEL.xhr = {

		cfg: {
			STATUS_MSG: "Loading..."
		},

		createXHR: function()
		{
			var res = null;
			if (typeof XMLHttpRequest == "undefined")
			{
				var i, objs = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
				for (i in objs)
					try { if (res = new ActiveXObject(objs[i])) break; } catch (e) {}
			}
			else
				res = new XMLHttpRequest();

			return res;
		},


		sendXHR: function()
		{
			if (this.request)
			{
				var self = this;
				this.request.onreadystatechange = function()
				{
					/*
						this.req.readyState:
						0 = uninitialized
						1 = loading
						2 = loaded
						3 = interactive
						4 = complete
					*/
					if (self.request.readyState == 4)
					{
						if (self.request.status == 200)
						{
							if (typeof self.resp_func == "function")
								self.resp_func(self.request.responseText, self.resp_param);

//							if (!MEL.ua.mozilla) self.request.abort();	// ff 1.0.x recursion bug
							self.request.abort();
//							self.request = null;
//							self.request = self.createXHR();
						}
						else if (typeof self.error_func == "function")
							self.error_func(self.request.status, self.request.statusText);
						else if (self.request.status == 404)
							alert("Error: URL doesn't exist!");
						else
							alert("Error: " + self.request.statusText);

						if (MEL.statusBar)
							MEL.statusBar.hide();
					}
				};

				this.request.open(this.method, this.url, this.async);

				if (this.method.toLowerCase() == "post")
					this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

				this.request.setRequestHeader("Content-length", (typeof this.vars == "string" ? this.vars.length : 0));
//				this.request.setRequestHeader("Connection", "close");
				try
				{
					this.request.send(this.vars);
					if (this.cfg.STATUS_MSG && MEL.statusBar)
						MEL.statusBar.show(this.cfg.STATUS_MSG);					
				}
				catch (e)
				{
					if (typeof this.error_func == "function")
						this.error_func(e.name, e.message);
					else
						alert(e.name + ": " + e.message);
				}
				return 0;
			}
			return this.request;
		},


		Create: function(url, method, vars, resp_func, error_func)
		{
			if (typeof method == "undefined") method = "GET";
			var obj = {};

			obj.cfg			= this.cfg;

			obj.url			= url;
			obj.resp_func	= resp_func;
			obj.error_func	= error_func;

			obj.async		= true;
			obj.method		= method;
			obj.vars		= vars;
			obj.resp_param	= null;

			obj.request		= this.createXHR();
			obj.send		= this.sendXHR;

			return obj;
		}

	}
//

