/*
	Creado por Jos� Miguel Rodr�guez Miranda <jmrm01@eprinsa.es> 7-junio-2006
	
	EPRINSA 2006
*/
/*
	Copyright (c) 2004-2006, The Dojo Foundation
	All Rights Reserved.

	Licensed under the Academic Free License version 2.1 or above OR the
	modified BSD license. For more information on Dojo licensing, see:

		http://dojotoolkit.org/community/licensing.shtml
*/

/**
 *  Modificado el 24-enero-2008 por Antonia Maria Herruzo Herruzo <amhh01@eprinsa.es>
 *  
 *  Motivo:
 *     - Agregacion de controles para limitar la navegación del 
 *       calendario a través de las fechas. 
 *  
 */

dojo.provide("dojo.widget.html.AgendaEprinsa");
dojo.require("dojo.widget.*");
dojo.require("dojo.widget.HtmlWidget");
dojo.require("dojo.widget.AgendaEprinsa");
dojo.require("dojo.event.*");
dojo.require("dojo.html");
dojo.require("dojo.date");

/*
	Some assumptions:
	- I'm planning on always showing 42 days at a time, and we can scroll by week,
	not just by month or year
	- To get a sense of what month to highlight, I basically initialize on the 
	first Saturday of each month, since that will be either the first of two or 
	the second of three months being partially displayed, and then I work forwards 
	and backwards from that point.
	Currently, I assume that dates are stored in the RFC 3339 format,
	because I find it to be most human readable and easy to parse
	http://www.faqs.org/rfcs/rfc3339.html: 		2005-06-30T08:05:00-07:00
	FIXME: scroll by week not yet implemented
*/


