/*
 * DatePicker
 * @author Rick Hopkins
 * @modified by Micah Nolte and Martin Va�ina
 * @version 0.3.2
 * @classDescription A date picker object. Created with the help of MooTools v1.11
 * MIT-style License.

-- start it up by doing this in your domready:

$$('input.DatePicker').each( function(el){
	new DatePicker(el);
});

 */

var res_tipo;

var dpjsonArray=new Array();

var DatePicker = new Class({

	/* set and create the date picker text box */
	initialize: function(dp){

		// Options defaults
		this.dayChars = 1; // number of characters in day names abbreviation
		this.dayNames = ['Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'S�bado'];
		this.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		this.format = 'yyyy-mm-dd';
		this.monthNames = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
		this.startDay = 1; // 1 = week starts on Monday, 7 = week starts on Sunday
		this.yearOrder = 'asc';
		this.yearRange = 2;
		this.yearStart = (new Date().getFullYear());
		this.callbackfunction = null;
		this.displaydates = 'after';
		
		this.json = [];
		this.cargarAjax = 0;		

		// Finds the entered date, or uses the current date
		if(dp.value != '') {
			dp.then = new Date(dp.value.substr(0,4)*1,dp.value.substr(5,2)*1-1,dp.value.substr(8,2)*1);
			dp.today = new Date();
		} else {
			dp.then = dp.today = new Date();
		}
		// Set beginning time and today, remember the original
		dp.oldYear = dp.year = dp.then.getFullYear();
		dp.oldMonth = dp.month = dp.then.getMonth();
		
		dp.oldDay = dp.then.getDate();
		dp.nowYear = dp.today.getFullYear();
		dp.nowMonth = dp.today.getMonth();
		dp.nowDay = dp.today.getDate();

		// Pull the rest of the options from the alt attr
		if(dp.alt) {
			options = Json.evaluate(dp.alt);
		} else {
			options = [];
		}
		dp.options = {
			monthNames: (options.monthNames && options.monthNames.length == 12 ? options.monthNames : this.monthNames) || this.monthNames, 
			daysInMonth: (options.daysInMonth && options.daysInMonth.length == 12 ? options.daysInMonth : this.daysInMonth) || this.daysInMonth, 
			dayNames: (options.dayNames && options.dayNames.length == 7 ? options.dayNames : this.dayNames) || this.dayNames,
			startDay : options.startDay || this.startDay,
			dayChars : options.dayChars || this.dayChars, 
			format: options.format || this.format,
			yearStart: options.yearStart || this.yearStart,
			yearRange: options.yearRange || this.yearRange,
			yearOrder: options.yearOrder || this.yearOrder,
			callbackfunction: options.callbackfunction || this.callbackfunction,
			displaydates: options.displaydates || this.displaydates,
			json : options.json || this.json,
			cargarAjax : options.cargarAjax || this.cargarAjax

		};
		dp.setProperties({'id':dp.getProperty('name'), 'readonly':true});
		dp.container = false;
		dp.calendar = false;
		dp.interval = null;
		dp.active = false;
//		dp.onclick = dp.onfocus = this.create.pass(dp, this);
		dp.onclick = this.create.pass(dp, this);
		dp.json = {};

		
	},

	/* create the calendar */
	create: function(dp){
		
		/*
		if(dp.month == 0 && dp.year==2010 ){
			alert(dp.month + "-" + dp.year);
		}
		*/

		if(dp.value=='Entrada' || dp.value=='Salida'){
			dp.value='';
			dp.setStyles({'color':'#000000'});
			$('mensaje_error_fechas').innerHTML='';
		}
		
		if (dp.calendar) return false;
		

		if( dp.options.cargarAjax=='1' ){
			
			res_tipo = ($('res_tipo').value=='')?0:$('res_tipo').value;
			
			this.loading(dp);

			if(dpjsonArray[res_tipo+'-'+dp.month+'-'+dp.year]==null){
	
				url="modulos/reservas/reservas.php";
		
				datos = { 
	//						action  : "OBTENER_CALENDARIO_TIPO_ESTANCIA",
							action  : "OBTENER_CALENDARIO_TIPO_ESTANCIA",
							m		: dp.month, 
							a		: dp.year, 
							id_tipo_estancia:res_tipo,
							ajax	:"1"
				};
					
				new Ajax(url, { method:'get', data:datos, onComplete: function(eee){
			
					if(eee.trim()!=''){
										
						dp.json=eval("(" + eee + ")");
						
					}
					
					dpjsonArray[res_tipo+'-'+dp.month+'-'+dp.year]=eee;
										
					//alert(0);
					this.cargar(dp);
					
					
				}.bind(this) } ).request();
			
			
			} else {
				
				if(dpjsonArray[res_tipo+'-'+dp.month+'-'+dp.year].trim()!=''){
				
					dp.json=eval("(" + dpjsonArray[res_tipo+'-'+dp.month+'-'+dp.year] + ")");
				
				}
				
				this.cargar(dp);
							
			}
			
			
		
		} else {
			
			this.cargar(dp);
			
		}

		return false;		
		
	},
	
	loading: function(dp){

		dp.container = new Element('div', {'class':'cal_loader'}).injectBefore(dp).appendText("cargando...");
		
	},

	cargar: function(dp){	

		$$('.cal_loader').each(function(el){
			el.remove();
		});
		// Hide select boxes while calendar is up
		
		if(window.ie6){
			$$('select').addClass('dp_hide');
		}
		
		/* create the outer container */
		var coords = dp.getCoordinates();
		var pos2 = coords['left'];
		var pos = coords['top'];		
		dp.container = new Element('div', {'class':'cal_container'}).injectInside(document.body);
		dp.container.setStyles({'top':pos,'left':pos2,'position':'absolute'});
		/* create timers */
		dp.container.onmouseover = dp.onmouseover = function(){
			$clear(dp.interval);
		};
		
		dp.container.onmouseout = dp.onmouseout = function(){
			dp.interval = setInterval(function(){
				if (!dp.active) this.remove(dp);
			}.bind(this), 500);
		}.bind(this);
		
		var fechacal;
		var hoy = eval(dp.nowYear*10000 + dp.nowMonth*100 + dp.nowDay*1);
		
		/* create the calendar */
		dp.calendar = new Element('div', {'class':'dp_cal'}).injectInside(dp.container);
		
		/* create the date object */
		var date = new Date();
		
		/* create the date object */
		if (dp.month && dp.year) {
			date.setFullYear(dp.year, dp.month, 1);
		} else {
			dp.month = date.getMonth();
			dp.year = date.getFullYear();
			date.setDate(1);
		}
		/*Primer Calendario */
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		dp.year % 4 == 0 ? dp.options.daysInMonth[1] = 29 : dp.options.daysInMonth[1] = 28;
		
		/* set the day to first of the month */
		var firstDay = (1-(7+date.getDay()-dp.options.startDay)%7);
		
		
		
		/* create the month select box */
		monthSel = new Element('select', {'id':dp.id + '_monthSelect'});
		for (var m = 0; m < dp.options.monthNames.length; m++){
			monthSel.options[m] = new Option(dp.options.monthNames[m], m);
			if (dp.month == m) monthSel.options[m].selected = true;
		}
		
		/* create the year select box */
		yearSel = new Element('select', {'id':dp.id + '_yearSelect'});
		i = 0;
		dp.options.yearStart ? dp.options.yearStart : dp.options.yearStart = date.getFullYear();
		if (dp.options.yearOrder == 'desc'){
			for (var y = dp.options.yearStart; y > (dp.options.yearStart - dp.options.yearRange - 1); y--){
				yearSel.options[i] = new Option(y, y);
				if (dp.year == y) yearSel.options[i].selected = true;
				i++;
			}
		} else {
			for (var y = dp.options.yearStart; y < (dp.options.yearStart + dp.options.yearRange + 1); y++){
				yearSel.options[i] = new Option(y, y);
				if (dp.year == y) yearSel.options[i].selected = true;
				i++;
			}
		}

		nextLink = new Element('a', {'class':'nextLink','id':dp.id + '_nextLink'});
		prevLink = new Element('a', {'class':'prevLink','id':dp.id + '_prevLink'});


		/* start creating calendar */
		calTable = new Element('table');
		calTableThead = new Element('thead');
		calSelRow = new Element('tr');
		calSelCell = new Element('th', {'colspan':'7'});
		monthSel.injectInside(calSelCell);
		yearSel.injectInside(calSelCell);
		calSelCell.injectInside(calSelRow);
		calSelRow.injectInside(calTableThead);
		calTableTbody = new Element('tbody');

		prevLink.injectInside(calSelCell);
		nextLink.injectInside(calSelCell);	
		
		/* create day names */
		calDayNameRow = new Element('tr');
		for (var i = 0; i < dp.options.dayNames.length; i++) {
			calDayNameCell = new Element('th');
			calDayNameCell.appendText(dp.options.dayNames[(dp.options.startDay+i)%7].substr(0, dp.options.dayChars)); 
			calDayNameCell.injectInside(calDayNameRow);
		}
		calDayNameRow.injectInside(calTableTbody);
				
		/* create the day cells */
		while (firstDay <= dp.options.daysInMonth[dp.month]){
			calDayRow = new Element('tr');
			for (i = 0; i < 7; i++){
				if ((firstDay <= dp.options.daysInMonth[dp.month]) && (firstDay > 0)){
					calDayCell = new Element('td', {'class':dp.id + '_calDay', 'axis':dp.year + '|' + (parseInt(dp.month) + 1) + '|' + firstDay}).appendText(firstDay).injectInside(calDayRow);
				} else {
					calDayCell = new Element('td', {'class':'dp_empty'}).appendText(' ').injectInside(calDayRow);
				}
				// Show the previous day
				if ( (firstDay == dp.oldDay) && (dp.month == dp.oldMonth ) && (dp.year == dp.oldYear) ) {
					calDayCell.addClass('dp_selected');
				}
				// Show today
				if ( (firstDay == dp.nowDay) && (dp.month == dp.nowMonth ) && (dp.year == dp.nowYear) ) {
					calDayCell.addClass('dp_today');
				}
				
			fechacal=eval(dp.year*10000 + dp.month*100 + firstDay*1);
			
			if(dp.options.displaydates == 'after')
			{
				if( fechacal < hoy )
				{
					calDayCell.addClass('pasado');
					calDayCell.removeClass(dp.id + '_calDay');				
				}			
			}
			if(dp.options.displaydates == 'before')
			{
				if( fechacal > hoy )
				{
					calDayCell.addClass('pasado');
					calDayCell.removeClass(dp.id + '_calDay');				
				}			
			}			

				var jjson=dp.json;
				for(var t=0;t<jjson.length;t++){
					if(jjson[t].ocupado==dp.year + '|' + (parseInt(dp.month) + 1) + '|' + firstDay){	
						if( fechacal < hoy ){
							calDayCell.addClass('pasado_ocupado');
							calDayCell.setProperties({'title':'ocupado'});							
						} else {						
							calDayCell.addClass('ocupado'); 
							calDayCell.setProperties({'title':'ocupado'});
						}
					} else {
						if( fechacal > hoy ){						
							calDayCell.setProperties({'title':'disponible'});
						} 
					}
				}
					
				firstDay++;
			}
			calDayRow.injectInside(calTableTbody);
		}
		/* table into the calendar div */
		calTableThead.injectInside(calTable);
		calTableTbody.injectInside(calTable);
		
		/*Segundo Calendario */
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		//alert(dp.year + "-" + dp.month);
		
		/*
		
		if( dp.month==11 ){
		dp.month=0;
		dp.year=dp.year + 1;
		} else {
		dp.month=dp.month + 1;				
		}
			
		//alert(dp.year + "-" + dp.month);

		dp.year % 4 == 0 ? dp.options.daysInMonth[1] = 29 : dp.options.daysInMonth[1] = 28;
		

		
		
		
	
		
		calTable2 = new Element('table');
		calTableThead2 = new Element('thead');
		calSelRow2 = new Element('tr');
		calSelCell2 = new Element('th', {'colspan':'7','class':dp.id + '_calthead'});

		calSelCell2.injectInside(calSelRow2);
		calSelRow2.injectInside(calTableThead2);
		calTableTbody2 = new Element('tbody');
		
		calDayNameRow2 = new Element('tr');
		for (var i = 0; i < dp.options.dayNames.length; i++) {
			calDayNameCell2 = new Element('th');
			calDayNameCell2.appendText(dp.options.dayNames[(dp.options.startDay+i)%7].substr(0, dp.options.dayChars)); 
			calDayNameCell2.injectInside(calDayNameRow2);
		}
		calDayNameRow2.injectInside(calTableTbody2);
		

		var firstDay2 = (1-(7+date.getDay()-dp.options.startDay)%7);
		
		//$('caja-busqueda').value =date.getDay() + " - " + dp.options.startDay + "-" + firstDay + " - " + dp.options.daysInMonth[dp.month] ;
		
		while (firstDay2 <= dp.options.daysInMonth[dp.month]){
			calDayRow2 = new Element('tr');
			for (i = 0; i < 7; i++){
				if ((firstDay2 <= dp.options.daysInMonth[dp.month]) && (firstDay2 > 0)){
					calDayCell2 = new Element('td', {'class':dp.id + '_calDay', 'axis':dp.year + '|' + (parseInt(dp.month) + 1) + '|' + firstDay2}).appendText(firstDay2).injectInside(calDayRow2);
				} else {
					calDayCell2 = new Element('td', {'class':'dp_empty'}).appendText(' ').injectInside(calDayRow2);
				}
				// Show the previous day
				if ( (firstDay2 == dp.oldDay) && (dp.month == dp.oldMonth ) && (dp.year == dp.oldYear) ) {
					calDayCell2.addClass('dp_selected');
				}
				// Show today
				if ( (firstDay2 == dp.nowDay) && (dp.month == dp.nowMonth ) && (dp.year == dp.nowYear) ) {
					calDayCell2.addClass('dp_today');
				}
				
				fechacal=eval(dp.year*10000 + dp.month*100 + firstDay2*1);
				if( fechacal < hoy ){
					calDayCell2.addClass('pasado');
					calDayCell2.removeClass(dp.id + '_calDay');
				}			
				
				firstDay2++;
			}
			calDayRow2.injectInside(calTableTbody2);
		}		
		
		calTableThead2.injectInside(calTable2);
		calTableTbody2.injectInside(calTable2);
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		

		*/
		
		calTable.injectInside(dp.calendar);
		//calTable2.injectInside(dp.calendar);
		
		/* set the onmouseover events for all calendar days */
		$$('td.' + dp.id + '_calDay').each(function(el){
			el.onmouseover = function(){
				el.addClass('dp_roll');
			}.bind(this);
		}.bind(this));
		
		/* set the onmouseout events for all calendar days */
		$$('td.' + dp.id + '_calDay').each(function(el){
			el.onmouseout = function(){
				el.removeClass('dp_roll');
			}.bind(this);
		}.bind(this));
		

		/* set the onclick events for all calendar days */
		$$('td.' + dp.id + '_calDay').each(function(el){
			el.onclick = function(){
				
				ds = el.axis.split('|');
				dp.value = this.formatValue(dp, ds[0], ds[1], ds[2]);
				this.remove(dp);
				if(dp.options.callbackfunction!=null){
					setTimeout(dp.options.callbackfunction+"();",500);
				}
				return false;
				
			}.bind(this);
		}.bind(this));
		
		/* set the onchange event for the month & year select boxes */
		monthSel.onfocus = function(){ dp.active = true; };
		monthSel.onchange = function(){
			dp.month = monthSel.value;
			dp.year = yearSel.value;
			this.remove(dp);
			this.create(dp);
		}.bind(this);
		
		yearSel.onfocus = function(){ dp.active = true; };
		yearSel.onchange = function(){
			dp.month = monthSel.value;
			dp.year = yearSel.value;
			this.remove(dp);
			this.create(dp);
		}.bind(this);
		
		
		nextLink.onclick = function(){
			if( monthSel.value==11 ){
			monthSel.value=0;
			yearSel.value=yearSel.value*1 + 1;
			} else {
			monthSel.value=monthSel.value*1 + 1;				
			}
			dp.month = monthSel.value;
			dp.year = yearSel.value;
			this.remove(dp);
			this.create(dp);		
		}.bind(this);
		
		prevLink.onclick = function(){
			if( monthSel.value==0 ){
			monthSel.value=11;
			yearSel.value=yearSel.value - 1;
			} else {
			monthSel.value=monthSel.value - 1;				
			}
			dp.month = monthSel.value;
			dp.year = yearSel.value;
			this.remove(dp);
			this.create(dp);			
		}.bind(this);
		
	},
	
	/* Format the returning date value according to the selected formation */
	formatValue: function(dp, year, month, day){
		/* setup the date string variable */
		var dateStr = '';
		
		/* check the length of day */
		if (day < 10) day = '0' + day;
		if (month < 10) month = '0' + month;
		
		/* check the format & replace parts // thanks O'Rey */
		dateStr = dp.options.format.replace( /dd/i, day ).replace( /mm/i, month ).replace( /yyyy/i, year );
		dp.month = dp.oldMonth = '' + (month - 1) + '';
		dp.year = dp.oldYear = year;
		dp.oldDay = day;
		
		/* return the date string value */
		return dateStr;
	},
	
	/* Remove the calendar from the page */
	remove: function(dp){
		$clear(dp.interval);
		dp.active = false;
		if (window.opera) dp.container.empty();
		else if (dp.container) dp.container.remove();
		dp.calendar = false;
		dp.container = false;
		$$('select.dp_hide').removeClass('dp_hide');
		
		if(dp.value=='' && dp.id=='from'){
		dp.value='Entrada';
		dp.setStyles({'color':'#ccc'});		
		}
		if(dp.value=='' && dp.id=='to'){
		dp.value='Salida';
		dp.setStyles({'color':'#ccc'});		
		}		
		
	}
});
