//	10/05/2011

TCalendario._iInstancias = 1;

TCalendario.prototype.siguiente      = ' > ';
TCalendario.prototype.anterior       = ' < ';
TCalendario.prototype.floatSiguiente = 'right';

TCalendario.prototype.Ancho    = '';
TCalendario.prototype.Clase    = 'Calendario';
TCalendario.prototype.aFecha   = null;
TCalendario.prototype.Fecha    = '';
TCalendario.prototype.MaxFecha = null;
TCalendario.prototype.MinFecha = null;
TCalendario.prototype.vars     = null;

TCalendario.prototype.onCargarMes   = null;
TCalendario.prototype.onDia         = null;
TCalendario.prototype.onSeleccionar = null;

TCalendario.prototype._iInstancia  = 0;
TCalendario.prototype._oTabla      = null;
TCalendario.prototype._oTBody      = null;


TCalendario.$ = function ()
{
	var Aux  = document.getElementById (arguments [0]);
	var Pars = null;
	
	switch (arguments.length)
	{	case 1: return Aux;
		case 2: return Aux ? Aux [arguments [1]] : null;
		case 3: 
			if (Aux) 
			{	Pars = arguments [1].split ('.');
				for (var i = 0; i < Pars.length - 1; i++) Aux = Aux [Pars [i]];
			  Aux [Pars [i]] = arguments [2]; 
			}
			break;
		default: alert ('TCalendario.$, número de parámetros incorrectos.');
	}
}


TCalendario.prototype._diaActual = function ()
{
	var fecha = new Date ();

	if (fecha.getMonth () + 1 == this.aFecha [1] && fecha.getFullYear () == this.aFecha [2])
	{	if (fecha.getDate () == this.aFecha [0]) 
		{	var td = this._td (this.aFecha [0]);
			td.className += (td.className ? ' ' : '') + 'DiaActual';
		}	else this._td (fecha.getDate ()).className =  'DiaActual';
	}
}


TCalendario._evento = function (elemento, evento, funcion)
{
	if (elemento.addEventListener)	elemento.addEventListener (evento, funcion, false);
	else if (elemento.attachEvent) elemento.attachEvent ('on' + evento, funcion);
}


TCalendario.prototype._marcarDia = function (dia)
{	
	var td;
	
	if (this.aFecha [0])
	{	td = this._td (this.aFecha [0]);
		if (td.getAttribute ('Seleccionado'))
		{	td.setAttribute ('Seleccionado', '');
			var aux = td.className.split (' ');
			for (var i = aux.length - 1; i >= 0; i--)	if (aux [i] == 'Seleccionado') aux [i] = '';
			td.className = aux.join (' ');
		}
	}

	this.aFecha [0] = dia;
	td = this._td (dia);
	if (td)
	{	td.setAttribute ('Seleccionado', '1');
		td.className += (td.className ? ' ': '') + 'Seleccionado';
	}
}


TCalendario.prototype.setFecha = function (fecha)
{
	var formato   = /^([0-9]{1,2})+[\/\.\-]+([0-9]{1,2})+[\/\.\-]+([0-9]{1,4})$/;
	
	if (typeof (fecha) != 'undefined' && fecha && formato.test (fecha))
	{	var afecha = fecha.split (/[\/\.\-]/);

		afecha [0] = afecha [0].replace (/^0*/g, '').asInteger ();
		afecha [1] = afecha [1].replace (/^0*/g, '').asInteger ();
		afecha [2] = afecha [2].replace (/^0*/g, '').asInteger ();
		if (afecha [2] > 0 && afecha [2] < 100) afecha [2] += 2000;
		if (afecha [0] > 0 && afecha [1] > 0 && afecha [1] <= 12 && afecha [2] > 0)
		{	this.aFecha [0] = afecha [0];
			this.aFecha [1] = afecha [1];
			this.aFecha [2] = afecha [2];
		}
	}
}


