//============================================================================\\
//                              CALENDARIO                                    \\
//============================================================================\\
/** 
 * Funcion de utilidad que se encarga de crear un calendario
 * Para cambiar la presentaci�n del calendario, tocar este metodo!!!!
 */
var CampoEntrada=null;
function showCalendar(anchorName,idioma,newInputField,showYearNav,day,month,year) {
	// Ver si el calendario estaba ya creado recorriendo el array de calendarios

	  CampoEntrada=newInputField;
	var calendar = null;
	for (var i=0; i<window.calendarInstances.length; i++) {
		if (window.calendarInstances[i].oInputField == newInputField) {calendar = window.calendarInstances[i];
		}
	}
    if (calendar == null) {
    	calendar = new Calendar("p01popUpWindowCalendar");		// Calendario en una capa
//    	calendar = new Calendar();					// Calendario en una nueva ventana
    	calendar.setInputField(newInputField); 
    	calendar.setLanguaje(idioma);
    	calendar.oCalendarWindow.isMoveable = true;	// Cambiar para permitir una capa movible o no
    	if (showYearNav != null) calendar.isShowYearNavigation = showYearNav;
    }
    if (arguments.length == 7) calendar.setDate(year,month,day);
    calendar.showCalendar(anchorName);
    return calendar;
}
function showCalendar2(anchorName,idioma,newInputField,showYearNav,day,month,year) {
	// Ver si el calendario estaba ya creado recorriendo el array de calendarios
	var calendar = null;
	for (var i=0; i<window.calendarInstances.length; i++) {
		if (window.calendarInstances[i].oInputField == newInputField) calendar = window.calendarInstances[i];
	}
    if (calendar == null) {
    	calendar = new Calendar();					// Calendario en una nueva ventana
    	calendar.setInputField(newInputField); 
    	calendar.setLanguaje(idioma);    	
    	if (showYearNav != null) calendar.isShowYearNavigation = showYearNav;
    }
    if (arguments.length == 7) calendar.setDate(year,month,day);
	calendar.oCalendarWindow.autoHideEnabled = true; 
    calendar.showCalendar(anchorName);
    return calendar;
}

//___________________________________________________________________________\\
// Propiedades de presentacion del calendario (son variables est�ticas) que se guardan 
// en el contexto de la ventana
if (!window.calendarInitialized) {
	window.calendarInstances = new Array();		// Variable global que es un array que contiene los objetos calendar de la ventana
		
	window.calendarMonthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	window.calendarDayHeaders = new Array("S","M","T","W","T","F","S");
	window.calendarTodayString = "Today";
	window.calendarWeekStartDay = 0;
	window.calendarTitle = "Calendar";
	window.calendarIsShowYearNavigation = false;
	window.calendarInitialized = true;
}






//___________________________________________________________________________\\
// CONSTRUCTOR del objeto calendario
// @param: day
// @param: month
// @param: year
function Calendar() {
	// Mapeo de metodos
		this.setDate = Calendar_setDate;
		this.setInputField = Calendar_setInputField;
		this.setMonthNames = Calendar_setMonthNames;
		this.setDayHeaders = Calendar_setDayHeaders;
		this.setTodayLiteral = Calendar_setTodayLiteral;
		this.setWeekStartDay = Calendar_setWeekStartDay;
		this.setTitle = Calendar_setTitle;
		this.setLanguaje = Calendar_setLanguaje;
		this.showCalendar = Calendar_showCalendar;
		this.hideCalendar = Calendar_hideCalendar;
		this.idioma="cast";
	// Miembros
		var date;				// La fecha que guarda el calendario
		var index;				// Indice del calendario en el array global de calendarios window.calendarInstances
		var oCalendarWindow;	// Ventana con el calendario
		var oInputField;		// Objeto INPUT al que se va a devolver la fecha
		var returnFunction;		// Funcion a llamar al devolver
		
	// Inicializacion
		// Meter el objeto actual en un array global
		this.index = window.calendarInstances.length;
		window.calendarInstances[this.index] = this;
		// Inicializar la fecha que se muestra en el calendario
		this.date = new Date();		// Por defecto se establece la fecha de hoy
		// Ver si el calendario se muestra en un div o en una ventana
		if (arguments.length > 0) {		// Se abre en un div cuyo nombre se pasa como argumento
			this.oCalendarWindow = new PopUpWindow(arguments[0]);
			this.oCalendarWindow.isMoveable = true;
		} else {						// Se abre en una nueva ventana
			this.oCalendarWindow = new PopUpWindow();
		}
		// Establecer las opciones del popUp
		this.oCalendarWindow.setSize(150,165);
		this.oCalendarWindow.offsetX = -152;
		this.oCalendarWindow.offsetY = 25;
		this.oCalendarWindow.autoHide();	
		// Funci�n a la que se llama para devolver el resultado
		this.returnFunction = "tmpReturnFunction";
		// Input field asociado al calendario
		this.oInputField = null;
}
//___________________________________________________________________________\\
/**
 * Funcion que establece la fecha del calendario a partir del a�o, mes y dia
 */
