/*
 * 
 *  JS API (Javascript Simplified API) ver. 0.2.0
 * 
 */

/**
 * 
 * 
 * jsx API
 * 
 * 
 */

/*
 * jsx Object
 * + jsx constants
 * used mostly for browser detecting
 */

var jsx = {
	version: '0.2.0',
	uA: navigator.userAgent.toLowerCase(),	
	_ie4: /msie 4/.test(navigator.userAgent.toLowerCase()),
	_ie5: /msie 5/.test(navigator.userAgent.toLowerCase()),
	_ie6: /msie 6/.test(navigator.userAgent.toLowerCase()),
	_ie7: /msie 7/.test(navigator.userAgent.toLowerCase()),
	_ie8: /msie 8/.test(navigator.userAgent.toLowerCase()),
	_gecko: /gecko/.test(navigator.userAgent.toLowerCase()),
	_safari: /safari/.test(navigator.userAgent.toLowerCase()),
	_opera: /opera/.test(navigator.userAgent.toLowerCase()),
	
	/*
	tags_all: 'a,abbr,acronym,address,applet,area,b,base,basefont,bdo,big,blockquote,body,br,button,caption,center,cite,code,col,colgroup,dd,del,dir,div,dfn,dl,dt,em,fieldset,font,form,frame,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,optgroup,option,p,param,pre,q,s,samp,script,select,span,strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,title,tr,tt,u,ul,var,xmp',
	tags_format: 'b,basefont,big,center,font,i,q,s,strike,strong,sub,sup,u',
	tags_applet: 'applet,param',
	tags_inputs: 'button,fieldset,input,label,legend,optgroup,option,select,textarea',
	tags_maintags: 'a,div,dd,dl,dt,img,li,ol,p,table,tbody,td,textarea,tfoot,th,thead,ul,span'
	*/
};

/*
 * jsx Object
 * + document.getElement(s)By(Id/TagName) wrapped
 */

/* @name: _
 * @desc: retrieves the object who's id name is `id`, contained by `element` object
 * 			if `element` object it not mentioned, it will be replaced by document object
 * @input: id / String - 
 * @input: element / Object
 */
jsx._ = function(id, element) 
	{ 
		if (!element)
			return document.getElementById(id); 
		else
			return element.getElementById(id);
	};
	
/* object.getElementsByTagName */	
jsx.__ = function(tagName, element) 
	{ 
		if (!element)
			return document.getElementsByTagName(tagName); 
		else
			return element.getElementsByTagName(tagName); 
	};

/* document.getElementByTagName + className filter */	
jsx.$ = function(classname, taglist) 
	{
		return this.$$(classname, taglist, document);
	};

/* object.getElementByTagName + className filter */	
jsx.$$ = function(classname, taglist, element)
	{
		elems = new Array();
		if (!taglist) taglist = this.tags_maintags;
		tags = taglist.split(/,/);
		for (i = 0; i < tags.length; i++) 
		{
			te = this.__(tags[i], element);
			for(j = 0; j < te.length; j++) if (te[j])
			{
				classes = te[j].className.split(" ");
				for (k = 0; k < classes.length; k++)
					if (classes[k] && classes[k] == classname)
					{
						elems[elems.length] = te[j];
						break;
					}
			}
		}
		return elems;
	};
	
/* js file loader */
jsx.loadClass = function(classname, srcpath) 
{
	s = document.createElement('script');
	s.type='text/javascript';
	s.language = 'javascript';
	s.src = srcpath + 'jsx.' + classname + '.js';
	jsx.__('head')[0].appendChild(s);
}


/*
 * jsx.Ajax
 * + jsx.AjaxRequest constants
 */

jsx.AjaxRequest = {
	_GET : 		'get',
	_POST : 	'post',
	_IMG :		'img',
	_JS :		'js'	/* not implemted yet - check Ajax.sendRequest */
}
/* 0.1 connection */ var AjaxRequest = jsx.AjaxRequest;

/*
 * jsx.Ajax
 * + jsx.AjaxResponse constants
 */

jsx.AjaxResponse = {
	UNSENT : 	0,	// 0 UNSENT
	OPEN :		1,	// 1 OPEN
	SENT :		2,	// 2 SENT
	LOADING : 	3,	// 3 LOADING 
	DONE :		4	// 4 DONE
}
/* 0.1 connection */ var AjaxResponse = jsx.AjaxResponse;

/*
 * jsx.Ajax
 * + jsx.Ajax constructor
 */

