// v1.6.0;

/*===================================================================
 function: escapeHTML
 	Escapa el texto contenido en str y lo devuelve con las entidades
	HTML que corresponde.
 Devuelve:
	El string resultado.
 Parametros:
 	str		->	El texto a escapar.
=====================================================================*/

function escapeHTML (str)
{
	if (!str) return '';
	var div = document.createElement('div');
	var text = document.createTextNode(str);
	div.appendChild(text);
	return div.innerHTML;
}

/*===================================================================
 function: AnchorLink
 	Agrega un anchor a los elementos del id que equivale al href, esto sirve
 	para el HistoryBack button
 Devuelve:
	false
 Parametros:
 	id		->	Id del atributo que contiene los A (si se omite, son todos los A)
=====================================================================*/
function AnchorLink(id)
{
	$(id).each(function() {
		if($(this).attr('id') != "ingles" && $(this).attr('id') != "espanol")
		if( $(this).attr('href') ) {
			var aHREF = $(this).attr('href').split('?');
	 		if(aHREF.length > 1) {
				$(this).attr('href', $(this).attr('href') + "#" + aHREF[1]);
				$(this).click(function(){
					$.historyLoad(aHREF[1]);
					return false;
				});
			}
			else
			{
				$(this).click(function(){
					location.href = this.getAttribute('href');
					return false;
				});
			}
		}
	});
}

/*===================================================================
 function: BigPhoto
 	Repite Hace un efecto de poner una imagen en otro. El uso logico es
 	pasar de una imagen chica a una grande
 Devuelve:
	El string resultado.
 Parametros:
 	id		->	Id del la imagen donde se va a poner.
 	arch	->	path del archivo nuevo (relativo o absoluto).
=====================================================================*/

function BigPhoto(id, arch) {
	if( $(id).attr('src')!= arch ) {
		$(id).stop();
		$(id).stop().fadeTo(300, 0, function() {  //fade image out
	            $(id).attr('src','');  //give new image a src attribute
	            $(id).attr('src',arch);  //give new image a src attribute
	        }).fadeTo("slow", 1);
  }
	return false;
}

/*===================================================================
 function: repetir
 	Repite sTexto hasta llegar a iRepetir.
 Devuelve:
	El string resultado.
 Parametros:
 	sTexto		->	El texto a repetir.
 	iRepetir	->	La cantidad de veces.
=====================================================================*/

function repetir(sTexto, iRepetir)
{
	try
	{
		var sCompletar = '';

		if (sTexto.length != 1 ) return false;

		for(iPos = 0; iPos < iRepetir; iPos++)
			sCompletar += sTexto;

		return sCompletar;
	}
	catch(oError)
	{
		return null;
	}
}
/*===================================================================
 function: completar
 	Completa el value de oInput, con sTexto hasta llegar al máximo.
 Devuelve:
	True si todo OK, false en caso que los datos no concuerden,
	null en caso de error.
 Parametros:
 	oInput			 ->	Objeto Input de tipo.
 	sTexto			 ->	El texto a repetir.
 	bCompletarVacios ->	Completar aún si está vacio.
=====================================================================*/

function completar(oInput, sTexto, bCompletarVacios)
{
	try
	{
		if (!oInput || !sTexto		) return false;
		if (sTexto.length != 1		) return false;
		if (oInput.type   != 'text'	) return false;
		if (!bCompletarVacios && oInput.value == '') return true;

		var iMax = parseInt(oInput.getAttribute('maxLength'));
		var iRepetir = 0;
		var sCompletar = '';

		if (!isNaN(iMax) && iMax != oInput.value.length)
			iRepetir = (iMax - oInput.value.length);

		sCompletar = repetir(sTexto, iRepetir) + oInput.value;

		oInput.value = sCompletar;
		return true;
	}
	catch(oError)
	{
		return null;
	}
}

/*===================================================================
 function: seleccionar
 	Selecciona un valor de un SELECT, o el primero si no encontró
 	el valor y bPrimero es TRUE.
 Devuelve:
	No retorna ningún valor.
 Parametros:
 	oSelect	->	El objeto SELECT en el cual debe buscarse sDato.
 	Datos	->	Cadena o Array de cadenas a buscar en value del
 				SELECT.
=====================================================================*/

