//  calendar and ajax updater
//  michael kayson for strawcamel.com for chamonix networks


var Cals = {
    list: []	
};

var CalInfo = [];
var CurrentCal = null;

var Calendar = Class.create();
Calendar.prototype = {
    initialize: function(container,rentalRates,bookings,num,month,flat){
		this.flat = flat || null;
		this.num = num; // position in global array (in template)
		this.container = $(container.id);
		this.rentalRates = rentalRates;
		this.bookings = bookings;
		this.d = new Date();
	    this.today = this.d.getDate();
		this.month = this.d.getMonth();
		this.year = this.d.getFullYear();
		this.displayMonth = month || this.month;
		this.displayYear = this.year;
		this.months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		this.days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
		this.weIds = [106,107,113,114,120,121,127,128,134,135,141,142,206,207,213,214,220,221,227,228,234,235,241,242,306,307,313,314,320,321,327,328,334,335,341,342];
		if(this.flat!=null) {this.display(12,this.container,true);}
		else {this.display(1,this.container);}
		this.populate(this.rentalRates,this.bookings,0,false);
	},
	
	display: function( num, wrapper, bool ) {
		this.DisplayLength = num || this.DisplayLength || 1;
		this.wrapper = wrapper || this.wrapper;
		$( this.wrapper ).innerHTML = "";
		if(bool) $( this.wrapper ).appendChild( this.toFlatHTML( this.DisplayLength ) );
		else $( this.wrapper ).appendChild( this.toHTML( this.DisplayLength ) );
		var tds = $( this.wrapper ).getElementsByTagName( 'td' );
		for( var i = 0; i < tds.length; i++ ) {
            if( tds[i].id.slice( 0, 4 ) == 'cell' ) {
				var num = parseInt(tds[i].id.slice(-2));
				if( ( num % 7 == 0 ) && num != 0 ) {
				    $(tds[i-1].id).addClassName('weekendCell left');
			        $(tds[i].id).addClassName('weekendCell right');
				}
			}
		}
	},
	
	toHTML: function( months ) {
		months++;
	    var div = document.createElement( 'div' );
	    div.id = 'calDiv_' + this.wrapper.id;
		div.className = 'cal';
	    var html = '';
		for( var h = 1; h < months; h++ ) {
    	    html += "<table id='calTable_" + this.wrapper.id + "_" + h + "'cellpadding='2' cellspacing='0'>";
			html += "<tr><td style='cursor:pointer;' onclick=\"Cals.list["+this.num+"].AJAX(-3);\">&lt;&lt;</td><td style='cursor:pointer;' onclick=\"Cals.list["+this.num+"].AJAX(-1);\">&lt;</td>";
			html += "<td colspan='3' id='month_" + this.wrapper.id + "_" + h + "'></td>";
			html += "<td style='cursor:pointer;' onclick=\"Cals.list["+this.num+"].AJAX(1);\">&gt;</td><td style='cursor:pointer;' onclick=\"Cals.list["+this.num+"].AJAX(3);\">&gt;&gt;</td></tr>";
	        html += "<tr><td>Mon</td><td>Tue</td><td>Wed</td><td>Thu</td><td>Fri</td><td>Sat</td><td>Sun</td></tr>";
		    var num = 1;
			for( var i = 1; i < 7; i++ ) {
				html += "<tr>";
				for( var j = 1; j < 8; j++ ) {
				    html += "<td id='cell_" + this.wrapper.id + "_" + ( h * 100 + num ) +"'>&nbsp;</td>";
					num++;
				}
				html += "</tr>";
		    }
	        html += "</table>";
		}
		//html += "<div style='clear:both;'>&nbsp;</div>";
		div.innerHTML = html;
		
	    return div;
	},
	
	toFlatHTML: function(months){
	    months++;
	    var div = document.createElement( 'div' );
	    div.id = 'calDiv_' + this.wrapper.id;
		div.className = 'cal';
	    var html = "<table cellpadding='2' cellspacing='0'>";
		for(var x=0;x<6;x++){
			if(x==0){
				html += "<td></td>";
			}
			if(x<5){
				    html += "<td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td><td>S</td>";
			} else {
				html += "<td>M</td><td>T</td>";
			}
		}
		for( var h = 1; h < months; h++ ) {
    	    html += "<tr id='calTable_" + this.wrapper.id + "_" + h + "'><td id='month_" + this.wrapper.id + "_" + h + "' class='calMonth'></td>";
			//html += "<tr><td style='cursor:pointer;' onclick=\"Cals["+this.num+"].populate([],-3);\">&lt;&lt;</td><td style='cursor:pointer;' onclick=\"Cals["+this.num+"].populate([],-1);\">&lt;</td>";
			//html += "<td colspan='3' id='month_" + this.wrapper.id + "_" + h + "'></td>";
			//html += "<td style='cursor:pointer;' onclick=\"Cals["+this.num+"].populate([],1);\">&gt;</td><td style='cursor:pointer;' onclick=\"Cals["+this.num+"].populate([],3);\">&gt;&gt;</td></tr>";
	        /*if(h==1){
				for(var x=0;x<6;x++){
				    html += "<td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td><td>S</td>";
				}
			}
			*/
			//html += "</tr><tr>";
		    var num = 1;
			for( var i = 1; i < 7; i++ ) {
				for( var j = 1; j < 8; j++ ) {
					if(i<6){
				        html += "<td id='cell_" + this.wrapper.id + "_" + ( h * 100 + num ) +"'>&nbsp;</td>";
					} else {
						if(j<3){
						    html += "<td id='cell_" + this.wrapper.id + "_" + ( h * 100 + num ) +"'>&nbsp;</td>";
						}
					}
					num++;
				}
		    }
	        html += "</tr>";
		}
		html += "</table>";
		div.innerHTML = html;
		
	    return div;
	},
	
	selectDate: function( ) {
	    
	},
	isWeekendCell: function( id ) {
		if( id.length == 2 ) {
			var n = id.slice( 5 );
		} else {
		    var n = id.slice( 6 );
		}
		return( n == '07' ||  n == '14' ||  n == '21' ||  n == '28' || n == '35' || n == '06' ||  n == '13' ||  n == '20' ||  n == '27' ||  n == '34' );
	},
	populate: function( rentalRates, bookings, adv, revert ) {
		// get the right element ids
		var tableIdNum = 100;
		// if we're reverting to the current date
		if( revert ) {
		    this.displayMonth = this.month;
			this.displayYear = this.year;
		}
		
		// jump to next month if we're after the 22nd of this one
		if((this.displayMonth == this.d.getMonth()) && this.d.getDate()>27) this.displayMonth++;
		
		// how many months we're jumping ahead / behind
		var adv = adv || 0;
		if( rentalRates ) {
		    this.rentalRates = $A([rentalRates]).flatten();
		} else {
		    this.rentalRates = this.rentalRates || [];
		}
		
		if( bookings ) {
		    this.bookings = $A([bookings]).flatten();
		} else {
		    this.bookings = this.bookings || [];
		}
		
		if( this.displayYear == this.year && ( ( this.displayMonth + adv ) < this.month ) ) {
		    this.displayMonth = this.month;	
		} else {
		    this.displayMonth += adv;
		}
		// handle a change of year
		if( this.displayMonth > 11 ) {
		    this.displayMonth = this.displayMonth - 12;
			this.displayYear++;
		}
		if( this.displayMonth < 0 ) {
		    this.displayMonth = this.displayMonth + 12;
			this.displayYear--;
		}
		// save the starting point so we can revert at the end of the function
		var startMonth = this.displayMonth;
		var startYear = this.displayYear;
		// how many months we're displaying
		this.DisplayLength = this.DisplayLength || 12;
		// clear the current contents
		if(this.flat!=null) {this.display(12,this.container,true);}
		else {this.display(1,this.container);}
		var ln = this.DisplayLength +1; // because the for loop starts at 1 not 0
		// for this many months
		for( var j = 1; j < ln; j++ ) {
			// for this many days in the month
			var cellShift = this.cellShift( );
	        for( var i = 0; i < this.monthLength( this.displayMonth, this.displayYear ); i++ ) {
		        var date = i + 1;
				//date = (parseInt(date)<10)? "&nbsp;"+date:date;
				
			    var cell = "cell_" + this.wrapper.id + "_" + ( tableIdNum + i + cellShift );
			    $( cell ).innerHTML = date;
				$( cell ).abbr = this.formatDate( date, this.displayMonth, this.displayYear );
				if(bookings) this.bookings = bookings;
				if( this.bookings ) {
					// loop through the booked dates
					/*var b = this.bookings;
					for(var k=0;k<b.length;k++){
					    var start = parseInt(b[i].start_date);
						var end = parseInt(b[i].end_date);
						var abbr = parseInt($( cell ).abbr);
						if(abbr>=start&&abbr<=end){
						    var newClass;
							if(b[i].type_name==null){
							    newClass = b[i].status;
							} else {
								newClass = b[i].type_name;
    							if(abbr==start) newClass += " start";
	    						if(abbr==end) newClass += " end";
							}
						    $(cell).addClassName(newClass);
						}
					}
					*/
					
					this.bookings.each(function(el){
							var start = parseInt(el.start_date);
							var end = parseInt(el.end_date);
							var abbr = parseInt($( cell ).abbr);
						    if(abbr>=start&&abbr<=end){
								var newClass;
								if(el.type_name==null){
								    newClass = el.status;
								} else {
									newClass = el.type_name;
    								if(abbr==start) newClass += " start";
	    							if(abbr==end) newClass += " end";
								}
						        $(cell).addClassName(newClass);
										/* if(newClass=='booked') $(cell).innerHTML = 'X';
										if($(cell).className.indexOf('start')!=-1) $(cell).innerHTML = '/';
										if($(cell).className.indexOf('end')!=-1) $(cell).innerHTML = '\'; */
							}
						});
				}
				if( this.rentalRates ) {
					// loop through the booked dates
					this.rentalRates.each(function(el){
							var start = parseInt(el.start_date);
							var end = parseInt(el.end_date);
							var abbr = parseInt($( cell ).abbr);
						    if(abbr>=start&&abbr<=end){
								var newClass;
								if(el.type_name==null){
								    newClass = 'type_'+el.type;
								} else {
									newClass = el.type_name;
    								if(abbr==start) newClass += " start";
	    							if(abbr==end) newClass += " end";
								}
						        $(cell).addClassName(newClass);
							}
						});
				}
		    }
			if($( 'month_' + this.wrapper.id + "_" + j )){  // show the month name
			    var yr = ""+this.displayYear;
				yr = "'"+yr.slice(2);
				$( 'month_' + this.wrapper.id + "_" + j ).innerHTML = "<strong>" + this.months[this.displayMonth].slice(0,3) + "&nbsp;" + yr + "</strong>";
			}
			this.displayMonth++;
			if( this.displayMonth == 12 ) {
			    this.displayMonth = 0;
				this.displayYear++;
			}
			tableIdNum += 100;
		}
		this.displayMonth = startMonth;
		this.displayYear = startYear;
	},
	isLeapYear: function( y ) {
	    return( y%4 == 0 && ( y%100 != 0 || y%400 == 0 ) );
	},
	monthLength: function( m, y ) {
	    m = parseInt( m );
		switch( m ) {
			case 1:  if( this.isLeapYear( y ) ) { return 29; } else { return 28; }
			case 3:  return 30;
			case 5:	 return 30;
			case 8:	 return 30;
			case 10: return 30;
			default: return 31;
		}   
	},
	cellShift: function( ) {
	    var c = new Date(this.displayYear,this.displayMonth,1);
		//var m = this.displayMonth;
		//c.setMonth( m );
		//var mn = c.getMonth();
		//c.setYear( this.displayYear );
		//c.setDate( 1 );
		var cs = c.getDay( );
		//alert( c.getDate()+" / "+c.getMonth()+" "+c.getYear()+" is on the "+c.getDay()+" of the week");
		if( cs == 0 ){ cs = 7; }
		return cs;
	},
	dateSuffix: function( n ) {
	    switch( parseInt( n ) ) {
			case 1 : return 'st';
			case 2 : return 'nd';
			case 3 : return 'rd';
			case 21: return 'st';
			case 22: return 'nd';
			case 23: return 'rd';
			case 31: return 'st';
			default: return 'th';
		}  
	},
	formatDate: function( d, m, y ) {
        d = ( d < 10 ) ? "0" + d : d;
		m = m + 1;
		m = ( m < 10 ) ? "0" + "" + m : m;
		return y + "" + m + "" + d;
	},
	AJAX: function(num){
    var loc = window.location.toString();
		loc = loc.split('accommodationchamonix.com');
		var url = loc[0]+"accommodationchamonix.com/cadajax";
		for(var i=0;i<Cals.list.length;i++){
			var params = "ruId="+Cals.list[i].container.id.slice(9);
			var pos = i;
		  CurrentCal = Cals.list[i]; //Cals.list[this.num];
		  CurrentCal.adv = num;
		  var m = this.displayMonth+num+1;
		  var y = this.displayYear;
		  if(m>12){
		    m=m-12;
			  y++;
		  } else if(m<1){
		    m=m+12;
			  y--;
		  }
		  m = (m<10)? "0"+m : m;
		  params += "&date="+y+""+m;
			params += "&num="+pos;
		  new Ajax.Request(url,{method:'post',parameters:params,onSuccess:function(obj){
				  var r = eval(obj.responseText);
				  Cals.list[r[2]].populate(r[0],r[1],Cals.list[r[2]].adv);
	      }}); //CurrentCal.HandleResponse});
		  CurrentCal.container.innerHTML = "updating...";
    }/*
		var loc = window.location.toString();
		loc = loc.split('chamserve.com');
		var url = loc[0]+"chamserve.com/cadajax";
		var params = "ruId="+this.container.id.slice(9);
		CurrentCal = Cals.list[this.num];
		CurrentCal.adv = num;
		var m = this.displayMonth+num+1;
		var y = this.displayYear;
		if(m>12){
		    m=m-12;
			y++;
		} else if(m<1){
		    m=m+12;
			y--;
		}
		m = (m<10)? "0"+m : m;
		params += "&date="+y+""+m;
		new Ajax.Request(url,{method:'post',parameters:params,onSuccess:CurrentCal.HandleResponse});
		CurrentCal.container.innerHTML = "updating...";
		*/
	},
	HandleResponse: function(obj){
		        var r = null;
				var r = eval(obj.responseText);
				CurrentCal.populate(r[0],r[1],CurrentCal.adv);
	}
};