jsx.Ajax = function(ObjectName) {

	this.hash = {};	
	this.httpRequest = false;
	
	if (window.XMLHttpRequest){ // if !IE
		try {
			this.httpRequest = new XMLHttpRequest();
		} catch (e) {
			alert("Error [non IE / XMLHttpRequest]:\n " + e);
		}
		if (this.httpRequest.overrideMimeType) 
			this.httpRequest.overrideMimeType('text/xml');
	}
	else if (window.ActiveXObject){ // if IE
		try {
			this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) { 
				alert("Error [IE / Microsoft.XMLHTTP/Msxml2.XMLHTTP]:\n " + e); 
			}
		}
	}
	if (!this.httpRequest) {
		alert('Your browser does not support Ajax. Please select another browser.');
		return false;
	}
	this.ObjectName = ObjectName;
	this.ObjectVertion = "0.4 beta";
	this.handleResponse = null;

}

/*
 * jsx.Ajax
 * + jsx.Ajax prototype
 */

jsx.Ajax.prototype = {
	
	// XMLHttpRequest Functions
	open: function (method, url, async, user, password) {
		if (jsx.AjaxRequest._IMG == method || jsx.AjaxRequest._JS == METHOD)
		{
			alert('This `method` is supported only with sendRequest* method.');
			return;
		}
		this.httpRequest.open(method, url, async, user, password);
	},
	
	abort: function () { 
		this.abort(); 
	},
	
	setRequestHeader: function (header, value_) {
		this.httpRequest.setRequestHeader(header, value_);
	},
	
	send: function (data) {
		this.httpRequest.send(data);
	},
	
	getResponseHeader: function (header) {
		return this.httpRequest.getResponseHeader(header);
	},
	
	getAllResponseHeaders: function () {
		return this.httpRequest.getAllResponseHeaders();
	},
	
	// XMLHttpRequest _get Functions
	readyState: function () {
		return this.httpRequest.readyState;
	},
	
	responseText: function () {
		return this.httpRequest.responseText;
	},
	
	responseXML: function () {
		return this.httpRequest.responseXML;
	},
	
	status: function() {
		return this.status();
	},
	
	statusText: function () {
		return this.httpRequest.statusText;
	},
	
	// Ajax Added Functions	
	sendRequest: function( requestMethod, requestLink, requestParams, handleResponse, async, user, pass) {
		if (!this.httpRequest) {
			alert("Error in "+this.ObjectName+" object: \n No request object created.");
			return;
		}
		if (handleResponse != null) this.handleResponse = handleResponse;
		if ( this.handleResponse == null ) {
			alert("Error in "+this.ObjectName+" object: \n Ajax object has not requestHandle.");
			return;
		}		
		if (requestParams && requestParams.constructor == Array) {
			par = requestParams; 
			requestParams = "";
			for (i = 0; i < par.length; i++) if (par[i]) 
				if (par[i].constructor == Object) requestParams += "&" + par[i].name + "=" + par[i].value;
				else requestParams += "&" + i + "=" + par[i];
		}
		requestParams += "&ajax4time=" + new Date().getTime();
		//alert(requestLink+((requestLink.indexOf("?") < 0)?"?":"")+requestParams);
		//alert(requestMethod);
		//
		// IMG
		//
		if (requestMethod == AjaxRequest._IMG)  {
			img = document.createElement('img');
		    img.onload = this.handleResponse;
		    img.src = requestLink+((requestLink.indexOf("?") < 0)?"?":"")+requestParams;
		} else
		//
		// POST
		//
		if (requestMethod == AjaxRequest._POST) {
			try {
				this.httpRequest.onreadystatechange = this.handleResponse;
				this.httpRequest.open(requestMethod, requestLink, async, user, pass);
				this.httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.httpRequest.setRequestHeader("Content-length", requestParams.length);
				this.httpRequest.setRequestHeader("Connection", "close");
				this.httpRequest.send(requestParams);
			} catch (e) {
				alert("Error in "+this.ObjectName+" object: \n" + e);
			}
		// GET or anything else
		} else 
			try {
				this.httpRequest.onreadystatechange = this.handleResponse;
				this.httpRequest.open(requestMethod, requestLink+((requestLink.indexOf("?") < 0)?"?":"")+requestParams, async, user, pass);
				this.httpRequest.send("");
			} catch (e) {
				alert("Error in "+this.ObjectName+" object: \n" + e);
			}
	},
	
	sendRequest_POST: function (requestLink, requestParams, handleResponse) {
		this.sendRequest(AjaxRequest._POST, requestLink, requestParams, handleResponse, true);
	},

	sendRequest_GET: function (requestLink, requestParams, handleResponse) {
		this.sendRequest(AjaxRequest._GET, requestLink, requestParams, handleResponse, true);
	},
	
	sendRequest_IMG: function (requestLink, requestParams, handleResponse) {
		this.sendRequest(AjaxRequest._IMG, requestLink, requestParams, handleResponse, true);
	}
}