dojo.widget.html.AgendaEprinsa = function(){

	dojo.widget.AgendaEprinsa.call(this);
	dojo.widget.HtmlWidget.call(this);

	var _this = this;
	// today's date, JS Date object
	this.today = "";
	// selected date, JS Date object
	this.date = "";
	// rfc 3339 date
	this.storedDate = "";
	// date currently selected in the UI, stored in year, month, date in the format that will be actually displayed
	this.currentDate = {};
	// stored in year, month, date in the format that will be actually displayed
	this.firstSaturday = {};
	
	// Campo para almacenar los dias activos de la agenda y usarlo en el constructor del aspecto gr�fico
	this.diasActivos = "";
	// Campo para almacenar los dias activos de un evento seleccionado y usarlo en el constructor del aspecto gr�fico
	this.diasActivosEvento = "";
	// Campo para guardar la ruta del enlace de los d�as activos de la agenda
	this.ruta = "";

		
	this.classNames = {
		previous: "previousMonth",
		current: "currentMonth",
		next: "nextMonth",
		currentDate: "currentDate",
		selectedDate: "selectedItem",
		diaActivo: "diaActivo",
		diaActivoSinEnlace: "diaActivoSinEnlace",
		diaActivoEvento: "diaActivoEvento",
		hover: "hover",
		//Clases de los elementos de navegacion del calendario, 
		//especificadas en js/dojo/src/widget/templates/HtmlAgendaEprinsa.html
		incrementoSemana: "incrementControl increase semana", 
		decrementoSemana: "incrementControl decrease semana", 
		incrementoMes: "incrementControl increase mes", 
		decrementoMes: "incrementControl decrease mes"
	}

	this.templatePath =  dojo.uri.dojoUri("src/widget/templates/HtmlAgendaEprinsa.html");
	this.templateCssPath = dojo.uri.dojoUri("src/widget/templates/HtmlAgendaEprinsa.css");
	
	this.fillInTemplate = function(){
		this.initData();
		this.initUI();
	}

	this.initData = function() {		
		if (this.bNavegacionMensual && this.bNavegacionAnual) {
			navegacion_mensual = document.getElementById(this.bNavegacionMensual).value;
			navegacion_anual = document.getElementById(this.bNavegacionAnual).value;
			if (navegacion_mensual == 0 && navegacion_anual == 0) {				
				this.today = new Date(this.iAnoMenor, this.iMesMenor - 1, 1);
			}
			else {
				this.today = new Date();								
			}
		}
		else {
			this.today = new Date();
		}
		if (this.date == "") {
			if(this.storedDate && (this.storedDate.split("-").length > 2)) {
				this.date = dojo.widget.AgendaEprinsa.util.fromRfcDate(this.storedDate);
			} else {
				this.date = this.today;
			}
		}
		
		
		// calendar math is simplified if time is set to 0
		this.today.setHours(0);
		this.date.setHours(0);
		var month = this.date.getMonth();

		var tempDomingo = dojo.widget.AgendaEprinsa.util.initPrimerDomingo(this.date.getMonth().toString(), this.date.getFullYear());
		this.firstSaturday.year = tempDomingo.year;
		this.firstSaturday.month = tempDomingo.month;
		this.firstSaturday.date = tempDomingo.date;
	}
	
	this.setDate = function(rfcDate) {
		this.storedDate = rfcDate;
	}
	
	this.initUI = function() {
		this.selectedIsUsed = false;
		this.currentIsUsed = false;
		var currentClassName = "";
		var previousDate = new Date();
		var calendarNodes = this.calendarDatesContainerNode.getElementsByTagName("td");
		var currentCalendarNode;
		// set hours of date such that there is no chance of rounding error due to 
		// time change in local time zones
		previousDate.setHours(8);
		var nextDate = new Date(this.firstSaturday.year, this.firstSaturday.month, this.firstSaturday.date, 8);

		if(this.firstSaturday.date < 7) {
			// this means there are days to show from the previous month
			var dayInWeek = 6;
			for (var i=this.firstSaturday.date; i>0; i--) {
				currentCalendarNode = calendarNodes.item(dayInWeek);
				currentCalendarNode.innerHTML = nextDate.getDate();				
				// Compruebo si el dia esta entre los activos para ponerle otro class
				sclass = "current";
				if(this.diasActivos != "")
					if(this.comprobarDiaActivo(nextDate))
						if(!this.noPermitirEnlaces)
							sclass = "diaActivo";
						else
							sclass = "diaActivoSinEnlace";
				if(this.diasActivosEvento != "")
					if(this.comprobarDiaActivoEvento(nextDate))
						sclass = "diaActivoEvento";

				dojo.html.setClass(currentCalendarNode, this.getDateClassName(nextDate, sclass));
				dayInWeek--;
				previousDate = nextDate;
				nextDate = this.incrementDate(nextDate, false);				
			}
			for(var i=dayInWeek; i>-1; i--) {
				currentCalendarNode = calendarNodes.item(i);
				currentCalendarNode.innerHTML = nextDate.getDate();
				// Compruebo si el dia esta entre los activos para ponerle otro class
				sclass = "previous";
				if(this.diasActivos != "")
					if(this.comprobarDiaActivo(nextDate))
						if(!this.noPermitirEnlaces)
							sclass = "diaActivo";
						else
							sclass = "diaActivoSinEnlace";
				if(this.diasActivosEvento != "")
					if(this.comprobarDiaActivoEvento(nextDate))
						sclass = "diaActivoEvento";
				
				dojo.html.setClass(currentCalendarNode, this.getDateClassName(nextDate, sclass));
				dojo.html.setClass(currentCalendarNode, this.classNames["previous"]+ " " + this.getDateClassName(nextDate, sclass));
				if(this.componeFecha(this.date)==this.componeFecha(nextDate)) {
					dojo.html.setClass(currentCalendarNode, dojo.html.getClass(currentCalendarNode) + " " + this.classNames["selectedDate"]);
					this.selectedIsUsed = 1;
				}
				if(this.componeFecha(this.today)==this.componeFecha(nextDate)) {
					dojo.html.setClass(currentCalendarNode, dojo.html.getClass(currentCalendarNode) + " " + this.classNames["currentDate"]);
					this.currentIsUsed = 1;
				}				
				previousDate = nextDate;
				nextDate = this.incrementDate(nextDate, false);				
			}
		} else {
			nextDate.setDate(this.firstSaturday.date-6);
			for(var i=0; i<7; i++) {
				currentCalendarNode = calendarNodes.item(i);
				currentCalendarNode.innerHTML = nextDate.getDate();
				// Compruebo si el dia esta entre los activos para ponerle otro class
				sclass = "current";
				if(this.diasActivos != "")
					if(this.comprobarDiaActivo(nextDate))
						if(!this.noPermitirEnlaces)
							sclass = "diaActivo";
						else
							sclass = "diaActivoSinEnlace";
				if(this.diasActivosEvento != "")
					if(this.comprobarDiaActivoEvento(nextDate))
						sclass = "diaActivoEvento";

				dojo.html.setClass(currentCalendarNode, this.getDateClassName(nextDate, sclass));
				previousDate = nextDate;
				nextDate = this.incrementDate(nextDate, true);												
			}
		}
		previousDate.setDate(this.firstSaturday.date);
		previousDate.setMonth(this.firstSaturday.month);
		previousDate.setFullYear(this.firstSaturday.year);
		nextDate = this.incrementDate(previousDate, true);
		var count = 7;
		currentCalendarNode = calendarNodes.item(count);
		while((nextDate.getMonth() == previousDate.getMonth()) && (count<42)) {
			currentCalendarNode.innerHTML = nextDate.getDate();
			// Compruebo si el dia esta entre los activos para ponerle otro class
			sclass = "current";
			if(this.diasActivos != "")
				if(this.comprobarDiaActivo(nextDate))
					if(!this.noPermitirEnlaces)
							sclass = "diaActivo";
						else
							sclass = "diaActivoSinEnlace";
			if(this.diasActivosEvento != "")
				if(this.comprobarDiaActivoEvento(nextDate))
					sclass = "diaActivoEvento";

			dojo.html.setClass(currentCalendarNode, this.getDateClassName(nextDate, sclass));
			currentCalendarNode = calendarNodes.item(++count);			
			previousDate = nextDate;
			nextDate = this.incrementDate(nextDate, true);
		}
		
		while(count < 42) {
			currentCalendarNode.innerHTML = nextDate.getDate();
			// Compruebo si el dia esta entre los activos para ponerle otro class
			sclass = "next";
			if(this.diasActivos != "")
				if(this.comprobarDiaActivo(nextDate))
					if(!this.noPermitirEnlaces)
							sclass = "diaActivo";
						else
							sclass = "diaActivoSinEnlace";
			if(this.diasActivosEvento != "")
				if(this.comprobarDiaActivoEvento(nextDate))
					sclass = "diaActivoEvento";
			
			dojo.html.setClass(currentCalendarNode, this.getDateClassName(nextDate, sclass));
			dojo.html.setClass(currentCalendarNode, this.classNames["next"]+ " " +this.getDateClassName(nextDate, sclass));
			if(this.componeFecha(this.date)==this.componeFecha(nextDate)) {
				dojo.html.setClass(currentCalendarNode, dojo.html.getClass(currentCalendarNode) + " " + this.classNames["selectedDate"]);
				this.selectedIsUsed = 1;
			}	
			if(this.componeFecha(this.today)==this.componeFecha(nextDate)) {
				dojo.html.setClass(currentCalendarNode, dojo.html.getClass(currentCalendarNode) + " " + this.classNames["currentDate"]);
				this.currentIsUsed = 1;
			}			
			currentCalendarNode = calendarNodes.item(++count);			
			previousDate = nextDate;
			nextDate = this.incrementDate(nextDate, true);
		}
		this.setMonthLabel(this.firstSaturday.month);
		this.setYearLabels(this.firstSaturday.year);

		//Si existe bNavegacionMensual y el elemento está definido, entramos a configurar 
		//la navegación de la fecha 
		if (this.bNavegacionMensual && document.getElementById("increaseMonthNode")) {
			this.configurarNavegacion();
		}
	}

	//Método para configurar la navegación
	/**
	 * Variables utilizadas:
	 *  - bNavegacionMensual: indica si se va a permitir navegar por los meses o no
	 *  - bNavegacionAnual: indica si se va a haber años diferentes en las fechas.
	 *  - iMesMenor: el menor mes de las fechas del evento
	 *  - iMesMayor: el mayor mes de las fechas del evento
	 *  - iAnoMenor: el menor año de las fechas del evento
	 *  - iAnoMayor: el mayor año de las fechas del evento
	 *  - mes_actual: el mes actual en la navegación del calendario
	 *  - ano_actual: el año actual en la navegación del calendario
	 */ 
	
	
	this.configurarNavegacion = function() {
		if (this.bNavegacionMensual) {
			navegacion_mensual = document.getElementById(this.bNavegacionMensual).value;
			//Si el evento está programado para el mismo mes y mismo año, no se permite navegacion
			if (navegacion_mensual == 0) {	
				//se le ponene a los elementos clases que eliminan los elementos de navegación
				dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
				dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
				dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoSemana"]);
				dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoSemana"]);																
			}
			//hay navegacion mensual
			else {
				if (this.bNavegacionAnual) {
					navegacion_anual = document.getElementById(this.bNavegacionAnual).value;
					//Averiguo los datos
					var mes_actual = this.getMonthIndex() + 1;
					var mes_menor = this.iMesMenor;
					var mes_mayor = this.iMesMayor; 
					var ano_actual = this.currentYearLabelNode.innerHTML;
					var ano_mayor = this.iAnoMayor;
					var ano_menor = this.iAnoMenor;
					
					//dentro del mismo año
					if (navegacion_anual == 0) {
						//Si el mes actual del calendario es menor que el mes menor, las flechas de decrecimiento de las fechas debo eliminarlas
						if (mes_actual <= mes_menor) {						
							dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
							dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoSemana"]);																
						}
						else {							
							//Si no, la de la semana se elimina y la del mes se coloca,
							dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
							dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoMes"]);																
						}
						//
						if (mes_actual >= mes_mayor) {							
							dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
							dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoSemana"]);
						}
						else {							
							dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
							dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoMes"]);
						}						
					}
					//en años diferentes
					else {						
						if (ano_actual == ano_menor) {
							if (mes_actual <= mes_mayor) {								
								dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
								dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoSemana"]);																
							}
							else {
								dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
								dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoMes"]);																
							}
							
							if (mes_actual <= mes_menor) {								
								dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
								dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoSemana"]);
							}
							else {									
								dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
								dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoMes"]);
							}													
						}
						if (ano_actual == ano_mayor) {
							if (mes_actual > mes_menor) {
								dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
								dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoSemana"]);
							}
							else {								
								dojo.html.setClass(document.getElementById("increaseWeekNode"), this.classNames["incrementoSemana"]);
								dojo.html.setClass(document.getElementById("increaseMonthNode"), this.classNames["incrementoMes"]);
							}
							
							if (mes_actual <= mes_mayor) {	
								dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
								dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoMes"]);																
							}
							else {								
								dojo.html.setClass(document.getElementById("decreaseWeekNode"), this.classNames["decrementoSemana"]);
								dojo.html.setClass(document.getElementById("decreaseMonthNode"), this.classNames["decrementoSemana"]);																
							}
																			
						}
					}				
				}
			}
		}
	}




	this.incrementDate = function(date, bool) {
		// bool: true to increase, false to decrease
		var time = date.getTime();
		var increment = 1000 * 60 * 60 * 24;
		time = (bool) ? (time + increment) : (time - increment);
		var returnDate = new Date();
		returnDate.setTime(time);
		return returnDate;
	}
	
	this.incrementWeek = function(date, bool) {
		dojo.unimplemented('dojo.widget.html.AgendaEprinsa.incrementWeek');
	}

	this.incrementMonth = function(date, bool) {
		dojo.unimplemented('dojo.widget.html.AgendaEprinsa.incrementMonth');
	}

	this.incrementYear = function(date, bool) {
		dojo.unimplemented('dojo.widget.html.AgendaEprinsa.incrementYear');
	}

	this.onIncrementDate = function(evt) {
		dojo.unimplemented('dojo.widget.html.AgendaEprinsa.onIncrementDate');
	}

	this._daysIn = function(month,year) {
		var daysIn = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 
		
		if (month==1) {
			return (year%400 == 0) ? 29: (year%100 == 0) ? 28: (year%4 == 0) ? 29: 28;
		} else {
			return daysIn[month];
		}
	}	

	this.onIncrementWeek = function(evt) {
		// FIXME: should make a call to incrementWeek when that is implemented
		evt.stopPropagation();
		var date = this.firstSaturday.date;
		var month = this.firstSaturday.month;
		var year = this.firstSaturday.year;
		switch(evt.target) {
			case this.increaseWeekNode.getElementsByTagName("img").item(0): 
			case this.increaseWeekNode:
				date = date + 7;
				if (date>this._daysIn(month,year)) {
					date = date - this._daysIn(month,year);
					if (month < 11) {
						month++;	
					} else {
						month=0;
						year++;
					}
				}
				break;
			case this.decreaseWeekNode.getElementsByTagName("img").item(0):
			case this.decreaseWeekNode:
				if (date > 7) {
					date = date - 7;
				} else {
					var diff = 7 - date;
					if (month > 0) {
						month--;
						date = this._daysIn(month,year) - diff;
					}else {
						year--;
						month=11;
						date = 31 - diff;
					}
				}
				break;

		}

		this.firstSaturday.date=date;
		this.firstSaturday.month=month;
		this.firstSaturday.year=year;
		this.initUI();
	}

	this.onIncrementMonth = function(evt) {
		// FIXME: should make a call to incrementMonth when that is implemented
		evt.stopPropagation();
		var month = this.firstSaturday.month;
		var year = this.firstSaturday.year;
		switch(evt.currentTarget) {
			case this.increaseMonthNode:
				if(month < 11) {
					month++;
				} else {
					month = 0;
					year++;
					
					this.setYearLabels(year);
				}
				break;
			case this.decreaseMonthNode:
				if(month > 0) {
					month--;
				} else {
					month = 11;
					year--;
					this.setYearLabels(year);
				}
				break;
			case this.increaseMonthNode.getElementsByTagName("img").item(0):
				if(month < 11) {
					month++;
				} else {
					month = 0;
					year++;
					this.setYearLabels(year);
				}
				break;
			case this.decreaseMonthNode.getElementsByTagName("img").item(0):
				if(month > 0) {
					month--;
				} else {
					month = 11;
					year--;
					this.setYearLabels(year);
				}
				break;
		}
		var tempSaturday = dojo.widget.AgendaEprinsa.util.initPrimerDomingo(month.toString(), year);
		this.firstSaturday.year = tempSaturday.year;
		this.firstSaturday.month = tempSaturday.month;
		this.firstSaturday.date = tempSaturday.date;
		this.initUI();
	}

	this.onIncrementYear = function(evt) {
		// FIXME: should make a call to incrementYear when that is implemented
		evt.stopPropagation();
		var year = this.firstSaturday.year;
		switch(evt.target) {
			case this.nextYearLabelNode:
				year++;
				break;
			case this.previousYearLabelNode:
				year--;
				break;
		}
		var tempSaturday = dojo.widget.AgendaEprinsa.util.initPrimerDomingo(this.firstSaturday.month.toString(), year);
		this.firstSaturday.year = tempSaturday.year;
		this.firstSaturday.month = tempSaturday.month;
		this.firstSaturday.date = tempSaturday.date;
		this.initUI();
	}

	var meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];

	this.setMonthLabel = function(monthIndex) {
		this.monthLabelNode.innerHTML = meses[monthIndex];
	}

	this.getMonthLabel = function() {
		return this.monthLabelNode.innerHTML;
	}
	
	this.getMonthIndex = function() {
		for (index = 0; index < meses.length; index++) {
			if (this.getMonthLabel() == meses[index]) {
				return index;				
			} 
		}
		return -1;
	}
    

	this.setYearLabels = function(year) {
		this.previousYearLabelNode.innerHTML = year - 1;
		this.currentYearLabelNode.innerHTML = year;
		this.nextYearLabelNode.innerHTML = year + 1;
	}

	this.getDateClassName = function(date, monthState) {
		var currentClassName = this.classNames[monthState];			
		if ((!this.selectedIsUsed) && (date.getDate() == this.date.getDate()) && (date.getMonth() == this.date.getMonth()) && (date.getFullYear() == this.date.getFullYear())) {			
			currentClassName = this.classNames.selectedDate + " " + currentClassName;
			this.selectedIsUsed = 1;
		}		
		if((!this.currentIsUsed) && (date.getDate() == this.today.getDate()) && (date.getMonth() == this.today.getMonth()) && (date.getFullYear() == this.today.getFullYear())) {
			currentClassName = currentClassName + " "  + this.classNames.currentDate;
			this.currentIsUsed = 1;
		}
		return currentClassName;
	}

	this.onClick = function(evt) {
		dojo.event.browser.stopEvent(evt)
	}

	this.onSetDate = function(evt) {
		dojo.event.browser.stopEvent(evt);
		this.selectedIsUsed = 0;
		this.todayIsUsed = 0;
		var month = this.firstSaturday.month;
		var year = this.firstSaturday.year;
		if (dojo.html.hasClass(evt.target, this.classNames["next"])) {
			month = ++month % 12;
			// if month is now == 0, add a year
			year = (month==0) ? ++year : year;
		} else if (dojo.html.hasClass(evt.target, this.classNames["previous"])) {
			month = --month % 12;
			// if month is now == 0, add a year
			year = (month==11) ? --year : year;
		}		
		this.date = new Date(year, month, evt.target.innerHTML);
		this.setDate(dojo.widget.AgendaEprinsa.util.toRfcDate(this.date));
		this.initUI();
	}
	

	/**
	* Funci�n: cargarDiasAgenda()
	* 
	* Carga los d�as activos de la agenda leyendo el valor de un campo oculto cuyo identificador se pasa como 
	* par�metro. El formato de dichos valores es: dd/mm/aaaa;dd/mm/aaaa; ... ;dd/mm/aaaa
	*
	* @param		string		id_campo_dias_activos		Identificador del campo oculto que contiene los dias activos.
	* @param		string		id_dias_activos_evento		identificador del campo oculto que contiene los dias activos de un evento.
	* 
	* @return No devuelve nada.
	*/
	this.cargarDiasAgenda = function(id_campo_dias_activos, id_dias_activos_evento, id_dia_seleccionado) {
		//Se comprueba si existen estos elementos antes, en IE puede haber problemas
		if (document.getElementById(id_campo_dias_activos)) 
			this.diasActivos = document.getElementById(id_campo_dias_activos).value;

		if (document.getElementById(id_dias_activos_evento)) 			
			this.diasActivosEvento = document.getElementById(id_dias_activos_evento).value;
													
        if (document.getElementById(id_dia_seleccionado)) 										
			this.date = new Date(this.traduceFecha(document.getElementById(id_dia_seleccionado).value));
						
		this.initUI();
	}

	/**
	* Funci�n: comprobarDiaActivoEvento()
	* 
	* Comprueba si el dia pasado como par�metro es uno de los d�as activos de un evento seleccionado previamente
	*
	* @param		object		fecha		Fecha del dia a comprobar.
	* 
	* @return true|false Devuelve si lo ha encontrado o no en la lista.
	*/	
	this.comprobarDiaActivoEvento = function(fecha) {
	
		var comprobandoFecha = this.componeFecha(fecha);
		
		var arrayDias = this.diasActivosEvento.split(';');
		for(i = 0; i < arrayDias.length; i++)
			if(comprobandoFecha == arrayDias[i])
				return true;
		
		return false;
	}
	
	/**
	* Funci�n: comprobarDiaActivo()
	* 
	* Comprueba si el dia pasado como par�metro es uno de los d�as activos de la agenda
	*
	* @param		object		fecha		Fecha del dia a comprobar.
	* 
	* @return true|false Devuelve si lo ha encontrado o no en la lista.
	*/
	this.comprobarDiaActivo = function(fecha) {
	
		var comprobandoFecha = this.componeFecha(fecha);
		
		var arrayDias = this.diasActivos.split(';');
		for(i = 0; i < arrayDias.length; i++)
			if(comprobandoFecha == arrayDias[i])
				return true;
		
		return false;
	}
	
	/**
	* Funci�n: componeFecha()
	* 
	* Compone una fecha con el formato dd/mm/aaaa a partir de un objeto de la clase dojo.date
	*
	* @param		object		fecha		Fecha del dia a componer.
	* 
	* @return 		string 		Fecha con formato dd/mm/aaaa.
	*/
	this.componeFecha = function(fecha) {
		var dia = fecha.getDate();
		var mes = fecha.getMonth() + 1;
		var anual = fecha.getYear();
		if(anual < 1900)
			anual += 1900;
		var sAnual = anual;
		
		var fechaFinal = dia + "/" + mes + "/" + sAnual;
		
		return fechaFinal;
	}
	/**
	* Funci�n:traduceFecha()
	* 
	* Compone una fecha con el formato mm/dd/aaaa a partir de una fecha con formato dd/mm/aaaa
	*
	* @param		string		Fecha con formato mm/dd/aaaa.
	* 
	* @return 		string 		Fecha con formato dd/mm/aaaa.
	*/	
	this.traduceFecha = function(fecha) {
		var aFecha = fecha.split("/");
		if(aFecha.length=3) 	return aFecha[1] + "/" + aFecha[0] + "/" + aFecha[2];		
		else	return "";		
	}
	
	/**
	* Funcion mouseOver())
	*
	* Asigna estilo hover para simular el :hover de un enlace
	* 
	* @param		object		evt		Evento de Dojo.
	* 
	*/	
	this.mouseOver = function(evt) {		
		dojo.event.browser.stopEvent(evt);
		if(!this.noPermitirEnlaces) {
			var month = this.firstSaturday.month;
			var year = this.firstSaturday.year;
			if (dojo.html.hasClass(evt.target, this.classNames["next"])) {
				month = ++month % 12;
				// if month is now == 0, add a year
				year = (month==0) ? ++year : year;
			} else if (dojo.html.hasClass(evt.target, this.classNames["previous"])) {
				month = --month % 12;
				// if month is now == 0, add a year
				year = (month==11) ? --year : year;
			}		
			month++;
			var comprobandoFecha = evt.target.innerHTML + "/" + month + "/" + year;
			var arrayDias = this.diasActivos.split(';');
			for(i = 0; i < arrayDias.length; i++)
				if(comprobandoFecha == arrayDias[i]) {
					dojo.html.setClass(evt.target, dojo.html.getClass(evt.target) + " " + this.classNames["hover"]);
				}
		}
	}

	/**
	* Funcion mouseOut())
	*
	* Quita el estilo hover de los estilos cuando sale el raton de encima
	*
	* @param		object		evt		Evento de Dojo.
	* 
	*/	
	this.mouseOut = function(evt) {		
		dojo.event.browser.stopEvent(evt);
		if(!this.noPermitirEnlaces) {
			var month = this.firstSaturday.month;
			var year = this.firstSaturday.year;
			var sClass=this.classNames["diaActivo"];
			if (dojo.html.hasClass(evt.target, this.classNames["next"])) {
				month = ++month % 12;
				// if month is now == 0, add a year
				year = (month==0) ? ++year : year;
			} else if (dojo.html.hasClass(evt.target, this.classNames["previous"])) {
				month = --month % 12;
				// if month is now == 0, add a year
				year = (month==11) ? --year : year;
			}
			if (dojo.html.hasClass(evt.target, this.classNames["hover"])) {						
				var aClass = dojo.html.getClass(evt.target).split(" ");
				for(i=0;i<aClass.length;i++) {
					if(aClass[i]!="hover") sClass= sClass + " " + aClass[i];
				}
			}
			
			month++;
			var comprobandoFecha = evt.target.innerHTML + "/" + month + "/" + year;
			var arrayDias = this.diasActivos.split(';');
			for(i = 0; i < arrayDias.length; i++)
				if(comprobandoFecha == arrayDias[i]) {
					dojo.html.setClass(evt.target, sClass);
				}
		}
	}	
	
	/**
	* Funci�n: irEnlace()
	* 
	* Nos envia a la url del enlace
	*
	* @param		object		evt		Evento de Dojo.
	* 
	*/	
	this.irEnlace = function(evt) {
		dojo.event.browser.stopEvent(evt);
		// Comprobamos si el widget se ha creado permitiendo los enlaces en las fechas
		if(!this.noPermitirEnlaces) {
			var month = this.firstSaturday.month;
			var year = this.firstSaturday.year;
			if (dojo.html.hasClass(evt.target, this.classNames["next"])) {
				month = ++month % 12;
				// if month is now == 0, add a year
				year = (month==0) ? ++year : year;
			} else if (dojo.html.hasClass(evt.target, this.classNames["previous"])) {
				month = --month % 12;
				// if month is now == 0, add a year
				year = (month==11) ? --year : year;
			}
			month++;
			var comprobandoFecha = evt.target.innerHTML + "/" + month + "/" + year;
			var arrayDias = this.diasActivos.split(';');
			for(i = 0; i < arrayDias.length; i++)
				if(comprobandoFecha == arrayDias[i]) {
					// mandamos a la url de busqueda de eventos de esa fecha
					var ruta = this.ruta + comprobandoFecha;				
					location.href = ruta;
				}
		}
	}

	/**
	* Funci�n: establecerRuta()
	* 
	* Establece la ruta de los enlaces de los dias activos de la agenda
	*
	* @param		string		rutaEnlace		Rutas de los enlaces.
	* 
	*/	
	this.establecerRuta = function(rutaEnlace) {
		this.ruta = rutaEnlace;
	}
}
dojo.inherits(dojo.widget.html.AgendaEprinsa, dojo.widget.HtmlWidget);