function seleccionar(oSelect, Datos, bPrimero)
{
	try
	{
		var sDato = null;

		if (typeof(Datos) == 'string')
			Datos = new Array(Datos);

		oSelect.selectedIndex = -1;
		for(j = 0; j < Datos.length; j++)
		{
			sDato = Datos[j];
			for(i = 0; i < oSelect.options.length; i++)
			{
				if (oSelect.options[i].value == sDato)
				{
					if (oSelect.multiple)
						oSelect.options[i].selected = true;
					else
					{
						oSelect.selectedIndex = i;
						break;
					}
				}
			}
		}

		if (bPrimero && oSelect.selectedIndex == -1 && oSelect.options.length)
			oSelect.selectedIndex = 0;

		return oSelect.selectedIndex;
	}
	catch(oError)
	{
		return false;
	}
}

/*********************************************************************
Funcion: mostrarOcultarHasta
Motivo:
	Muestra u oculta los campos, se utiliza usualmente para manejo
	de filtros DESDE - HASTA y Operacion.
Parametros:
	oSelect		->	Es SELECT que actua como filtro.
	sObjID		->	Es ID del objeto a ocultar/mostrar.
	iNoLimpiar	->	Si TRUE no inicializa el valor del INPUT encerrado
					en sObjID.
Devuelve:
	True si todo OK, false si no existe el select.
**********************************************************************/
function  mostrarOcultarHasta(oSelect, sObjID, iNoLimpiar)
{
	if (!oSelect) return false;

	if (oSelect.value != 'between')
		$('#' + sObjID).hide();
	else
		$('#' + sObjID).show();

	if (!iNoLimpiar)
	{
		$('#' + sObjID).find('*:input').each(
			function(iPos, oInput)
			{
				oInput.value = '';
			});
	}

	return true;
}

/*********************************************************************
Funcion: trim
Motivo:
	Elimina los espacios al principio y al final.
Parametros:
	cadena	->	La cadena a la que se le quiere aplicar la funcion.
Devuelve:
	La cadena resultado.
**********************************************************************/
function trim(cadena)
{
  cadena = cadena.replace(/^\s*|\s*$/g,"");
  return cadena;
}


/*===================================================================
 function: ValidarFecha
 Devuelve:
	Devuelve verdadero o falso si la fecha es verdadera o falsa
 Parametros:
 	sTexto -> La fecha como string (d/m/aaaa)
=====================================================================*/

function ValidarFecha(sFecha, sFormato)
{
	var oFormato = {dd: 0, mm: 1, yyyy: 2};

	if (!sFecha) return false;
	if (!sFormato)
		sFormato = 'dd/mm/yyyy';
	else
	{
		var aFormato = sFormato.split('/');
		for(iPos in  aFormato)
		{
			eval('oFormato.' + aFormato[iPos] + ' = ' + String(iPos));
		}
	}

	var aFecha = sFecha.split('/');
	if (aFecha.length != 3 ) return false;
	if (isNaN(parseInt(aFecha[oFormato.dd  ])) ) return false;
	if (isNaN(parseInt(aFecha[oFormato.mm  ])) ) return false;
	if (isNaN(parseInt(aFecha[oFormato.yyyy])) ) return false;

	if (sFecha.length < 10 && sFecha.length >= 8)
	{
		if (aFecha[oFormato.dd].length == 1) aFecha[oFormato.dd] = '0' + aFecha[oFormato.dd];
		if (aFecha[oFormato.mm].length == 1) aFecha[oFormato.mm] = '0' + aFecha[oFormato.mm];

		sFecha = aFecha[oFormato.dd] + '/' + aFecha[oFormato.mm] + '/' + aFecha[oFormato.yyyy];
	}
	else
		sFecha = aFecha[oFormato.dd] + '/' + aFecha[oFormato.mm] + '/' + aFecha[oFormato.yyyy];

	borrar = sFecha;
	if ((sFecha.substr(2,1) == "/") && (sFecha.substr(5,1) == "/"))
	{
		for (i=0; i<10; i++)
		{
			if (((sFecha.substr(i,1)<"0") || (sFecha.substr(i,1)>"9")) && (i != 2) && (i != 5))
			{
				borrar = '';
				break;
			}
		}
		if (borrar)
		{
			a = sFecha.substr(6,4);
			c = sFecha.substr(6,2);
			m = sFecha.substr(3,2);
			d = sFecha.substr(0,2);
			if((a < 1900) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31))
				borrar = '';
			else
			{
				if(((a%4 != 0) || ((sFecha.substr(8,2)=='00') && (c%4 != 0))) && (m == 2) && (d > 28))
					borrar = ''; // Año no bisiesto y es febrero y el dia es mayor a 28
				else
				{
					if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29)))
						borrar = '';
				}  // fin else
			} // fin else
		} // if (error)
	} // if ((sFecha.substr(2,1) == "/") && (sFecha.substr(5,1) == "/"))
	else
		borrar = '';

	if (borrar == '')
		return false;
	else
		return true;
}

