
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//------------------------------------------

function ida() {
	document.getElementById('dia_v').disabled = true;
	document.getElementById('mes_v').disabled = true;
}

function idavuelta() {
	document.getElementById('dia_v').disabled = false;
	document.getElementById('mes_v').disabled = false;
}

function nodebuenos() {
	if (document.getElementById('origen').value == 28 || document.getElementById('origen').value == 16) {
		document.getElementById('dia_v').disabled = true;
		document.getElementById('mes_v').disabled = true;
		document.getElementById('idv2').checked = true;
	} else {
		document.getElementById('dia_v').disabled = false;
		document.getElementById('mes_v').disabled = false;
		document.getElementById('idv1').checked = true;
	}
}

function noneall () {
	//document.getElementById('a').style.display = 'none';
	document.getElementById('b').style.display = 'none';
	document.getElementById('c').style.display = 'none';
	document.getElementById('d').style.display = 'none';
}
function show (element) {
	noneall();
	document.getElementById(element).style.display = '';
}
function hidde (element) {
	document.getElementById(element).style.display = 'none';
}

//--------------------------------------
function generic_test (checkMe,messtxt) {
	var theResult = true;
	if (checkMe.value == "" || checkMe.value == "undefined" || checkMe.value == "null") {
		alert(messtxt);
		theResult = false;
		checkMe.focus();
		checkMe.select();
	}
	return theResult;
}
function select_test (checkMe,messtxt) {
	var theResult = true;
	if (checkMe.value == "" || checkMe.value == "undefined" || checkMe.value == "null") {
		alert(messtxt);
		theResult = false;
		checkMe.focus();
	}
	return theResult;
}
function email_test (checkMe,messtxt) {
	var theResult = true;
	if (checkMe.value.indexOf('@') == -1 || checkMe.value.indexOf('.') == -1 || checkMe.value == "" || checkMe.value == "undefined" || checkMe.value == "null") {
		alert(messtxt);
		theResult = false;
		checkMe.focus();
		checkMe.select();
	}
	return theResult;
}
function numeric_test (checkMe,messtxt) {
	var theResult = true;
	if (checkMe.value == "" || checkMe.value == "undefined" || checkMe.value == "null" || isNaN(checkMe.value)) {
		alert(messtxt);
		theResult = false;
		checkMe.focus();
		checkMe.select();
	}
	return theResult;
}
function repassword_test (checkMe,recheckMe,messtxt) {
	var theResult = true;
	if (recheckMe.value == "" || recheckMe.value == "undefined" || recheckMe.value == "null" || recheckMe.value != checkMe.value) {
		alert(messtxt);
		theResult = false;
		checkMe.focus();
		checkMe.select();
	}
	return theResult;
}


//-----------------------------------
function cerrarSesion()
{
	if(confirm('¿Está seguro que desea cerrar la sesión y salir del sistema?'))
		document.location = 'request.php?tarea=LOGOUT';
}

function mapaclick(destino)
{
	url = "?destino=" + destino;
	document.location.replace(url);
}

function start_calendar()
{
	calendar_posLeft = 56;
	calendar_posTop = -65;
	boton = getObj('button_calendar');
	fecha = getObj('fecha');
	displayCalendar(fecha, "dd-mm-yyyy", boton);
}

//funcion relacionada con maskInput
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

//funcion relacionada con maskInput
removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

//maskInput se usa como mascara para los campos FECHA
maskInput = function(f, m)
{
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
			rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};

function getHtml(obj)
{
	obj = getObj(obj);
	return (isDef(obj)? obj.innerHTML : "");
}

function arrayIndexOf(arr, obj, start)
{
	start = (start) ? start : 0;
	for(var i=start; i<arr.length; i++)
	{
		if(arr[i]==obj)
			return i;
	}
	return -1;
}

//devuelve una referencia al objeto
function getObj(obj)
{
	return (document.getElementById(obj));
}


//devuelve si es un Array o no
function isArray(obj)
{
	return (isObj(obj) && obj.constructor == Array);
}


