// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=now.getDate();
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					month=i+1;
					if (month>12) { month -= 12; }
					i_val += month_name.length;
					break;
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return false; }
			}
		else { if (date > 28) { return false; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return false; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh+=12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

    
   function HoraActual ()
   {
	var marcacion = new Date();
	var Hora = marcacion.getHours();
	var Minutos = marcacion.getMinutes();
	var Segundos = marcacion.getSeconds();
	if (Hora<=9) Hora = "0" + Hora;
	if (Minutos<=9) Minutos = "0" + Minutos
	if (Segundos<=9) Segundos = "0" + Segundos
	var Ahora = Hora + ":" + Minutos + ":" + Segundos;
	return Ahora;
   }
   
  function FechaActual() {
    fec = new Date();
    day = fec.getDate();
	 month = fec.getMonth();
	 year = fec.getYear();
    formatDate(new Date(),'dd/MM/yyyy');
	 return formatDate(new Date(year,month,day-1),'dd/MM/yyyy');
  }	

  function DameFecha() {
    fec = new Date();
    day = fec.getDate();
	 month = fec.getMonth();
	 year = fec.getYear();
    formatDate(new Date(),'dd/MM/yyyy');
	 return formatDate(new Date(year,month,day),'dd/MM/yyyy');
  }	
  
  function PintarFechaSistema ()
  {
    var Fecha = DameFecha() + " " + HoraActual();
    document.write(Fecha);
  }
  

// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=now.getDate();
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					month=i+1;
					if (month>12) { month -= 12; }
					i_val += month_name.length;
					break;
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return false; }
			}
		else { if (date > 28) { return false; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return false; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh+=12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

    
   function HoraActual ()
   {
	var marcacion = new Date();
	var Hora = marcacion.getHours();
	var Minutos = marcacion.getMinutes();
	var Segundos = marcacion.getSeconds();
	if (Hora<=9) Hora = "0" + Hora;
	if (Minutos<=9) Minutos = "0" + Minutos
	if (Segundos<=9) Segundos = "0" + Segundos
	var Ahora = Hora + ":" + Minutos + ":" + Segundos;
	return Ahora;
   }
   
  function FechaActual() {
    fec = new Date();
    day = fec.getDate();
	 month = fec.getMonth();
	 year = fec.getYear();
    formatDate(new Date(),'dd/MM/yyyy');
	 return formatDate(new Date(year,month,day-1),'dd/MM/yyyy');
  }	

  function DameFecha() {
    fec = new Date();
    day = fec.getDate();
	 month = fec.getMonth();
	 year = fec.getYear();
    formatDate(new Date(),'dd/MM/yyyy');
	 return formatDate(new Date(year,month,day),'dd/MM/yyyy');
  }	
  
  function PintarFechaSistema ()
  {
    var Fecha = DameFecha() + " " + HoraActual();
    document.write(Fecha);
  }
  
// ===================================================================
// Ejemplo: 
//   Fecha Inicio: 
//     <input type="Text" id="FECHA_INICIO" onkeypress="return acceptKeysFecha(event)" 
//       onkeydown="teclaFecha(this,event)" value="01/01/2004" maxlength="10">
// ===================================================================
    /********************************************************************/
    // Nombre de la funcion: GetToken
    // Explicaci?n: Deveulve strings intermedios
    // Ejemplo: getToken('192.168.0.1', '.', 0) = '192';
    //          getToken('192.168.0.1', '.', 1) = '168';
    //          getToken('192.168.0.1', '.', 2) = '0';
    //          getToken('192.168.0.1', '.', 3) = '1';
    //          getToken('192.168.0.1', '.', 4) = '';
    //
    /********************************************************************/
    function getToken (Texto, Token, Position) {
      var TokenCount = 0;
      var idx = 0;
      while ((idx <= Texto.length) && (TokenCount < Position)) {
        if (Texto.substring(idx, idx + Token.length) == Token) {
          TokenCount++;
          idx = idx + Token.length;
        } else
          idx++;
      }
      
      var Result = "";
      while ((idx <= Texto.length) && (Texto.substring(idx, idx + Token.length) != Token)) {
        Result = Result + Texto.substring(idx, idx + 1);
        idx++;      
      }
      
      return Result;
    }
    
    /********************************************************************/
    // Nombre de la funcion: tokenCount
    // Explicaci?n: Devuelve la cantidad de elementos que hay en una 
    //   cadena. Se usa con el GetToken.
    // Ejemplo: TokenCount('192.168.0.1', '.') = 4;
    //
    /********************************************************************/
    function tokenCount (Texto, Token) {
      var idx;
      var Result = 1;
      for (idx = 1; idx <= Texto.length; idx++) {
        if (Texto.substring(idx, idx + Token.length) == Token) 
          Result++;
      }
      
      return Result;
    }
  
    function alertAllTokens(Texto, Token) {
      var idx;
      alert(Texto);
      for (idx = 0; idx <= tokenCount(Texto, Token) - 1; idx++) 
        alert(Texto + "[" + idx + "]: " + getToken(Texto, Token, idx));
    }
    
    function divide(numerator, denominator) {
      // In JavaScript, dividing integer values yields a floating point result (unlike in Java, C++, C)
      // To find the integer quotient, reduce the numerator by the remainder first, then divide.
      var remainder = numerator % denominator;
      var quotient = ( numerator - remainder ) / denominator;
      
      return quotient;
    }

    /* Days between 1/1/0001 and 12/31/1899 */
    DateDelta = 693594;

    /* The MonthDays array can be used to quickly find the number of
       days in a month:  MonthDays[IsLeapYear(Y), M] */
    var monthDays = new Array(true, false);
    monthDays[false] = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    monthDays[true] = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    
    /* IsLeapYear determines whether the given year is a leap year. */
    function isLeapYear(Year) {
      return ((Year % 4 == 0) && ((Year % 100 != 0) || (Year % 400 == 0)));
    }
    
    /* encodeDate encodes the given year, month, and day into a TDateTime value.
       The year must be between 1 and 9999, the month must be between 1 and 12,
       and the day must be between 1 and N, where N is the number of days in the
       specified month. If the specified values are not within range, an
       EConvertError exception is raised. The resulting value is the number of
       days between 12/30/1899 and the given date. */
    function encodeDate(Year, Month, Day) {
      var idx;
      var Result;
      var dayTable = monthDays[isLeapYear(Year)];
      if ((Year >= 1) && (Year <= 9999) && (Month >= 1) && (Month <= 12) && (Day >= 1) && (Day <= dayTable[Month - 1])) {
        for (idx = 1; idx <= Month - 1; idx++)
          Day += dayTable[idx - 1];
        idx = Year - 1;

        Result = (idx * 365) + divide(idx, 4) - divide(idx, 100) + divide(idx, 400) + Day - DateDelta;
        return Result;
      } else
        return NaN;
    }
    
    /********************************************************************/
    // Nombre de la funcion: strToDate
    // Explicaci?n: Devuelve la cantidad de d?as desde el 31/12/1899 de 
    //   la fecha pasada por parametro. S?lo se acepta el formato D/M/Y, 
    //   sin importar la cantidad de d?gitos. Si la fecha es incorrecta 
    //   devolverra NaN.
    // Ejemplo: strToDate('10/10/2004') = 38270;
    //
    /********************************************************************/
    function strToDate(Texto) {
      if (tokenCount(Texto, "/") != 3) return NaN;

      var iDay = Number(getToken(Texto, "/", 0));
      var iMonth = Number(getToken(Texto, "/", 1));
      var iYear = Number(getToken(Texto, "/", 2));
      if (isNaN(iDay) || isNaN(iMonth) || isNaN(iYear)) return NaN;
      
      return encodeDate(iYear, iMonth, iDay);      
    }
    
    function stringOfChar(chr, Count) {
      var idx;
      var Result = "";
      for (idx = 0; idx <= Count - 1; idx++) Result += chr;
      return Result;
    }
    
    function fillString(Texto, chr, Count) {
      var fill = stringOfChar(chr, Count - Texto.length);
      return Texto + fill;
    }
    
    function fillInteger(Numero, chr, Count) {
      var Texto = new String(Numero);
      var fill = stringOfChar(chr, Count - Texto.length);
      return fill + Texto;
    }
    
    function dateToStr(Date) {
      // Constantes
      var D1 = 365;
      var D4 = D1 * 4 + 1;
      var D100 = D4 * 25 - 1;
      var D400 = D100 * 4 + 1;
            
      // Variables
      var iDay;
      var iMonth;
      var iYear;
      var idx;
      var DayTable;
      var Result = new String;
      
      var T = DateDelta + Date;
      T--;
      iYear = 1;
      while (T >= D400) {
        T -= D400;
        iYear += 400;
      }
      idx = divide(T, D100);
      iDay = T % D100;
      if (idx == 4) {
        idx--;
        iDay += D100;
      }
      iYear += (idx * 100);
      idx = divide(iDay, D4);
      iDay = iDay % D4;
      iYear += idx * 4;
      idx = divide(iDay, D1);
      iDay = iDay % D1;
      if (idx == 4) {
        idx--;
        iDay += D1;
      }
      iYear += idx;
      DayTable = monthDays[isLeapYear(iYear)];
      iMonth = 1;
      idx = DayTable[iMonth - 1];
      while (idx <= iDay) {
        iDay -= idx;
        iMonth++;
        idx = DayTable[iMonth - 1];
      }
      iDay++;
      
      if (isNaN(iDay) || isNaN(iMonth) || isNaN(iYear)) Result = NaN
      else      
        Result = 
          fillInteger(iDay, "0", 2) + "/" + 
          fillInteger(iMonth, "0", 2) + "/" + 
          fillInteger(iYear, "0", 4);          
      
      return  Result;
    }
    
    function incDay(Fecha, Dias) {
      var dtFecha;
      if (isNaN(Fecha)) {
        dtFecha = strToDate(Fecha);
      } else {
        dtFecha = Fecha;
      }
      dtFecha += Dias;    
      if (isNaN(Fecha)) return dateToStr(dtFecha)
      else return dtFecha;
    }

    function teclaFecha(obj,e) {
      var tecla = (document.all) ? window.event.keyCode : e.which ;
      var Fecha = new String(obj.value);

      if ((tecla == 13) || // Return
        (tecla == 107) ||  // + (keypad)
        (tecla == 187) ||  // + (numpad)
        (tecla == 109) ||  // - (keypad)
        (tecla == 189)) {  // - (numpad)

        if (tecla == 13) {
          Fecha = dateToStr(strToDate(Fecha));
        } else if ((tecla == 107) || (tecla == 187)) {
          Fecha = incDay(Fecha, 1);
        } else if ((tecla == 109) || (tecla == 189)) {
          Fecha = incDay(Fecha, -1);
        }

        if (String(Fecha) != "NaN") obj.value = Fecha
        else if (tecla == 13) obj.value = "";

        return false;
      }
    }
    
    var nav4 = window.Event ? true : false;
    function acceptKeysFecha(evt) {
      var key = nav4 ? evt.which : evt.keyCode;
//      BackSpace, Return, "/", "0".."9"
      return ((key <= 13) || (key == 47) || ((key >= 48) && (key <= 57)));
    }



// Funciones para tratar las fechas como en Delphi
// Ejemplo: 
//   Fecha Inicio: 
//     <input type="Text" id="FECHA_INICIO" onkeypress="return acceptKeysFecha(event)" 
//       onkeydown="teclaFecha(this,event)" value="01/01/2004" maxlength="10">
// ===================================================================
    /********************************************************************/
    // Nombre de la funcion: GetToken
    // Explicaci?n: Deveulve strings intermedios
    // Ejemplo: getToken('192.168.0.1', '.', 0) = '192';
    //          getToken('192.168.0.1', '.', 1) = '168';
    //          getToken('192.168.0.1', '.', 2) = '0';
    //          getToken('192.168.0.1', '.', 3) = '1';
    //          getToken('192.168.0.1', '.', 4) = '';
    //
    /********************************************************************/
    function getToken (Texto, Token, Position) {
      var TokenCount = 0;
      var idx = 0;
      while ((idx <= Texto.length) && (TokenCount < Position)) {
        if (Texto.substring(idx, idx + Token.length) == Token) {
          TokenCount++;
          idx = idx + Token.length;
        } else
          idx++;
      }
      
      var Result = "";
      while ((idx <= Texto.length) && (Texto.substring(idx, idx + Token.length) != Token)) {
        Result = Result + Texto.substring(idx, idx + 1);
        idx++;      
      }
      
      return Result;
    }
    
    /********************************************************************/
    // Nombre de la funcion: tokenCount
    // Explicaci?n: Devuelve la cantidad de elementos que hay en una 
    //   cadena. Se usa con el GetToken.
    // Ejemplo: TokenCount('192.168.0.1', '.') = 4;
    //
    /********************************************************************/
    function tokenCount (Texto, Token) {
      var idx;
      var Result = 1;
      for (idx = 1; idx <= Texto.length; idx++) {
        if (Texto.substring(idx, idx + Token.length) == Token) 
          Result++;
      }
      
      return Result;
    }
  
    function alertAllTokens(Texto, Token) {
      var idx;
      alert(Texto);
      for (idx = 0; idx <= tokenCount(Texto, Token) - 1; idx++) 
        alert(Texto + "[" + idx + "]: " + getToken(Texto, Token, idx));
    }
    
    function divide(numerator, denominator) {
      // In JavaScript, dividing integer values yields a floating point result (unlike in Java, C++, C)
      // To find the integer quotient, reduce the numerator by the remainder first, then divide.
      var remainder = numerator % denominator;
      var quotient = ( numerator - remainder ) / denominator;
      
      return quotient;
    }

    /* Days between 1/1/0001 and 12/31/1899 */
    DateDelta = 693594;

    /* The MonthDays array can be used to quickly find the number of
       days in a month:  MonthDays[IsLeapYear(Y), M] */
    var monthDays = new Array(true, false);
    monthDays[false] = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    monthDays[true] = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    
    /* IsLeapYear determines whether the given year is a leap year. */
    function isLeapYear(Year) {
      return ((Year % 4 == 0) && ((Year % 100 != 0) || (Year % 400 == 0)));
    }
    
    /* encodeDate encodes the given year, month, and day into a TDateTime value.
       The year must be between 1 and 9999, the month must be between 1 and 12,
       and the day must be between 1 and N, where N is the number of days in the
       specified month. If the specified values are not within range, an
       EConvertError exception is raised. The resulting value is the number of
       days between 12/30/1899 and the given date. */
    function encodeDate(Year, Month, Day) {
      var idx;
      var Result;
      var dayTable = monthDays[isLeapYear(Year)];
      if ((Year >= 1) && (Year <= 9999) && (Month >= 1) && (Month <= 12) && (Day >= 1) && (Day <= dayTable[Month - 1])) {
        for (idx = 1; idx <= Month - 1; idx++)
          Day += dayTable[idx - 1];
        idx = Year - 1;

        Result = (idx * 365) + divide(idx, 4) - divide(idx, 100) + divide(idx, 400) + Day - DateDelta;
        return Result;
      } else
        return NaN;
    }
    
    /********************************************************************/
    // Nombre de la funcion: strToDate
    // Explicaci?n: Devuelve la cantidad de d?as desde el 31/12/1899 de 
    //   la fecha pasada por parametro. S?lo se acepta el formato D/M/Y, 
    //   sin importar la cantidad de d?gitos. Si la fecha es incorrecta 
    //   devolverra NaN.
    // Ejemplo: strToDate('10/10/2004') = 38270;
    //
    /********************************************************************/
    function strToDate(Texto) {
      if (tokenCount(Texto, "/") != 3) return NaN;

      var iDay = Number(getToken(Texto, "/", 0));
      var iMonth = Number(getToken(Texto, "/", 1));
      var iYear = Number(getToken(Texto, "/", 2));
      if (isNaN(iDay) || isNaN(iMonth) || isNaN(iYear)) return NaN;
      
      return encodeDate(iYear, iMonth, iDay);      
    }
    
    function stringOfChar(chr, Count) {
      var idx;
      var Result = "";
      for (idx = 0; idx <= Count - 1; idx++) Result += chr;
      return Result;
    }
    
    function fillString(Texto, chr, Count) {
      var fill = stringOfChar(chr, Count - Texto.length);
      return Texto + fill;
    }
    
    function fillInteger(Numero, chr, Count) {
      var Texto = new String(Numero);
      var fill = stringOfChar(chr, Count - Texto.length);
      return fill + Texto;
    }
    
    function dateToStr(Date) {
      // Constantes
      var D1 = 365;
      var D4 = D1 * 4 + 1;
      var D100 = D4 * 25 - 1;
      var D400 = D100 * 4 + 1;
            
      // Variables
      var iDay;
      var iMonth;
      var iYear;
      var idx;
      var DayTable;
      var Result = new String;
      
      var T = DateDelta + Date;
      T--;
      iYear = 1;
      while (T >= D400) {
        T -= D400;
        iYear += 400;
      }
      idx = divide(T, D100);
      iDay = T % D100;
      if (idx == 4) {
        idx--;
        iDay += D100;
      }
      iYear += (idx * 100);
      idx = divide(iDay, D4);
      iDay = iDay % D4;
      iYear += idx * 4;
      idx = divide(iDay, D1);
      iDay = iDay % D1;
      if (idx == 4) {
        idx--;
        iDay += D1;
      }
      iYear += idx;
      DayTable = monthDays[isLeapYear(iYear)];
      iMonth = 1;
      idx = DayTable[iMonth - 1];
      while (idx <= iDay) {
        iDay -= idx;
        iMonth++;
        idx = DayTable[iMonth - 1];
      }
      iDay++;
      
      if (isNaN(iDay) || isNaN(iMonth) || isNaN(iYear)) Result = NaN
      else      
        Result = 
          fillInteger(iDay, "0", 2) + "/" + 
          fillInteger(iMonth, "0", 2) + "/" + 
          fillInteger(iYear, "0", 4);          
      
      return  Result;
    }
    
    function incDay(Fecha, Dias) {
      var dtFecha;
      if (isNaN(Fecha)) {
        dtFecha = strToDate(Fecha);
      } else {
        dtFecha = Fecha;
      }
      dtFecha += Dias;    
      if (isNaN(Fecha)) return dateToStr(dtFecha)
      else return dtFecha;
    }

    function teclaFecha(obj,e) {
      var tecla = (document.all) ? window.event.keyCode : e.which ;
      var Fecha = new String(obj.value);

      if ((tecla == 13) || // Return
        (tecla == 107) ||  // + (keypad)
        (tecla == 187) ||  // + (numpad)
        (tecla == 109) ||  // - (keypad)
        (tecla == 189)) {  // - (numpad)

        if (tecla == 13) {
          Fecha = dateToStr(strToDate(Fecha));
        } else if ((tecla == 107) || (tecla == 187)) {
          Fecha = incDay(Fecha, 1);
        } else if ((tecla == 109) || (tecla == 189)) {
          Fecha = incDay(Fecha, -1);
        }

        if (String(Fecha) != "NaN") obj.value = Fecha
        else if (tecla == 13) obj.value = "";

        return false;
      }
    }
    
    var nav4 = window.Event ? true : false;
    function acceptKeysFecha(evt) {
      var key = nav4 ? evt.which : evt.keyCode;
//      BackSpace, Return, "/", "0".."9"
      return ((key <= 13) || (key == 47) || ((key >= 48) && (key <= 57)));
    }

			function setFecha(valor) {
					if (document.getElementById(valor)!=null) {
						valor = document.getElementById(valor).value;
					}
					return valor;
			}

			function compruebaFecha (obj, valorpDefecto, minFecha, maxFecha, msg) {
				 if (document.getElementById(valorpDefecto)!=null) {
						valorpDefecto = document.getElementById(valorpDefecto).value;
					}
	
					if (document.getElementById(minFecha)!=null) {
						minFecha = document.getElementById(minFecha).value;						
					}
			
					if (document.getElementById(maxFecha)!=null) {
						maxFecha = document.getElementById(maxFecha).value;
					}

					var sino = true;
					if (validaFechaNull(obj.value)==false) {
						sino = false;
					} else {
							if ((minFecha!=null) && (minFecha.length>0)) {
								var tmp = compareDates(minFecha, 'dd/MM/yyyy', obj.value, 'dd/MM/yyyy');
								if (tmp!=0) {
									sino = false;
								}
							}
							
							if ((maxFecha!=null) && (maxFecha.length>0)) {
								var tmp = compareDates(obj.value, 'dd/MM/yyyy', maxFecha, 'dd/MM/yyyy');
								if (tmp!=0) {
									sino = false;
								}
							}
					}
					if (sino==false) {
						obj.focus();
						obj.value = valorpDefecto;
						if ((msg!=null) && (msg.length>0)) {
							alert(msg);
						}
					}
					return sino;
			}

			function validaFecha (Valor) {
				var F = new String(Valor);
				var SiNo = EsFechaCorrecta (F);
				return SiNo;
			}
    
			function validaFechaNull (Valor) {
			 var F = new String(Valor);
    var SiNo;
    if (F=="") SiNo = true;
    else if (F.length==0) SiNo = true;
    else SiNo = EsFechaCorrecta (F);
				return SiNo;
			}
		
			function EsFechaCorrecta (Valor) {
				FormatoCorrecto = true;
				FechaCorrecta = true;
				NumCorrecto = true;
				if (Valor.length!=10) FormatoCorrecto = false;
				if (Valor.substring(2,3)!="/") FormatoCorrecto = false;
				if (Valor.substring(5,6)!="/") FormatoCorrecto = false;
				var Dia = Valor.substring(0,2);
				var Mes = Valor.substring(3,5);
				var Anio = Valor.substring(6,10);
				if (ValNumero(Dia)==false) NumCorrecto = false;
				if (ValNumero(Mes)==false) NumCorrecto = false;
				if (ValNumero(Anio)==false) NumCorrecto = false;
				FechaCorrecta = validarFecha(Dia,Mes,Anio);
				if (FormatoCorrecto==true && NumCorrecto==true && FechaCorrecta==true)
					return true;
				else
					return false;
			}
	
			function ValNumero (Num) {
			  var Ini = 0;
			  var Fin = Num.length;
			  var Correcto = true;
			  for (i=Ini;i<Fin;i++)
			  {	
			    var Temp = parseInt(Num.substring(i,i+1));
			  	if (!(Temp == 0 || Temp == 1 || Temp == 2 || Temp == 3 || Temp == 4 || Temp == 5 || Temp == 6 || Temp == 7 || Temp == 8 || Temp == 9))
						{
							Correcto = false;
						}
			  }
			  return Correcto;
			}
	
			function validarFecha(dia, mes, anio) { 
				if (dia<0 || dia>31 || mes<0 || mes >12) 
					valida=false; 
				else if ((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30) 
					valida=false; 
				else if (mes==2 && dia>28+bisiesto(anio)) 
					valida=false; 
				else 
					valida=true; 
				return valida; 
			} 

			function bisiesto(anio) { 
					var EsBisiesto = false;
					if (anio%4!=0) 
						EsBisiesto=false; 
					else if (anio%400==0) 
						EsBisiesto=true; 
					else if (anio%100==0) 
						EsBisiesto=false; 
					else EsBisiesto=true; 
					return EsBisiesto; 
			} 

		
	  function ValidarHora(Hora, Campo) {
	  	 var PosHora = Hora.indexOf(":");
	  	 if (PosHora != -1)
				 {
				  Hora = Hora.substring (0,PosHora) + Hora.substring (PosHora+1, Hora.length);
				  Campo.value = Hora;
				 }
		 
				 var SiNo = IsANumber (Hora,1);
				 if (SiNo == false) Campo.value="";
				 if (Campo.value.length>4) Campo.value = Campo.value.substring(0,4);
				 if (Campo.value.length<4)
				 {
				   var Tamano = Campo.value.length;
				   var NuevoTamano = 4 - Tamano;
				   for (i=0;i<NuevoTamano;i++)
					   {
					     Campo.value = Campo.value.toString() + '0';
					   }
					 }
					 var Temp = Campo.value.substring(0,2);
					 var Temp2 = Campo.value.substring(2,Campo.value.length);
					 if (parseInt(Temp)>23) Campo.value = "";
					 if (parseInt(Temp2)>59) Campo.value = "";
					 if (Campo.value.length!=4) Campo.value = "";
					 if (Campo.value != "") {
  				 Campo.value = Campo.value.substring(0,2)+":"+Campo.value.substring(2,Campo.value.length);
  				 return true;
  				} else {
  				 return false;
  				} 
					 
	  }
		  
			function IsANumber(InString, IntFlag) {
	   if(!parseFloat(InString)) {
		         return false ;
	   }
	   XX="" ;
	   for (var i=0; i<InString.length; i++) {
						X=InString.charAt(i) ;
						XX =XX + X ;
						if (IntFlag != "1") {
			    if( (X != " ") && (X != ",") && (X != "0") ) {
	        if (!parseInt(X)) {
			        return false ;
			        break ;
	        }
	      }
	     }
	     if(IntFlag == "1") {
			    if( (X != " ") && (X != "0") ) {
	        if (!parseInt(X)) {
		        return false ;
		        break ;
	        }
	      }
	     }
	   }
			 return true;
		 }
		
	
		function Dias_M(Mes, Ano) {
			var Dias_m;
			switch (Mes) {
				case 1, 3, 5, 7, 8, 10, 12:
					Dias_m = 31;
				case 4, 6, 9, 11:
					Dias_m = 30
				case 2:
					if (EsFechaCorrecta("29/02/"+Ano))
						Dias_m = 29;
					else
						Dias_m = 28;
			}
			return Dias_m;
		}


		function ClickCalendarioFin(obj, indice, objformini, objformfin,holiday){
		   if(obj) obj.fEndPop(objformini,objformfin,holiday);
		   return false;    
		}
		
		//Funciones propias de los tags FechaDesde y FechaHasta.
		
		function ClickCalendarioDesde(obj, indice, ini, fin){
     var objformini = document.getElementById(ini + indice);
     var objformfin = document.getElementById(fin + indice);
     if(obj) obj.fStartPop(objformini,objformfin);
     
     return false;    
  }
  
  function ClickCalendarioHasta(obj, indice, ini, fin){
     var objformini = document.getElementById(ini + indice);
     var objformfin = document.getElementById(fin + indice);
     if(obj) obj.fEndPop(objformini,objformfin);
     
     return false;    
  }
  //Las fechas en blanco son validas.
  function compruebaFecha2 (obj, valorpDefecto, minFecha, maxFecha, msg) {
				 if (document.getElementById(valorpDefecto)!=null) {
						valorpDefecto = document.getElementById(valorpDefecto).value;
					}
	
					if (document.getElementById(minFecha)!=null) {
						minFecha = document.getElementById(minFecha).value;
						
					}
			
					if (document.getElementById(maxFecha)!=null) {
						maxFecha = document.getElementById(maxFecha).value;
					}

					var sino = true;
					if (validaFechaNull(obj.value)==false) {
						sino = false;
					} else {
							if ((minFecha!=null) && (minFecha.length>0) && (obj.value!=null) && (obj.value.length>0)) {
								var tmp = compareDates(minFecha, 'dd/MM/yyyy', obj.value, 'dd/MM/yyyy');
								if (tmp!=0) {
									sino = false;
								}
							}
							
							if ((maxFecha!=null) && (maxFecha.length>0) && (obj.value!=null) && (obj.value.length>0)) {
								var tmp = compareDates(obj.value, 'dd/MM/yyyy', maxFecha, 'dd/MM/yyyy');
								if (tmp!=0) {
									sino = false;
								}
							}
					}
					if (sino==false) {
						obj.focus();
						obj.value = valorpDefecto;
						if ((msg!=null) && (msg.length>0)) {
							alert(msg);
						}
					}
					return sino;
			}