/*===================================================================
 function: dateDiff
 Devuelve:
	Devuelve la diferencia en dias entre dos fechas
	Se esperan fechas con formato d/m/aaaa
 Parametros:
 	fecha1 -> La fecha hasta
 	fecha1 -> La fecha desde
=====================================================================*/

function dateDiff(fecha1, fecha2, sFormato)
{
	var aFecha1, aFecha2, diff;
	var oFormato = {dd: 0, mm: 1, yyyy: 2};

	// Si no son válidas
	if( !fecha1 || !fecha2 ||
		fecha1.length == 0  ||
		fecha2.length == 0)
		return false;

	if (!sFormato)
		sFormato = 'dd/mm/yyyy';
	else
	{
		var aFormato = sFormato.split('/');
		for(iPos in  aFormato)
		{
			eval('oFormato.' + aFormato[iPos] + ' = ' + String(iPos));
			iPos++;
		}
	}

	var aFecha1 = fecha1.split('/');
	var aFecha2 = fecha2.split('/');
	if (aFecha1.length != 3 ) return false;
	if (aFecha2.length != 3 ) return false;
	if (isNaN(parseInt(aFecha1[oFormato.dd  ])) ) return false;
	if (isNaN(parseInt(aFecha1[oFormato.mm  ])) ) return false;
	if (isNaN(parseInt(aFecha1[oFormato.yyyy])) ) return false;
	if (isNaN(parseInt(aFecha2[oFormato.dd  ])) ) return false;
	if (isNaN(parseInt(aFecha2[oFormato.mm  ])) ) return false;
	if (isNaN(parseInt(aFecha2[oFormato.yyyy])) ) return false;

	// Array con la fecha

	// getTime() devuelve la cantidad de milisegundos
	// desde 1 de Enero de 1970.
	diff = Date.UTC(aFecha1[oFormato.yyyy], (aFecha1[oFormato.mm] - 1), aFecha1[oFormato.dd]) - Date.UTC(aFecha2[oFormato.yyyy], (aFecha2[oFormato.mm] - 1), aFecha2[oFormato.dd]);

	// 86400000 es la cantidad de milisegundos en un dia
	if (!isNaN(diff))
		return (diff/86400000 * -1);
	else
		return 0;

}

/*===================================================================
 function: dateTimeDiff
 Devuelve:
	Devuelve la diferencia en dias entre dos fechas
	Se esperan fechas con formato:
		d/m/aaaa hh:mm:ss:ms
	puede ser:
		mes/anio, d/m/aaaa, d/m/aaaa hh, d/m/aaaa hh:mm, d/m/aaaa hh:mm:ss, d/m/aaaa hh:mm:ss:ms
	Si el dia no es provisto se utiliza "1" para el mismo.
 Parametros:
 	fecha1 -> La fecha hasta
 	fecha1 -> La fecha desde
=====================================================================*/

