// JavaScript Document


function Calendar(id, month, year, context) {
	this.current_date  = new Date();
	this.id            = id;
	this.month         = (isNaN(month) || month == null) ? this.current_date.getMonth()  : month;
	this.year          = (isNaN(year)  || year == null) ? this.current_date.getFullYear() : year;
	this.html          = '';
	this.day_labels    = ['D', 'L', 'M', 'M', 'J', 'V', 'S'];// these are labels for the days of the week
	this.month_labels  = ['Ene', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dic'];// these are human-readable month name labels, in order
	this.days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];// these are the days of the week for each month, in order
	this.context       = context;
	this.bookedDates   = new Array();
	this.bookedCount   = 0;
	this.curcol        = ''
	this.dbid          = '';
	//this.generateHTML();
}

Calendar.prototype.generateHTML = function(){
	var firstDay    = new Date(this.year, this.month, 1);
	var startingDay = (firstDay.getDay() - 1 < 0) ? 6 : firstDay.getDay() - 1;
	var blanks      = startingDay;
	var monthLength = this.days_in_month[this.month];
	var monthName   = this.month_labels[this.month]
	
	// compensate for leap year
	if (this.month == 1) { // February only!
		if((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0){
			monthLength = 29;
		}
	}
	
	var totalboxes  = blanks + monthLength;
	var totalrows   = Math.ceil(totalboxes / 7);
	    totalboxes  = totalrows * 7;
	 
	var daycount = 1;
	var col = 1;
	
	var calstr = '';

	// previous month
	prevmonth = this.month;
	if (this.month == "0"){
		prevmonth = "11" 
	}else{
		prevmonth--;
	} 
	
	// previous year
	prevyear = this.year;
	if (prevmonth == "11"){
		prevyear--;    
	}
	
	// next month
	nextmonth = this.month;
	if (this.month == "11"){
		nextmonth = "0" 
	}else{
		nextmonth++;
	}
	
	// next year
	nextyear = this.year;
	if (nextmonth == 0){
		nextyear++;    
	}
	
	prevmonthname = this.month_labels[prevmonth]
	nextmonthname = this.month_labels[nextmonth]
	
	this.prevmonth = prevmonth
	this.prevyear = prevyear
	
	this.nextmonth = nextmonth
	this.nextyear = nextyear
	
	if(this.context == 'admin'){
		var action = 'toogleDate(day, month, year)';
	}else{
		var action = '';
	}
	
	
	
	while(totalboxes > 0){
		if(col == 1) calstr += '<tr>';
		
		if(blanks){
			calstr +=  '<td align="center" valign="middle" bgcolor="#ffffff">&nbsp;</td>';
			blanks--;
		}else if(daycount <= monthLength){
			var  addclass = '';
			
			// match booked dates
			for(k = 0; k < this.bookedCount; k++){
				
				testdate = this.year + '-' + padDigits(this.month+1, 2) + '-' + padDigits(daycount, 2);
				
				if(testdate == this.bookedDates[k]){
					addclass = ' notavailable';
					break;
				}else{
					addclass = '';
				}
			}
			
			if(this.context == 'admin'){
				addclass += ' clickable';
			}

			calstr +=  '<td align="center" valign="middle" bgcolor="#ebebeb" class="caltd' + addclass + '" ';

			// if in admin give action
			if(this.context == 'admin'){
				calstr += 'onClick="' + this.id + '.toogleDate($(this), ' + daycount + ', ' + this.month + ', ' + this.year + ')"';
			}

			calstr +=  '>' + daycount + '</td>';
			daycount ++;

		}else{
			calstr +=  '<td align="center" valign="middle" bgcolor="#ffffff">&nbsp;</td>';
		}
		
		totalboxes--;
		
		if(col == 7){
			calstr +=  '</tr>'; 
			col = 1;
		}else{
			col++;
		}
	}


	this.html = '<table border="0" align="right" cellpadding="2" cellspacing="2" class="availability_calendar" ><tr><td colspan="7" align="center">Calendario&nbsp;de&nbsp;Disponibilidad</td></tr><tr bgcolor="#d7d7d7"><td colspan="7" class="calendartop" align="center"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="33%" align="left"><a href="javascript:' + this.id + '.goPrev()">&lt; ' + prevmonthname + '</a></td><td width="34%" align="center"><b>' + monthName + '/' + this.year.toString().substr(2) + '</b></td><td width="33%" align="right"><a href="javascript:' + this.id + '.goNext()">' + nextmonthname + ' &gt;</a></td></tr></table></td></tr><tr><td width="14%" align="center" valign="middle" bgcolor="#ffffff">L</td><td width="14%" align="center" valign="middle" bgcolor="#ffffff">M</td><td width="14%" align="center" valign="middle" bgcolor="#ffffff">M</td><td width="14%" align="center" valign="middle" bgcolor="#ffffff">J</td><td width="14%" align="center" valign="middle" bgcolor="#ffffff">V</td><td width="14%" align="center" valign="middle" bgcolor="#ffffff">S</td><td width="14%" align="center" valign="middle" bgcolor="#ffffff">D</td></tr>' + calstr  + '</table>';
	
	this.setHTML()
	
	this.addMouseEvents()
	
}


Calendar.prototype.setTo = function(month, year) {
  this.month = month;
  this.year  = year;
  this.generateHTML();
}

Calendar.prototype.setHTML = function() {
	var html = this.html
	$('#' + this.id).each(function(){
		$(this).html(html);
	});
}


Calendar.prototype.goNext = function() {
	
	this.month = this.nextmonth
	this.year = this.nextyear
	this.generateHTML();
}

Calendar.prototype.goPrev = function() {
	
	this.month = this.prevmonth
	this.year = this.prevyear
	this.generateHTML();
}

Calendar.prototype.addBookedDate = function(date){
	this.bookedDates[this.bookedCount] = date
	this.bookedCount++;
}

Calendar.prototype.removeBookedDate = function(date){
	for(k = 0; k < this.bookedCount; k++){
		if(date == this.bookedDates[k]){
			this.bookedDates.splice(k, 1);
			this.bookedCount--;
			break;
		}
	}
}

Calendar.prototype.toogleDate = function(o, d, m, y){
	d = padDigits(d, 2) 
	m = padDigits(m+1, 2) 
	var dat =  y + '-' + m + '-' + d;
	var tid = this.id;
	
	if(o.hasClass('notavailable')){
		var action = 'remove'
	}else{
		var action = 'add'
	}
	
	cal = this;
	
	$.post("book.php", {action: action, id: this.dbid, date: dat}, function(data)
	{
		if(data)
		{
			if(o.hasClass('notavailable'))
			{
				cal.removeBookedDate(data)
			}else{
				cal.addBookedDate(data)
			}
			
			cal.generateHTML();
		}
		else
		{
			$('#' + tid).html('Imposible actualizar.<br />Recargue por favor.');
		}
	});

	$('#' + tid).html('Actualizando...');
}

Calendar.prototype.addMouseEvents = function(){
	$('#' + this.id).find('.clickable').mouseover(function(){
		$(this).addClass('active');
	});
		
	$('#' + this.id).find('.clickable').mouseout(function(){
		$(this).removeClass('active');
	});
	
}

function padDigits(n, totalDigits) { 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) { 
			pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
} 



/*<script type="text/javascript">
  var cal = new Calendar();
  cal.generateHTML();
  document.write(cal.getHTML());
</script>*/
