//=====================================================================================================
// Desabilita el clic derecho
//=====================================================================================================
/*
function disableIE(){
	if (document.all){
		return false;
	}
}

function disableNS (e){
	if (document.layers||(document.getElementById&&! document.all)){
		if (e.which==2||e.which==3){
			return false;
		}
	}
}

if (document.layers){
	document.captureEvents(Event.MOUSEDOWN);
	document.onmousedown=disableNS;
}else{
	document.onmouseup=disableNS;
	document.oncontextmenu=disableIE;
}

document.oncontextmenu=new Function("return false")
*/
//=====================================================================================================
// Elimina los bordes de los links en explorer
//=====================================================================================================
function ExplorerFix(){
	for (a in document.links)
		document.links[a].onfocus=document.links[a].blur;
}

if (document.all){
	document.onmousedown="ExplorerFix()";
}

//=====================================================================================================
// Muestra un mensaje en la barra de estado
//=====================================================================================================

//=====================================================================================================
// Detecta flash
//=====================================================================================================
/*
var flashReqVer = 6;     // Version mínima requerida de Flash
var flashMaxVersion = 7; // Versión límite conocida
var lang="<%=lang%>";
flash2Installed=false, flash3Installed=false, flash4Installed=false, flash5Installed=false, flash6Installed=false, flash7Installed=false;
issue="", actualVersion=0, document.write('<scr'+'ipt language=VBScript\> \n');
document.write('on error resume next \n');

for (x=1; x<=flashMaxVersion; x++)
	document.write('flash'+x+'Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+x+'"))) \n');

document.write('</scr'+'ipt\> \n');

function flash(){
	for (var i = 2; i<=flashMaxVersion; i++)
			if (eval("flash"+i+"Installed")==true) actualVersion=i;
	//alert("Flash Player " + actualVersion); //Para mirar la versión
	if (actualVersion<flashReqVer) issue=(actualVersion>=2) ? "&issue=update&cmp=flash&current="+actualVersion : "&cmp=flash&issue=notinstalled";

	if (issue!="") window.location=("../content/checking.asp?lang="+lang+issue);
}

//=====================================================================================================
// DETECTA EL NAVEGADOR
//=====================================================================================================
var ua = navigator.userAgent.toLowerCase();
var os,browser,version,data;

navlang=navigator.language ? navigator.language : navigator.userLanguage;
lang=navlang.substr(0, 2);
if (lang=="pt") lang="pr";

if (detect('konqueror')) {browser = "Konqueror"; os = "Linux";}
else if (detect('safari')) browser = "Safari";
else if (detect('omniweb')) browser = "OmniWeb";
else if (detect('firefox')) browser = "Firefox";
else if (detect('opera')) browser = "Opera";
else if (detect('webtv')) browser = "WebTV";
else if (detect('icab')) browser = "iCab";
else if (detect('msie')) browser = "Internet Explorer";
else if (!detect('compatible')) {browser = "Netscape"; version = ua.charAt(8);}
else browser = "An unknown browser";

if (!version) version = ua.charAt(stringposition + data.length);

if (!os) {
	if (detect('linux')) os = "Linux";
	else if (detect('x11')) os = "Unix";
	else if (detect('mac')) os = "Mac";
	else if (detect('win')) os = "Windows";
	else os = "An unknown operating system";
}

function detect(text) {
	stringposition = ua.indexOf(text) + 1;
	data = text;
	return stringposition;
}

if (browser=="Netscape"){
	if (version<7) window.location=("../content/checking.asp?issue=update&cmp=netscapez&lang="+lang+"&current="+version); else flash();
}else if (browser=="Opera"){
	if (version<7) window.location=("../content/checking.asp?issue=update&cmp=opera&lang="+lang+"&current="+version); else flash();
}else if (browser=="Firefox"){
	if (version<1) window.location=("../content/checking.asp?issue=update&cmp=firefox&lang="+lang+"&current="+version); else flash();
}else if (browser=="Internet Explorer"){
	if (version<6) window.location=("../content/checking.asp?issue=update&cmp=ie&lang="+lang+"&current="+version); else flash();
}else{
	window.location=("../content/checking.asp?issue=change&lang="+lang);
}
*/
//=====================================================================================================
// VALIDA CHECKBOXES
//=====================================================================================================

function valChckBxs (obj, mess){
	count=0
	len=obj.length                                        // get the number of fields in the form

	for (a=0; a<len; a++){
			if (obj[a].type=="checkbox"&&obj[a].checked){ // only look at form elements that are checkbox type
				count++                                   // count the number of checked boxes
			}
	}
	if (count==0){
		alert(mess)
		return false; // don't submit the form if no boxes are checked)
	}else return true;
}

//=====================================================================================================
// FUNCIÓN PARA LA HORA
//=====================================================================================================

var tag = "";
now=new Date();
hour=now.getHours();

if (hour>12){
	hour=hour-12;
	tag="p.m."
}else{
	tag="a.m."
}

minutes=now.getMinutes();

if (minutes<10) minutes="0"+minutes;

seconds=now.getSeconds();

//Obtiene las fechas
function fecha(){
	tag="", hour="", minutes="", seconds="";
	now=new Date();
	hour=now.getHours();

	if (hour>12){
		hour=hour-12;
		tag="p.m."
	}else{
		tag="a.m."
	}

	minutes=now.getMinutes();

	if (minutes<10) minutes="0"+minutes;

	seconds=now.getSeconds();

	if (seconds<10) seconds="0"+seconds;

	return (hour+":"+minutes+":"+seconds+" "+tag);
}