//devuelve si un valor esta dentro de un array
function inArray(arr, val)
{
	//ret = arr.indexOf(val) != -1;
	ret = arrayIndexOf(arr, val) != -1;
	return ret
}

//devuelve si es Undefined o no
function isDef(val)
{
	return ((typeof(val)=="undefined") || (val==null) ? false : true);
}

//devuelve si es Objeto o no
function isObj(val)
{
	return (typeof(val)=="object");
}

//devuelve una propiedad especifica de un objeto
function objProp(obj, propName)
{
	return obj.getAttribute(propName);
}

//devuelve las coord de un obj en un array[posLeft, posTop]
function objPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

//cambia el class style de un objeto
function objStyle(obj, style)
{
	obj = getObj(obj);
	if (obj != null)
	{
		obj.className = style;
	}
}

//cambia el class style de un objeto
function changeStyle(NomObj, estilo1, estilo2)
{
	objeto = getObj(NomObj);
	if (objeto != null)
	{
		estilo_actual = objeto.className;
		estilo_actual = estilo_actual.toLowerCase();
		estilo1 = estilo1.toLowerCase();
		estilo2 = estilo2.toLowerCase();
		if (estilo_actual == estilo1)
			objeto.className = estilo2;
		else
			objeto.className = estilo1;
	}
}

function trim(txt)
{
	txt = "" + txt;
	txt = txt.replace(/^\s+|\s+$/g,'');
	return(txt);
}

function replace(strOrig, strBuscar, strNew)
{
	ret = strOrig;
	while (ret.indexOf(strBuscar) > -1)
	{
		pos = ret.indexOf(strBuscar);
		ret = "" + (ret.substring(0, pos) + strNew + ret.substring((pos + strBuscar.length), ret.length));
	}
	return ret;
}

//parametro 'insens' (opcional) (default=true)= insensible a mayus/minus
function strReplace(strOrig, strBuscar, strNew, insens)
{
	insens = (!isDef(insens) || insens) ? "i" : "";
	strBuscar = new RegExp(strBuscar, "g"+insens);
	return strOrig.replace(strBuscar, strNew);
}

function xor(v1, v2)
{
	v1 = empty(v1);
	v2 = empty(v2);
	res = (v1 ^ v2) ? true : false;
	return res;
}

function empty(val)
{
	if(!isDef(val)) return true;
	if(val==null) return true;
	if(trim("" + val)=="") return true;
	return false;
}

function vacio(val)
{
	return (empty(val));
}

function clear(val)
{
	ret = val;
	ret = (empty(ret)) ? "" : ret;
	ret = (isObj(ret)) ? ret.value : ret;
	return ret;
}

//convierte a minusculas.
function low(val)
{
	return (empty(val) ? val : val.toLowerCase());
}
//convierte a mayusculas.
function upp(val)
{
	return (empty(val) ? val : val.toUpperCase());
}

function debug()
{
	return debug_r(arguments);
}

function debug_r(arrvals)
{
	var ret = "";
	if (typeof(arrvals) == "string")
		arrvals = arrvals.split(",");

	for (i = 0; i < arrvals.length; i++)
	{
		ret += "" + " = " + arrvals[i] + "\n";
	}
	alert(ret);
	return;
}

function isNum(val)
{
	if(empty(val)) return false;
	var str = "1234567890,.";
	for(i = 0; i < val.length; i++)
	{
		tmp = val.substring(i,i+1);
		if (str.indexOf(tmp, 0) == -1)
		return false;
	}
	return true;
}

function cInt(val)
{
	if (empty(val) || isNaN(val)) val = 0;
	return parseInt(val,10);
}

function abs(val)
{
	return Math.abs(val);
}

function floor(val)
{
	return Math.floor(val);
}

//verifica si es un email válido
function isMail(emailStr, req)
{
	if(!isDef(req)) req = false;
	if(!req && empty(emailStr)) return true;

	var emailStr = trim(emailStr);
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var firstChars=validChars
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom="(" + firstChars + 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) return false;

	var user=matchArray[1]
	var domain=matchArray[2]

	if (user.match(userPat)==null) return false;

	var domainArray=domain.match(domainPat)

	if (domainArray==null) 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)
		return false;

	if (domArr[domArr.length-1].length==3 && len<2)
		return false;

	return true;

}


