var objCalendar = Class.create (); 

objCalendar.prototype = {

	initialize: function(fieldname, options) {

		this.date_value			= 	null;
		this.date_browse		= 	null;		
		this.datefield			=   null;		

		this.options = Object.extend ({
			date_format:				"{d}{s}{m}{s}{Y}",
			date_separator: 			"/",
			left: 						0,
			top: 						0,
			callbackfunction:			function() { },			
			allow_gobacktoday:			true,			
			allow_next_month:			true, 
			allow_next_year:			true,
			allow_prev_month:			true,			
			allow_prev_year:			true,
			allowdaysarray:				null,
			dayofweek:					new Array("Do","Lu","Ma","Mi","Ju","Vi","Sa"),
			dayofweekLong:				new Array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado"),			
			months:						new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"),
			customdaysOfWeek:			new Array(true,true,true,true,true,true,true),			
			customdays_bgcolor:			"#E2E2F1",
			todaydate_bgcolor:			"#f7e3f1",
			actualdate_bordeecolor:		"red",			
			tableheader_bgcolor:		"#8080C0",
			tabledays_bgcolor:			"#FFFFFF",				
			tabledayofWeek_bgcolor:		"#9C84BD",		
			tabledaysEndofWeek_bgcolor:	"#DDDDDD"					
		} , options || {});	
		
		this.asigndate(fieldname);
		
		this._btnPrevYear = this.prevyear.bindAsEventListener(this);		
		this._btnPrevMonth = this.prevmonth.bindAsEventListener(this);
		this._btnNextYear = this.nextyear.bindAsEventListener(this);		
		this._btnNextMonth = this.nextmonth.bindAsEventListener(this);		
		this._MouseClick = this.eventMouseClick.bindAsEventListener(this);		
		

	},
	asigndate: function (fieldname) { 
	
		if ($(fieldname)) {		
			this.datefield = fieldname;
			if ( $(fieldname).value == "") { 			
			  this.date_value = new Date();
			  this.date_browse = new Date(this.date_value);
			 }
			 else {
			  this.date_value = new Date($(fieldname).value.substr(6,4)+"/"+ $(fieldname).value.substr(3,2) +"/"+ $(fieldname).value.substr(0,2) );
			  this.date_browse = new Date(this.date_value);
			 }			  
			return true;
		}
		else {
			this.date_value = new Date();		
			  this.date_browse = new Date(this.date_value);
			alert("No se ha inicializado o no existe el campo fecha");
			return false;
		}
	},
	right: function (str, n) {	
		if (n <= 0)
		   return "";
		else if (n > String(str).length)
		   return str;
		else {
		   var iLen = String(str).length;
		   return String(str).substring(iLen, iLen - n);
		}	
	},
	selectDay: function(event, oCampo) {	
		if ( this.datefield != null ) {
			
			this.date_browse.setDate(oCampo);
			
			day = this.right( "00" + this.date_browse.getDate(), 2 );
			month = this.right( "00" + (this.date_browse.getMonth() + 1) , 2 );			
			year = this.date_browse.getFullYear();
			daylong = this.options.dayofweekLong[this.date_browse.getDay()];
			Monthlong = this.options.months[this.date_browse.getMonth()];			

			var fecha = this.options.date_format;
			fecha = fecha.replace("{d}",day); 
			fecha = fecha.replace("{s}",this.options.date_separator);
			fecha = fecha.replace("{m}",month);			
			fecha = fecha.replace("{s}",this.options.date_separator);			
			fecha = fecha.replace("{Y}",year);	
			$(this.datefield).value = fecha;			
			this.date_value = new Date(this.date_browse);			
			this.options.callbackfunction();
			this.destroy();
		}
		return false;
	},
	getDay: function () {
		if (this.date_browse != null)
			return this.right("00" + this.date_browse.getDate(),2);
		else
			return "";
	},
	getDayOfWeek: function () {
		if (this.date_browse != null)
			return this.options.dayofweekLong[this.date_browse.getDay()];
		else
			return "";
	},	
	getMonth: function () {
		if (this.date_browse != null) 
			return this.right("00"+ (this.date_browse.getMonth() + 1),2);
		else 
			return "";
	},	
	getLongMonth: function () {
		if (this.date_browse != null)
			return this.options.months[this.date_browse.getMonth()];
		else 
			return "";		
	},	
	getYear: function () {
		if (this.date_browse != null) 
			return this.date_browse.getFullYear();
		else
			return "";
	},	
	nextyear: function ( ) {
		if ( this.options.allow_next_year == true) {		
			this.date_browse.setDate(1);		
			this.date_browse.setYear(this.date_browse.getFullYear() + 1);		
			this.builtable();	
		}
	},	
	nextmonth: function ( ) {	
		if ( this.options.allow_next_month == true) {			
			this.date_browse.setDate(1);		
			this.date_browse.setMonth(this.date_browse.getMonth() + 1);
			this.builtable();	
		}
	},	
	prevyear: function ( ) {
		
		fechaactual = new Date();
		
		if ( this.options.allow_prev_year == true ) {
		
			if (this.options.allow_gobacktoday == false  && this.date_browse.getFullYear() == fechaactual.getFullYear()  ) {
				// no pasa	
			} else {
				if ( (this.date_browse.getFullYear() -1) <=  fechaactual.getFullYear() && 
					this.date_browse.getMonth() <  fechaactual.getMonth() ) {
					this.date_browse = new Date(fechaactual);
					this.builtable();					
				} else {
					this.date_browse.setDate(1);							
					this.date_browse.setYear(this.date_browse.getFullYear() - 1);		
					this.builtable();										
				}
			}
		}
	
	},
	prevmonth: function ( ) {
		
		fechaactual = new Date();				
		if ( this.options.allow_prev_month == true) {	
			if (this.options.allow_gobacktoday == false  && this.date_browse.getFullYear() == fechaactual.getFullYear() && 
					this.date_browse.getMonth() == fechaactual.getMonth() ) {
				// no pasa	
			} else {
				this.date_browse.setDate(1);						
				this.date_browse.setMonth(this.date_browse.getMonth() - 1);		
				this.builtable();			
			}
		
		}
		
	},
	show: function () {

		this.destroy();
				
		var oBody = document.getElementsByTagName("body")[0];
	
		var myDivMain = document.createElement("DIV");		
		Element.writeAttribute( myDivMain,"id","div_calendar_main");				 
		Element.writeAttribute( myDivMain,"style","background-color:#6060B0;width:220px;position:absolute;top:"+this.options.top+"px;left:"+this.options.left+"px;");

		var myDivhdr = document.createElement("DIV");		
		Element.writeAttribute( myDivhdr,"id","div_calendar_hdr");
		Element.writeAttribute( myDivhdr ,"style","margin:0px;padding:0px;font-family:Tahoma, Verdana, sans-serif; font-size:12px;");		

		var myDivbody = document.createElement("DIV");		
		Element.writeAttribute( myDivbody,"id","div_calendar_body");  
		Element.writeAttribute( myDivbody ,"style","margin:0px;padding:0px;font-family:Tahoma, Verdana, sans-serif; font-size:12px;");		
		
		var myDivfooter = document.createElement("DIV");		
		Element.writeAttribute( myDivfooter,"id","div_calendar_footer");  
		Element.writeAttribute( myDivfooter,"align","center");  		
		Element.writeAttribute( myDivfooter ,"style","background-color:"+this.options.tableheader_bgcolor+";margin:0px;padding:5px;font-family:Tahoma, Verdana, sans-serif; font-size:12px;color:#FFFFFF;");			
					
		myDivMain.appendChild(myDivhdr);		 			
		myDivMain.appendChild(myDivbody);		 
		myDivMain.appendChild(myDivfooter);		 		
		oBody.appendChild(myDivMain);	

		Event.observe(document, "mousedown", this._MouseClick);
		
		this.builtable();	 
		
	},
	eventMouseClick: function (event) { 

		if ( $("div_calendar_main") ) { 

			if (  event.pageX >= ( $("div_calendar_main").viewportOffset().left +  document.viewport.getScrollOffsets().left ) && 
				  event.pageX <= ( $("div_calendar_main").viewportOffset().left +  document.viewport.getScrollOffsets().left + $("div_calendar_main").getWidth() ) && 
				 event.pageY  >= ( $("div_calendar_main").viewportOffset().top + document.viewport.getScrollOffsets().top )  && 
				 event.pageY  <= ( $("div_calendar_main").viewportOffset().top + document.viewport.getScrollOffsets().top + $("div_calendar_main").getHeight() ) ) {
			}
			else {
					this.destroy();
			}			
		}		
		
	},	
	buildcalendarheader: function () {

		$("div_calendar_hdr").innerHTML = "";

		var mytable = document.createElement("TABLE");
		Element.writeAttribute( mytable,"id","tbl_calendar_hdr"); 
		Element.writeAttribute( mytable,"width","100%");
		Element.writeAttribute( mytable,"border","0");	
		
		var myhead = document.createElement("THEAD");		
		var oFilaHdr = document.createElement("TR");
		Element.writeAttribute( oFilaHdr,"style","background-color:"+this.options.tableheader_bgcolor+"; color: #FFFFFF;font-family:Tahoma, Verdana, sans-serif ; font-size:12px;");		
				
		var oCelda = document.createElement("TD");	
		oCelda.innerHTML = "<img src='images/doble_back.gif' style='border: 1px solid #FFFFFF;cursor: pointer;'/>";
		oCelda.onclick = this._btnPrevYear;				
		Element.writeAttribute(oCelda,"align","center");			
		oFilaHdr.appendChild(oCelda);	
				
		oCelda = document.createElement("TD");
		oCelda.innerHTML = "<img src='images/simple_back.gif' style='border: 1px solid #FFFFFF;cursor: pointer;'/>";
		oCelda.onclick = this._btnPrevMonth ;					
		Element.writeAttribute(oCelda,"align","center");							
		oFilaHdr.appendChild(oCelda);

		oCelda = document.createElement("TD");
		oDivtitle = document.createElement("DIV");
		Element.writeAttribute(oDivtitle,"id","div_calendar_hdr_title");	  
		Element.writeAttribute(oDivtitle,"align","center");	
		Element.writeAttribute(oDivtitle,"style","color: #FFFFFF;padding:3px 0px 3px 0px; margin:0px 3px 0px 3px;");					
		
		oCelda.appendChild(oDivtitle);
		//oCelda.innerHTML = "<div id='div_calendar_hdr_title' style = 'div_calendar_cells' align='center'></div>";
		oFilaHdr.appendChild(oCelda);
		
		oCelda = document.createElement("TD");
		Element.writeAttribute(oCelda,"align","center");	
		oCelda.onclick = this._btnNextMonth ;							
		oCelda.innerHTML = "<img src='images/simple_next.gif' style='border: 1px solid #FFFFFF;cursor: pointer;'/>";
		oFilaHdr.appendChild(oCelda);		

		oCelda = document.createElement("TD");
		Element.writeAttribute(oCelda,"align","center");
		oCelda.onclick = this._btnNextYear;									
		oCelda.innerHTML = "<img src='images/doble_next.gif' style='border: 1px solid #FFFFFF;cursor: pointer;'/>";
		oFilaHdr.appendChild(oCelda);		
		
		myhead.appendChild(oFilaHdr);
		mytable.appendChild(myhead);
		
		$("div_calendar_hdr").appendChild(mytable);
		
		$("div_calendar_hdr_title").innerHTML = this.getLongMonth() + " " + this.getYear();		
	
	},
		
	buildcalendarbody: function () {
		
		$("div_calendar_body").innerHTML = "";

		var mytable = document.createElement("TABLE");		
		Element.writeAttribute( mytable,"id","tbl_calendar_body"); 
		Element.writeAttribute( mytable,"width","100%");
		Element.writeAttribute( mytable,"border","0");		
		
		var myhead = document.createElement("THEAD");
		var oFilaHdr = document.createElement("TR");
		Element.writeAttribute( oFilaHdr,"style","background-color:"+this.options.tabledayofWeek_bgcolor+"; color: #FFFFFF;font-family:Tahoma, Verdana, sans-serif ; font-size:12px;");						
		
		for (i=0;i<=6;i++) {
			
			var oCelda = document.createElement("TD");
			Element.writeAttribute( oCelda, "width","10%");
			Element.writeAttribute( oCelda, "align","center");
			var oTextNode = document.createTextNode(this.options.dayofweek[i]);
			oCelda.appendChild(oTextNode);
			oFilaHdr.appendChild(oCelda);			
		
		}	
		
		myhead.appendChild(oFilaHdr);
			
		mytable.appendChild(myhead);
		$("div_calendar_body").appendChild(mytable);
		
	},
	builddays: function (){
		
		var myTable= $("tbl_calendar_body");
		
		var myBody = document.createElement("TBODY");				
		
		fechaIni = new Date(this.date_browse);
		fechaIni.setDate(1);
		fechaIni.setDate(0 -fechaIni.getDay() + 1 );
		
		fechaFin = new Date(this.date_browse);
		fechaFin.setDate(1);
		fechaFin.setMonth(fechaFin.getMonth() + 1 );		
		fechaFin.setDate( -1 );
		var Fechatmp = null;
		for (j=0;j<10;j++) {		
		
			var oFila = document.createElement("TR");
			Element.writeAttribute( oFila,"style","height:20px;");				
			Fechatmp = new Date(fechaIni);
			Fechatmp.setDate(Fechatmp.getDate() + 1 );
			
			if (Fechatmp.getMonth() != this.date_browse.getMonth() && j > 0 ) 
				break;

			var Numday = 0;
			
			for (i=0;i<=6;i++) {
				
				if ( j == 0 && i == 0) {
					Numday = fechaIni.getDate();
				} else {
					fechaIni.setDate(fechaIni.getDate() + 1);
					Numday = fechaIni.getDate();					
				}							
				
				var oCelda = document.createElement("TD");						
				Element.writeAttribute( oCelda, "align","center");	
				
				if ( this.date_browse.getYear() != fechaIni.getYear() || this.date_browse.getMonth() != fechaIni.getMonth())						
					Numday = '';
				if (i == 0 || i == 6) 
					oCelda.setStyle({backgroundColor: this.options.tabledaysEndofWeek_bgcolor});				
				else 
					oCelda.setStyle({backgroundColor: this.options.tabledays_bgcolor});	 									
				
				var oDiv = document.createElement("DIV");
				oDiv.innerHTML = Numday;
				
				if ( this.options.customdaysOfWeek[i] == true && this.date_browse.getMonth() == fechaIni.getMonth() ) {						
					oCelda.setStyle({backgroundColor: this.options.customdays_bgcolor});
					oCelda.setStyle({cursor: 'pointer'});	
					this._CellClick = this.selectDay.bindAsEventListener(this,Numday);
					oDiv.onclick = this._CellClick; 
				}
				
				if ( this.date_value.getYear() == fechaIni.getYear() && this.date_value.getMonth() == fechaIni.getMonth()
					 && this.date_value.getDate() == fechaIni.getDate() && this.date_browse.getMonth() == fechaIni.getMonth() ) {		
					oCelda.setStyle({border: '1px solid '+ this.options.actualdate_bordeecolor });
				}	
				var FechadeHoy = new Date();
				if ( FechadeHoy.getYear() == fechaIni.getYear() && FechadeHoy.getMonth() == fechaIni.getMonth() && 
						FechadeHoy.getDate() == fechaIni.getDate() && this.date_browse.getMonth() == fechaIni.getMonth() ) {						
					oCelda.setStyle({backgroundColor: this.options.todaydate_bgcolor });
				}					
				oCelda.appendChild(oDiv);
				oFila.appendChild(oCelda);								
			}
			
			myBody.appendChild(oFila);			
				
		}	
		
		myTable.appendChild(myBody);
		var FechadeHoy = new Date();
		$("div_calendar_footer").innerHTML = "Hoy : " + FechadeHoy.getDate()+ " "+ 
		this.options.months[FechadeHoy.getMonth()] + " " + FechadeHoy.getFullYear();		
		 
	},	
	builtable: function () {
	
		this.buildcalendarheader();	
		this.buildcalendarbody();
		this.builddays();	
		
	},
	destroy: function () {
		if ($("div_calendar_main")) { 
			var obody = document.getElementsByTagName("body")[0];
			Event.stopObserving(document, "mousedown", this._MouseClick);	
			obody.removeChild($("div_calendar_main"));			
		}

	}
}
