var Calendario = Class.create({
	initialize: function(obj,format,lang,week_start,divCalId) {
		if( ! lang ) lang = 'es';
		this.lang = lang;
		if( ! obj) this.cal_error( 'not_obj' );
		this.obj = obj;
		if( ! format ) format = 'dd/mm/yyyy';
		this.format = format;
		if( ! week_start ) week_start = 0;
		this.week_start = week_start;
		if( ! divCalId ) {
			this.divCalId = 'divCalendario';
			var objBody = document.getElementsByTagName("body").item(0);
	
			var divCalTelon = document.createElement("div");
			divCalTelon.setAttribute('id','divCalTelon');
	
			divCalTelon.style.position = 'absolute';
			divCalTelon.style.top = 0;
			divCalTelon.style.left = 0;
			divCalTelon.style.zIndex = 80;
			divCalTelon.style.width = '100%';
			divCalTelon.style.opacity = .5;
			divCalTelon.style.filter = 'alpha(opacity=50)';
			divCalTelon.style.height = document.body.clientHeight+'px';
			divCalTelon.style.backgroundColor = '#ffffff';
			objBody.appendChild(divCalTelon);
			var flashObjects = document.getElementsByTagName("object");
			for (i = 0; i < flashObjects.length; i++) {
				flashObjects[i].style.visibility = "hidden";
			}
		
			var flashEmbeds = document.getElementsByTagName("embed");
			for (i = 0; i < flashEmbeds.length; i++) {
				flashEmbeds[i].style.visibility = "hidden";
			}
			var selects = document.getElementsByTagName("select");
			for (i = 0; i != selects.length; i++) {
				selects[i].style.visibility = "hidden";
			}
	
			var objDiv = document.createElement("div");
			objDiv.setAttribute('id',this.divCalId);
			//objDiv.style.display = 'none';
			objDiv.style.position = 'absolute';
			objDiv.style.zIndex = 90;
			objDiv.style.width = '200px';
			objDiv.style.backgroundColor = '#ffffff';
			objBody.appendChild(objDiv);
			objDiv = document.getElementById( "divCalendario" );
			var offset = this.findPos(this.obj);
			objDiv.style.left = offset[0]+'px';
			objDiv.style.top = (offset[1]+this.obj.offsetHeight+1)+'px';
		} else this.divCalId = divCalId;
		this.setLang();
		if( this.obj.tagName == 'INPUT' && this.obj.value != '' ) {
			this.value = this.str2date( obj.value );
		} else {
			this.value = new Date();
			this.value.setMilliseconds(0);
		}
		this.valueini = new Date( this.value );
		//alert(this.value.getDay());
		this.showCal( this.value );
	},

	end: function() {
		var objBody = document.getElementsByTagName("body").item(0);
		//objBody.removeChild(document.getElementById('divCalTelon'));
		var i = 0;
		while( obj = objBody.childNodes[i] ) {
			if( obj.id == 'divCalTelon' ) {
				objBody.removeChild(objBody.childNodes[i]);
				if( ! document.getElementById(this.divCalId) ) break;
				i--;
			}
			if( obj.id == this.divCalId ) {
				objBody.removeChild(objBody.childNodes[i]);
				if( ! document.getElementById('divCalTelon') ) break;
				i--;
			}
			i++;
		}
		var flashObjects = document.getElementsByTagName("object");
		for (i = 0; i < flashObjects.length; i++) {
			flashObjects[i].style.visibility = "visible";
		}
	
		var flashEmbeds = document.getElementsByTagName("embed");
		for (i = 0; i < flashEmbeds.length; i++) {
			flashEmbeds[i].style.visibility = "visible";
		}
		var selects = document.getElementsByTagName("select");
		for (i = 0; i != selects.length; i++) {
			selects[i].style.visibility = "visible";
		}
		if(eval('window.chg__'+this.obj.name)) eval('chg__'+this.obj.name+'(this)');
		return true;
	},
	
	setLang: function() {
		switch (this.lang) {
			case 'es':
				this.arr_months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio","Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
				this.arr_weekdays = ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"];
				this.blank = 'Blanquear Fecha';
				this.yeardown = 'Ao Anterior';
				this.monthdown = 'Mes Anterior';
				this.monthup = 'Mes Siguiente';
				this.yearup = 'Ao Siguiente';
				this.exit = 'Cerrar Calendario';
				this.hourup = 'Hora Siguiente';
				this.hourdown = 'Hora Anterior';
				this.minuteup = 'Minuto Siguiente';
				this.minutedown = 'Minuto Anterior';
				this.secondup = 'Segundo Siguiente';
				this.seconddown = 'Segundo Anterior';
				break;
			case 'en':
				this.arr_months = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
				this.arr_weekdays = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
				this.blank = 'Blank Date';
				this.yeardown = 'Year Before';
				this.monthdown = 'Month Before';
				this.monthup = 'Month After';
				this.yearup = 'Year After';
				this.exit = 'Close Calendar';
				this.hourup = 'Hour After';
				this.hourdown = 'Hour Before';
				this.minuteup = 'Minute After';
				this.minutedown = 'Minute Before';
				this.secondup = 'Second After';
				this.seconddown = 'Second Before';
				break;
			default:
				this.cal_error( 'err_setLang' );
				break;
		}
	},
	
	showCal: function( val ) {
		var padre = this;
		objTable = document.createElement("table");
		objTable.setAttribute("width","100%");
		objTable.setAttribute("cellspacing","1");
		objTable.setAttribute("cellpaddig","3");
		objTable.setAttribute("border","0");
		objTable.style.backgroundColor = '#4682B4';
		//objTable.style.backgroundColor = '#ff0000';
		objTable.style.fontSize = '9pt';
			objTBody = document.createElement("tbody");
				objTr = document.createElement("tr");
					objTd = document.createElement("td");
					objTd.setAttribute("colSpan","7");
					objTd.style.backgroundColor = '#4682B4';
					objTd.style.color = '#ffffff';
					//// Header
						objTable1 = document.createElement("table");
						objTable1.setAttribute("width","100%");
						objTable1.setAttribute("cellspacing","0");
						objTable1.setAttribute("border","0");
							objTBody1 = document.createElement("tbody");
								objTr1 = document.createElement("tr");
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.blank);
									objTd1.setAttribute("align",'left');
									objTd1.setAttribute("width",'6%');
									if( this.obj.tagName == 'INPUT' ) {
										objTd1.style.cursor = 'pointer';
										objTd1.onclick = function() {padre.obj.value = '';padre.value=null; padre.end();};
										objTd1.appendChild(document.createTextNode('B'));
									} else {
										objTd1.style.cursor = 'default';
										objTd1.appendChild(document.createTextNode(' '));
									}
									//objTd.style.backgroundColor = '#999999';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.yeardown);
									objTd1.setAttribute("align",'left');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setFullYear( padre.value.getFullYear() - 1); padre.showCal(padre.value);};
									objTd1.appendChild(document.createTextNode('<<'));
									//objTd1.style.backgroundColor = '#ff9999';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.monthdown);
									objTd1.setAttribute("align",'left');
									objTd1.setAttribute("width",'6%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setMonth( padre.value.getMonth() - 1); padre.showCal(this.value);};
									objTd1.appendChild(document.createTextNode('<'));
									//objTd1.style.backgroundColor = '#99ff99';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("align",'center');
									objTd1.appendChild(document.createTextNode(this.arr_months[this.value.getMonth()]+' '+this.value.getFullYear()));
									objTd1.style.cursor = 'default';
									//objTd1.style.backgroundColor = '#9999ff';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.monthup);
									objTd1.setAttribute("align",'right');
									objTd1.setAttribute("width",'6%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setMonth( padre.value.getMonth() + 1); padre.showCal(this.value);};
									objTd1.appendChild(document.createTextNode('>'));
									//objTd1.style.backgroundColor = '#99ff99';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.yearup);
									objTd1.setAttribute("align",'right');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setFullYear( padre.value.getFullYear() + 1); padre.showCal(padre.value);};
									objTd1.appendChild(document.createTextNode('>>'));
									//objTd1.style.backgroundColor = '#ff9999';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.exit);
									objTd1.setAttribute("align",'right');
									objTd1.setAttribute("width",'6%');
									objTd1.style.cursor = 'pointer';
									objTd1.onclick = function() {padre.end();};
									objTd1.appendChild(document.createTextNode('X'));
									//objTd.style.backgroundColor = '#999999';
								objTr1.appendChild(objTd1);
							objTBody1.appendChild(objTr1);
						objTable1.appendChild(objTBody1);
					objTd.appendChild(objTable1);
				objTr.appendChild(objTd);
			objTBody.appendChild(objTr);
				// Das de la semana
				objTr = document.createElement("tr");
				for (var n=0; n<7; n++) {
					objTd = document.createElement("td");
					objTd.setAttribute("align","center");
					objTd.style.backgroundColor = '#87cefa';
					objTd.style.cursor = 'default';
					objTd.appendChild(document.createTextNode(this.arr_weekdays[(this.week_start+n)%7]));
					objTr.appendChild(objTd);
				}
			objTBody.appendChild(objTr);
			var cal_day = new Date(this.value);
			cal_day.setDate(1);
			cal_day.setDate(1 - (7 + cal_day.getDay() - this.week_start) % 7);
			while ( cal_day <= this.value || cal_day.getMonth() == this.value.getMonth() ) {
				objTr = document.createElement("tr");
				for (var n=0; n<7; n++) {
					objTd = document.createElement("td");
					objTd.style.textAlign = 'center';
					if( cal_day.getMonth() == this.value.getMonth() ) {
						if( cal_day.valueOf() == this.valueini.valueOf() ) objTd.style.backgroundColor = '#B9FE03';
						else {
							if( cal_day.getDay() == 0 || cal_day.getDay() == 6 ) objTd.style.backgroundColor = '#dbeaf5';
							else objTd.style.backgroundColor = '#ffffff';
						}
						objTd.style.cursor = 'pointer';
						objTd.id = cal_day.valueOf();
						objTd.onclick = function() {padre.setValue(new Date(parseInt(this.id)));};
					} else {
						objTd.style.backgroundColor = '#dddddd';
						objTd.style.cursor = 'default';
					}
					objTd.appendChild(document.createTextNode(cal_day.getDate()));
					objTr.appendChild(objTd);
					cal_day.setDate( cal_day.getDate() + 1 );
				}
				objTBody.appendChild(objTr);
			}
			if( this.format.indexOf("hh:ii:ss") > 0 ) {
				objTr = document.createElement("tr");
					objTd = document.createElement("td");
					objTd.setAttribute("colSpan","7");
					objTd.style.backgroundColor = '#4682B4';
					objTd.style.color = '#ffffff';
					//// Time
						objTable1 = document.createElement("table");
						objTable1.setAttribute("width","100%");
						objTable1.setAttribute("cellspacing","0");
						objTable1.setAttribute("border","0");
							objTBody1 = document.createElement("tbody");
								objTr1 = document.createElement("tr");
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.hourdown);
									objTd1.setAttribute("align",'left');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setHours((padre.value.getHours()-1)%24);padre.setTimeVal(padre.value);};
									objTd1.appendChild(document.createTextNode('<<<'));
									//objTd.style.backgroundColor = '#999999';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.minutedown);
									objTd1.setAttribute("align",'left');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setMinutes((padre.value.getMinutes()-1)%60);padre.setTimeVal(padre.value);};
									objTd1.appendChild(document.createTextNode('<<'));
									//objTd1.style.backgroundColor = '#ff9999';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.seconddown);
									objTd1.setAttribute("align",'left');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setSeconds((padre.value.getSeconds()-1)%60);padre.setTimeVal(padre.value);};
									objTd1.appendChild(document.createTextNode('<'));
									//objTd1.style.backgroundColor = '#99ff99';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("align",'center');
									objTd1.setAttribute("id",'TdCalTime');
									objTd1.style.cursor = 'default';
									objTd1.appendChild(document.createTextNode(this.getTimeStr(this.value)));
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.monthup);
									objTd1.setAttribute("align",'right');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setSeconds((padre.value.getSeconds()+1)%60);padre.setTimeVal(padre.value);};
									objTd1.appendChild(document.createTextNode('>'));
									//objTd1.style.backgroundColor = '#99ff99';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.yearup);
									objTd1.setAttribute("align",'right');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setMinutes((padre.value.getMinutes()+1)%60);padre.setTimeVal(padre.value);};
									objTd1.appendChild(document.createTextNode('>>'));
									//objTd1.style.backgroundColor = '#ff9999';
								objTr1.appendChild(objTd1);
									objTd1 = document.createElement("td");
									objTd1.setAttribute("title",this.exit);
									objTd1.setAttribute("align",'right');
									objTd1.setAttribute("width",'9%');
									objTd1.style.cursor = 'pointer';
									objTd1.style.fontSize = '6pt';
									objTd1.onclick = function() {padre.value.setHours((padre.value.getHours()+1)%24);padre.setTimeVal(padre.value);};
									objTd1.appendChild(document.createTextNode('>>>'));
									//objTd.style.backgroundColor = '#999999';
								objTr1.appendChild(objTd1);
							objTBody1.appendChild(objTr1);
						objTable1.appendChild(objTBody1);
					objTd.appendChild(objTable1);
				objTr.appendChild(objTd);
				objTBody.appendChild(objTr);
			}
		objTable.appendChild(objTBody);
		while( document.getElementById(this.divCalId).childNodes[0]) {
			document.getElementById(this.divCalId).removeChild(document.getElementById(this.divCalId).childNodes[0]);
		}			
		document.getElementById(this.divCalId).appendChild(objTable);
	},
	
	setValue: function(day) {
		//alert(day);
		if( this.obj.tagName == 'INPUT' ) this.obj.value = this.date2str(day);
		this.value = day;
		this.end();
	},
	
	setTimeVal: function(value) {
		obj = document.getElementById('TdCalTime');
		while( obj.childNodes[0]) {
			obj.removeChild(obj.childNodes[0]);
		}
		obj.appendChild(document.createTextNode(this.getTimeStr(value)));
	},
	
	getTimeStr: function(value) {
		var hour = value.getHours();
		if( hour < 10 ) hour = '0'+hour;
		var minute = value.getMinutes();
		if( minute < 10 ) minute = '0'+minute;
		var second = value.getSeconds();
		if( second < 10 ) second = '0'+second;
		return hour+':'+minute+':'+second;
	},
	
	str2date: function(str) {
		var ret = new Date();
		var dateFormat = this.format;
		if( this.format.indexOf(" ") > 0 ) dateFormat = this.format.substring(0,this.format.indexOf(" "))
		switch (dateFormat) {
			case 'dd/mm/yyyy':
				ret.setDate( str.substr( 0 , 2 ) );
				ret.setMonth( str.substr( 3 , 2 )-1 );
				ret.setYear( str.substr( 6 , 4 ) );
				break;
			default:
				this.cal_error( 'err_str2date' );
				break;
		}
		if( this.format.indexOf("hh:ii:ss") > 0 ) {
			var indx = this.format.indexOf("hh:ii:ss");
			ret.setHours( str.substr( indx , 2 ) );
			ret.setMinutes( str.substr( indx+3 , 2 ) );
			ret.setSeconds( str.substr( indx+6 , 2 ) );
		} else {
			ret.setHours( 0 );
			ret.setMinutes( 0 );
			ret.setSeconds( 0 );
		}
		ret.setMilliseconds(0);
		return ret;
	},
	
	date2str: function(date) {
		var day = date.getDate();
		if( day < 10 ) day = '0'+day;
		var month = date.getMonth()+1;
		if( month < 10 ) month = '0'+month;
		var dateFormat = this.format;
		if( this.format.indexOf(" ") > 0 ) dateFormat = this.format.substring(0,this.format.indexOf(" "))
		switch (dateFormat) {
			case 'dd/mm/yyyy':
				ret = day+"/"+month+"/"+date.getFullYear();
				break;
			default:
				this.cal_error( 'err_date2str' );
				break;
		}
		if( this.format.indexOf("hh:ii:ss") > 0 ) {
			var hour = this.value.getHours();
			if( hour < 10 ) hour = '0'+hour;
			var minute = this.value.getMinutes();
			if( minute < 10 ) minute = '0'+minute;
			var second = this.value.getSeconds();
			if( second < 10 ) second = '0'+second;
			ret += ' '+hour+':'+minute+':'+second
		}
		return ret;
	},
	
	findPos: function(obj) {
		var curleft = 0;
		var curtop = 0;
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curleft += obj.offsetLeft-obj.scrollLeft;
				curtop += obj.offsetTop-obj.scrollTop;
				var position='';
				if (obj.style&&obj.style.position) position=obj.style.position.toLowerCase();
				if ((position=='absolute')||(position=='relative')) break;
				while (obj.parentNode!=obj.offsetParent) {
					obj=obj.parentNode;
					curleft -= obj.scrollLeft;
					curtop -= obj.scrollTop;
				}
				obj = obj.offsetParent;
			}
		} else {
			if (obj.x) curleft += obj.x;
			if (obj.y) curtop += obj.y;
		}
		return [curleft,curtop];
	},

	cal_error: function(error) {
		var msg;
		switch (error) {
			case 'not_obj':
				switch (this.lang) {
					case 'es':
						msg = 'El control destino no existe';
						break;
					case 'en':
						msg = 'Target control not exists';
						break;
					default:
						msg = 'Lenguaje '+this.lang+' no especificado para el error '+error;
						break;
				}
				break;
			case 'err_str2date':
				switch (this.lang) {
					case 'es':
						msg = 'Formato de fecha '+this.format+' no especificado en str2date';
						break;
					case 'en':
						msg = 'Date format '+this.format+' not especified in str2date';
						break;
					default:
						msg = 'Lenguaje '+this.lang+' no especificado para el error '+error;
						break;
				}
				break;
			case 'err_date2str':
				switch (this.lang) {
					case 'es':
						msg = 'Formato de fecha '+this.format+' no especificado en date2str';
						break;
					case 'en':
						msg = 'Date format '+this.format+' not especified in date2str';
						break;
					default:
						msg = 'Lenguaje '+this.lang+' no especificado para el error '+error;
						break;
				}
				break;
			case 'err_setLang':
				switch (this.lang) {
					case 'es':
						msg = 'Lenguaje '+this.lang+' no especificado en setLang';
						break;
					case 'en':
						msg = 'Not especified Languaje '+this.lang+' in setLang';
						break;
					default:
						msg = 'Lenguaje '+this.lang+' no especificado para el error '+error;
						break;
				}
				break;
			default:
				msg = 'Error '+error+' no especificado en cal_error';
				break;
		}
		alert(msg);
		this.end();
	}
});