TCalendario.prototype._td = function (dia)
{
	return TCalendario.$ ('idTD' + this._iInstancia + '-' + dia);
}



// 15/10/2010
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////


TCalendario.Anyo = function ()
{
	return new Date ().getFullYear ();
}


TCalendario._Ajax = function (sURL, oVars, fOnCargar)
{
	var aVersiones =  ['Microsoft.XMLHttp', 'MSXML2.XMLHttp', 'MSXML2.XMLHttp.3.0',
	                   'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.5.0'];
	var Pars       = new Array ();
	var oAjax      = null;

	if (window.XMLHttpRequest) 
  {	try
   	{	oAjax = new XMLHttpRequest ();
   	} catch(e)
   	{	oAjax = null;
   	}
  } else if (window.ActiveXObject) 
	{	for  (var i = aVersiones.length - 1; i >= 0 && ! oAjax; i--)
		{	try
			{	oAjax = new ActiveXObject (aVersiones [i]);
		  } catch (E)
      {	oAjax = null;
    	}
    }
  }

	if (oAjax)
	{	oAjax.onreadystatechange = function ()
		{	switch (oAjax.readyState)
			{	case 0:		// Sin inicializar
					break;
				case 1:		// Cargando
					break;
				case 2:		// Cargado
					break;
				case 3:		// Interactivo
					break;
				case 4:		// Completado
					if (oAjax.status == 200) fOnCargar (oAjax.responseText);	// SI LA PETICION TIENE EXITO
					oAjax = null;
					break;
			}
		}
	}

	for (var Par in oVars) 
	{	//alert (Par);
		Pars.push (escape (Par) + '=' + escape (oVars [Par]));
	}

	oAjax.open ('POST', sURL, true);
	oAjax.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
	oAjax.send (Pars.join ('&'));
}


TCalendario.prototype._Calendario = function ()
{
	var Tr      = document.createElement ('tr');
	var DiaSem  = new Date (this.aFecha [2], this.aFecha [1] - 1, 1).getDay ();
	var UltDia  = new Date (this.aFecha [2], this.aFecha [1], 0).getDate ();
	var i       = 1;	
	var d       = 1;
	var j       = 1;

	if (this._oTBody) this._oTabla.removeChild (this._oTBody);
	this._oTBody = document.createElement ('tbody');

	TCalendario.$ ('id' + this._iInstancia + 'Mes', 'innerHTML', TCalendario.MesNombre (this.aFecha [1]) + '&nbsp;&nbsp;' + this.aFecha [2]);
	if (DiaSem == 0) DiaSem = 7;
	i = this._PreDias (Tr, DiaSem);

	while (d <= UltDia)
	{	while (i <= 7)
		{	if (d <= UltDia) this._DiaMes (Tr, d);
			else this._SinDia (Tr, j++);
			d++;
			i++;
		}
		this._oTBody.appendChild (Tr);
		if (d <= UltDia) Tr = document.createElement ('tr');
		i = 1
	}
	this._oTabla.appendChild (this._oTBody);
}




TCalendario.prototype._CargarMes = function ()
{
//	var aux = {}

	if (this.onCargarMes)
	{	if (typeof (this.onCargarMes) == 'function') this.onCargarMes (this);
		else if (typeof (this.onCargarMes == 'string'))
		{	var self = this;
//			for (var propiedad in this.vars) aux [propiedad] = this.vars [propiedad];
			self.vars.anyo = self.aFecha [2];
			self.vars.mes  = self.aFecha [1];
			TCalendario._Ajax (this.onCargarMes, self.vars,
			                   function (sPeticion) { self.CargarMes (sPeticion.split (',')); })
		}
	}
}


TCalendario.prototype.celda = function (dia)
{
	return $ ('#idTD' + this._iInstancia + '-' + dia);
}