// VALIDACION DE FECHAS ***************************

//año bisiesto? true/false
function leap(year)
{
	return (year % 4 == 0);
}

//cantidad de dias para cada mes del año
function month_days(month)
{
	switch (parseInt(month,10))
	{
		case 1:	return 31;	break;
		case 2:	return 29;	break;
		case 3:	return 31;	break;
		case 4:	return 30;	break;
		case 5:	return 31;	break;
		case 6:	return 30;	break;
		case 7:	return 31;	break;
		case 8:	return 31;	break;
		case 9:	return 30;	break;
		case 10:return 31;	break;
		case 11:return 30;	break;
		case 12:return 31;	break;
		default:return 31;
	}
}

function fechaOk(fecha)
{
	if(empty(fecha)) return false;
	if(fecha.length != 8 && fecha.length != 10) return false;
	dia = fechaParte(fecha, "d");
	mes = fechaParte(fecha, "m");
	anio = fechaParte(fecha, "a");
	if(dia > month_days(mes)) return false;
	if(mes == 2 && !leap(anio) && dia > 28) return false;
	return true;
}

function horaOk(hora)
{
	if(empty(hora)) return false;
	if(hora.length != 5) return false;
	h = hora.substr(0, 2);
	m = hora.substr(3, 2);
	if(h<0 || h>23) return false;
	if(m<0 || m>59) return false;
	return true;
}


function formatDate(fecha)
{
	if(!isDef(fecha) || low(fecha)=="hoy")
	{
		fecha = new Date();
		dia = fecha.getDate();
		mes = fecha.getMonth() +1;
		anio = fecha.getFullYear();
		//debug(dia, mes, anio);
	}
	else
	{
		dia = fechaParte(fecha, "d");
		mes = fechaParte(fecha, "m");
		anio = fechaParte(fecha, "a");
	}
	fecha = anio + "/" + mes + "/" + dia;
	//debug(fecha);
	//return new Date( parseInt(anio), parseInt(mes-1), parseInt(dia), 0,0,0);
	return new Date(fecha);
}

function fechaMayor(fecha1, fecha2)
{
	return fechaDif(fecha1, fecha2, "MAYOR");
}

function horaMayor(hora1, hora2)
{
	hora1 = new Date("1970/01/01 " + hora1);
	hora2 = new Date("1970/01/01 " + hora2);
	//debug(hora1, hora2, (hora1 == hora2));
	if(hora1 > hora2) return 1;
	else if(hora1 < hora2) return 2;
	else return 0;
}

function fechaParte(fecha, parte)
{
	dia = fecha.substr(0, 2);
	mes = fecha.substr(3, 2);
	anio = fecha.substr(6);
	if(anio.length < 4)
	{
		if(parseInt(anio) < 70) anio = "20" + anio;
		else anio = "19" + anio;
	}
	switch(low(parte))
	{
		case "d": case "dia": case "day":
			return dia;
			break;
		case "m": case "mes": case "month":
			return mes;
			break;
		case "a": case "anio": case "y": case "year":
			return anio;
			break;
	}
}




function fechaDif(fecha1, fecha2, intervalo)
{
	fecha1 = formatDate(fecha1);
	fecha2 = formatDate(fecha2);

	//resto a una fecha la otra en segundos
	seg_dif = fecha1 - fecha2;
	seg_dif = seg_dif / 1000; //correccion JS

	min_dif = seg_dif / 60; //segundos a minutos
	horas_dif = min_dif / 60; //minutos a horas
	dias_dif = horas_dif / 24; //horas a días
	meses_dif = dias_dif / 31; //días a meses
	anios_dif = meses_dif / 12; //meses a años



	if(!isDef(intervalo)) intervalo = "D";
	intervalo = upp(intervalo);
	retMayor = false;
	if(intervalo == "MAYOR")
	{
		intervalo = "S";
		retMayor = true;
	}

	switch(intervalo)
	{
		case "H":	ret = horas_dif;	break;
		case "I":	ret = min_dif;		break;
		case "S":	ret = seg_dif;		break;
		case "M":	ret = meses_dif;	break;
		case "Y":	ret = anios_dif;	break;
		case "D":
		default:	ret = dias_dif;		break;
	}


	if(retMayor)
	{
		ret = floor(ret);
		if(ret > 0) {ret = 1;}
		else if(ret < 0) {ret = 2;}
		else {ret = 0;}
	}
	else
	{
		ret = abs(ret);
		ret = floor(ret);
	}

	return ret;

}