var Ajax = jsx.Ajax;

/**
 * 
 *  Standard Global Objects eXtentions
 * 
 */


/*
 * Object
 */

Object.prototype.inspect = 
	function(obj) {
		try {
			if (obj === undefined) { return 'undefined'; }
			else if (obj === null) { return 'null'; }
			else { return obj.toString(); }
		} catch (err) {
			if (err instanceof RangeError) { return ' '; }
			throw err;
		}
	};

//
// does not work on IE lte 6
// not tested on IE 7
//
Object.prototype.add_propertries = 
	function(propertry, value) {
		if (propertry.constructor == Array) {
			try {
				for (p in propertry) { 
					if (propertry[p]) { this[propertry[p]] == value[p]; }
				}
			} catch (err) {
				throw err;
			}
		} else {
			try {
				this[propertry] = value;
			} catch (err) {
				throw err;
			}
		}
	};

//
// should work on everything
//	
Object.prototype.add_propertries_to = 
	function(propertry, value, toObj) {
		if (Object.inspect(toObj) == 'undefined' || Object.inspect(toObj) === null) { return; }
		if (propertry.constructor == Array) {
			try {
				for (p in propertry) {
					if (propertry[p]) { toObj[propertry[p]] == value[p]; }
				}
			} catch (err) {
				throw err;
			}
		} else {
			try {
				toObj[propertry] = value;
			} catch (err) {
				throw err;
			}
		}
	};
	
//
// does not work on IE lte 6
// not tested on IE 7
//
Object.prototype.add_event = 
	function(propertry, value) {
		try {
			this[propertry] = value;
		} catch (err) {
			throw err;
		}
	};

//
// should work on everything
//	
Object.prototype.add_event_to = 
	function(propertry, value, toObj) {
		if (Object.inspect(toObj) == 'undefined' || Object.inspect(toObj) === null) { return; }
		try {
			toObj[propertry] = value;
		} catch (err) {
			throw err;
		}
	};

/*
 * Array
 */

Array.prototype = {};

/*
 * String
 */

String.prototype.replaceAll = 
	function (pattern, value) {
		s = pattern.toString();
		if (s.indexOf("/") != 0) throw "String.replaceAll(pattern, value): "+s+" is not RegExp";
		if (s.match(/\/[a-z]*g[a-z]*$/)) { return this.replace(pattern, value); }
		else { s += 'g'; }
		//return "["+s.substr(1, s.lastIndexOf("/") - 1)+"|"+s.substr(s.lastIndexOf("/") + 1, s.length)+"]";
		r = new RegExp(s.substr(1, s.lastIndexOf("/") - 1), s.substr(s.lastIndexOf("/") + 1, s.length));
		return this.replace(r, value);
	};
	
String.prototype.matchAll = 
	function (pattern) {
		s = pattern.toString();
		if (s.indexOf("/") != 0) throw "String.replaceAll(pattern, value): "+s+" is not RegExp";
		if (s.match(/\/[a-z]*g[a-z]*$/)) { return this.match(pattern); }
		else { s += 'g'; }
		r = new RegExp(s.substr(1, s.lastIndexOf("/") - 1), s.substr(s.lastIndexOf("/") + 1, s.length));
		return this.match(r);
		//*/
	};
	
String.prototype.isInt = 
	function () {
		return ((!isNaN(parseInt(this))) ? true : false);
	};
	
String.prototype.isFloat = 
	function () {
		return (!isNaN(parseFloat(inputString))) ? true : false;
	};
	
String.prototype.isNumber = 
	function () {
		return (this.isInt() || this.isFloat());
	};
	
String.prototype.htmlEncodeString = 
	function () {
		return escape(this);
	};

String.prototype.htmlUnencodeString =
	function () {
		return unescape(this);
	};

/*
 * Number
 */

Number.prototype.toHEX = 
	function (value) {
		if (!value) value = this;
		dec = value;
		hexStr = "0123456789ABCDEF";
		low = dec % 16;
		high = (dec - low)/16;
		hex = "" + hexStr.charAt(high) + hexStr.charAt(low);
		return hex;
	};
	
Number.prototype.fromHEX = 
	function (value) {
		return parseInt(value, 16);
	};

/*
 * Date
 */

Date.prototype = {};

/*
 * Function
 */

Function.prototype = {};

/***
 *** RegExp Class Extend
 ***/

RegExp.prototype = {};

/*
 * Boolean
 */

Boolean.prototype = {}

/**
 * 
 * DOM Window, Document eXtensions
 * 
 */

/*
 * DOM Window
 */

