// Title: Tigra Calendar
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.2 (European date format)
// Date: 10/14/2002 (mm/dd/yyyy)
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar?.js and calendar.html



//**********************************************************************
//		   dateCalendar(date_target, yearIni, yearFin)
//**********************************************************************
//Esta función crea un calendario simple, solo fecha, sin hora, colocandola 
//en el campo especificado, los parametros que recibe son:
//@param date_target El campo (textField) en donde se colocará la fecha 
//@param yearIni El año inicial del rango de años a presentarse
//@param yearFin El año final del rango de años a presentarse
function dateCalendar(date_target, yearIni, yearFin){
	recallNonSep = false;
	var cal3 = new calendarOneFied(date_target, yearIni, yearFin);
	cal3.year_scroll = true;
	cal3.time_comp = false;
	cal3.popup();
 }

//**********************************************************************
//	 dateTimeCalendarSeparated(date_target, time_target, yearIni, yearFin)
//**********************************************************************
//Esta función crea un calendario con fecha y hora, colocando cada uno en 
//campos diferentes, los parametros que recibe son:
//@param date_target El campo (textField) en donde se colocará la fecha 
//@param time_target El campo (textField) en donde se colocará la hora 
//@param yearIni El año inicial del rango de años a presentarse
//@param yearFin El año final del rango de años a presentarse
 function dateTimeCalendarSeparated(date_target, time_target, yearIni, yearFin){
	recallSep = false;
	var cal3 = new calendarTwoFields(date_target, time_target, yearIni, yearFin);
	cal3.year_scroll = true;
	cal3.time_comp = true;
	cal3.popup();
 }
//**********************************************************************
//	 dateTimeCalendarUnited(date_time_target, time_target, yearIni, yearFin)
//**********************************************************************
//Esta función crea un calendario con fecha y hora, colocando ambos en un
//solo campo, los parametros que recibe son:
//@param date_time_target El campo (textField) en donde se colocará la fecha y hora 
//@param yearIni El año inicial del rango de años a presentarse
//@param yearFin El año final del rango de años a presentarse
 function dateTimeCalendarUnited(date_time_target, yearIni, yearFin){
	recallNonSep = false;
	var cal3 = new calendarOneFied(date_time_target, yearIni, yearFin);
	cal3.year_scroll = true;
	cal3.time_comp = true;
	cal3.popup();
 }


//**********************************************************************
//**********************************************************************
//**********************************************************************
//					CODIGO QUE CONSTRUYE EL CALENDARIO
//**********************************************************************
//**********************************************************************
//**********************************************************************
// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;

var calendars = [];
var RE_NUM = /^\-?\d+$/;
var recallNonSep = false;
var recallSep = false;
var meses = new Array(12);	
meses[0] = "ENE";
meses[1] = "FEB";
meses[2] = "MZO";
meses[3] = "ABR";
meses[4] = "MAY";
meses[5] = "JUN";
meses[6] = "JUL";
meses[7] = "AGO";
meses[8] = "SEP";
meses[9] = "OCT";
meses[10] = "NOV";
meses[11] = "DIC";


				
function calendarOneFied(obj_target, pIniYear, pFinYear) {
	// assigning methods
	this.gen_date = cal_gen_date1;
	this.gen_time = cal_gen_time1;
	this.gen_hour = cal_gen_hour;
	this.gen_min  = cal_gen_min;
	this.gen_tsmp = cal_gen_tsmp1;
	this.prs_date = cal_prs_date1;
	this.prs_time = cal_prs_time1;
	this.prs_tsmp = cal_prs_tsmp1;
	this.popup    = cal_popup_non_separated;

	// validate input parameters
	if (!obj_target)
		return cal_error("Error al llamar el calendario: no se ha especificado un target control");
	if (obj_target.value == null)
		return cal_error("Error al llamar el calendario: el parámetro especificado no es un target control válido");
	this.target = obj_target;
	this.time_comp = BUL_TIMECOMPONENT;
	this.year_scroll = BUL_YEARSCROLL;
	
	// register in global collections
	this.id = calendars.length;
	

	this.iniYear = pIniYear;
	this.finYear = pFinYear;
	calendars[this.id] = this;
}


