/**
 * Copyright © 2009 This file belongs to a series of files that comprise the
 * Framework Goaamb within the area of utilities and javascript.
 * 
 * This file as well as the components of the framework are protected under
 * license LGPLv3 (http://www.gnu.org/licenses/lgpl-3.0.html), being possible to
 * distribute this product but you can not change it without my permission (
 * Goaamb). If this file is changed without authorization or not to preserve the
 * copyrights will break the license of this file or others making up the
 * Framework
 * 
 * @author Goaamb<goaamb@gmail.com>
 * 
 */
/**
 * Container package module belonging to Javascript Framework Goaamb
 */
var G = {
	cookie : {
		get : function(c_name) {
			if (document.cookie.length > 0) {
				c_start = document.cookie.indexOf(c_name + "=");
				if (c_start != -1) {
					c_start = c_start + c_name.length + 1;
					c_end = document.cookie.indexOf(";", c_start);
					if (c_end == -1)
						c_end = document.cookie.length;
					return unescape(document.cookie.substring(c_start, c_end));
				}
			}
			return "";
		},
		set : function(c_name, value, expiredays) {
			var exdate = new Date();
			exdate.setDate(exdate.getDate() + expiredays);
			document.cookie = c_name
					+ "="
					+ escape(value)
					+ ((expiredays == null) ? "" : ";expires="
							+ exdate.toGMTString());
		}
	},
	url : {
		_GET : function(str) {
			var url = location.href.split("?");
			if (url.length > 1) {
				var pars = url[1].split("&");
				for ( var i = 0; i < pars.length; i++) {
					var vari = pars[i].split("=");
					if (vari.length > 1 && vari[0] === str) {
						var varx = vari[1].split("#");
						return varx[0];
					}
				}
			}
			return false;
		},
		_setGET : function(par, val, url) {
			if (!url) {
				url = location.href;
			}
			url = url.split("#");
			url = url[0];
			url = url.split("?");
			if (url.length > 1) {
				var pars = url[1].split("&");
				var entro = false;
				for ( var i = 0; i < pars.length; i++) {
					var vari = pars[i].split("=");
					if (vari.length > 1 && vari[0] === par) {
						var varx = vari[1].split("#");
						varx[0] = val;
						vari[1] = varx.join("#");
						entro = true;
					}
					pars[i] = vari.join("=");
				}

				url[1] = pars.join("&");
				var adicional = "";
				if (!entro) {
					adicional = "&" + par + "=" + val;
				}
				return url.join("?") + adicional;
			}
			return url[0] + "?" + par + "=" + val;
		}
	},
	/**
	 * Dom object that lets you work with DOM elements and functions a bit
	 * smaller and optimal
	 */
	dom : {
		/**
		 * function that obtains the DomElement by id
		 * 
		 * @param {String}
		 *            id Id of a tag inside HTML code
		 * @return returns the DomElement that have the ID
		 * @type {Document}
		 */
		$ : function(id) {
			if (!id) {
				return false;
			}
			return document.getElementById(id);

		},
		/**
		 * function that obtains the unique or list of DomElements by name
		 * 
		 * @param {String}
		 *            name Name of the DomElement
		 * @param {Integer}
		 *            position position in the list of DomElements
		 * @return returns the DomElement that have the Name
		 * @type {Array|Document}
		 */
		$$ : function(name, position) {
			if (!name) {
				return false;
			}
			var list = document.getElementsByName(name);
			return position >= 0 ? list[position] : list;
		},
		/**
		 * function that obtains the unique or list of DomElements by the tag
		 * name
		 * 
		 * @param {String}
		 *            tagname the Tag Name of the DomElement
		 * @param {Integer}
		 *            position position in the list of DomElements
		 * @param {Document}
		 *            doc A DomElement container of other DomElements
		 * @return returns the DomElement that have the Tag Name
		 * @type {Array|Document}
		 */
		$$$ : function(tagname, position, doc) {
			if (!tagname) {
				return false;
			}
			if (!doc) {
				doc = document;
			}
			if (doc.getElementsByTagName) {
				var list = doc.getElementsByTagName(tagname);
				return position >= 0 ? list[position] : list;
			}
			return false;
		},
		/**
		 * function that create a DOMElement by a tagname
		 * 
		 * @param {String}
		 *            tagname the Tag Name for the DomElement
		 * @param {String}
		 *            id identifier of the new DomElement
		 * @param {String}
		 *            name name of the new DomElement
		 * @param {String}
		 *            value name of the new DomElement in case of have value
		 *            attribute
		 * @return returns the new DomElement by Tag Name
		 * @type {Document}
		 */
		create : function(tagname, id, name, value) {
			if (tagname) {
				var el = document.createElement(tagname);
				if (id) {
					el.id = id;
				}
				if (name) {
					el.name = name;
				}
				if (typeof value !== "undefined") {
					el.value = value;
				}
				return el;
			}
			return false;
		},
		createSelect : function(id, name) {
			var s = this.create("select", id, name);
			s.addOption = function(v, t) {
				var o = G.dom.create("option", "", "", v);
				o.innerHTML = t;
				this.appendChild(o);
			};
			s.clear = function() {
				this.innerHTML = "";
			};
			s.removeByPos = function(pos) {
				this.removeChild(this.children[pos]);
			};
			s.removeByValue = function(value) {
				var c = this.children;
				for ( var i = 0; i < c.length; i++) {
					if (c[i].value === value) {
						this.removeChild(c[i]);
					}
				}
			};
			return s;
		},
		parseSelect : function(s) {
			if (s) {
				var ss = this.createSelect();
				s.addOption = ss.addOption;
				s.clear = ss.clear;
				s.removeByPos = ss.removeByPos;
				s.removeByValue = ss.removeByValue;
			}
		},
		createTable : function(id, name) {
			var table = this.create("table", id, name);
			table.addColumn = function(el, f, c) {
				if (!this.tbody) {
					this.tbody = G.dom.create("tbody");
					this.appendChild(this.tbody);
				}
				if (!this.rowsx) {
					this.rowsx = G.dom.$$$("tr", -1, this.tbody);
				}
				var rows = this.rowsx;
				if (f === undefined) {
					f = rows.length;
				}
				if (rows.length <= f) {
					var min = rows.length;
					var max = f;
					for ( var i = min; i <= max; i++) {
						this.tbody.appendChild(G.dom.create("tr"));
					}
					this.rowsx = G.dom.$$$("tr", -1, this.tbody);
					rows = this.rowsx;
				}
				if (!rows.colsx) {
					rows[f].colsx = G.dom.$$$("td", -1, rows[f]);
				}
				var cols = rows[f].colsx;
				if (c === undefined) {
					c = cols.length;
				}
				if (cols.length <= c) {
					var min = cols.length;
					var max = c;
					for ( var i = min; i <= max; i++) {
						rows[f].appendChild(G.dom.create("td"));
					}
					rows[f].colsx = G.dom.$$$("td", -1, rows[f]);
					cols = rows[f].colsx;
				}
				G.dom.appendChild(cols[c], el);
				return cols[c];
			};
			return table;
		},
		/**
		 * function that create a TextElement
		 * 
		 * @param {String}
		 *            value of the Text
		 * @return returns the new TextElement
		 * @type {TextElemnt}
		 */
		createText : function(value) {
			if (!value) {
				value = "";
			}
			return document.createTextNode(value);
		},
		/**
		 * function append a child inside the tree of the Element
		 * 
		 * @param {DomElement}
		 *            element Element to append a child
		 * @param {String|DomElement}
		 *            child for append the element
		 */
		appendChild : function(element, child) {
			if (element) {
				if (!child.appendChild) {
					element.appendChild(this.createText(child));
				} else {
					element.appendChild(child);
				}
			}
		},
		_ : function(regla) {
			var st = document.styleSheets;
			if (st) {
				G.util.listAtt(st[0]);
				for ( var i = 0; i < st.length; i++) {
					var r;
					if (st[i].cssRules) {
						r = st[i].cssRules;
					} else if (st[i].rules) {
						r = st[i].rules;
					}
					alert(r.length);
				}
			}
			return false;
		},
		query : function() {

		}
	},
	util : {
		setDate : function(field, type) {
			if (this.form && this.form[field]) {
				var v = this.value >= 10 ? this.value : "0" + this.value;
				var f = this.form[field].value;
				var p = /\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}/;
				if (!p.test(f)) {
					this.form[field].value = f = "0000-00-00 00:00";
				}
				switch (type) {
				case "d":
					f = f.substring(0, 8) + v + f.substring(10);
					break;
				case "m":
					f = f.substring(0, 5) + v + f.substring(7);
					break;
				case "y":
					f = v + f.substring(4);
					break;
				case "h":
					f = f.substring(0, 11) + v + f.substring(13);
					break;
				case "i":
					f = f.substring(0, 14) + v;
					break;
				}
				this.form[field].value = f;
			}
		},
		explodeDate : function(fday, fmonth, fyear, fhour, fminute) {
			if (this.form) {
				var v = this.value;
				var p = /(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})/;
				if (!p.test(v)) {
					return true;
				}
				var $res = v.match(p);
				if (this.form[fday]) {
					this.form[fday].value = parseInt($res[3], 10);
				}
				if (this.form[fmonth]) {
					this.form[fmonth].value = parseInt($res[2], 10);
				}
				if (this.form[fyear]) {
					this.form[fyear].value = parseInt($res[1], 10);
				}
				if (this.form[fhour]) {
					this.form[fhour].value = parseInt($res[4], 10);
				}
				if (this.form[fminute]) {
					this.form[fminute].value = parseInt($res[5], 10);
				}
				return true;
			}
			return true;
		},
		parse : function(source, target, notreplace) {
			if (source && target) {
				try {
					for ( var i in source) {
						if (target[i] && notreplace) {
							continue;
						}
						target[i] = source[i];
					}
					return true;
				} catch (e) {
					return false;
				}
			}
			return false;
		},
		listAtt : function(obj) {
			if (obj) {
				var text = "";
				for ( var id in obj) {
					text += "<b>" + id + "</b>: " + obj[id] + "<br/>";
				}
				ventana = window.open("", "",
						"width=300,height=300,scrollbars=yes");
				ventana.document
						.write("<html><head><title>Looking a object</title></head><body>"
								+ text + "<body></html>");
				ventana.focus();
			}
		},
		ready : function(fn) {
			if (fn) {
				G.event.addEvent(window, "load", fn);
			}
		},
		trim : function(t) {
			return t ? t.replace(/^\s+/, "").replace(/\s+$/, "") : "";
		},
		getExt : function(t) {
			var pos = t.lastIndexOf(".");
			return t.substring(pos + 1);
		},
		arraySearch : function(a, t, c) {
			for ( var i = 0; i < a.length; i++) {
				if (c) {
					a[i] = a[i].toLowerCase();
					t = t.toLowerCase();
				}
				if (a[i] == t) {
					return i;
				}
			}
			return -1;
		},
		includeJS : function(src) {
			var h = G.dom.$$$("head", 0);
			if (h) {
				var scrs = G.dom.$$$("script", -1, h);
				if (scrs) {
					var pos = -1;
					for ( var i = 0; i < scrs.length && pos === -1; i++) {
						if (scrs[i].src === src) {
							pos = i;
						}
					}
					if (pos === -1) {
						var tscr = G.dom.create("script");
						tscr.src = src;
						h.appendChild(tscr);
					}
				} else {
					var tscr = G.dom.create("script");
					tscr.src = src;
					h.appendChild(tscr);
				}
			}
		}
	},
	ajax : function(object) {
		this.accion = undefined;
		this.erroraccion = undefined;
		this.TEXT = undefined;
		this.XML = undefined;
		this.JSON = undefined;
		this.pagina = undefined;
		this.post = undefined;
		this.get = undefined;
		this.json = false;
		this.el = undefined;
		if (object) {
			G.util.parse(object, this);
		}

		this.darObjectoAJAX = function() {
			var xmlhttp = false;
			if (typeof ActiveXObject != 'undefined') {
				try {
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (E) {
						xmlhttp = false;
					}
				}
			}
			if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
				xmlhttp = new XMLHttpRequest();
			}
			return xmlhttp;
		};
		this.xmlhttp = this.darObjectoAJAX();

		this.direccionLocal = function() {
			var dirlocal = document.location.href.split("http://");
			if (dirlocal.length > 1) {
				dirlocal = dirlocal[1].split("/");
				if (dirlocal.length > 0) {
					dirlocal = dirlocal[0].toLowerCase();
				} else {
					return false;
				}
				var dirpagina = this.pagina.split("http://");
				if (dirpagina.length > 1) {
					dirpagina = dirpagina[1].split("/");
					if (dirpagina.length > 0) {
						dirpagina = dirpagina[0].toLowerCase();
						if (dirpagina === dirlocal) {
							return true;
						} else {
							window.open(this.pagina);
						}
					}
				} else {
					return true;
				}
			}
			return false;
		};
		this.cancelar = function() {
			if (this.enviado) {
				this.xmlhttp.abort();
			}
		};

		this.enviar = function() {
			if (this.pagina && this.direccionLocal()) {
				var method = "post";
				if (this.get) {
					method = "get";
				}
				var envio = false;
				if (this.post) {
					envio = "";
					for ( var el in this.post) {
						envio += "&" + el + "=" + this.post[el];
					}
				}
				if (this.get) {
					this.pagina += "?";
					for ( var el in this.get) {
						this.pagina += "&" + el + "=" + this.get[el];
					}
				}
				this.xmlhttp.open(method, this.pagina, true);
				if (method === "post") {
					this.xmlhttp.setRequestHeader("Content-Type",
							"application/x-www-form-urlencoded");
				}
				if (envio) {
					this.xmlhttp.send(envio);
					this.enviado = true;
				} else {
					this.xmlhttp.send("");
					this.enviado = true;
				}
			}
		};
		this.recibir = function(id) {
			var el;
			if (typeof id === "string") {
				el = G.dom.$(id);
			} else if (id && id.appendChild) {
				el = id;
			}
			if (el) {
				this.el = el;
				this.viejaAccion = this.accion;
				this.accion = function() {
					this.el.innerHTML = this.TEXT;
					if (this.viejaAccion) {
						this.viejaAccion();
					}
				};
				this.enviar();
			}
		};
		this.conectado = false;
		this.error = 0;
		this.enviado = false;
		var AJAX = this;
		var xmlhttp = this.xmlhttp;
		this.xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState === 4) {
				if (xmlhttp.status === 200) {
					AJAX.TEXT = xmlhttp.responseText;
					if (AJAX.json) {
						try {
							eval("AJAX.JSON=" + AJAX.TEXT + ";");
						} catch (e) {
						}
					} else {
						AJAX.XML = this.responseXML;
					}
					if (AJAX.accion) {
						AJAX.accion();
					}
					AJAX.conectado = true;
				} else {
					AJAX.error = this.status;
					if (AJAX.erroraccion) {
						AJAX.erroraccion();
					}
				}
			}
		};
	},
	event : {
		getKey : function(e) {
			if (G.nav.isIE) {
				return window.event.keyCode;
			}
			return e.which;
		},
		getType : function(e) {
			e = e ? e : window.event;
			return e.type;
		},
		getPos : function(e) {
			var x = 0, y = 0;
			if (G.nav.isIE) {
				e = window.event;
				var d = document;
				var dd = d.documentElement;
				x = e.clientX + dd.scrollLeft + d.body.scrollLeft;
				y = e.clientY + dd.scrollTop + d.body.scrollTop;
			} else {
				x = e.clientX + window.scrollX;
				y = e.clientY + window.scrollY;
			}
			return {
				x : x,
				y : y
			};
		},
		addEvent : function(el, type, fn) {
			if (el) {
				if (el.addEventListener) {
					el.addEventListener(type, fn, false);
					return true;
				} else if (el.attachEvent) {
					return el.attachEvent("on" + type, fn);
				}
			}
			return false;
		},
		removeEvent : function(el, type, fn) {
			if (el) {
				if (el.removeEventListener) {
					el.removeEventListener(type, fn, false);
					return true;
				} else if (el.detachEvent) {
					return el.detachEvent("on" + type, fn);
				}
			}
			return false;
		}
	},
	valid : {
		int : function(e) {
			return G.valid.test(e, /^\d$/);
		},
		float : function(e) {
			return G.valid.test(e, /^[\d\.\,]$/);
		},
		email : function(e) {
			return G.valid.test(e, /^[a-zA-Z0-9\_\-\.\@]$/);
		},
		test : function(e, p) {
			if (this.controlKey(e))
				return true;
			var k = G.event.getKey(e);
			k = String.fromCharCode(k);
			return p.test(k);
		},
		controlKey : function(e) {
			var k = G.event.getKey(e);
			switch (G.event.getType(e)) {
			case "keypress":
				return this.controlKeyOKP(k);
				break;
			case "keyup":
			case "keydown":
				return this.controlKeyOKD(k);
				break;
			}
		},
		controlKeyOKD : function(k) {
			return (k >= 35 && k <= 40) || k === 8 || k === 27 || k === 13
					|| k === 9 || k === 45 || k === 46 || (k >= 16 && k <= 20)
					|| k === 0;
		},
		controlKeyOKP : function(k) {
			return k === 8 || k === 13 || k === 0;
		},
		isInt : function(t) {
			return G.valid.validar(t, /^\d+$/);
		},
		isFloat : function(t) {
			return G.valid.validar(t, /^\d*[\.\,]{0,1}\d+$/);
		},
		isEmail : function(t) {
			mensaje(G.valid
					.validar(t,
							/^[a-zA-Z0-9\_\-\.]{2,}\@[a-zA-Z0-9\_\-\.]{2,}\.[a-zA-Z0-9\_\-\.]{2,6}$/));
			return G.valid
					.validar(t,
							/^[a-zA-Z0-9\_\-\.]{2,}\@[a-zA-Z0-9\_\-\.]{2,}\.[a-zA-Z0-9\_\-\.]{2,6}$/);
		},
		isEmpty : function(t) {
			return G.util.trim(t) === "";
		},
		areEquals : function(a) {
			for ( var i = 0; i < a.length; i++) {
				for ( var j = i + 1; j < a.length; j++) {
					if (a[i].value !== a[j].value) {
						return false;
					}
				}
			}
			return true;
		},
		validar : function(t, p) {
			return p.test(t);
		}
	},
	nav : {
		isIE : false,
		isNS : false,
		isOP : false,
		isSA : false,
		isCH : false,
		version : null,
		load : function() {
			ua = navigator.userAgent;
			s = "MSIE";
			if ((i = ua.indexOf(s)) >= 0) {
				this.isIE = true;
				this.version = parseFloat(ua.substr(i + s.length));
			} else {
				s = "Netscape6/";
				if ((i = ua.indexOf(s)) >= 0) {
					this.isNS = true;
					this.version = parseFloat(ua.substr(i + s.length));
				} else {
					s = "Netscape/8";
					if ((i = ua.indexOf(s)) >= 0) {
						this.isNS = true;
						this.version = 8;
					} else {
						s = "Firefox";
						if ((i = ua.indexOf(s)) >= 0) {
							this.isNS = true;
							this.version = parseFloat(ua.substr(i + s.length));
						} else {
							s = "Opera";
							if ((i = ua.indexOf(s)) >= 0) {
								this.isOP = true;
								this.version = parseFloat(ua.substr(i
										+ s.length));
							} else {
								s = "Chrome";
								if ((i = ua.indexOf(s)) >= 0) {
									this.isCH = true;
								} else {
									s = "Safari";
									if ((i = ua.indexOf(s)) >= 0) {
										this.isSA = true;
									} else {
										s = "Gecko";
										if ((i = ua.indexOf(s)) >= 0) {
											this.isNS = true;
										} else {
											this.isIE = true;
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
};
G.nav.load();