/**
 * Javascript cLibrary
 * cLibrary.js
 * ------------------------------------------------------------------------------------------------------------
 * @author ciscodelgado http://www.ciscodelgado.com
 * @version 1.0
 * 
 */
var cLibrary = {
	
	Version : '1.0'
};
var isIE = (document.all);
var isWin = (document.all);

var Ajax = {
	request : function(theUrl)
	{
		try {
			var url = theUrl; 
			var sendData = null;
			var isUpdate = false;
			var argIndex = 1;
			if(typeof arguments[1] == "boolean")
			{
				
				isUpdate = true;
				argIndex = 3;
				var container = arguments[2];
			}
			
			var options = arguments[argIndex] || {};
			
			var rMethod = options.method || "get";
			var asynchronous = options.asynchronous || true;
			var execScripts = options.execScripts || false;
			var nocache = encodeURIComponent("r")+"="+encodeURIComponent(randomize());
			var oXmlHttp = oAjax();
			
			if(rMethod == "post")
			{
				sendData = (options.params) ? options.params+"&" : "";
				sendData += nocache;
			}
			else if(rMethod == "get")
			{
				sendData = (options.params) ? "?"+options.params+"&" : "?";
				url += sendData + nocache;
			}
		
			var onLoading = options.onLoading || null;
			var onError = options.onError || null;
			var onComplete = (typeof options.onComplete == "function") ? function(r){ options.onComplete(r); } : null;

			oXmlHttp.open(rMethod, url, asynchronous);
				
			if(rMethod == "post")
			{
				oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			}	
		    oXmlHttp.onreadystatechange = function ()
			{
		        try {
					if (oXmlHttp.readyState == 1) // Cargando
					{
						if(typeof onLoading == "function")
						{
							onLoading();	
						}
					}
		            else if (oXmlHttp.readyState == 4) // Completado
					{
		                if (oXmlHttp.status == 200) 
						{ 		 
							if(isUpdate)
							{
								container.innerHTML = oXmlHttp.responseText;
							}
							
							if(execScripts)
							{
								var script = "(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)";
								var r = oXmlHttp.responseText;
								var matchScripts = new RegExp(script, "g");
								while(r.search(script) != -1)
								{
									var matches = matchScripts.exec(r);
									ind = r.search(script);
									r = r.substring(0,ind) + r.substring(ind+matches[0].length+1, r.length);
									try{
										eval(matches[1]);
									}catch(e)
									{
										alert(e.message);
										break;
									}
								}
							}                
							if(typeof onComplete == "function")
							{
								options.onComplete(oXmlHttp);	
							}   
		                }
						else
						{
							if(typeof onError == "function")
							{
								onError();	
							}
						} 
		            }
		        } catch (oException) {
		            if(typeof onError == "function")
					{
						onError();	
					}
		        }
		    };
			if(rMethod == "post")
			{
		    	oXmlHttp.send(sendData);
			}
			else if(rMethod == "get")
			{
				oXmlHttp.send(null);
			}
		} catch(oException) {}
	},	
	update : function(theUrl, container)
	{
		if(typeof container == "string")
		{
			container = $(container);
		}
		var options = arguments[2] || {};
		this.request(theUrl, true, container, options);
	}
};
Forms = function(theForm)
{
	this.theForm = getType(theForm);
	this.Forms = Forms;
	this.sendForm = sendForm;
	this.isFormValid = isFormValid;
	this.toQueryString = toQueryString;
	this.sendOnEnter = sendOnEnter;
	this.validate = validate;
	this.cancelForm = cancelForm;
	this.responseValidation = responseValidation;
	this.focusFirst = focusFirst;
	this.focusFirst();
	this.arrPasswords = [];
};

focusFirst = function()
{
	var	theForm = this.theForm;
	var objInput;
	for(i = 0; i < theForm.elements.length; i++)
	{
		objInput = theForm.elements[i];
		if(objInput.type != "hidden" 
			&& objInput.type != "button"
			&& objInput.type != "reset"
			&& objInput.type != "submit"
			&& objInput.type != "checkbox"
			&& objInput.type != "radio"
		)
		{
			objInput.focus();
			break;
		}
		else
		{
			continue;	
		}	
	}
};