//Convierte los retornos de carro
function br (input){
	var output = "";

	for (var i = 0; i<input.length; i++){
			if ((input.charCodeAt(i)==13)&&(input.charCodeAt(i+1)==10)){
				i++;
				output+="<br>";
			}else{
				output+=input.charAt(i);
			}
	}
	return (output);
}

function textCounter (field, maxlimit){
	if (field.value.length>maxlimit) field.value=field.value.substring(0, maxlimit);
}

function upDownAdmin (a, b){
	if (a.style.display==""){
		a.style.display="none";
		b.src="../media/images/icoMnuExp.gif";
		b.alt="Expandir pánel ...";
	}else{
		a.style.display="";
		b.src="../media/images/icoMnuCon.gif";
		b.alt="Contraer pánel ...";
	}
}

function upDownPanel (a, b){
	if (a.style.display==""){
		a.style.display="none";
		b.src="../media/images/icoPlus.gif";
		b.alt="Expandir pánel ...";
	}else{
		a.style.display="";
		b.src="../media/images/icoMinus.gif";
		b.alt="Contraer pánel ...";
	}
}

function replaceChars (entry){
	out="&";       // replace this
	add="z";       // with this
	temp=""+entry; // temporary holder

	while(temp.indexOf(out)>- 1){
		pos=temp.indexOf(out);
		temp=""+(temp.substring(0, pos)+add+temp.substring((pos+out.length), temp.length));
	}
	document.subform.text.value=temp;
}

// Función para checkboxes gráficos
var state = "";

function checkbox (a, b){ // (checkbox y campo oculto)
	target=eval("document.all."+a);
	field=eval("document.all."+b);
	if (field.value=="0"){
		target.src="../media/images/checkBox01.gif";
		field.value="1";
	}else{
		target.src="../media/images/checkBox02.gif";
		field.value="0";
	}
}

function CA (element){
	for (var i = 0; i<document.frmMessages.elements.length; i++){
			var e = document.frmMessages.elements[i];
			if (e.name!="allbox") e.checked=document.frmMessages.allbox.checked;
	}
}

function getChild (a, b, c){ // a: parámetro de filtro, b: nombre del menu hijo, c: archivo con la rutina de servidor
	// Determina el menú hijo
	target=eval("document.getElementById."+b)

	// Borra las entradas actuales del Menú Hijo
	for (i=target.length; i>0; i--){
		target.options[i-1]=null
	}

	// Genera la opción inicial y la selecciona por defecto
	target.options[0]=new Option("Seleccione ...", 0)
	target.selectedIndex=0

	// Procesos de Base de Datos con RemoteScripting
	if (a!=0){
		objRS=RSGetASPObject(c);
		objResult=objRS.getChild(a);
		strChild=objResult.return_value;
		//alert(strChild); // Certifica que los datos se estén recibiendo
		arrChild=strChild.split("*");

		// Genera las entradas de la BD
		for (i=0; i<arrChild.length; i++){
				child=arrChild[i]
				start=child.indexOf("-");
				end=child.length;
				id=child.substring(0, start)
				label=child.substring(start+1, end)
				target.options[i+1]=new Option(label, id)
		}
		target.disabled=false
	}else{
		target.disabled=true
	}
}

function P7_Snap(){ //v2.62 by PVII
	var x, y, ox, bx, oy, p, tx, a, b, k, d, da, e, el, args = P7_Snap.arguments;
	a=parseInt(a);

	for (k=0; k<(args.length-3); k+=4)
		if ((g=MM_findObj(args[k]))!=null){
			el=eval(MM_findObj(args[k+1]));
			a=parseInt(args[k+2]);
			b=parseInt(args[k+3]);
			x=0;
			y=0;
			ox=0;
			oy=0;
			p="";
			tx=1;
			da="document.all['"+args[k]+"']";

			if (document.getElementById){
				d="document.getElementsByName('"+args[k]+"')[0]";
				if (!eval(d)){
					d="document.getElementById('"+args[k]+"')";
					if (!eval(d)){
						d=da;
					}
				}
			}else if (document.all){
				d=da;
			}

			if (document.all||document.getElementById){
				while(tx==1){
					p+=".offsetParent";
					if (eval(d+p)){
						x+=parseInt(eval(d+p+".offsetLeft"));
						y+=parseInt(eval(d+p+".offsetTop"));
					}else{
						tx=0;
					}
				}

				ox=parseInt(g.offsetLeft);
				oy=parseInt(g.offsetTop);
				var tw = x+ox+y+oy;
				if (tw==0||(navigator.appVersion.indexOf("MSIE 4")>- 1&&navigator.appVersion.indexOf("Mac")>- 1)){
					ox=0;
					oy=0;
					if (g.style.left){
						x=parseInt(g.style.left);
						y=parseInt(g.style.top);
					}else{
						var w1 = parseInt(el.style.width);
						bx=(a<0) ? -5-w1 : -10;
						a=(Math.abs(a)<1000) ? 0 : a;
						b=(Math.abs(b)<1000) ? 0 : b;
						x=document.body.scrollLeft+event.clientX+bx;
						y=document.body.scrollTop+event.clientY;
					}
				}
			}else if (document.layers){
				x=g.x;
				y=g.y;
				var q0 = document.layers, dd = "";
				for (var s = 0; s<q0.length; s++){
						dd='document.'+q0[s].name;
						if (eval(dd+'.document.'+args[k])){
							x+=eval(dd+'.left');
							y+=eval(dd+'.top');
							break;
						}
				}
			}
			if (el){
				e=(document.layers) ? el : el.style;
				var xx = parseInt(x+ox+a), yy = parseInt(y+oy+b);

				if (navigator.appName=="Netscape"&&parseInt(navigator.appVersion)>4){
					xx+="px";
					yy+="px";
				}

				if (navigator.appVersion.indexOf("MSIE 5")>- 1&&navigator.appVersion.indexOf("Mac")>- 1){
					xx+=parseInt(document.body.leftMargin);
					yy+=parseInt(document.body.topMargin);
					xx+="px";
					yy+="px";
				}

				e.left=xx;
				e.top=yy;
			}
		}
}

