
/*
Copyright 2007 Piotr Korzeniewski www.mintAjax.pl

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.
*/

// mintAjax version 1.0.1
 
var mint =
{
	Request : function()
	{
		var newRequestObject =
		{
			xmlHttpRequest : null,

			responseText : null,
			responseXML : null,
			responseJSON : null,
			getJSON : false,

			params : new Array(),

			url : "",
			async : true,
			method : "GET",
			contentType : "text/plain",
			username : "",
			password : "",

			form : null,
			disableForm : true,
			
			status : null,
			statusText : null,

			reqDone : false,
			retryCount : 0,
			retryNum : 0,
			timeout : 5000,

			OnStateChange : function() {},
			OnLoading : function() {},
			OnLoaded : function() {},
			OnInteractive : function() {},
			OnComplete : function() {},
			OnSuccess : function() {},
			OnError : function() {},
			OnAbort : function() {},
			OnRetry : function() {},
			OnTimeout : function() {},

			Send : function(url, target)
			{
				var paramStr = "";

				this.reqDone = false;

				!url ? url = this.url : this.url = url;

				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");
					}
				}

				for(var i in this.params)
				{
					if(i != 0)
						paramStr += "&";

					paramStr += this.params[i].name+"="+this.params[i].value;
				}

				if(this.method == "post")
					this.xmlHttpRequest.open(this.method, url, this.async, this.username, this.password);
				else
					this.xmlHttpRequest.open(this.method, url+(!/\?/.test(url) ? "?"+paramStr : "&;"+paramStr), this.async, this.username, this.password);
					
				try {
				if(this.method == "post")
					this.xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				else
					this.xmlHttpRequest.setRequestHeader("Content-Type", this.contentType);
				} catch(e) {}
					
				try {
					this.xmlHttpRequest.setRequestHeader("If-Modified-Since", "Sat, 11 Jan 1977 00:00:00 GMT");
				} catch(e) {}

				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();

							if(that.xmlHttpRequest.status == 200)
							{
								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)
									$(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;
									}
								}

								that.OnSuccess();
							}
							else
								that.OnError(that.xmlHttpRequest.status);

							break;
					}
				}
					
				if(this.method == "post")
					this.xmlHttpRequest.send(paramStr);
				else
					this.xmlHttpRequest.send(null);

				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);

				this.params.length = 0;
			},

			SendForm : function(form, url, method)
			{
				this.form = $(form);

				method ? this.method = method : this.method = this.form.method

				if(!url) url = this.form.action;

				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(url);
			},

			AddParam : function(name, value)
			{
				var newParam =
				{
					name : name,
					value : value
				}

				this.params.push(newParam);
			}
		}

		return newRequestObject;
	}
};

function AddEvent(obj, type, handler)
{
	obj = $(obj);

	if(!obj.events)
		obj.events = new Array();
		
	if(!obj.events["on"+type])
		obj.events["on"+type] = new Array();

	obj.events["on"+type].push(handler);

	obj["on"+type] =
	function(event)
	{
		event = event || window.event;
	
		var returnValue = true;
		var eventHandlers = this.events["on"+event.type];

		if(eventHandlers)
		{
			for(var i in eventHandlers)
			{
				this.$eventHandler = eventHandlers[i];
				returnValue = this.$eventHandler(event);
			}
		}
	
		return returnValue;
	}
}

function RemoveEvent(obj, type, handler)
{
	obj = $(obj);
	
	var eventHandlers = obj.events["on"+type];

	for(var i in eventHandlers)
	{
		if(eventHandlers[i] == handler)
		{
			eventHandlers.splice(i, 1);
			return true;
		}
	}
	
	return false;
}

function GetEventTarget(event)
{
	return event.target || event.srcElement;
}

function GenerateID()
{
	return new Date().getTime().toString();
}

function GetPos(obj)
{
	obj = $(obj);

	if(obj.style.position == "absolute")
	{
		if(window.getComputedStyle)
			return {'x':parseInt(getComputedStyle(obj, "").getPropertyValue("left")), 'y':parseInt(getComputedStyle(obj, "top").getPropertyValue("top"))};
		else if(obj.currentStyle)
			return {'x':parseInt(obj.currentStyle.left), 'y':parseInt(obj.currentStyle.top)};
	}

	var x = obj.offsetLeft, y = obj.offsetTop, marginLeft = 0, marginTop = 0;

	if(window.getComputedStyle)
	{
		marginLeft = parseInt(getComputedStyle(obj, "").getPropertyValue("margin-left"));
		marginTop = parseInt(getComputedStyle(obj, "").getPropertyValue("margin-top"));
	}
	else if(obj.currentStyle)
	{
		marginLeft = parseInt(obj.currentStyle.marginLeft);
		marginTop = parseInt(obj.currentStyle.marginTop);
	}

	while(obj = obj.offsetParent)
	{
		x += obj.offsetLeft - obj.scrollLeft;
		y += obj.offsetTop - obj.scrollTop;
	}

	if(marginLeft) x -= marginLeft;
	if(marginTop) y -= marginTop;

	return {'x':x, 'y':y};
}

function GetX(obj)
{
	return GetPos(obj).x;
}

function GetY(obj)
{
	return GetPos(obj).y;
}


function SetPos(obj, x, y)
{
	SetX(obj, x);
	SetY(obj, y);
}

function GetSize(obj)
{
	return {'width':GetWidth(obj), 'height':GetHeight(obj)};
}

function GetOpacity(obj)
{
	obj = $(obj);

	if(obj.style.opacity)
		return Math.round(obj.style.opacity*100);
	else if(obj.style.filter)
		return Math.round(/\d+/.exec(obj.style.filter)[0]);
	else
		return 100;
}

function IsInside(obj, x, y)
{
	obj = $(obj);
	var pos = GetPos(obj); size = GetSize(obj);

	if(pos.x < x && pos.x+size.width > x && pos.y < y && pos.y+size.height > y)
		return true;

	return false;
}

function GetChildAtPos(obj, x, y)
{
	var child = $(obj).childNodes;

	for(var i = 0; i < child.length; i++)
	{
		if(child[i].nodeName != "#text" && IsInside(child[i], x, y))
			return child[i];
	}

	return null;
}

function HexToRGB(hex)
{
	hex = hex.replace(/#/, "");

	return {	r: parseInt(hex.substring(0, 2), 16),
				g: parseInt(hex.substring(2, 4), 16),
				b: parseInt(hex.substring(4, 6), 16)};
}