function dateTimeDiff(fecha1, fecha2)
{
	var vecFecha1, vecFecha2, diff;

	// Si no son válidas
	if(fecha1.length <= 0 || fecha2.length <= 0)
		return 0;

	// Array con la fecha
	vecFechaHora1 = fecha1.split(' ');
	vecFechaHora2 = fecha2.split(' ');

	vecFecha1 = vecFechaHora1[0].split('/');
	vecFecha2 = vecFechaHora2[0].split('/');

	if (vecFechaHora1.length > 1)
		vecHora1 = vecFechaHora1[1].split(':');
	else
		vecHora1 = new Array();

	if (vecFechaHora2.length > 1)
		vecHora2 = vecFechaHora2[1].split(':');
	else
		vecHora2 = new Array();


	if (vecFecha1.length >= 2)
	{
		if (vecFecha1.length == 2)
			date1 = Date.UTC(vecFecha1[0], (vecFecha1[1] - 1), 1);

		else if (vecHora1.length == 0 &&  vecFecha1.length == 3)
			date1 = Date.UTC(vecFecha1[2], (vecFecha1[1] - 1), vecFecha1[0]);

		else if (vecHora1.length == 1 &&  vecFecha1.length == 3)
			date1 = Date.UTC(vecFecha1[2], (vecFecha1[1] - 1), vecFecha1[0], vecHora1[0]);

		else if (vecHora1.length == 2 &&  vecFecha1.length == 3)
			date1 = Date.UTC(vecFecha1[2], (vecFecha1[1] - 1), vecFecha1[0], vecHora1[0], vecHora1[1]);

		else if (vecHora1.length == 3 &&  vecFecha1.length == 3)
			date1 = Date.UTC(vecFecha1[2], (vecFecha1[1] - 1), vecFecha1[0], vecHora1[0], vecHora1[1], vecHora1[2]);

		else if (vecHora1.length == 4 &&  vecFecha1.length == 3)
			date1 = Date.UTC(vecFecha1[2], (vecFecha1[1] - 1), vecFecha1[0], vecHora1[0], vecHora1[1], vecHora1[2], vecHora1[3]);

		else
			return 0;

		////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if (vecFecha2.length == 2)
			date2 = Date.UTC(vecFecha2[0], (vecFecha2[1] - 1));

		else if (vecHora2.length == 0 &&  vecFecha2.length == 3)
			date2 = Date.UTC(vecFecha2[2], (vecFecha2[1] - 1), vecFecha2[0]);

		else if (vecHora2.length == 1 &&  vecFecha2.length == 3)
			date2 = Date.UTC(vecFecha2[2], (vecFecha2[1] - 1), vecFecha2[0], vecHora2[0]);

		else if (vecHora2.length == 2 &&  vecFecha2.length == 3)
			date2 = Date.UTC(vecFecha2[2], (vecFecha2[1] - 1), vecFecha2[0], vecHora2[0], vecHora2[1]);

		else if (vecHora2.length == 3 &&  vecFecha2.length == 3)
			date2 = Date.UTC(vecFecha2[2], (vecFecha2[1] - 1), vecFecha2[0], vecHora2[0], vecHora2[1], vecHora2[2]);

		else if (vecHora2.length == 4 &&  vecFecha2.length == 3)
			date2 = Date.UTC(vecFecha2[2], (vecFecha2[1] - 1), vecFecha2[0], vecHora2[0], vecHora2[1], vecHora2[2], vecHora2[3]);

		else
			return 0;
	}
	else
		return 0;


	// Los meses van del 0 al 11 en JavaScript
	// new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )

	// getTime() devuelve la cantidad de milisegundos
	// desde 1 de Enero de 1970.
	diff = date1 - date2;

	// 86400000 es la cantidad de milisegundos en un dia
	if (!isNaN(diff))
		return (diff/86400000 * -1);
	else
		return 0;

}

/*===================================================================
 function: dateDiff2 - v2.0.9
 Devuelve:
	Devuelve un objeto con atributos days, months, years (sólo si
	bIncludeYears es verdadero), from, until o falso si la fechas no
	son válidas
 Parametros:
 	sFechaDesde		-> La fecha desde
 	sFechaHasta		-> La fecha hasta
 	sFormato		-> El formato de las fechas
 	bIncludeYears	-> Calcula los años y los resta de los meses
=====================================================================*/