toQueryString = function()
{
    var	theForm = this.theForm;
	var aParams = [];
	
	var oInput;
	for(i = 0; i < theForm.elements.length; i++)
	{
		oInput = theForm.elements[i];
		if(oInput.type != "button" && oInput.type != "reset" && oInput.type != "submit")
		{
			inputValue = oInput.value;
			if(oInput.type == 'password')
			{
				inputValue = hex_md5(oInput.value);
			}
			if(oInput.type == 'checkbox')
			{
				inputValue = (oInput.checked) ? 'on' : '';
			}
			var sName = oInput.name || oInput.id;
			var queryString = encodeURIComponent(sName); 
			queryString += "=";
			queryString += encodeURIComponent(inputValue);
			aParams.push(queryString);
		}
	}
	return aParams.join("&");
};
	
validate = function(dir, objValidation)
{
	var urlCode = dir + "validateform.php";
	var theForm = this.theForm;
	var qParams = [];
	var oSelf = this;
	var times = 0;
	if("rePassword" in objValidation)
	{
		var bRetypePass = objValidation["rePassword"];
		if(bRetypePass)
		{
			for(field in objValidation)
			{
				if(field != "lForm" && field != "rePassword")
				{
					if($(field).type == "password")
					{
						this.arrPasswords.push($(field));
					}
				}
			}
		}
	}
	for(field in objValidation)
	{
		if(field != "lForm" && field != "rePassword")
		{
			$(field).validation = objValidation[field]['validation'];
			$(field).required = objValidation[field]['required'];
			$(field).valid = false;
			Elements.insert('img', 'img_'+field, 'after', $(field), {"style":"display:none", "align":"absmiddle", "hspace":"3", "src":errorIcon});
			var arrPasswords = this.arrPasswords;
			function validateField()
			{
				if (processing){return;}
				setProcessing(true);
				var oVal = this.value;
				if(this.type == "password")
				{
					oVal = hex_md5(this.value);	
					if(bRetypePass)
					{
						times++;
					}
				}
				var callback = function(r){ oSelf.responseValidation(r, oSelf); };
				if(times >= 2)
				{
					var sParams = "p1="+hex_md5(oSelf.arrPasswords[0].value)+"&name1="+oSelf.arrPasswords[0].name+"&p2="+hex_md5(oSelf.arrPasswords[1].value)+"&name2="+oSelf.arrPasswords[1].name+"&validation=comparePass";
					new Ajax.request(urlCode, { method:'post', params:sParams, onComplete:callback });
				}
				else
				{
					var pars = "name="+this.name+"&value="+oVal+"&required="+this.required+"&validation="+this.validation;
					if(this.type == "password")
					{
						pars += "&max="+objValidation[field]['max']+"&min="+objValidation[field]['min']+"&rlen="+this.value.length;	
					}
					var request = new Ajax.request(urlCode, { method:'post', params:pars, onComplete:callback });
				}
			}
			$(field).onchange = validateField;
		}
	}
	
};

responseValidation = function(response, objSelf)
{
	var sResult = response.responseText.split("||");
	var sValidation = sResult[0];
	var arrInputs = [];
	var arrErrImg = [];
	if(sResult[1].indexOf("#") > -1)
	{
		var inputs = sResult[1].split("#");
		for(i = 0; i<inputs.length; i++)
		{
			arrInputs.push($(inputs[i]));
			arrErrImg.push($("img_"+inputs[i]));
		}
	}
	else
	{
		arrInputs.push($(sResult[1]));
		arrErrImg.push($("img_"+sResult[1]));
	}
	var sInput = null;
	var sMsg = sResult[2];
	var fMsg = sResult[3];
	var errorImage = null;
	sResult = null;
	if(sValidation == "false")
	{
		for(i = 0; i< arrInputs.length; i++)
		{
			sInput = arrInputs[i];
			errorImage = arrErrImg[i];
			sInput.valid = false;
			Elements.removeClassName(sInput, 'inpOK');
			Elements.addClassName(sInput, 'inpError');
			errorImage.src = errorIcon;
			errorImage.style.display = "";
			errorImage.title = fMsg;
		}
		Elements.addClassName('pMsg', 'pError');
		$('pMsg').style.display = "";
		$('pMsg').innerHTML = sMsg;	
	}
	else
	{
		for(i = 0; i< arrInputs.length; i++)
		{
			sInput = arrInputs[i];
			errorImage = arrErrImg[i];
			sInput.valid = true;
			Elements.removeClassName(sInput, 'inpError');
			Elements.addClassName(sInput, 'inpOK');
			errorImage.src = okIcon;
			errorImage.style.display = "";
			errorImage.title = "";
		}
		if(objSelf.isFormValid())
		{
			Elements.removeClassName('pMsg', 'pError');
			$('pMsg').style.display = "none";
			$('pMsg').innerHTML = "";
		}
	}
	setProcessing(false);
};
	