function P7_autoLayers(){ //v1.2 by PVII
	var g, b, k, f, args = P7_autoLayers.arguments;
	var a = parseInt(args[0]);

	if (isNaN(a)) a=0;

	if (!document.p7setc){
		p7c=new Array();
		document.p7setc=true;
		for (var u = 0; u<10; u++){
			p7c[u]=new Array();
		}
	}

	for (k=0; k<p7c[a].length; k++){
			if ((g=MM_findObj(p7c[a][k]))!=null){
				b=(document.layers) ? g : g.style;
				b.visibility="hidden";
			}
	}

	for (k=1; k<args.length; k++){
			if ((g=MM_findObj(args[k]))!=null){
				b=(document.layers) ? g : g.style;
				b.visibility="visible";
				f=false;

				for (j=0; j<p7c[a].length; j++){
						if (args[k]==p7c[a][j]){
							f=true;
						}
				}
				if (!f){
					p7c[a][p7c[a].length++]=args[k];
				}
			}
	}
}

//=====================================================================================================
// FUNCION QUE PERMITE LOS MENUS CONECTADOS DINÁMICOS
//=====================================================================================================

function DynamicOptionList(){
	if (arguments.length<2){
		alert("Not enough arguments in DynamicOptionList()");
	}

	// Name of the list containing dynamic values
	this.target=arguments[0];
	// Set the lists that this dynamic list depends on
	this.dependencies=new Array();

	for (var i = 1; i<arguments.length; i++){
		this.dependencies[this.dependencies.length]=arguments[i];
	}

	// The form this list belongs to
	this.form=null;
	// Place-holder for currently-selected values of dependent select lists
	this.dependentValues=new Object();
	// Hold default values to be selected for conditions
	this.defaultValues=new Object();
	// Storage for the dynamic values
	this.options=new Object();
	// Delimiter between dependent values
	this.delimiter="|";
	// Logest string currently a potential options (for Netscape)
	this.longestString="";
	// The total number of options that might be displayed, to build dummy options (for Netscape)
	this.numberOfOptions=0;
	// Method mappings
	this.addOptions=DynamicOptionList_addOptions;
	this.populate=DynamicOptionList_populate;
	this.setDelimiter=DynamicOptionList_setDelimiter;
	this.setDefaultOption=DynamicOptionList_setDefaultOption;
	this.printOptions=DynamicOptionList_printOptions;
	this.init=DynamicOptionList_init;
}

// Set the delimiter to something other than | when defining condition values
function DynamicOptionList_setDelimiter (val){
	this.delimiter=val;
}

// Set the default option to be selected when the list is painted
function DynamicOptionList_setDefaultOption (condition, val){
	if (typeof this.defaultValues[condition]=="undefined"||this.defaultValues[condition]==null){
		this.defaultValues[condition]=new Object();
	}
	for (var i = 1; i<arguments.length; i++){
		this.defaultValues[condition][arguments[i]]=1;
	}
}

// Init call to map the form to the object and populate it
function DynamicOptionList_init (theform){
	this.form=theform;
	this.populate();
}

// Add options to the list.
// Pass the condition string, then the list of text/value pairs that populate the list	
function DynamicOptionList_addOptions (dependentValue){
	if (typeof this.options[dependentValue]!="object"){
		this.options[dependentValue]=new Array();
	}
	for (var i = 1; i<arguments.length; i+=2){
			// Keep track of the longest potential string, to draw the option list
			if (arguments[i].length>this.longestString.length){
				this.longestString=arguments[i];
			}

			this.numberOfOptions++;
			this.options[dependentValue][this.options[dependentValue].length]=arguments[i];
			this.options[dependentValue][this.options[dependentValue].length]=arguments[i+1];
	}
}

// Print dummy options so Netscape behaves nicely
function DynamicOptionList_printOptions(){
	// Only need to write out "dummy" options for Netscape
	if ((navigator.appName=='Netscape')&&(parseInt(navigator.appVersion)<=4)){
		var ret = "";

		for (var i = 0; i<this.numberOfOptions; i++){
			ret+="<OPTION>";
		}

		ret+="<OPTION>"

		for (var i = 0; i<this.longestString.length; i++){
			ret+="_";
		}
		document.writeln(ret);
	}
}