function cal_popup_non_separated (str_datetime) {
	this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
	//alert("dt_current:"+dt_current);
	//alert("En el popup");
	if (!this.dt_current) return;
	//alert("URL: "+'calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id+ '&iniYear=' + this.iniYear+ '&finYear=' + this.finYear);
	var obj_calwindow = "";
	
	if(recallNonSep == true){
		obj_calwindow = window.open(
			'./calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id+ '&iniYear=' + this.iniYear+ '&finYear=' + this.finYear + '&separated=false',
			'Calendar', 'width=200,height='+(this.time_comp ? 230 : 200)+
			',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
		);
	}else {
		obj_calwindow = window.open(
			'./resources/html/calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id+ '&iniYear=' + this.iniYear+ '&finYear=' + this.finYear + '&separated=false',
			'Calendar', 'width=200,height='+(this.time_comp ? 230 : 200)+
			',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
		);
		recallNonSep = true;
	}
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}


function calendarTwoFields(obj_date_target, obj_time_target, pIniYear, pFinYear) {
	// assigning methods
	this.gen_date = cal_gen_date1;
	this.gen_time = cal_gen_time1;
	this.gen_hour = cal_gen_hour;
	this.gen_min = cal_gen_min;
	this.gen_tsmp = cal_gen_tsmp1;
	this.prs_date = cal_prs_date1;
	this.prs_time = cal_prs_time1;
	this.prs_tsmp = cal_prs_tsmp2;
	this.popup    = cal_popup_separated;

	// validate input parameters
	if (!obj_date_target)
		return cal_error("Error al llamar el calendario: no se ha especificado un target control para la fecha");
	if (!obj_time_target)
		return cal_error("Error al llamar el calendario: no se ha especificado un target control para la hora");
	if (obj_date_target.value == null)
		return cal_error("Error al llamar el calendario: el parámetro especificado no es un target control válido para la fecha");
	if (obj_time_target.value == null)
		return cal_error("Error al llamar el calendario: el parámetro especificado no es un target control válido para la hora");
	this.date_target = obj_date_target;
	this.time_target = obj_time_target;
	this.time_comp = BUL_TIMECOMPONENT;
	this.year_scroll = BUL_YEARSCROLL;
	
	// register in global collections
	this.id = calendars.length;
	

	this.iniYear = pIniYear;
	this.finYear = pFinYear;
	calendars[this.id] = this;
}


function cal_popup_separated (str_datetime, str_time) {

	this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.date_target.value, str_time ? str_time : this.time_target.value);
	//alert("En el popup");
//	alert("dt_current:"+dt_current);
	if (!this.dt_current) return;
	//alert("URL: "+'calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id+ '&iniYear=' + this.iniYear+ '&finYear=' + this.finYear);
	var obj_calwindow = "";
	
	
	if(recallSep == true){
		obj_calwindow = window.open(
			'./resources/html/calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id+ '&iniYear=' + this.iniYear+ '&finYear=' + this.finYear + '&separated=true',
			'Calendar', 'width=200,height='+(this.time_comp ? 230 : 200)+
			',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
		);
	}else{
		obj_calwindow = window.open(
			'./resources/html/calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id+ '&iniYear=' + this.iniYear+ '&finYear=' + this.finYear + '&separated=true',
			'Calendar', 'width=200,height='+(this.time_comp ? 230 : 200)+
			',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
		);
		recallSep = true;
	}
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}


// timestamp generating function
function cal_gen_tsmp1 (dt_datetime) {
	return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}


function get_month(mes){
	return meses[mes];
}
	
function getIdMonth(mes){
	if(mes == "ENE")
		return 0;
	else if(mes == "FEB")
		return 1;
	else if(mes == "MZO")
		return 2;
	else if(mes == "ABR")
		return 3;
	else if(mes == "MAY")
		return 4;
	else if(mes == "JUN")
		return 5;
	else if(mes == "JUL")
		return 6;
	else if(mes == "AGO")
		return 7;
	else if(mes == "SEP")
		return 8;
	else if(mes == "OCT")
		return 9;
	else if(mes == "NOV")
		return 10;
	else if(mes == "DIC")
		return 11;
	else return "";
}