isFormValid = function()
{
	var blnValid = true;
	
	for(var i = 0; i < this.theForm.elements.length; i++)
	{
		if(typeof this.theForm.elements[i].valid == "boolean")
		{
			blnValid = blnValid && this.theForm.elements[i].valid;
		}
	}
	return blnValid;
};

sendOnEnter = function(callback)
{
	var theForm = this.theForm;
	for(i = theForm.elements.length - 1; i >= 0 ; i--)
	{
		oInput = theForm.elements[i];
		if(oInput.type == "text" || oInput.type == 'password')
		{
			oInput.onkeyup = function(objEvent)
			{
				var iAscii;
				try
				{
					iAscii = event.keyCode;
				}
				catch(e)
				{
					iAscii = objEvent.which;
				}  
				if (iAscii == 13)
				{
					if(typeof callback == "function")
					{
						callback();	
					}
				} 
			}
			break;
		}
		else
		{
			continue;	
		}
	}
};

cancelForm = function()
{
	var theForm = this.theForm;
	var sInput;
	theForm.reset();
	for(i = 0; i < theForm.elements.length; i++)
	{
		sInput = theForm.elements[i].id;
		$("img_"+sInput).style.display = "none";
		Elements.removeClassName(sInput, 'inpError');
		Elements.removeClassName(sInput, 'inpOK');
	}
	Elements.removeClassName('pMsg', 'pError');
	$('pMsg').innerHTML = "";
	$('pMsg').style.display = "none";
	this.focusFirst();
}
sendForm = function(urlCode, callback)
{
	if(processing) return;
	setProcessing(true);
	var pars = this.toQueryString();
	function fnLoading()
	{
		$("spnSending").style.display = "";
	}
	var request = new Ajax.request(urlCode, { method:'post', params:pars, onComplete:callback, onLoading:fnLoading});	
};

/**
 * 
 * Tabs
 * 
 * 
 */