// FIN FECHAS ******************************


//recibe un objeto "checkbox" o "radio"...
//devuelve TRUE si hay algun elemento "checked"
//si no, FALSE
function chkOptions(obj)
{
	if(isDef(obj.length))
	{
		for (var i=0; i < obj.length; i++)
		{
			if(obj[i].checked) return true;
		}
		return false;
	}
	else
	{
		return obj.checked;
	}
}

var accChk = false;

//accion 0=check/uncheck
//accion 1=validar si hay checked
//accion 2=devolver array values checked
function chkAll(objName, L, accion)
{
	accChk = !accChk;
	if(!isDef(accion)) accion=0;
	if(accion==2) arrVal = new Array();
	var j=0;
	for (var i=0; i <= L; i++)
	{
		obj = getObj(objName + "[" + i + "]");
		//debug(L, i, j, obj);
		if(isDef(obj))
		{
			switch(accion)
			{
				case 1: if(obj.checked) return true; break;
				case 2: if(obj.checked) {arrVal[j] = obj.value; j++;} break;
				default: obj.checked = accChk; break;
			}
			//debug(accion, L, j, arrVal);
		}

	}
	switch(accion)
	{
		case 1: return false; break;
		case 2: return arrVal; break;
		default: return true; break;
	}
}


// CONTROLES DE FORMS (COMBOS, INPUTS, BOTONES)
function selected(valor, selec, tipo)
{
	ret = "";
	str_selec = "selected";
	if(!empty(tipo) && low(tipo)=='chk') str_selec = "checked";
	//debug(valor, selec);
	valor = low(trim(valor));

	selec = low(trim(selec));
	if (valor == selec) ret = " str_selec ";
	return ret;
}

//devuelve un input text
function input_text(nombre, valor, maxL, size, op)
{
	if(empty(maxL)) maxL=50;
	if(empty(size)) size=53;
	ret  = "<input type='text' id='" + nombre + "' name='" + nombre + "' value='" + valor + "' maxlength='" + maxL + "' size='" + size + "' " + clear(op) + " />";
	return ret;
}

//devuelve un input hidden
function input_hidden(nombre, valor, op)
{
	ret  = "<input type='hidden' id='" + nombre + "' name='" + nombre + "' value='" + valor + "' " + clear(op) + " />";
	return ret;
}
//devuelve un input radio o checkbox
function input_option(nombre, valor, selec, tipo, op)
{
	tipo = (tipo==0) ? "checkbox" : "radio";
	ret  = "<input type='" + tipo + "' id='" + nombre + "' name='" + nombre + "' value='" + valor + "' " + selected(valor, selec, 'chk') + " " + clear(op) + " />";
	return ret;
}

function cancelarAccion(url, strAccion)
{
	//if(empty(strAccion)) strAccion = "la Operación";
	if(empty(url)) url = "";
	ok = empty(strAccion) ? true : confirm("¿Confirma que desea " + strAccion + "?");
	if(ok) document.location.replace(url);
}


function ocultarCombos(ocultar)
{
	vis = (ocultar) ? "hidden" : "visible";
	if(ie6)
	{
		combos = document.getElementsByTagName("select");
		//str = "";
		for(i=0; i < combos.length; i++)
		{
			obj = combos[i];
			hideMenu = objProp(obj, "hideMenu") ? true : false;
			if(hideMenu)
			{
				//visActual = obj.style.visibility;
				//if(low(visActual)!="hidden") visActual = "visible";
				obj.style.visibility = vis;
				//str += obj.id + " = " + hideMenu + "\n";
			}
		}
		//alert(str);
	}
}