// Populate the list
function DynamicOptionList_populate(){
	var theform = this.form;
	var i, j, obj, obj2;
	// Get the current value(s) of all select lists this list depends on
	this.dependentValues=new Object;
	var dependentValuesInitialized = false;

	for (i=0; i<this.dependencies.length; i++){
			var sel = theform[this.dependencies[i]];
			var selName = sel.name;
			// If this is the first dependent list, just fill in the dependentValues
			if (!dependentValuesInitialized){
				dependentValuesInitialized=true;
				for (j=0; j<sel.options.length; j++){
						if (sel.options[j].selected){
							this.dependentValues[sel.options[j].value]=true;
						}
				}
			}
			// Otherwise, add new options for every existing option
				else{
				var tmpList = new Object();
				var newList = new Object();

				for (j=0; j<sel.options.length; j++){
						if (sel.options[j].selected){
							tmpList[sel.options[j].value]=true;
						}
				}

				for (obj in this.dependentValues){
						for (obj2 in tmpList){
							newList[obj+this.delimiter+obj2]=true;
						}
				}
				this.dependentValues=newList;
			}
	}

	var targetSel = theform[this.target];

	// Store the currently-selected values of the target list to maintain them (in case of multiple select lists)
	var targetSelected = new Object();

	for (i=0; i<targetSel.options.length; i++){
			if (targetSel.options[i].selected){
				targetSelected[targetSel.options[i].value]=true;
			}
	}

	targetSel.options.length=0; // Clear all target options

	for (i in this.dependentValues){
			if (typeof this.options[i]=="object"){
				var o = this.options[i];
				for (j=0; j<o.length; j+=2){
						var text = o[j];
						var val = o[j+1];
						targetSel.options[targetSel.options.length]=new Option(text, val, false, false);
						if (typeof this.defaultValues[i]!="undefined"&&this.defaultValues[i]!=null){
							for (def in this.defaultValues[i]){
									if (def==val){
										targetSelected[val]=true;
									}
							}
						}
				}
			}
	}

	targetSel.selectedIndex=- 1;

	// Select the options that were selected before
	for (i=0; i<targetSel.options.length; i++){
			if (targetSelected[targetSel.options[i].value]!=null&&targetSelected[targetSel.options[i].value]==true){
				targetSel.options[i].selected=true;
			}
	}
}

// ========================================================================================================================
//Verifica un EMail
function emailCheck (emailStr){
	var emailPat = /^(.+)@(.+)$/
	var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars = "\[^\\s"+specialChars+"\]"
	var quotedUser = "(\"[^\"]*\")"
	var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom = validChars+'+'
	var word = "("+atom+"|"+quotedUser+")"
	var userPat = new RegExp("^"+word+"(\\."+word+")*$")
	var domainPat = new RegExp("^"+atom+"(\\."+atom+")*$")
	var matchArray = emailStr.match(emailPat)

	if (matchArray==null){
		alert("Verifique @ y puntos en el E-Mail.");
		return (false)
	}

	var user = matchArray[1]
	var domain = matchArray[2]

	if (user.match(userPat)==null){
		alert("Verifique el nombre de usuario en su E-Mail.");
		return (false)
	}

	var IPArray = domain.match(ipDomainPat)

	if (IPArray!=null){
		for (var i = 1; i<=4; i++){
				if (IPArray[i]>255){
					alert("Verifique la dirección I.P. de su E-Mail")
					return (false);
				}
		}
		return (true);
	}

	var domainArray = domain.match(domainPat)

	if (domainArray==null){
		alert("Verifique el dominio en su E-Mail.");
		return (false);
	}

	var atomPat = new RegExp(atom, "g")
	var domArr = domain.match(atomPat)
	var len = domArr.length

	if (domArr[domArr.length-1].length<2||domArr[domArr.length-1].length>3){
		alert("El E-Mail debe terminar en tres letras de dominio o en dos de país.");
		return (false);
	}

	if (len<2){
		var errStr = "This address is missing a hostname!";
		alert(errStr);
		return (false)
	}
	return (true);
}

// ========================================================================================================================
// Capitaliza de diferentes maneras
function cap (str){
	result=str.substr(0, 1).toUpperCase()+str.substr(1).toLowerCase();
	return (result);
}

function capAll (txtVar){
	MyText=trim(txtVar.value);
	txtVar.value=MyText.substr(0).toUpperCase();
}

function capWord (txtVar){
	MyText=trim(txtVar.value);
	var pattern = /(\w)(\w*)/;               // a letter, and then one, none or more letters 
	var a = MyText.split(/\s+/g);            // split the sentence into an array of words

	for (i=0; i<a.length; i++){
			var parts = a[i].match(pattern); // just a temp variable to store the fragments in.

			var firstLetter = parts[1].toUpperCase();
			var restOfWord = parts[2];

			a[i]=firstLetter+restOfWord; // re-assign it back to the array and move on
	}
	txtVar.value=a.join(' ');            // join it back together
}

// ========================================================================================================================
// Resetea todos los valores de los campos recibiendo el ID del Objeto a resetear
function resetValues (a){
	if (a){
		target=eval("document.all."+a);
	}else{
		target=eval("document")
	}

	arrFields=target.getElementsByTagName("SELECT");   // Obtiene una matriz con todos los elementos SELECT del objeto

	for (x=0; x<arrFields.length; x++)                 // Hace el loop sobre la matriz
		arrFields[x].options[0].selected=true;         // Selecciona la primera opción del menú

	arrFields=target.getElementsByTagName("INPUT");    // Obtiene una matriz con todos los elementos INPUT del objeto

	for (x=0; x<arrFields.length; x++)                 // Hace el loop sobre la matriz
		arrFields[x].value="";                         // Pone el valor en blanco

	arrFields=target.getElementsByTagName("TEXTAREA"); // Obtiene una matriz con todos los elementos TEXTAREA del objeto
	for (x=0; x<arrFields.length; x++)                 // Hace el loop sobre la matriz
		arrFields[x].value="";                         // Pone el valor en blanco
}