TCalendario.prototype._DiaMes = function (oTr, iDia)
{
	var self = this;
	var Td   = document.createElement ('td');

	if (this.onDia) this.onDia (this, Td, iDia)
	else
	{	Td.setAttribute ('conDatos', '0');
		Td.innerHTML = iDia;
	}
	Td.id = 'idTD' + this._iInstancia + '-' + iDia;
	if (Td.addEventListener) Td.addEventListener ('click', function (event) { self._onSeleccionar (Td, iDia); }, false);
	else if (Td.attachEvent) Td.attachEvent ('onclick', function () { self._onSeleccionar (Td, iDia); });
	oTr.appendChild (Td);
}


TCalendario.DiaSemana = function (iDia, iMes, iAnyo)
{
	var Fecha = new Date (iAnyo, iMes - 1, iDia);

	return Fecha.getDay () == 0 ? 7 : Fecha.getDay ();
}




TCalendario.prototype._MaxFecha = function ()
{
	if (! this.MaxFecha) return true;
	return new Date (this.aFecha [1] > 11 ? this.aFecha [2] + 1 : this.aFecha [2], this.aFecha [1] > 11 ? 0 : this.aFecha [1], 
	                 this.MaxFecha.getDate (), this.MaxFecha.getHours (), this.MaxFecha.getMinutes (),
	                 this.MaxFecha.getSeconds (), this.MaxFecha.getMilliseconds () - 1) < this.MaxFecha;
}


TCalendario.Mes = function ()
{
	return new Date ().getMonth () + 1;
}


TCalendario.prototype._MesAnt = function ()
{
	if (this._MinFecha ())
	{	this.aFecha [1]--;
		if (this.aFecha [1] < 1)
		{	this.aFecha [1] = 12;
			this.aFecha [2]--;
		}
		this.aFecha [0] = TCalendario.UltimoDia (this.aFecha [1], this.aFecha [2]);
		this._Calendario ();
		this._CargarMes ();
	}
}


TCalendario.prototype._MesSig = function ()
{
	if (this._MaxFecha ())
	{	this.aFecha [1]++;
		if (this.aFecha [1] > 12)
		{	this.aFecha [1] = 1;
			this.aFecha [2]++;
		}
		this.aFecha [0] = 1;
		this._Calendario ();
		this._CargarMes ();
	}
}


TCalendario.MesNombre = function (iMes)
{
	var aMeses = ['', 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
	
	return aMeses [iMes];
}


TCalendario.prototype._MinFecha = function ()
{

	if (! this.MinFecha) return true;
	return new Date (this.aFecha [1] > 1 ? this.aFecha [2] : this.aFecha [2] - 1, this.aFecha [1] > 1 ? this.aFecha [1] - 2 : 11, 
	                 this.MinFecha.getDate (), this.MinFecha.getHours (), this.MinFecha.getMinutes (),
	                 this.MinFecha.getSeconds (), this.MinFecha.getMilliseconds ()) >= this.MinFecha;
}


TCalendario.prototype._onSeleccionar = function (oTD, iDia)
{
	this.Fecha = (iDia < 10 ? '0' : '') + iDia + '/';
	
	this.Fecha += (this.aFecha [1] < 10 ? '0' : '') + this.aFecha [1] + '/';
	this.Fecha += this.aFecha [2];

	
	if (this.onSeleccionar && this.onSeleccionar (this, oTD, iDia)) this._marcarDia (iDia);
}


TCalendario.prototype.PopUp = function (oEvent)
{
	var self = this;
	var Ventana = new TPopUp ();

	if (! oEvent) oEvent = window.event;
	if (oEvent.pageX)	Ventana.XY = [oEvent.pageX, oEvent.pageY];
	else Ventana.XY = [oEvent.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft), 
		                 oEvent.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)];
	Ventana.Titulo = '';
	Ventana.Cargar ();
	this.Show (Ventana.Contenedor);
	Ventana._oVentana.style.width  = '';
	Ventana._oVentana.style.height = '';
	Ventana._Centrar ();
}