function Calendar_setDate(newYear,newMonth,newDay) {
	var now = new Date();
	if (arguments.length > 2 && newDay != null) { 
		var day = arguments[2];
	} else {
		var day = now.getDate();
	}
	if (arguments.length > 1 && newMonth != null) {
		var month = arguments[1];
	} else {
		var month = now.getMonth()+1;
	}
	if (arguments.length > 0 && newYear != null) {
		var year = arguments[0];
	} else {
		var year = now.getFullYear();
	}
}
//___________________________________________________________________________\\
/**
 * Funcion que avisa cuando el calendario esta mal configurado y no se ha
 * especificado una funcion de retorno
 */
function Calendar_tmpReturnFunction() {
	alert('calendar: Utiliza al funcion setReturnFunction() para especificar a que funcion llamar cuando se pulse en un dia del calendario!');
}
//___________________________________________________________________________\\
/**
 * Establece la funcion a llamar cuando se pulsa en un dia
 */
function Calendar_setInputField(inputField) {
	if (inputField.tagName != "INPUT") {
		alert("calendar: El calendario solo se puede asociar a controles input y esto es un " + inputField.tagName);
		return;
	}
	this.oInputField = inputField;

}
//___________________________________________________________________________\\
/**
 * Sobreescribe los nombres de los meses con los que se pasan en el array
 */
function Calendar_setMonthNames() {
	for (var i=0; i<arguments.length; i++) {
		window.calendarMonthNames[i] = arguments[i];
	}
}
//___________________________________________________________________________\\
/**
 * Sobreescribe los nombres de los dias con los que se pasan en el array
 */
function Calendar_setDayHeaders() {
	for (var i=0; i<arguments.length; i++) {
		window.calendarDayHeaders[i] = arguments[i];
	}
}
//___________________________________________________________________________\\
/**
 * Sobreescribe el literal para el texto "hoy" que aparece al pie del calendario
 */
function Calendar_setTodayLiteral(newTodayLiteral) {
	window.calendarTodayString = newTodayLiteral
}

//___________________________________________________________________________\\
/**
 * Establece el dia de la semana en el cual empieza la semana
 * (Para paises distintos de US la semana empieza en lunes (dia 1)
 * por lo que hay que llamar a esta funcion con el argumento 1
 */
function Calendar_setWeekStartDay(day) {
	window.calendarWeekStartDay = day;
}
//___________________________________________________________________________\\
/**
 * Sobreescribe el literal para el titulo de la ventana
 */
function Calendar_setTitle(newTitle) {
	window.calendarTitle = newTitle
}

//___________________________________________________________________________\\
/**
 * Establece el idioma (ingles, euskera o castellano)
 */
function Calendar_setLanguaje(idioma1) {
	this.idioma=idioma1;
	if (idioma1 == "cast") {
		
		window.calendarMonthNames = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
		window.calendarDayHeaders = new Array("D","L","M","X","J","V","S");
		window.calendarWeekStartDay = 1;
		window.calendarTodayString = "Hoy";
		window.calendarTitle = "Calendario";
	} else if (idioma1 == "eusk") {
		window.calendarMonthNames = new Array("Urtarrilla","Otsaila","Martxoa","Apirila","Maiatza","Ekaina","Uztaila","Abuztua","Iraila","Urria","Azaroa","Abendua");
		window.calendarDayHeaders = new Array("I","A","A","A","O","O","L");
		window.calendarWeekStartDay = 1;
		window.calendarTodayStringeral = "Gaur";
		window.calendarTitle = "Egutegia";
	} else if (idioma1 == "eng") {
		window.calendarMonthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		window.calendarDayHeaders = new Array("S","M","T","W","T","F","S");
		window.calendarWeekStartDay = 0;
		window.calendarTodayString = "Today";
		window.calendarTitle = "Calendar";
	}
	this.oCalendarWindow.title = window.calendarTitle;
}
//___________________________________________________________________________\\
/**
 * Crear un nuevo calendario al lado del anchor <a> cuyo nombre se pasa
 */