// ========================================================================================================================
// Recibe:
// a: el menú a reescribir
// b: el texto y valor de la nueva opción (texto*valor)

function insertOption (a, b){
	menu=document.getElementById(a);
	selectTxt=menu.options[0].innerText; //Almacena el texto en la primera opción del menú
	menu.options[0]=null;                // Borra la primera entrada del menú que generalmente debe ser 'Seleccione'.
	arrVals=new Array();                 // Crea una matriz con los datos a almacenar;

	for (i=0; i<menu.length; i++){       // Extrae los datos del menú en pares label*valor
			val=menu.options[i].value;
			text=cap(menu.options[i].innerText);
			arrVals[i]=text+"*"+val;
	}

	for (i=menu.length; i>0; i--)                              //Borra todas las entradas del menú
		menu.options[i-1]=null;

	arrVals[arrVals.length]=cap(b);                            // Pone el dato (label*valor) como último elemento de la matriz
	arrVals=arrVals.sort();                                    // Ordena la matriz
	menu.options[0]=new Option(selectTxt, 0)                   //Crea la primera opción del menú usando el texto almacenado inicialmente
	for (i=0; i<arrVals.length; i++){                          // Hace el loop final sobre la matriz
			arrTmp=arrVals[i].split("*");                      // Crea una matriz de dos elementos (label*valor) por cada elemento de la matriz ppal.
			menu.options[i+1]=new Option(arrTmp[0], arrTmp[1]) // Adicione el item en el menú usando el método 'new Option (label, valor)';
	}
}

function cleanMenu (a){
	target=document.getElementById(a);
	for (i=target.length; i>0; i--) //Borra todas las entradas del menú
		target.options[i-1]=null;
}

// ========================================================================================================================
// Devuelve una referencia al objeto padre especificado. Parametros: (objeto de origen, tag del elemento a devolver)
function getParentTagObj (obj, tag){
	element=obj.parentElement;
	while(element.tagName!=tag)
		element=element.parentElement;
	return (element); // Devuelve la refencia al objeto
}

// ========================================================================================================================
// Permite sólo el ingreso de números en el campo. onkeypress="return numbers()"
function numbers(){
	if (event.keyCode<48||event.keyCode>57) return (false);
}