window.getSize = function(){
	if (!jsx.IE_BROWSER) 
		return {
			Width: document.body.clientWidth,
			Height: document.body.clientHeight
		};
	else 
		if (jsx._ie6 || jsx._ie7) 
			return {
				Width: document.documentElement.clientWidth,
				Height: document.documentElement.clientHeight
			};
		else 
			return {
				Width: document.body.clientWidth,
				Height: document.body.clientHeight
			};
  }
//		wWidth  = document.body.clientWidth;
//		wHeight = document.body.clientHeight;
//		return { Width: wWidth, Height: wHeight }

window.getSizeWithScrolBar = 
	function () {
		wWidthScrollBar  = (jsx.IE_BROWSER) ? document.documentElement.offsetWidth  : undefined;
		wHeightScrollBar = (jsx.IE_BROWSER) ? document.documentElement.offsetHeight : undefined
		return { Width: wWidthScrollBar, Height: wHeightScrollBar }
	}

/*
 * DOM Document
 */

/* Mouse Extension */

MouseButtons = {
	BUTTON_LEFT: 1,
	BUTTON_RIGHT: 2,
	BUTTON_CENTER: 3
}

document.getMouseButton = 
	function(e) {
		if (jsx.IE_BROWSER) {
			//return event.button;
			switch (event.button) {
				case 1: return 1; break
				case 2: return 3; break
				case 4: return 2; break
			}
		}
		else if (!jsx.IE_BROWSER && e) return e.which;
		return -1;
	}

document.getMousePos = 
	function(e) {
		if (jsx.IE_BROWSER) {
			mX = event.clientX + document.body.scrollLeft
			mY = event.clientY + document.body.scrollTop
		} else {
			mX = e.pageX;
			mY = e.pageY;
		}
		return { X: mX, Y: mY }
	}

/* KeyPad Extension */
	
KeyValues = {
	KEY_BACKSPACE:	8,
	KEY_ENTER:		13,
	KEY_ALT:		18,
	KEY_CTRL:		17,
	KEY_SHIFT:		16,
	KEY_UP:			38,
	KEY_DOWN:		40,
	KEY_LEFT:		37,
	KEY_RIGHT:		39,
	KEY_END:		35,
	KEY_HOME:		36,
	KEY_PGUP:		33,
	KEY_PGDOWN:		34,
	KEY_DEL:		46,
	KEY_INS:		45
}

document.getKeyPressed = 
	function (e) {
		if (!e) e = event;
		if (e.charCode) return e.charCode;
		else return e.keyCode;
	}

document.getSize = 
	function () {
		if (jsx.IE_BROWSER) 
			return {
				Width: document.body.clientWidth,
				Height: document.body.clientHeight
			};
		return {
			Width: document.documentElement.scrollWidth || document.body.scrollWidth,
			Height: document.documentElement.scrollHeight || document.body.scrollHeight
		};
	}
	
document.getScroll = 
//var scrOfX = 0, scrOfY = 0;
//  if( typeof( window.pageYOffset ) == 'number' ) {
//    //Netscape compliant
//    scrOfY = window.pageYOffset;
//    scrOfX = window.pageXOffset;
//  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//    //DOM compliant
//    scrOfY = document.body.scrollTop;
//    scrOfX = document.body.scrollLeft;
//  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//    //IE6 standards compliant mode
//    scrOfY = document.documentElement.scrollTop;
//    scrOfX = document.documentElement.scrollLeft;
//  }
//  return [ scrOfX, scrOfY ];
	function() {
		if( !jsx.IE_BROWSER ) {
			// !IE
			this.scrollY = window.pageYOffset;
			this.scrollX = window.pageXOffset;
		} else {
			// IE
			this.scrollY = document.body.scrollTop || document.documentElement.scrollTop;
			this.scrollX = document.body.scrollLeft || document.documentElement.scrollLeft;
		}
		return { X: this.scrollX, Y: this.scrollY };
	}

/* Environmental Extension */

document.envGET = 
	function (id) {
		url = (location)?location.href:((document.location)?document.location:window.location);
		url = String(url);
		url = url.substr(url.indexOf("?")+1);
		url = url.split("&");
		for (i = 0; i < url.length; i++) {
			url[i] = url[i].split("=");
			if (id && url[i][0] == id) return url[i][1];
		}
		if (id) return undefined;
		else return url;
}

document.envCookie = 
	function (id) {
		tx = id + "=";
		cookies = document.cookie.split(";");
		for (i = 0; i < cookies.length; i++)
			if (cookies[i].indexOf(tx) > -1) 
				return cookies[i].replace(new RegExp(tx, "i"), "");
		return null;
	}
	
document.envCookie_set = 
	function (name, value, hours) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(hours*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
document.envCookie_detele = 
	function (name) {
		document.envCookie_set(name, "", -1);
	}