function Calendar_showCalendar(anchorName) {
 	this.oCalendarWindow.populate( composeCalendarHTML(this.index,this.date) );	// Ojo!! invertir el orden (a�o/mes/dia)
	this.oCalendarWindow.showPopUp(anchorName);
}
//___________________________________________________________________________\\
/**
 * Esconde el objeto calendario
 */
function Calendar_hideCalendar() {
	this.oCalendarWindow.hidePopUp();
}
//___________________________________________________________________________\\		
// Funcion que refresca el contenido del calendario
function refreshCalendar(calendarIndex,newDate) {
	// A partir del indice del calendario obtener el objeto desde el
	// array global que contiene las instancias de calendario activas
	var thisCalendar = window.calendarInstances[calendarIndex];
	if (thisCalendar == null) thisCalendar = window.opener.calendarInstances[calendarIndex];
	// Refrescar el contenido del popUp
	if (thisCalendar.oCalendarWindow.type == "WINDOW") {
		thisCalendar.oCalendarWindow.popUpWindow.document.all('popUpContents').innerHTML = composeCalendarHTML(calendarIndex,newDate);
	} else {
		thisCalendar.oCalendarWindow.popUpWindow.all("popUpContents").innerHTML = composeCalendarHTML(calendarIndex,newDate);
	}
}