var Tabs = {

	onRollOver : function(sTabId)
	{
		var oTabRollOver = $(sTabId);
		if(!oTabRollOver.active)
		{
			Elements.addClassName(oTabRollOver.childNodes[1], "divTabMidHover");
		}
		
	},
	
	onRollOut : function(sTabId)
	{
		var oTabRollOver = $(sTabId);
		if(!oTabRollOver.active)
		{
			Elements.removeClassName(oTabRollOver.childNodes[1], "divTabMidHover");
		}
	},
	
	change : function(sTabId, fnCallback)
	{
		if(!$(sTabId))
		{
			var sTab = document.getElementsByClassName("divTabActive");
		
			if(!sTab)
			{
				return false;
			}
			else
			{
				sTabId = sTab[0].id;
			} 
		}
		var oTabActive = $(sTabId);
		var oDivMenu = oTabActive.parentNode;
		for(i = 0; i < oDivMenu.childNodes.length; i++)
		{
			if($(oDivMenu).childNodes[i].nodeName.toLowerCase() == "div")
			{
				$(oDivMenu.childNodes[i].id).active = false;
				Elements.replaceClassName($(oDivMenu.childNodes[i].id), "divTabIn", "divTabActive");
				var oTabRight = document.getElementsByClassName("divTabRightActive", oDivMenu.childNodes[i].id)[0];
				var oTabMid = document.getElementsByClassName("divTabMidActive", oDivMenu.childNodes[i].id)[0];
				var oTabLeft = document.getElementsByClassName("divTabLeftActive", oDivMenu.childNodes[i].id)[0];
				
				if(oTabRight) {Elements.replaceClassName($(oTabRight.id), "divTabRightIn", "divTabRightActive");}
				if(oTabMid)
				{
					Elements.replaceClassName($(oTabMid.id), "divTabMidIn", "divTabMidActive");
					Elements.removeClassName($(oTabMid.id), "divTabMidHover");
				} 
				if(oTabLeft) {Elements.replaceClassName($(oTabLeft.id), "divTabLeftIn", "divTabLeftActive");}
			}

		} 
		oTabActive.active = true;
		Elements.replaceClassName(oTabActive, "divTabActive", "divTabIn");
		Elements.replaceClassName(oTabActive.childNodes[0].id, "divTabLeftActive", "divTabLeftIn");
		Elements.replaceClassName(oTabActive.childNodes[1].id, "divTabMidActive", "divTabMidIn");
		Elements.replaceClassName(oTabActive.childNodes[2].id, "divTabRightActive", "divTabRightIn");
				
		if(fnCallback != null) 
		{
			var aAdditionalArgs = null; 
			if(arguments.length > 2) 
			{
				var iAdditionalArgsLength = arguments.length - 2; 
				aAdditionalArgs = new Array(iAdditionalArgsLength);
				for(var i = 0; i < iAdditionalArgsLength; i++)
				{
					aAdditionalArgs[i] = "'"+arguments[i + 2]+"'";
				}
			}
			var sExprToEval = 'fnCallback(';
			if(aAdditionalArgs != null)
			{
				sExprToEval += aAdditionalArgs.join(",");
				sExprToEval += ')';
			}
			eval(sExprToEval);
		}
	}
};
/**
 * 
 * Data Group
 * 
 * 
 */
var dataGroup = {

	toggle : function(sDatacontentId, sButtonId)
	{
		if($(sDatacontentId).style.display == "" || $(sDatacontentId).style.display == "block" || $(sDatacontentId).style.display === undefined)
		{
			$(sDatacontentId).style.display = "none";
		}
		else
		{
			$(sDatacontentId).style.display = "block";
		}
		if($(sButtonId).className == "aWinActionMin")
		{
			Elements.replaceClassName(sButtonId, "aWinActionMax","aWinActionMin");
		}
		else if($(sButtonId).className == "aWinActionMax")
		{
			Elements.replaceClassName(sButtonId, "aWinActionMin","aWinActionMax");
		}
	}	
	
}

/**
 * 
 * Elements
 * 
 * 
 */