// ========================================================================================================================
// Formatea un número en moneda así: $ 7.667.453,00
function formatCurrency (strValue){
	strValue=strValue.toString().replace(/\$|\,/g, '');
	dblValue=parseFloat(strValue);
	blnSign=(dblValue==(dblValue=Math.abs(dblValue)));
	dblValue=Math.floor(dblValue*100+0.50000000001);
	intCents=dblValue%100;
	strCents=intCents.toString();
	dblValue=Math.floor(dblValue/100).toString();

	if (intCents<10) strCents="0"+strCents;

	for (var i = 0; i<Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue=dblValue.substring(0, dblValue.length-(4*i+3))+'.'+dblValue.substring(dblValue.length-(4*i+3));
	//return (((blnSign) ? '' : '-')+'$ '+dblValue+','+strCents);
	return (((blnSign) ? '' : '-')+'$ '+dblValue);
}

// ========================================================================================================================
// Valida una fecha en formato dd/mm/yyyy
function valDate (field){
	date2val=field.value;
	var Datevalue = "";
	var DateTemp = "";
	var day;
	var month;
	var year;
	var leap = 0;

	if (date2val==""){
		alert("Ingrese alguna fecha. El formato es dd/mm/aaaa.");
		field.className="error";
		field.focus();
		return (false);
	}

	DateValue=date2val;
	//  Delete all chars except 0 to 9 
	checkstr="0123456789";

	for (i=0; i<DateValue.length; i++){
			if (checkstr.indexOf(DateValue.substr(i, 1))>=0) DateTemp=DateTemp+DateValue.substr(i, 1);
	}

	DateValue=DateTemp;

	//  Always change date to 8 digits - string, if year is entered as 2-digit / always assume 20xx
	if (DateValue.length==6) DateValue=DateValue.substr(0, 4)+'20'+DateValue.substr(4, 2);

	if (DateValue.length!=8){
		alert("Ingrese una fecha válida. El formato es dd/mm/aaaa.");
		field.className="error";
		field.focus();
		return (false);
	}

	//  year is wrong if year = 0000
	year=DateValue.substr(4, 4);

	if (year==0){
		alert("El año no puede ser 0.");
		field.className="error";
		field.focus();
		return (false);
	}

	//  Validation of month
	month=DateValue.substr(2, 2);

	if ((month<1)||(month>12)){
		alert("El mes debe estar entre 1 y 12.");
		field.className="error";
		field.focus();
		return (false);
	}

	//  Validation of day
	day=DateValue.substr(0, 2);

	if (day<1){
		alert("El día debe ser mayor que 1.");
		field.className="error";
		field.focus();
		return (false);
	}

	//  Validation leap-year / february / day 
	if ((year%4==0)||(year%100==0)||(year%400==0)) leap=1;

	if ((month==2)&&(leap==1)&&(day>29)){
		alert("En Febrero el día no puede ser mayor a 29");
		field.className="error";
		field.focus();
		return (false);
	}

	if ((month==2)&&(leap!=1)&&(day>28)){
		alert("En Febrero el día no puede ser mayor a 28");
		field.className="error";
		field.focus();
		return (false);
	}

	//  Validation of other months 
	if ((day>31)&&((month=="01")||(month=="03")||(month=="05")||(month=="07")||(month=="08")||(month=="10")||(month=="12"))){
		alert("El mes no puede tener más de 31 días.");
		field.className="error";
		field.focus();
		return (false);
	}

	if ((day>30)&&((month=="04")||(month=="06")||(month=="09")||(month=="11"))){
		alert("El mes no puede tener más de 30 días.");
		field.className="error";
		field.focus();
		return (false);
	}

	//  if 00 ist entered, no error, deleting the entry 
	if ((day==0)&&(month==0)&&(year==00)){
		alert("Ingrese una fecha válida. El formato es dd/mm/aaaa.");
		field.className="error";
		field.focus();
		return (false);
	}
	return (true);
}

// ========================================================================================================================
// FUNCIÓN PARA LOS RADIO BUTTS GRÁFICOS
function radioButt (a, b){ // Recibe la referencia del objeto que llama y el campo que alojará el valor del objeto.
	//target=eval("document.all."+a);
	var target = eval("document.all."+b);
	var parentTbl = (getParentTagId(a, "TABLE"));
	var arrOptions = parentTbl.getElementsByTagName("IMG");
	//alert(arrOptions.length);
	for (var i = 0; i<arrOptions.length; i++){
			if (arrOptions[i].src.indexOf("radio")!=- 1){
				if (arrOptions[i].id==a.id){
					arrOptions[i].src="../media/images/radioButt1.gif";
					target.value=arrOptions[i].value;
				}else{
					arrOptions[i].src="../media/images/radioButt0.gif";
				}
			}
	}
//alert(target.value);
}

// ========================================================================================================================
//REEMPLAZA UN TEXTO
function replaceChars (texto, buscar, reemplazar){
	temp=""+texto; // temporary holder

	while(temp.indexOf(buscar)>- 1){
		pos=temp.indexOf(buscar);
		temp=""+(temp.substring(0, pos)+reemplazar+temp.substring((pos+buscar.length), temp.length));
	}
	return temp;
}

// ========================================================================================================================
//HACE UNA PAUSA EN UN SCRIPT
function pause (Amount){
	d=new Date()        //today's date
	while(1){
		mill=new Date() // Date Now
		diff=mill-d     //difference in milliseconds
		if (diff>Amount) break;
	}
}

// ========================================================================================================================
//HACE UNA PAUSA EN UN SCRIPT
function showHide (el, img, plusimg, minusimg){
	target=document.getElementById(el);
	targetimg=document.getElementById(img);
	if (target.style.display=="none"){
		target.style.display="";
		targetimg.src=minusimg;
	}else{
		target.style.display="none";
		targetimg.src=plusimg;
	}
}

// ========================================================================================================================
// FUNCIONES CON CADENAS

// Extrae el número de caracteres a la izquierda
function left (str, number){
	//alert("String: "+str+", Number: "+number);
	str=str.substring(0, number)
	return str;
}

// Extrae el número de caracteres a la derecha
function right (str, number){
	str=str.substring(str.length-number)
	return str;
}

// Elimina el número de caracteres a la derecha
function delRight (str, number){
	str=str.substring(0, str.length-number)
	return str;
}

// Elimina el número de caracteres a la izquierda
function delLeft (str, number){
	str=str.substring(number)
	return str;
}

// devuleve true si se encuentra una cadena
function contains (str, tosearch){
	if (str.indexOf(tosearch)>- 1) return true;
	else return false;
}

// Extrae una cadena desde un caracter (o caracteres) especificados sin incluirlo(s)
function extFrom (str, chars){
	if (str.indexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return str.substring(init+1);
	}else return 'No se encontró el caractér de inicio especificado.';
}

// Extrae una cadena desde un caracter (o caracteres) especificados sin incluirlo(s)
function leftExtFrom (str, chars){
	if (str.indexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return str.substring(init+1);
	}else return 'No se encontró el caractér de inicio especificado.';
}

// Extrae una cadena desde un caracter (o caracteres) a la derecha especificados sin incluirlo(s)
function rightExtFrom (str, chars){
	if (str.lastIndexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return str.substring(init+1);
	}else return 'No se encontró el caractér de inicio especificado.';
}

// Extrae una cadena hasta un caracter (o caracteres) especificados sin incluirlo(s)
function extTo (str, chars){
	if (str.indexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return left(str, init)
	}else return 'No se encontró el caractér de inicio especificado.';
}
 // Elimina el caracter de una cadena especificada
function delSubstr(valor, caracter){
	b=valor;
	while(b.indexOf(caracter)>=0)
		b=b.replace(caracter,"");
	return b;
}

// Reemplaza un texto por otro en una cadena, recurrente.
function StrReplace (texto, buscar, reemplazar){
	temp=""+texto; // temporary holder

	while(temp.indexOf(buscar)>- 1){
		pos=temp.indexOf(buscar);
		temp=""+(temp.substring(0, pos)+reemplazar+temp.substring((pos+buscar.length), temp.length));
	}

	return temp;
}

// Extrae el número de caracteres a la izquierda
function StrLeft (str, number){
	//alert("String: "+str+", Number: "+number);
	str=str.substring(0, number)
	return str;
}

// Extrae el número de caracteres a la derecha
function StrRight (str, number){
	str=str.substring(str.length-number)
	return str;
}

// Elimina el número de caracteres a la derecha
function StrRightDel (str, number){
	str=str.substring(0, str.length-number)
	return str;
}

// Elimina el número de caracteres a la izquierda
function StrLeftDel (str, number){
	str=str.substring(number)
	return str;
}

// devuleve true si se encuentra una cadena
function StrContains (str, tosearch){
	if (str.indexOf(tosearch)>- 1) return true;
	else return false;
}

// Extrae una cadena desde un caracter (o caracteres) especificados sin incluirlo(s)
function StrExtFrom (str, chars){
	if (str.indexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return str.substring(init+1);
	}else return 'No se encontró el caractér de inicio especificado.';
}

// Extrae una cadena desde un caracter (o caracteres) especificados sin incluirlo(s)
function StrLeftExtFrom (str, chars){
	if (str.indexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return str.substring(init+1);
	}else return 'No se encontró el caractér de inicio especificado.';
}

// Extrae una cadena desde un caracter (o caracteres) a la derecha especificados sin incluirlo(s)
function StrRightExtFrom (str, chars){
	if (str.lastIndexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return str.substring(init+1);
	}else return 'No se encontró el caractér de inicio especificado.';
}

// Extrae una cadena hasta un caracter (o caracteres) especificados sin incluirlo(s)
function StrExtTo (str, chars){
	if (str.indexOf(chars)>- 1){
		var init = str.indexOf(chars);
		return left(str, init)
	}else return 'No se encontró el caractér de inicio especificado.';
}
 // Elimina el caracter de una cadena especificada
function StrDelSubstr(valor, caracter){
	b=valor;
	while(b.indexOf(caracter)>=0)
		b=b.replace(caracter,"");
	return b;
}

// ========================================================================================================================
// Función para Divs Flotantes
var ns = (navigator.appName.indexOf("Netscape")!=- 1);
var d = document;
var px = document.layers ? "" : "px";

function JSFX_FloatDiv (id, sx, sy){
	var el = d.getElementById ? d.getElementById(id) : d.all ? d.all[id] : d.layers[id];
	window[id+"_obj"]=el;

	if (d.layers) el.style=el;

	el.cx=el.sx=sx;
	el.cy=el.sy=sy;
	el.sP=function (x, y){
		this.style.left=x+px;
		this.style.top=y+px;
	};

	el.init=false;
	el.flt=function (){
		var pX, pY;
		pX=(this.sx>=0) ? 0 : ns ? innerWidth : document.documentElement&&document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
		pY=ns ? pageYOffset : document.documentElement&&document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;

		if (this.sy<0) pY+=ns ? innerHeight : document.documentElement&&document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;

		this.cx+=(pX+this.sx-this.cx)/8;
		this.cy+=(pY+this.sy-this.cy)/8;

		if (!this.init){
			this.init=true;
			this.cx=pX+this.sx;
			this.cy=pY+this.sy;
		}

		this.sP(this.cx, this.cy);
		setTimeout(this.id+"_obj.flt()", 40);
	}
	return el;
}

//============================================================================================================================
// REVISA SI LA EXTENSION DE UN CAMPO "FILE" ES DE DETERMINADA EXTENSIÓN.
// Recibe como parámetros el elemento (el) y la cadena de extensiones permitidas en formato (ext*ext*ext....)

function chkext (el, exts){
	ext=rightExtFrom(el, "."); // determina la extensión del archivo elegido
	res=exts.indexOf(ext);     // Determina si la extansión se encuantra dentro de la cadena a revisar
	if (res<0) return false;
	else return true;
}

//============================================================================================================================
// Detecta el bloqueo de popups en el navegador
function popupBlocker(){
	var objChild;                            // Window
	var reWork = new RegExp('object', 'gi'); // Regular expression
	try{
		objChild=window.open('', 'child', 'width=0,height=0,status=no,resizable=yes');
		objChild.close();
	}catch(e){}

	if (!reWork.test(String(objChild))) return true; else return false;
}

//============================================================================================================================
// Abre un popup
function popup (url, width, height){ //v2.0
	features="width="+width+", height="+height+", status=no, resizable=no, titlebar=no, toolbar=no;";
	window.open(url, 'popup', features);
}

//============================================================================================================================
// Acciones con cookies

function SetCookie (cookieName, cookieValue){
	cookieValue=escape(cookieValue);
	var nowDate = new Date();
	nowDate.setMonth(nowDate.getMonth()+12);
	cookieExpires=nowDate.toGMTString();
	document.cookie=cookieName+"="+cookieValue+";expires="+cookieExpires;
}

function GetCookie (cookieName){
	var cookieValue = document.cookie;
	var cookieStartsAt = cookieValue.indexOf(" "+cookieName+"=");
	if (cookieStartsAt==- 1){
		cookieStartsAt=cookieValue.indexOf(cookieName+"=");
	}
	if (cookieStartsAt==- 1){
		cookieValue=null;
	}else{
		cookieStartsAt=cookieValue.indexOf("=", cookieStartsAt)+1;
		var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);

		if (cookieEndsAt==- 1){
			cookieEndsAt=cookieValue.length;
		}

		cookieValue=unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
	}
	return cookieValue;
}