function dateDiff2(sFechaDesde, sFechaHasta, sFormato, bIncludeYears, bDebug)
{
	bIncludeYears = (bIncludeYears ? true : false);
	giDebug = (giDebug ? giDebug : false);
	bDebug = (((bDebug || giDebug) ? true : false) ? (console ? true : false) : false);
	var aFecha1, aFecha2, diff;
	var oFormato = eval('({"dd": 0,"mm": 1,"yyyy": 2})');

	if (bIncludeYears)
		var oReturn = eval('({"days": 0, "months": 0, "years": 0, "from":"' + sFechaDesde + '", "until":"' + sFechaHasta + '"})');
	else
		var oReturn = eval('({"days": 0, "months": 0			, "from":"' + sFechaDesde + '", "until":"' + sFechaHasta + '"})');

	// Formato
	if (!sFormato)
	{
		sFormato = 'dd/mm/yyyy';
	}
	else
	{
		var aFormato = sFormato.split('/');
		for(iPos in  aFormato)
		{
			eval('oFormato.' + aFormato[iPos] + ' = ' + String(iPos));
			iPos++;
		}
	}
	if (bDebug) console.log('Formato: ' + sFormato, aFormato, oFormato);

	// Validez
	if (!ValidarFecha(sFechaHasta, sFormato) ||
		!ValidarFecha(sFechaDesde, sFormato))
	{
		if (bDebug) console.log('Fecha(s) no válida(s): ' + sFechaHasta + ' al ' + sFechaDesde);
		return false;
	}

	// Date validity
	var aFechaDesde = sFechaDesde.split('/');
	var iDesdeDD = parseInt(aFechaDesde[oFormato.dd  ], 10);
	var iDesdeMM = parseInt(aFechaDesde[oFormato.mm  ], 10);
	var iDesdeYY = parseInt(aFechaDesde[oFormato.yyyy], 10);

	if (bDebug) console.log('Fecha Desde - Array - DD MM YYYY: ', aFechaDesde, iDesdeDD, iDesdeMM, iDesdeYY);

	var aFechaHasta = sFechaHasta.split('/');
	var iHastaDD = parseInt(aFechaHasta[oFormato.dd  ], 10);
	var iHastaMM = parseInt(aFechaHasta[oFormato.mm  ], 10);
	var iHastaYY = parseInt(aFechaHasta[oFormato.yyyy], 10);

	if (bDebug) console.log('Fecha Hasta - Array - DD MM YYYY: ', aFechaHasta, iHastaDD, iHastaMM, iHastaYY);

	// mismo año y mes
	if (iDesdeYY == iHastaYY && iDesdeMM == iHastaMM)
	{
		oReturn.months = 0;
		if (bDebug) console.log('mismo año y mismo mes');
	}
	// mismo año y distinto mes
	else if (iDesdeYY == iHastaYY && iDesdeMM != iHastaMM)
	{
		oReturn.months = (iHastaMM - iDesdeMM);
		if (bDebug) console.log('mismo año y distinto mes');
	}
	// distinto año
	else
	{
		// Meses de diferencia por años
		oReturn.months = ((iHastaYY - iDesdeYY) * 12);

		// Meses de diferencia en el año coincidente
		if (iHastaMM > iDesdeMM)
			oReturn.months += (iHastaMM - iDesdeMM);
		else
			oReturn.months += (iHastaMM + (12 - iDesdeMM) - 12);

		if (bDebug) console.log('distinto año');
	}

	// Años
	if (bIncludeYears)
	{
		if (bDebug) console.log('Calcula los años');
		oReturn.years  = Math.floor(oReturn.months / 12);
		oReturn.months -= oReturn.years * 12;
	}

	// Dias de diferencia
	// hasta es mayor o igual
	if (iHastaDD >= iDesdeDD)
	{
		oReturn.days = iHastaDD - iDesdeDD;
		if (bDebug) console.log('Dias de diferencia -> Dia hasta es mayor o igual');
	}

	// hasta es menor
	else
	{
		if (oReturn.months) oReturn.months--;
		var dd = new Date(iHastaYY, (iHastaMM - 1), 0); // El mes empieza en 0
		var iDiasMesAnterior = dd.getDate();
		oReturn.days = iHastaDD + iDiasMesAnterior - iDesdeDD;
		if (bDebug) console.log('iHastaDD + iDiasMesAnterior - iDesdeDD: ', iHastaDD, iDiasMesAnterior, iDesdeDD);
		if (bDebug) console.log('Dias de diferencia -> Dia hasta es menor, se restan meses');
	}

	if (bDebug) console.log('Se retorna: ', oReturn);
	return oReturn;

}