var Elements = {

	/**
	 * Añadir eventos a un elemento
	 * 
	 * @param {Object || String} oTarget
	 * @param {String} sEventType
	 * @param {Function} fnHandler
	 */
		
	addEventHandler : function(oTarget, sEventType, fnHandler)
	{
		oTarget = getType(oTarget);
		if(oTarget.addEventListener)
		{
			oTarget.addEventListener(sEventType, fnHandler, false);
		}
		else if(oTarget.attachEvent)
		{
			oTarget.attachEvent("on"+sEventType, fnHandler);
		}
		else
		{
			oTarget["on"+sEventType] = fnHandler;		
		}
	},
		
	addObjEventListener : function(oTarget, sEventType, oObj, fnObjMethod)
	{
		var oObjImpl = oObj;
		var fnObjMethodImpl = fnObjMethod;
		var oAdditionalArgs = null;

		if(arguments.length > 4)
		{
			var iAdditionalArgsLength = arguments.length - 4;
			oAdditionalArgs = new Array(iAdditionalArgsLength);
			for(var i=0; i<iAdditionalArgsLength; i++)
			{
				oAdditionalArgs[i] = arguments[i + 4];
			}
		}
		
		function EventListenerImpl()
		{
			var oEvent = Elements.getEvent();
			var sExprToEval = 'fnObjMethodImpl.call(oObjImpl, oEvent';
			if(oAdditionalArgs !== null)
			{
				for(var i=0; i<oAdditionalArgs.length; i++)
				{
					sExprToEval += ', oAdditionalArgs[' + i + ']';
				}
				sExprToEval += ');';
				eval(sExprToEval);
			}
			else
			{
				fnObjMethodImpl.call(oObjImpl, oEvent);
			}
			
		}
		
		Elements.addEventHandler(oTarget, sEventType, EventListenerImpl);
	},
	
	getEvent : function()
	{
		if(window.event)
		{
			return this.formatEvent(window.event);
		}
		else
		{
			return Elements.getEvent.caller.arguments[0];
		}
	},
	
	formatEvent : function(oEvent)
	{
		if (isIE && isWin) 
		{
			oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
			oEvent.isChar = (oEvent.charCode > 0);
			oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
			oEvent.pageY = oEvent.clientY + document.body.scrollTop;
			oEvent.preventDefault = function ()
			{
				this.returnValue = false;
			};
			if (oEvent.type == "mouseout") 
			{
			  	oEvent.relatedTarget = oEvent.toElement;
			} 
			else if (oEvent.type == "mouseover") 
			{
			  	oEvent.relatedTarget = oEvent.fromElement;
			}
			oEvent.stopPropagation = function () 
			{
			  	this.cancelBubble = true;
			};
			oEvent.target = oEvent.srcElement;
			oEvent.time = new Date().getTime();
		}
		return oEvent;
	},
	
	inputenable : function(sInpId)
	{
		$(sInpId).disabled = false;
		if(arguments.length > 1)
		{
			$(arguments[1]).disabled = true;
		}
	},
	/*
	 * Gestionar clases
	 */
	/**
	 * Añadir una clase a un elemento
	 * 
	 * @param {Object || String} el
	 * @param {String} theClassName
	 */
	addClassName : function(el, theClassName)
	{
		el = getType(el);
		var currentClassName = el.className;
		if(!currentClassName)
		{
			el.className = theClassName;
		}
		else
		{
			if(!currentClassName.match(theClassName))
			{
				el.className += " "+theClassName;
			}	 
		}
	},
	
	/**
	 * Cambiar la clase de un elemento
	 * 
	 * @param {Object || String} el
	 * @param {String} newClassName
	 * @param {String} oldClassName
	 */
	replaceClassName : function(el, newClassName, oldClassName)
	{
		if(newClassName == " " || oldClassName == " ") return;
		
		el = getType(el);
		
		var currentClassName = el.className;
		if(!currentClassName || !currentClassName.match(oldClassName))
		{
			this.addClassName(el, newClassName);
		}
		else
		{
			this.removeClassName(el, oldClassName);
			this.addClassName(el, newClassName);
		//	el.className = currentClassName.replace(oldClassName, newClassName);
		}
	},
	
	/**
	 * Eliminar una clase de un elemento
	 * 
	 * @param {Object || String} el
	 * @param {String} theClassName
	 */
	removeClassName : function(el, theClassName)
	{
		if(!theClassName) return;
		el = getType(el);
		var currentClassName = el.className;
		var tmpClassName = null;
		if(!currentClassName) return;
		
		if(currentClassName.match(theClassName))
		{
			tmpClassName = currentClassName.replace(theClassName, "");
			el.className = tmpClassName;
		}
	//	this.replaceClassName(el, "", theClassName);
	},
	
	/*
	 * Gestionar elementos
	 */
	
	alowedTags : ["span", "div"],
	
	/**
	 * Añadir un elemento a la página
	 * 
	 * @param {String} el
	 * @param {String} newId
	 */
	add : function(el, newId)
	{
		var options = arguments[2] || {};
		
		var targetNode = getType(options.targetNode) || document.getElementsByTagName("body")[0];
		return Elements.insert(el, newId, "inside", targetNode, options);
	},
	
	remove : function(el)
	{
		el = getType(el);
		el.parentNode.removeChild(el);
	},
	
	hide : function(el) 
	{
		el = getType(el);
    	el.style.display = 'none';
  	},
	
	show : function(el) 
	{
		el = getType(el);
    	el.style.display = '';
  	},
	
	insert : function(sElement, newId, position, refNode)
	{
		refNode = getType(refNode);
		el = document.createElement(sElement);

		if(arguments.length > 4)
		{
			var tagAttributes = arguments[4];
			for(attribute in tagAttributes)	
			{
				if(attribute == "style" && isIE)
				{
					var arrStyles = tagAttributes[attribute].split(";")
					for (var i = 0; i< arrStyles.length; i++)
					{
						var arrStyle = arrStyles[i].split(":");
						if(arrStyle[0].indexOf("-") == -1)
						{
							el.style[arrStyle[0]] = arrStyle[1];
						}
					}
				}
				el.setAttribute(attribute, tagAttributes[attribute]);
			}
		}
		el.id = newId;
		
		switch(position)
		{
			case "before": 
				refNode.parentNode.insertBefore(el, refNode); 
				break;
			case "after": 
				if(refNode.nextSibling)
				{
					refNode.parentNode.insertBefore(el, refNode.nextSibling);
				}
				else
				{
					refNode.parentNode.appendChild(el);	
				}
				break;
			case "inside":
				refNode.appendChild(el);
				break;
			default: break;
		}
		return $(newId);
	}
};