TCalendario.prototype._PreDias = function (oTr, iDiaSem)
{
	var i = 1;

	if (this.aFecha [1] > 0) var UltDia  = new Date (this.aFecha [2], this.aFecha [1] - 1, 0).getDate ();
	else var UltDia  = new Date (this.aFecha [2] - 1, 11, 0).getDate ();

	UltDia -= iDiaSem - 2;

	while (i < iDiaSem) { this._SinDia (oTr, UltDia++); i++; }
	return i;
}


TCalendario.PrimerDiaAnyo = function ()
{
	var Fecha = new Date (new Date ().getFullYear (), 0, 1);
	var Dia   = Fecha.getDate ()
	var Mes   = Fecha.getMonth () + 1
	
	return  (Dia < 10 ? '0' + Dia : Dia) + '/' + (Mes < 10 ? '0' + Mes : Mes) + '/' + Fecha.getFullYear ();
}


TCalendario.prototype.Show = function (vIdentificador)
{
	var Contenedor = typeof (vIdentificador) == 'string' ? document.getElementById (vIdentificador) : vIdentificador;

	if (! Contenedor) alert ('Identificador no encontrado (' + vIdentificardor + ')');
	Contenedor.innerHTML = '';
	Contenedor.className = this.Clase; 

	this._oTabla = document.createElement ('table');

	this._oTabla.setAttribute ('align', 'center');
	this._oTabla.setAttribute ('border', '0');
	this._oTabla.setAttribute ('cellPadding', '0');
	this._oTabla.setAttribute ('cellSpacing', '0');
	this._oTabla.setAttribute ('width', '100%');
	this._THead ();
	this._Calendario ();
	Contenedor.appendChild (this._oTabla);
	if (this.Ancho) Contenedor.style.width = this.Ancho;
	this._marcarDia (this.aFecha [0]);	
	this._diaActual ();
	this._CargarMes ();
}


TCalendario.prototype._SinDia = function (oTr, iDia)
{
	var Td = document.createElement ('td');
	
	Td.innerHTML = '&nbsp;'; 
	Td.className = 'SinDia';
	oTr.appendChild (Td);
}


TCalendario.prototype._THead = function ()
{
	var Head = document.createElement ('thead');
	
	this._TopMes (Head);
	this._TopDias (Head);
	this._oTabla.appendChild (Head);
}


TCalendario.prototype._TopDias = function (oHead)
{
	var Tr = document.createElement ('tr');
	var Td = document.createElement ('td');
	
	Tr.className = 'NomDias';
	
	Td.innerHTML = 'Lu';
	Tr.appendChild (Td);

	Td = document.createElement ('td');
	Td.innerHTML = 'Ma';
	Tr.appendChild (Td);

	Td = document.createElement ('td');
	Td.innerHTML = 'Mi';
	Tr.appendChild (Td);

	Td = document.createElement ('td');
	Td.innerHTML = 'Ju';
	Tr.appendChild (Td);
	
	Td = document.createElement ('td');
	Td.innerHTML = 'Vi';
	Tr.appendChild (Td);

	Td = document.createElement ('td');
	Td.innerHTML = 'Sa';
	Tr.appendChild (Td);

	Td = document.createElement ('td');
	Td.innerHTML = 'Do';
	Tr.appendChild (Td);

	oHead.appendChild (Tr);
}




TCalendario.UltimoDia = function (iMes, iAnyo)
{
	// El día 0 de un mes es siempre el ultimo día del mes anterior;
	return new Date(iAnyo, iMes, 0).getDate();
}


function TCalendario (iDia, iMes, iAnyo)
{
	var Fecha = new Date ();

	this.aFecha = Array ();
	this._iInstancia = TCalendario._iInstancias++;

	this.aFecha [0] = typeof (iDia)  == 'undefined' || ! iDia  ? Fecha.getDate ()      : iDia;
	this.aFecha [1] = typeof (iMes)  == 'undefined' || ! iMes  ? Fecha.getMonth () + 1 : iMes;
	this.aFecha [2] = typeof (iAnyo) == 'undefined' || ! iAnyo ? Fecha.getFullYear ()  : iAnyo;

	this.vars = {}
}


