String.prototype.replaceAll = function(regexp, string_rep)
{
	var s = this;
	while( j = s.search(regexp)+1 )
	{
		s = s.replace(regexp, string_rep);
	}
	return s;
}

String.prototype.toDigits = function(num)
{
	var txt = this;
	while(txt.length < num){
		txt = "0" + txt;
	}
	return txt;
}

//-----------------------------------------------------------------

/**
 * Ejemplo de uso: DateTools.getFormatedDate("%Day% %d% de %Month% de %yyyy%") >> Martes 24 de Junio de 2008
 */
var DateTools =
{
	$version:	"1.0",
	$autor:		"raohmaru",
	
	getFormatedDate: function(format, L_CHAR, R_CHAR, new_fecha)
	{
		try {
			if(!String.prototype.replaceAll) throw new Error();
		} catch(e) {
			return "DateTools.getFormatedDate() necesita la librería xString.js";
		}
		
		if(L_CHAR == undefined) var L_CHAR = "%";
		if(R_CHAR == undefined) var R_CHAR = "%";
		
		var fecha = (new_fecha == undefined) ? new Date() : new_fecha,
	
			dia_semana = fecha.getDay(),
			dias_nombres = new Array("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"),
	
			dia = fecha.getDate(),  //obtengo el día del mes
		
			mes = fecha.getMonth(),
			mes_nombres = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"),
		
			anno = fecha.getFullYear(),
			
			hora = fecha.getHours(),
			hora12 = (hora > 12) ? hora-12 : hora;
			minutos = fecha.getMinutes(),
			segundos = fecha.getSeconds();
			
		var pattern_object =
		{
			MER:	(hora > 12) ? "PM" : "AM",
	
			HH: 	hora.toString().toDigits(2),
			H: 		hora,
			hh: 	hora12.toString().toDigits(2),
			h: 		hora12,
			
			MM: 	minutos.toString().toDigits(2),
			M: 		minutos,
			
			SS: 	segundos.toString().toDigits(2),
			S: 		segundos,
			
			ms:		fecha.getMilliseconds(),
			
			Day:	dias_nombres[dia_semana],
			day:	dias_nombres[dia_semana].toLowerCase(),
			dd:		dia.toString().toDigits(2),
			d:		dia,
			
			Month:	mes_nombres[mes],
			month:	mes_nombres[mes].toLowerCase(),
			mm:		(mes+1).toString().toDigits(2),
			m:		(mes+1),
			
			yyyy:	anno,
			yy:		anno.toString().substr(2)
		};
		
		for(var PATTERN in pattern_object)
		{
			// Si no hay ningún caracter de variable ("%"), se considera que todo es una plantilla (DateTools.getFormatedDate("yyyy-mm-dd HH:MM:SS"))
			if(L_CHAR == "%" && R_CHAR == "%" && format.indexOf("%") == -1) L_CHAR = R_CHAR = "";
			format = format.replaceAll(new RegExp(L_CHAR+PATTERN+R_CHAR), pattern_object[PATTERN]);
		}	
		
		return format;
	}
}