//

var nodeTree = [];
document.getElementsByClassName = function(aClass)
{
	nodeTree = [];
	var classNames = [];
	var element = null;
	aParent = $(arguments[1]) || (document.body) ? document.body : document.getElementsByTagName("body")[0];
	getDOMTree(aParent);
	for(var i=0; i<nodeTree.length; i++)	
	{
		element = nodeTree[i];
		if(element.className.indexOf(aClass) > -1)
		{
			classNames.push(element);
		}
	}
	if(classNames.length > 0) 
	{
		return classNames;
	} 
	return false;
};

/**
 * 
 * 
 * 
 * 
 * 
 * 
 */
function getDOMTree(nRoot)
{
	for(var i=0; i<nRoot.childNodes.length; i++)
	{
		if(nRoot.childNodes[i].nodeType == 1)
		{
			nodeTree.push(nRoot.childNodes[i]);
			if(nRoot.childNodes[i].hasChildNodes())
			{
				getDOMTree(nRoot.childNodes[i]);
			}	
		}
	}
	
}
function $()
{
	var element;
	var idElements = [];
	for(var i=0; i<arguments.length; i++)
	{
		if(typeof arguments[i] == "string")
		{
			element = document.getElementById(arguments[i]);
		}
		else
		{
			element = arguments[i];
		}
		idElements.push(element);
	}
	if(idElements.length === 0)
	{
		return false;
	}
	else
	{
		return (idElements.length < 2) ? idElements[0] : idElements;
	}
}
function oAjax()
{	
	var http_request = false;
	if (window.XMLHttpRequest) 
	{ 
		// Mozilla, Safari,...
	    http_request = new XMLHttpRequest();
	    if (http_request.overrideMimeType) 
		{
	    //    http_request.overrideMimeType('text/xml');
	    }
	} 
	else if (window.ActiveXObject) 
	{ 
		// IE
	    try {
	        http_request = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	        try{ 
	            http_request = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch (e) {}
	    }
	}	
	return http_request;
}

function getType(el)
{
	if(typeof el == "string")
	{
		el = $(el);
	}
	return el;
}

var processing = false;
function setProcessing(bProcess)
{
	processing = bProcess;
	var docBody = (document.body) ? document.body : document.getElementsByTagName("body")[0];
	docBody.style.cursor = (bProcess) ? "wait" : "";
	
}
function randomize()
{
	var chars = new Array("a", "b", "c", "d", "e", "f", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
	var randomChar = "";
	var max = chars.length - 1;
	var min = 0;
	var index;
	for(i=0; i<32; i++)
	{
		index = Math.floor(Math.random() * (max - min + 1)) + min;
		randomChar += chars[index];
	}
	return randomChar;
}


function checkEmail(emailStr)
{
	var filter = /^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+.[A-Za-z0-9_.]+[A-za-z]$/;
//	var filter = /^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
	if (filter.test(emailStr))
	{
		return false;
	}
	else
	{
		return true;
	}
}