////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////

TCalendario.CompararFechas = function (sFecha1, sFecha2)
{
	// Las cadenas de entrada son del tipo dd/mm/aaaa
	var aFecha1 = sFecha1.split ('/');
	var aFecha2 = sFecha2.split ('/');

	if (aFecha1 [2].asInteger () < aFecha2 [2].asInteger ()) return -1;
	if (aFecha1 [2].asInteger () > aFecha2 [2].asInteger ()) return 1;
	if (aFecha1 [1].asInteger () < aFecha2 [1].asInteger ()) return -1;
	if (aFecha1 [1].asInteger () > aFecha2 [1].asInteger ()) return 1;
	if (aFecha1 [0].asInteger () < aFecha2 [0].asInteger ()) return -1;
	if (aFecha1 [0].asInteger () > aFecha2 [0].asInteger ()) return 1;
	return 0;
}





TCalendario.pedirFecha = function (oinit)
{
	var calendario = new TCalendario ();

	calendario.Ancho = oinit.ancho ? oinit.ancho + 'px' : '180px';
	if (oinit.onseleccionar) calendario.onSeleccionar = oinit.onseleccionar;
	else calendario.onSeleccionar = function (ocalendario)
																	{
																		oinit.control.value = ocalendario.Fecha;
																		TPopUp.Cerrar ();
																	};
	calendario.setFecha (oinit.control.value);
	calendario.PopUp (oinit.oevent);
}


TCalendario.prototype.CargarMes = function (aDias)
{
	var celda;
	
	for (var i = aDias.length - 1; i >= 0; i--)
	{	if ((celda = this.celda (aDias [i])))
		{	if (celda.attr ('Seleccionado')) celda.attr ('class', 'Seleccionado ConDatos');
			else celda.attr ('class', 'ConDatos');
			celda.attr ('conDatos', '1');
		}
	}
	
	var td = this._td (this.aFecha [0])
	if (! td.getAttribute ('conDatos').asInteger ())
	{	var aux = td.className.split (' ');
		for (var i = aux.length - 1; i >= 0; i--)	if (aux [i] == 'Seleccionado') aux [i] = '';
		td.className = aux.join (' ');
	}
}


TCalendario.prototype._TopMes = function (oHead)
{
	var self  = this;
	var Tr    = document.createElement ('tr');
	var Td    = document.createElement ('td');
	var div   = document.createElement ('div');
	var aux   = document.createElement ('div');
	var span  = document.createElement ('span');
	
	Tr.className = 'Mes';
	Td.className = 'Mes';
	Td.setAttribute ('colSpan', 7);

	div.style.textAlign = 'center';

	aux.className        = 'MesAnterior';
	aux.style.styleFloat = 'left';
	aux.style.cssFloat   = 'left';
	aux.innerHTML        = this.anterior;
	TCalendario._evento (aux, 'click', function () { self._MesAnt (); });
	div.appendChild (aux);

	aux                  = document.createElement ('div');
	aux.className        = 'MesSiguiente';
	aux.style.styleFloat = this.floatSiguiente;
	aux.style.cssFloat   = this.floatSiguiente;
	aux.innerHTML        = this.siguiente;
	TCalendario._evento (aux, 'click', function () { self._MesSig (); });
	div.appendChild (aux);
	
	
	span.id = 'id' + this._iInstancia + 'Mes';
	span.appendChild (document.createTextNode (TCalendario.MesNombre (this.aFecha [1]) + '  ' + this.aFecha [2]));
	div.appendChild (span);

	Td.appendChild (div);

	Tr.appendChild (Td);
	oHead.appendChild (Tr);

}