function DelCookie (cookieName){
	var nowDate = new Date();
	nowDate.setMonth(nowDate.getMonth()-12);
	cookieExpires=nowDate.toGMTString();
	document.cookie=cookieName+"=;expires="+cookieExpires;
}

function IsCookie (cookieName){
	if (typeof(GetCookie(cookieName)) == "string")
		return true;
	else
		return false;
}

function GetTime(){
	var tag = "";
	now = new Date();
	hour = now.getHours();
	if (hour >12){
		hour = hour - 12;
		tag = "p.m."
	} else {
		tag = "a.m."
	}
	minutes = now.getMinutes();
	seconds = now.getSeconds();
	if (minutes < 10)
		minutes = "0"+minutes;
	if (seconds < 10)
		seconds = "0"+seconds;
	document.write(hour + ":" + minutes+"  " + tag);
}

function getEl(id){ // Obtiene la referencia a un objeto
	if(typeof(id)=="object") return id;
	if (document.all) return document.all[id];
	if (document.getElementById(id)) return document.getElementById(id);
	return null;
}

function getXPos(element){ //  Returns the x position works in IE and Mozilla.
	element=getEl(element);
	var x=0;
	while (element!=null){
		x+=element.offsetLeft-element.scrollLeft;
		element=element.offsetParent;
	}
	return x;
}