//___________________________________________________________________________\\
function composeCalendarHTML(calendarIndex,date) {
	var day = date.getDate();
	var month = date.getMonth() + 1;
	var year = date.getFullYear();
	var daysinmonth = new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
	if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) daysinmonth[2] = 29;	// Bisiesto (leap)
	var current_month = new Date(year,month-1,1);
	var display_year = year;
	var display_month = month;
	var display_date = 1;
	var weekday = current_month.getDay();
	var offset = 0;
	if (weekday >= window.calendarWeekStartDay) {
		offset = weekday - window.calendarWeekStartDay;
	} else {
		offset = 7-window.calendarWeekStartDay + weekday;
	}
	if (offset > 0) {
		display_month--;
		if (display_month < 1) {
			display_month = 12;
			display_year--;
		}
		display_date = daysinmonth[display_month]-offset+1;
	}
	var next_month = month;
	var next_month_year = year;
	if (next_month > 12) {
 		next_month = 1;
		next_month_year++;
	}
	var last_month = month-2;
	var last_month_year = year;
	if (last_month < 0) {
		last_month = 11;
		last_month_year--;
	}
	// TABLA 1: CABECERA DE NAVEGACION POR MESES Y A�OS
	var sHtml = '';
	sHtml += "<table width='100%' cellspacing='0' cellpadding='0'>";
	sHtml += 	"<tr>";
	if (window.calendarIsShowYearNavigation) {
		sHtml +=	"<td class='p01calendarNavigator' width='144' align='center' valign='middle'>";
		sHtml +=		"<b><a class='p01calendar' href='JavaScript:refreshCalendar( " + calendarIndex + ",new Date(" + last_month_year + "," + last_month + "," + day + ") )'>&lt;</a></b>";
		sHtml +=		"&nbsp;&nbsp;" + window.calendarMonthNames[month-1] + "&nbsp;&nbsp;";
		sHtml += 		"<b><a class='p01calendar' href='JavaScript:refreshCalendar( " + calendarIndex + ",new Date(" + next_month_year + "," + next_month + "," + day + ") )'>&gt;</a></b>";
		sHtml +=		"&nbsp;&nbsp;&nbsp;&nbsp";
		sHtml +=		"<b><a class='p01calendar' href='JavaScript:refreshCalendar( " + calendarIndex + ",new Date(" + (year-1) + "," + month + "," + day + ") )'>&lt;</a></b>";
		sHtml +=		"&nbsp;&nbsp;" + year + "&nbsp;&nbsp;";
		sHtml +=		"<b><a class='p01calendar' href='JavaScript:refreshCalendar( " + calendarIndex + ",new Date(" + (year+1) + "," + month + "," + day + ") )'>&gt;</a></b>";
		sHtml +=	"</td>";
	} else {		
		sHtml +=	"<td class='p01calendarNavigator' width='22' align='center' valign='middle'>";
		sHtml +=		"<b><a class='p01calendar' href='JavaScript:refreshCalendar( " + calendarIndex + ",new Date(" + last_month_year + "," + last_month + "," + day + ") )'>&lt;&lt;</a></b>";
		sHtml +=	"</td>";
		sHtml +=	"<td class='p01calendarNavigator' width='100' align='center'>" + window.calendarMonthNames[month-1] + " " + year + "</td>";
		sHtml +=	"<td class='p01calendarNavigator' width='22' align='center' valign='middle'>";
		sHtml +=		"<b><a class='p01calendar' href='JavaScript:refreshCalendar( " + calendarIndex + ",new Date(" + next_month_year + "," + next_month + "," + day + ") )'>&gt;&gt;</a></b>";
		sHtml +=	"</td>";
	}	
	sHtml +=	"</tr>";
	sHtml += "</table>";
	sHtml += "<br />";
	// TABLA 2: EL CALENDARIO....
	sHtml += "<table width='120' border='0' cellspacing='1' cellpadding='0' align='center'>";
	// Cabeceras para los dias de la semana	
	sHtml += 	"<tr>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay)%7]   + "</td>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay+1)%7] + "</td>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay+2)%7] + "</td>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay+3)%7] + "</td>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay+4)%7] + "</td>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay+5)%7] + "</td>";
	sHtml +=		"<td class='p01calendarWeekDayTitle' align='right' width='14%'>" + window.calendarDayHeaders[(window.calendarWeekStartDay+6)%7] + "</td>";
	sHtml +=	"</tr>";
	
	// Linea vacia
	sHtml +=	"<tr><td colspan='7' align='center'><img src='graypixel.gif' width='120' height='1'></td></tr>";
	
	// Los dias del calendario
	// Cada uno de los dias
	for (var row=1; row <= 6; row++) { 
		sHtml +=	"<tr>";
		var date_class;
		for (var col=1; col <= 7; col++) { 
			if (display_month == month) { 
				date_class = 'p01calendarThisMonth';
			} else { 
				date_class = 'p01calendarOtherMonth';
			} 			
			if ((display_month == month) && (display_date == day) && (display_year == year)) {
				td_class = 'p01calendarToday'; 
			} else { 
				td_class = 'p01calendarMonth';
			} 
			sHtml += "<td class='" + td_class + "'>";
			sHtml += 	"<a href='JavaScript:returnCalendar( " + calendarIndex + "," + display_year + "," + display_month + "," + display_date + ");CampoEntrada.focus();' class=' " + date_class + "'>" + display_date + "</a>";
			sHtml += "</td>";
			display_date++; 		// Algo de JavaScript para seguir obteniendo dias
			if (display_date > daysinmonth[display_month]) { 
				display_date=1;
				display_month++; 
			} 
			if (display_month > 12) {
				display_month=1; 
				display_year++;
			} 
		} 	// for
		sHtml += "</tr>";
	}	// for
	
	// Una linea de separacion
	sHtml += "<tr><td colspan='7' align='center'><img src='graypixel.gif' width='120' height='1'></td></tr>";
	
	// El link con el dia de hoy
	var now = new Date();
	sHtml += "<tr>";
	sHtml += 	"<td colspan='7' align='center'>";
	sHtml +=		"<a class='p01calendarTodayLink' href='JavaScript:returnCalendar( " + calendarIndex + "," + now.getFullYear() + "," + (now.getMonth()+1) + "," + now.getDate() + ")'>" + window.calendarTodayString + "</a>";
	sHtml +=		"<br />";
	sHtml +=	"</td>";
	sHtml += "</tr>";
	
	
	sHtml += "</table>";
	return sHtml;
}	// fin de la funcion...
//___________________________________________________________________________\\
// Funcion que devuelve el resultado (el dia escogido)
function returnCalendar(calendarIndex,year,month,day) { 
	// A partir del indice del calendario obtener el objeto desde el
	// array global que contiene las instancias de calendario activas
alert(idioma);
	var thisCalendar = window.calendarInstances[calendarIndex];
	if (thisCalendar == null) thisCalendar = window.opener.calendarInstances[calendarIndex];
 
	// Copiar la fecha al inputField asociado
	if (thisCalendar.oInputField == null) {
		alert('Fecha Escogida: [' + day + ':' + month + ':' + year + ']');
	} else {
		var oInput;
		if (thisCalendar.oCalendarWindow.type == "WINDOW") {
			oInput = thisCalendar.oInputField;
			//oInput = window.opener.document.all(thisCalendar.oInputField.name);
		} else {
			oInput = document.all(thisCalendar.oInputField.name);
		}
	
		if (idioma != "eu")
		oInput.value = day + '/' + month + '/' + year;
		else
			oInput.value = year + '/' + month + '/' + day;

	}
	// Cerrar la ventana
	
	thisCalendar.oCalendarWindow.hidePopUp();



} 