// date generating function
function cal_gen_date1 (dt_datetime) {
	return (
		(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
		+ get_month(dt_datetime.getMonth())  + "/"
		+ dt_datetime.getFullYear()
	);
}
// time generating function
function cal_gen_time1 (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
		+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) 
		//+ ":"
		//+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}

// time generating function
function cal_gen_hour (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() 
		//+ ":"
		//+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) 
		//+ ":"
		//+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}


// time generating function
function cal_gen_min (dt_datetime) {
	return (
		//dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"+
		(dt_datetime.getMinutes() < 10 ? '0' : '') + dt_datetime.getMinutes()
		//+ ":"
		//+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}


// timestamp parsing function
function cal_prs_tsmp1 (str_datetime) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);
		
	// else treat as date in string format
	var arr_datetime = str_datetime.split(' ');
	return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}

// timestamp parsing function
function cal_prs_tsmp2 (str_datetime, str_time) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);
		
	// else treat as date in string format
	//var arr_datetime = str_datetime.split(' ');
	return this.prs_time(str_time, this.prs_date(str_datetime));
}

// date parsing function
function cal_prs_date1 (str_date) {

	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return cal_error ("Formato de fecha inválido: '" + str_date + "'.\nEl formato aceptado es dia-mes-año (dd-mm-yyyy).");
	if (!arr_date[0]) return cal_error ("Formato de fecha inválido: '" + str_date + "'.\nNingún día del mes indicado pudo se encontrado.");
	if (!RE_NUM.exec(arr_date[0])) return cal_error ("Día inválido para el mes: '" + arr_date[0] + "'.\nSólo se permiten valores enteros.");
	if (!arr_date[1]) return cal_error ("Formato de fecha inválido: '" + str_date + "'.\nNigún valor de mes pudo ser encontrado.");
	var idMes = getIdMonth(arr_date[1]);
	if (!RE_NUM.exec(idMes)) return cal_error ("Valor de mes inválido: '" + arr_date[1] + "'.\nSólo se permiten valores enteros.");
	if (!arr_date[2]) return cal_error ("Formato de fecha inválido: '" + str_date + "'.\nNingún valor de año pudo ser encontrado.");
	if (!RE_NUM.exec(arr_date[2])) return cal_error ("Valor de año inválido: '" + arr_date[2] + "'.\nSólo se permiten valores enteros.");

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[1] < 1 || arr_date[1] > 12) return cal_error ("Valor de mes inválido: '" + arr_date[1] + "'.\nSólo se permiten valores entre 01 y 12.");
	dt_date.setMonth(idMes);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[0]);
	if (dt_date.getMonth() != (idMes)) return cal_error ("Dïa inválido del mes: '" + arr_date[0] + "'.\nSólo se permiten valores entre 01 y "+dt_numdays.getDate()+".");

	return (dt_date)
}


// time parsing function
function cal_prs_time1 (str_time, dt_date) {

	if (!dt_date) return null;
	var arr_time = String(str_time ? str_time : '').split(':');

	if (!arr_time[0]) dt_date.setHours(0);
	else if (RE_NUM.exec(arr_time[0]))
		if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
		else return cal_errorFlag ("El valor '"+arr_time[0]+"' para las horas es inválido. \nSólo se permiten valores entre 00 y 23.", "hour");
	else return cal_errorFlag ("El valor '"+arr_time[0]+"' para las horas es inválido.\nSólo se permiten valores enteros sin signo.","hour");
	
	if (!arr_time[1]) dt_date.setMinutes(0);
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
		else return cal_errorFlag ("El valor '"+arr_time[1]+"' para los minutos es inválido.\nSólo se permiten valores entre 00 y 59.","min");
	else return cal_errorFlag ("El valor '"+arr_time[1]+"' de los minutos es inválido.\nSólo se permiten valores enteros sin signo.","min");

	if (!arr_time[2]) dt_date.setSeconds(0);
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
		else return cal_errorFlag ("El valor '"+arr_time[2]+"' para los segundos es inválido.\nSólo se permiten valores entre 00 y 59.","sec");
	else return cal_errorFlag ("El valor '"+arr_time[2]+"' de los segundos es inválido.\nSólo se permiten valores enteros sin signo.","sec");

	dt_date.setMilliseconds(0);
	return dt_date;
}

function cal_error (str_message) {
	alert (str_message);
	return null;
}

function cal_errorFlag (str_message, flag) {
	alert (str_message);
	return flag;
}