function getYPos(element){ //  Returns the y position works in IE and Mozilla.
	element=getEl(element);
	var y=0;
	while (element!=null){
		y+=element.offsetTop-element.scrollTop;
		element=element.offsetParent;
	}
	return y;
}

function setMnuElements(Matriz, Menu){ // Adiciona entradas a un menu de acuerdo a los contenidos de una matriz
	arr=typeof(Matriz)=="array"?Matriz:eval(Matriz);
	mnu=typeof(Menu)=="object"?Menu:getEl(Menu);
	if(mnu.length>1) for (i=mnu.length; i>1; i--) mnu.options[i-1]=null; // Borra todas las entradas dejando la primera por lo general 'Seleccione...'
	for (i=0; i<arr.length; i++){
		arr_data=arr[i].split("*"); // id*nombre
		mnu.options[i+1]=new Option(arr_data[1], arr_data[0]);
	}
	mnu.options[0].selected=true;
	mnu.disabled=false;
}


//============================================================================================================================
// Funciones para codificar cadenas a Base64

var enc64List, dec64List;

// Load the lookup arrays once
function initBase64(){
	enc64List=new Array();
	dec64List=new Array();
	var i;

	for(i=0; i<26; i++){
		enc64List[enc64List.length]=String.fromCharCode(65+i);
	}

	for(i=0; i<26; i++){
		enc64List[enc64List.length]=String.fromCharCode(97+i);
	}

	for(i=0; i<10; i++){
		enc64List[enc64List.length]=String.fromCharCode(48+i);
	}

	enc64List[enc64List.length]="+";
	enc64List[enc64List.length]="/";

	for(i=0; i<128; i++){
		dec64List[dec64List.length]=- 1;
	}

	for(i=0; i<64; i++){
		dec64List[enc64List[i].charCodeAt(0)]=i;
	}
}

function encrypt(str){
	var c, d, e, end = 0;
	var u, v, w, x;
	var ptr = -1;
	var input = str.split("");
	var output = "";

	while(end==0){
		c=( typeof input[++ptr]!="undefined") ? input[ptr].charCodeAt(0) :((end=1) ? 0 : 0);
		d=( typeof input[++ptr]!="undefined") ? input[ptr].charCodeAt(0) :((end+=1) ? 0 : 0);
		e=( typeof input[++ptr]!="undefined") ? input[ptr].charCodeAt(0) :((end+=1) ? 0 : 0);
		u=enc64List[c>>2];
		v=enc64List[(0x00000003&c)<<4|d>>4];
		w=enc64List[(0x0000000F&d)<<2|e>>6];
		x=enc64List[e&0x0000003F];

		// handle padding to even out unevenly divisible string lengths
		if (end>=1){
			x="=";
		}

		if (end==2){
			w="=";
		}
		if (end<3){
			output+=u+v+w+x;
		}
	}

	// format for 76-character line lengths per RFC
	var formattedOutput = "";
	var lineLength = 76;

	while(output.length>lineLength){
		formattedOutput+=output.substring(0, lineLength)+"\n";
		output=output.substring(lineLength);
	}

	formattedOutput+=output;
	return formattedOutput;
}

function decrypt(str){
	var c = 0, d = 0, e = 0, f = 0, i = 0, n = 0;
	var input = str.split("");
	var output = "";
	var ptr = 0;

	do{
		f=input[ptr++].charCodeAt(0);
		i=dec64List[f];
		if (f>=0&&f<128&&i!=- 1){
			if (n%4==0){
				c=i<<2;
			}else if (n%4==1){
				c=c|(i>>4);
				d=(i&0x0000000F)<<4;
			}else if (n%4==2){
				d=d|(i>>2);
				e=(i&0x00000003)<<6;
			}else{
				e=e|i;
			}

			n++;
			if (n%4==0){
				output+=String.fromCharCode(c)+String.fromCharCode(d)+String.fromCharCode(e);
			}
		}
	}while(typeof input[ptr]!="undefined");

	output+=(n%4==3) ? String.fromCharCode(c)+String.fromCharCode(d) :((n%4==2) ? String.fromCharCode(c) : "");
	return output;
}

function StrD(word){
	return decrypt(decrypt(word));
}

// Self-initialize the global variables
initBase64();

function CenterPopup(width, height){
	windowWidth=width;
	windowHeight=height;
	if (parseInt(navigator.appVersion) >= 4) window.moveTo((screen.width/2)-(windowWidth/2+10),(screen.height/2)-(windowHeight/2+20));
}
