/*
	mintajax.1.2.0.4
	www.mintajax.pl
	Copyright 2007 Piotr Korzeniewski
	Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
 
var mint = new Object();

mint.Request = function(url, target, OnSuccess, OnError)
{
	var req = {
		xmlHttpRequest : null,
		
		responseText : null,
		responseXML : null,
		responseJSON : null,
		
		getJSON : false,
		clearParams : true,
		clearHeader : true,
		
		params : new Array(),
		header : new Array(),
		
		group : null,
		
		url : null,
		async : true,
		method : "GET",
		encoding : "utf-8",
		contentType : "text/plain",
		username : "",
		password : "",
		
		form : null,
		disableForm : true,
		
		status : null,
		statusText : null,
		
		reqDone : false,
		retryCount : 0,
		retryNum : 3,
		timeout : 5000,
		
		OnStateChange : function() {},
		OnLoading : function() {},
		OnLoaded : function() {},
		OnInteractive : function() {},
		OnComplete : function() {},
		OnSuccess : function() {},
		OnError : function() {},
		OnAbort : function() {},
		OnRetry : function() {},
		OnTimeout : function() {},
		OnInsert : function() {},
		
		Send : function(url, target) {
			this.reqDone = false;
			
			if(window.XMLHttpRequest)
				this.xmlHttpRequest = new XMLHttpRequest();
			else if(window.ActiveXObject) {
				try	{
					this.xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e) {
					this.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				}
			}
			
			var paramStr = "";
			
			for(var i in this.params) {
				if(i != 0) paramStr += "&";
				paramStr += encodeURIComponent(this.params[i].name)+"="+encodeURIComponent(this.params[i].value);
			}
			
			if(url) this.url = url;
			
			if(this.method.toLowerCase() == "post")
				this.xmlHttpRequest.open(this.method.toUpperCase(), this.url, this.async, this.username, this.password);
			else
				this.xmlHttpRequest.open(this.method.toUpperCase(), this.url+(!/\?/.test(this.url) ? "?"+paramStr : "&amp;"+paramStr), this.async, this.username, this.password);
			
			for(var i in this.header)
				this.xmlHttpRequest.setRequestHeader(this.header[i].name, this.header[i].value);
			
			if(this.method.toLowerCase() == "post")
				this.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"+(this.encoding ? "; charset="+this.encoding : ""));
			else
				this.xmlHttpRequest.setRequestHeader("Content-Type", this.contentType);
				
			this.xmlHttpRequest.setRequestHeader("If-Modified-Since", "Sat, 11 Jan 1977 00:00:00 GMT");
			
			var that = this;
			
			this.xmlHttpRequest.onreadystatechange =
			function() {
				that.OnStateChange();
				
				switch(that.xmlHttpRequest.readyState) {
					case 1 : that.OnLoading(); break;
					case 2 : that.OnLoaded(); break;
					case 3 : that.OnInteractive(); break;
					case 4 : {
						that.OnComplete();
						
						try {
							if(that.xmlHttpRequest.status >= 200 && that.xmlHttpRequest.status < 300) {
								that.reqDone = true;
								
								that.responseText = that.xmlHttpRequest.responseText;
								that.responseXML = that.xmlHttpRequest.responseXML;
								
								that.status = that.xmlHttpRequest.status;
								that.statusText = that.xmlHttpRequest.statusText;
								
								if(target) $D(target).innerHTML = that.responseText;
								
								if(that.getJSON)
									that.responseJSON = eval("("+that.responseText+")");
									
								if(that.form && that.disableForm) {
									for(var i = 0; i < that.form.elements.length; ++i) {
										that.form.elements[i].disabled = false;
									}
								}
								
								if(that.group) {
									var groupDone = true;
									
									for(var i in that.group.req)
										if(!that.group.req[i].reqDone) groupDone = false;
										
									if(groupDone) {
										that.group.isRunning = false;
										that.group.OnDone(that);
									}
								}
								
								that.OnSuccess();
								
								if(that.clearParams) that.params.length = 0;
								if(that.clearHeader) that.header.length = 0;
							}
							else
								that.OnError(that.status);
						}
						catch (e) {
							that.OnError(-1);
						}	
						
						break;
					}
				}
			}
			
			if(this.group) {
				if(!this.group.isRunning) {
					this.group.isRunning = true;
					this.group.OnStart(this);
				}
			}
				
			if(this.method.toLowerCase() == "post")
				this.xmlHttpRequest.send(paramStr);
			else
				this.xmlHttpRequest.send(null);
			
			if(this.retryNum) {
				setTimeout(
						function() {
							if(!that.reqDone) {
								that.xmlHttpRequest.onreadystatechange = function() {};
								that.xmlHttpRequest.abort();
								that.OnTimeout();
								
								if(that.retryCount < that.retryNum) {
									that.retryCount++;
									that.Send();
									that.OnRetry();
								}
								else {
									that.retryCount = 0;
									that.OnAbort();
								}
							}
						},
						this.timeout);
			}
		},
		
		SendForm : function(form, url, method) {
			this.form = $D(form);
			
			this.url = url || this.form.action || this.url;
			this.method = method || this.form.method || "post";
			
			var input = this.form.elements;
			
			for(var i = 0; i < input.length; i++) {
				if(this.disableForm)
					input[i].disabled = true;
					
				switch(input[i].type) {
					case "radio":
					case "checkbox":
						if(input[i].checked)
							this.AddParam(input[i].name, input[i].value);
						break;
					case "select-one":
						this.AddParam(input[i].name, input[i].options[input[i].selectedIndex].value);
						break;
					case "select-multiple":
						for(var x = 0; x < input[i].options.length; ++x) {
							if(input[i].options[x].selected)
								this.AddParam(input[i].name, input[i].options[x].value);
						}
						break;
					default:
						this.AddParam(input[i].name, input[i].value);
				}
			}
			
			this.Send(this.url);
		},
		
		Set : function(name, value) {
			this[name] = value;
			return this;
		},
		
		AddParam : function(name, value) {
			this.params.push({name:name, value:value});
			return this;
		},
		
		RemoveParam : function(name) {
			for(var i in this.params) {
				if(this.params[i].name == name) {
					this.params.splice(i, 1);
					break;
				}
			}
			return this;
		},
		
		AddHeader : function(name, value) {
			this.params.push({name:name, value:value});
			return this;
		},
		
		RemoveHeader : function(name) {
			for(var i in this.header) {
				if(this.header[i].name == name) {
					this.header.splice(i, 1);
					break;
				}
			}
		}
	}
		
	if(OnSuccess && typeof OnSuccess == "function")
		req.OnSuccess = OnSuccess;
		
	if(OnError && typeof OnError == "function")
		req.OnError = OnError;
		
	if(url) target ? req.Send(url, target) : req.Send(url);
		
	return req;
};

mint.RequestGroup = function() {
	var group = {
		req : [],
		isRunning : false,
		
		OnStart : function() {},
		OnDone : function() {},
		
		Add : function() {
			for(var i = 0; i < arguments.length; ++i) {
				arguments[i].group = this;
				this.req.push(arguments[i]);
			}
		}
	}
	
	for(var i = 0; i < arguments.length; ++i)
		group.Add(arguments[i]);
	
	return group;
};

function $D(obj) {
	return (typeof obj == "string") ? document.getElementById(obj) : obj;
}
