//------------------------------------------------------------------------------
// Calendar Setup
//------------------------------------------------------------------------------

var numToDo = 1;

function Calendar() {
	
	//constants
	this.DAY_NAMES = new Array('Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
	this.SHORT_DAY_NAMES = new Array('Sun','Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
	this.MONTH_NAMES = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December');
	this.SHORT_MONTH_NAMES = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec');

	//variables
	this.parent = null;
	this.userid = null;
	this.host_offset = null;
	this.mode = "view";
	this.currentPosition = 0;
	this.firstDate = new Date();
	this.positionsFilled = new Array();
	this.inTransition = false;
	this.eraserActive = false;
	this.toSave = new Array();
	this.toErase = new Array();
	this.incomingDates = new Array();
	this.balloon = null;
	this.offset = 0;
	this.currentChunkStart = null;
	this.currentChunkEnd = null;
	this.currentBalloonSmallParent = null;
	this.firstChunk = null;
	this.recurring = false;
	this.defaultBalloonShown = false;
	
}

//------------------------------------------------------------------------------
// Create
//------------------------------------------------------------------------------

Calendar.prototype.init = function(){
	
	document.calendar = this;
	
	//reset positions filled
	this.positionsFilled = new Array();
	
	if(this.mode=="edit"){
		document.getElementById('calendar_menu').style.display = "";
	}
	
	if(this.offset==0){
//		this.offset = getTimeZoneOffset();
	}
	
	if(this.mode=="view"){
//		if((this.host_offset != this.offset) && this.host_offset!=""){
//			document.getElementById('notice_offset').style.display="";
//			var timezone_name = getTimeZoneAbbr();
//			document.getElementById('notice_offset').innerHTML += "<strong>"+timezone_name+"</strong>.";
//		}
	}
	
	this.firstDate.startThisWeek(this.offset);

	//get date information
	new Ajax.Request(document.base_url+'ajax/calendar', {method:'post', postBody:'action=getdates&user_id='+this.userid+"&mode="+this.mode+"&recurring="+this.recurring, onComplete:this.create});
	
	//position the recurring slider, and show/hide els
	if(this.recurring && this.mode=="edit"){
		$('repeat_slider_slider').style.left = "32px";
		$('calendar_titlebar_arrow_left').style.display = "none";
		$('calendar_titlebar_arrow_right').style.display = "none";
		$('calendar_titlebar_corner_left').style.display = "";
		$('calendar_titlebar_corner_right').style.display = "";
		$('calendar_prevweek').style.display = "none";
		$('calendar_nextweek').style.display = "none";
	}else{
	  if($('repeat_slider_slider'))	{
	    $('repeat_slider_slider').style.left = "0px";
  		$('calendar_titlebar_arrow_left').style.display = "";
  		$('calendar_titlebar_arrow_right').style.display = "";
  		$('calendar_titlebar_corner_left').style.display = "none";
  		$('calendar_titlebar_corner_right').style.display = "none";
  		$('calendar_prevweek').style.display = "";
  		$('calendar_nextweek').style.display = ""; 
	  }
	}
	
	
}

Calendar.prototype.create = function(t){
	
	if(t.responseText){
    var incomingparts =  String(t.responseText).split("#");
    var parts = String(incomingparts[0]).split(/\s/gi);
    var dateparts = parts[0].split(/\-/gi);
    var timeparts = parts[1].split(/\:/gi);
    document.profileownertime = new Date(dateparts[0], (dateparts[1]-1), dateparts[2], timeparts[0], timeparts[1], timeparts[2]);
    if(incomingparts[1]) {
   	  if(document.calendar.recurring) {
     		document.calendar.incomingDates = String(incomingparts[1]).split(",");
	    } else {
	      var dates = String(incomingparts[1]).split(',');
  	    for (var i = dates.length - 1; i >= 0; i--){
  	      var parts = String(dates[i]).split(/\s/gi);
    	    var dateparts = parts[0].split(/\-/gi);
    	    var timeparts = parts[1].split(/\:/gi);
    	    var d=new Date(dateparts[0], (dateparts[1]-1), dateparts[2], timeparts[0], timeparts[1], timeparts[2]);
    	    dates[i] = String(d.getTime()/1000);
    	  };
    	  //console.log(dates);
        document.calendar.incomingDates = dates;
      }
	  } else {
	    document.calendar.incomingDates = [];
	  }
	}
	
	//find the first available chunk
	document.calendar.findFirstAvailableChunk();
	//console.log(document.calendar.firstChunk);
	var weekOffset = 0;
	
	//find the first available week based on the chunk above
	if(document.calendar.firstChunk){
		var tempWeekDate = new Date();
		tempWeekDate.setTime(document.calendar.firstChunk*1000);
		tempWeekDate.startWeek(document.calendar.offset);
		document.calendar.firstDate = tempWeekDate; //change the first date to our new week start
	}
//	console.log(document.calendar.firstDate);
	
	//remove the spinner
	if($('calendar_progress')){
		document.getElementById('calendar_container').removeChild(document.getElementById('calendar_progress'));	
	}
	
	//reset the parent pos
	$(document.calendar.parent).style.left = "0px";
	
	if(document.calendar.recurring && document.calendar.mode=="edit"){
	
		document.calendar.createRecurringWeek();
	
	}else{
	
		//create prev week to the left
		document.calendar.createWeek( -1 )
		
		//create this week
		document.calendar.createWeek( 0 );
		
		//create the next week to the right
		document.calendar.createWeek( 1 );
		
	}
	
	document.calendar.setCalendarTitle();
	
	//balloon
	if(document.calendar.mode=="edit" && !document.calendar.defaultBalloonShown){
		//document.calendar.showBalloon("Click on slots to indicate your availability.","Clicking again erases a slot. By clicking on next week you can pre-populate your time slots in advance.",50,100);
		document.calendar.defaultBalloonShown = true;
	}
	
	//event handler
	if(document.calendar.mode=="edit"){
		Event.observe(document, 'mousedown', document.calendar.handleMouseDown);
		Event.observe(document, 'mouseup', document.calendar.handleMouseUp);	
	}
	
	//if view then show the balloon for first available chunk
	if(document.calendar.mode=="view"){
		document.calendar.showFirstAvailableChunk();
	}
	
	//do we check the box?
	if(document.calendar.mode=="edit"){
		var el_checkbox = document.getElementById('checkbox_myavailability');
		if(document.calendar.incomingDates.length > 1){
			el_checkbox.className = "titlebar_checkbox_on";
		}else{
			el_checkbox.className = "titlebar_checkbox_off";
		}
	}
	
}

Calendar.prototype.findFirstAvailableChunk = function(){

		if(this.incomingDates.length>0){
				var nowGMTDate = document.profileownertime;
				nowGMTDate.setMinutes(0);
				nowGMTDate.setSeconds(0);
				nowGMTDate.setMilliseconds(0);
				
				if(this.recurring){
				
					var tempDate = new Date(this.firstDate);
									
					for(var i = 0; i<this.incomingDates.length; i++){
							
							tempDate = new Date(this.firstDate);
							tempDate.setHours(this.incomingDates[i]);
							
							if(tempDate >= nowGMTDate && !this.firstChunk){
								
								this.firstChunk = Math.floor(tempDate.getTime()/1000);
								
							}
					}
					
					//if we still havne't found a date we need to go to the next week and try again, since we're prolly past the date
					if(!this.firstChunk){
						
						//reset the check
						nowGMTDate.setDate(nowGMTDate.getDate() - nowGMTDate.getDay());
						
						for(var i = 0; i<this.incomingDates.length; i++){
							
							tempDate = new Date(this.firstDate);
							tempDate.setDate(tempDate.getDate()+7); //add a week onto this
							tempDate.setHours(tempDate.getHours() + this.incomingDates[i]);
							
							if(tempDate >= nowGMTDate && !this.firstChunk){
								
								this.firstChunk = Math.floor(tempDate.getTime()/1000);
								
							}
						}
						
					}
					
					
					
				
				}else{
				
					for(var i = 0; i<this.incomingDates.length; i++){
					  //console.log(this.incomingDates[i], '>=' , nowGMTDate.getTime()/1000,':', this.incomingDates[i]>=(nowGMTDate.getTime()/1000));
							if(this.incomingDates[i]>=(nowGMTDate.getTime()/1000) && !this.firstChunk){
								this.firstChunk = this.incomingDates[i];
							}
					}
				
				}
				
		}

}

Calendar.prototype.resetCalendar = function(t){

	var el = $(document.calendar.parent);
		
	if ( el.hasChildNodes() ){
		while ( el.childNodes.length >= 1 ){
			el.removeChild( el.firstChild );       
		} 
	}
	
	document.calendar.init();
	
}

//------------------------------------------------------------------------------
// Mouse Events
//------------------------------------------------------------------------------

Calendar.prototype.handleMouseDown = function(event){
	document.mouseDown = true; 
}

Calendar.prototype.handleMouseUp = function(event){
	
	document.mouseDown = false; 
	
		//save
		if(document.calendar.toErase.length>0){
			
			new Ajax.Request(document.base_url+'ajax/calendar', {method:'post', postBody:'action=erasedates&dates='+String(document.calendar.toErase)+"&recurring="+String(document.calendar.recurring),onComplete:document.calendar.checkMark});
			document.calendar.toErase = new Array();
			
		}else if(document.calendar.toSave.length>0){
		
			new Ajax.Request(document.base_url+'ajax/calendar', {method:'post', postBody:'action=savedates&dates='+String(document.calendar.toSave)+"&recurring="+String(document.calendar.recurring),onComplete:document.calendar.checkMark});
			document.calendar.toSave = new Array();
			
		}

	
}

Calendar.prototype.checkMark = function(t){
	var el_checkbox = document.getElementById('checkbox_myavailability');
	if(Number(t.responseText) > 0){
		el_checkbox.className = "titlebar_checkbox_on";
	}else{
		el_checkbox.className = "titlebar_checkbox_off";
	}
}

Calendar.prototype.handleMouseOverCell = function(event){

	var el = Event.element(event);
	
	if(el.calendar){ 
	
		if(el.calendar.mode=="edit"){
		
			if(document.mouseDown){
				el.calendar.toggleSelect(el,false);
			}
			
		}else if(el.calendar.mode=="view"){
		
			if(el.isSelected){

				el.calendar.checkCell(el);
			
			
			}else{
				//el.calendar.hideBalloonSmall();
			}
		
		}
		
	}
}

Calendar.prototype.checkCell = function(el){

			//create our variables
			var currentId = el.id;
			var tempDate = null;
			var tempCheck = null;
			var chunkStart = null;
			var chunkEnd = null;
			
			//find the date of the cell that the user has hovered over
			var thisDay = new Date(Number(currentId*1000));
			thisDay.setHours(thisDay.getHours()-el.calendar.offset);
			
			//create a date for right now that we can compare against
			var nowDate = document.profileownertime;
			nowDate.setHours(nowDate.getHours()-el.calendar.offset-1);
			nowDate.setMinutes(0);
			nowDate.setSeconds(0);
			nowDate.setMilliseconds(0);
			
			//create a date for right now with no offset to compare against
			var nowGMTDate = document.profileownertime;
			nowGMTDate.setMinutes(0);
			nowGMTDate.setSeconds(0);
			nowGMTDate.setMilliseconds(0);
				
			//find the chunk start
			tempDate = Number(currentId);
			tempDateObject = new Date(Number(currentId*1000));
			tempDateObject.setHours(tempDateObject.getHours()-el.calendar.offset);
			while(chunkStart == null){
					tempDate = tempDate - 3600;
					tempDateObject.setHours(tempDateObject.getHours()-1);
					tempCheck = document.getElementById(String(tempDate));
					if(!tempCheck || !tempCheck.isSelected || tempDateObject.getDate()!=thisDay.getDate() || (tempDateObject.getTime()/1000)==(nowDate.getTime()/1000) ){
						chunkStart = tempDate + 3600;
					}
			}
				
			//find the chunk end
			tempDate = Number(currentId);
			tempDateObject = new Date(Number(currentId*1000));
			tempDateObject.setHours(tempDateObject.getHours()-el.calendar.offset);
			while(chunkEnd == null && tempDateObject.getDate()==thisDay.getDate()){
					tempDate = tempDate + 3600;
					tempDateObject.setHours(tempDateObject.getHours()+1);
					tempCheck = document.getElementById(String(tempDate));
					if(!tempCheck || !tempCheck.isSelected || tempDateObject.getDate()!=thisDay.getDate() ){
						chunkEnd = tempDate - 3600;
				}
			}

			//if we're not already showing it and it's in the future, show the balloon
			if(el.calendar.currentChunkStart != chunkStart && el.calendar.currentChunkEnd != chunkEnd && chunkStart>(nowGMTDate.getTime()/1000) && chunkEnd>=(nowGMTDate.getTime()/1000)){
				
				//if there's more than 2 slots, let's attempt to 'center' it by changing the element we're handling
				var chunkDiff = chunkEnd - chunkStart;
				var chunkHours = (chunkDiff/3600) + 1; //correct the number of hours
				
				if(chunkHours>=3){ //3 slots;
					var newElName = (Math.floor(chunkHours/2)*3600)+chunkStart;
					if(document.getElementById(newElName)){
						el = document.getElementById(newElName);
					}
				}
				
				el.calendar.showBalloonSmall(el,chunkStart,chunkEnd);
					
			}
				
}

Calendar.prototype.handleMouseDownCell = function(event){
	var el = Event.element(event);
	if(el.calendar.mode=="edit"){
		if(document.getElementById('balloon')){
			el.calendar.hideBalloon();
		}else{
			el.calendar.toggleSelect(el,false);
		}
	}else if(el.calendar.mode=="view"){
		if(el.className=="calendarCell calendarCellSelected"){
			el.calendar.launchRequest();
		}
	}
}

Calendar.prototype.toggleSelect = function(el,override){
	if(el.isSelected){
		el.className = el.classHolder;
		el.isSelected = false;
		this.toErase.push(el.datetime);
	}else{
		el.className = "calendarCell calendarCellSelected";	
		el.isSelected = true;
		this.toSave.push(el.datetime);
	}
}

Calendar.prototype.handleBalloonClick = function(event){
	document.calendar.hideBalloon();
}

//------------------------------------------------------------------------------
// Movement
//------------------------------------------------------------------------------


Calendar.prototype.nextWeek = function(){
	
	if(!this.inTransition){
	
		this.inTransition = true;
		
		this.hideBalloonSmall();
		
		new Effect.Move(this.parent, {
				x: -500, y: 0, duration: .5, parent:this, fps:100,
				transition: Effect.Transitions.linear,
				afterFinish: this.nextWeekDone
		});
		
	}

}

Calendar.prototype.nextWeekDone = function(effect){
	
	var calendarPointer = effect.options.parent;
	
	calendarPointer.inTransition = false;
	
	calendarPointer.currentPosition++;
	
	if(calendarPointer.positionsFilled.indexOf(calendarPointer.currentPosition + 1)==-1){
		
		calendarPointer.createWeek( calendarPointer.currentPosition + 1 );
		
	}
	
	calendarPointer.setCalendarTitle();
	
}

Calendar.prototype.prevWeek = function(){
	
	if(!this.inTransition){
	
		this.inTransition = true;
		
		this.hideBalloonSmall();
		
		new Effect.Move(this.parent, {
				x: 500, y: 0, duration: .5, parent:this, fps:100,
				transition: Effect.Transitions.linear,
				afterFinish: this.prevWeekDone
		});
		
	}

}

Calendar.prototype.prevWeekDone = function(effect){
	
	var calendarPointer = effect.options.parent;
	
	calendarPointer.inTransition = false;
	
	calendarPointer.currentPosition--;
	
	if(calendarPointer.positionsFilled.indexOf(calendarPointer.currentPosition - 1)==-1){
	
		calendarPointer.createWeek( calendarPointer.currentPosition - 1 );
		
	}
	
	calendarPointer.setCalendarTitle();
	
}

Calendar.prototype.setCalendarTitle = function(){

	 var weekStartDate = new Date(this.firstDate);
	 weekStartDate.setDate( weekStartDate.getDate() + ( this.currentPosition * 7 ) );
	 var weekEndDate = new Date( weekStartDate );
	 weekEndDate.setDate(weekStartDate.getDate() + 6);
	 
	 //Set the Calendar Title
	 if(this.recurring && this.mode=="edit"){
		$('calendar_titlebar_text').innerHTML = "Monday - Sunday";
	}else{
		$('calendar_titlebar_text').innerHTML = this.DAY_NAMES[weekStartDate.getDay()] + " " + (weekStartDate.getMonth()+1) + "/" + (weekStartDate.getDate()) + " - " + this.DAY_NAMES[weekEndDate.getDay()] + " " + (weekEndDate.getMonth()+1) + "/" + (weekEndDate.getDate());
	}
	
}

Calendar.prototype.showFirstAvailableChunk = function(){
	if(this.firstChunk){
		this.checkCell(document.getElementById(this.firstChunk));
	}
}

//------------------------------------------------------------------------------
// Week Instance
//------------------------------------------------------------------------------

Calendar.prototype.createWeek = function(position){
	
	 this.positionsFilled.push(position);
	 //console.log(this.firstDate);
	 var startDate = new Date(this.firstDate);
	 startDate.setDate( startDate.getDate() + ( position * 7 ) );
//	 console.log(startDate);
    // Calendar Table
	 var table = new Element('div')
	 table.className = 'calendar_week';
	 var column = null
	 table.setStyle( {left: position*500 + "px" });
	 var rowClass = null;
	 var cellClass = null;
	 var leftCellClass = null;
	 var cellId = null;
	 var cellClassToUse = null;
	 var tempGMT = new Date(startDate);
	 tempGMT.setHours(this.offset); //offset
	 var tempWeek = new Date(startDate);
	 var tempHours = new Date();
	 tempHours.setHours(tempHours.getHours() - this.offset);
	 var fieldset = null;
	 
	 //temp variables count up
	 
	var nowLocal = new Date();
	nowLocal.setHours(nowLocal.getHours() - this.offset);
	
	var rCount = 0;// this.offset;
			
	var nowGMT = new Date();
	nowGMT.setMinutes(0);
	nowGMT.setSeconds(0);
	nowGMT.setMilliseconds(0);
	 
    // Each Column
    for (var i = 0; i < 8; i++) {
		 
		column = new Element('div');
		column.className = 'column';
		fieldset = column.appendChild(new Element('fieldset'));

		//Each Cell
		 for (var j = 0; j < 25; j++) {
		 
			//row background color
			if(j%2){ rowClass = " alt"; }else{ rowClass = " "; }
			
			if(i==0){ //left column
				
				column.className = 'column_left';
				
				if(j==0){ //first row
				
					cell = fieldset.appendChild(new Element('div'));
					cell.className = 'calendarLeftCell calendarHeader';
					cell.unselectable = 'on';

				}else{
					
					leftCellClass = 'calendarLeftCell';
					
					if(document.profileownertime.getHours()==(j-1)){
						leftCellClass += ' calendarCellThisHour';
					}
					
					if(j>8){ //only after 8 am
					
						cell = fieldset.appendChild(new Element('div'));
						cell.className = leftCellClass + rowClass
						cell.unselectable = 'on';
						//cell.innerHTML = this.prefixNumber(j-1) + "h";
						cell.innerHTML = formatHour(j-1);
					
					}
					
				}
	
			}else{ //other columns
			
				column.className = 'column';
			
				//column backgound color
				if(document.profileownertime.getDate() == tempWeek.getDate() && document.profileownertime.getMonth() == tempWeek.getMonth() &&  document.profileownertime.getFullYear() == tempWeek.getFullYear()){ 
						cellClass = " calendarCellToday" + rowClass;
						cellClass = cellClass.replace("alt","alt_today");
				}else{
						cellClass = rowClass;	
				}
			
				
				if(j==0){ //first row
				
					cell = fieldset.appendChild(new Element('div'));
					cell.className = 'calendarCell calendarHeader' + cellClass;
					cell.unselectable = 'on';
					cell.innerHTML = this.SHORT_DAY_NAMES[tempWeek.getDay()] + " " + (tempWeek.getMonth()+1) + "/" + tempWeek.getDate();				
				
				}else{
					
					if(j>8){ //only after 8 am
					
						//set the hour to the row
						cellId = Math.floor(tempGMT.getTime()/1000);
						isSelected = false;
						
						if(this.recurring){
												
							if(this.incomingDates.indexOf(String(rCount))!=-1){
									if(tempGMT.getTime() <= document.profileownertime.getTime()){ cellClassToUse = "calendarCell calendarCellSelectedPast"; }else{ cellClassToUse = 'calendarCell calendarCellSelected'; }
									isSelected = true;
									
							}else{
								cellClassToUse = 'calendarCell' + cellClass;
							}
						
						}else{
						  //console.log(cellId, this.incomingDates, this.incomingDates.indexOf(String(cellId)));
							if(this.incomingDates.indexOf(String(cellId))!=-1){
									if(tempGMT.getTime() <= document.profileownertime.getTime()){ cellClassToUse = "calendarCell calendarCellSelectedPast"; }else{ cellClassToUse = 'calendarCell calendarCellSelected'; }
									isSelected = true;
									
							}else{
								cellClassToUse = 'calendarCell' + cellClass;
							}
							
						}
						
						if(this.mode=="edit"){
							cellClassToUse += ' hover';
						}
						//console.log(cellId);
						cell = fieldset.appendChild(new Element('div', { id: cellId}));
						cell.datetime = tempGMT.getFullYear()+'-'+(9 > tempGMT.getMonth() ?( '0'+(tempGMT.getMonth()+1)) : (tempGMT.getMonth()+1) )+'-'+(10 > tempGMT.getDate() ? ('0'+tempGMT.getDate()) : tempGMT.getDate() ) + ' ' + (10 > tempGMT.getHours() ? ('0'+tempGMT.getHours()) : tempGMT.getHours()) + ':' + (10 > tempGMT.getMinutes() ? ('0'+tempGMT.getMinutes()) : tempGMT.getMinutes()) + ':' + (10 > tempGMT.getSeconds() ? ('0'+tempGMT.getSeconds()) : tempGMT.getSeconds());
						cell.className = cellClassToUse;
						cell.classHolder = 'calendarCell' + cellClass;
						cell.isSelected = isSelected;
						cell.calendar = this;
						cell.unselectable = 'on';
						cell.row = j;
						cell.col = i;
						//cell.innerHTML = cellId;
						
						Event.observe(cell, 'mouseover', this.handleMouseOverCell);
						Event.observe(cell, 'mousedown', this.handleMouseDownCell);
						
					}
					
					tempWeek.setHours(tempWeek.getHours()+1);
					tempGMT.setHours(tempGMT.getHours()+1);
					rCount++;
					
				}
				
			}
			
			
		 }
		 
		column.appendChild(fieldset);
		table.appendChild(column);

    }

    // Append to parent element
    document.getElementById(this.parent).appendChild(table);

}

Calendar.prototype.createRecurringWeek = function(){

	 var startDate = new Date(this.firstDate);

    // Calendar Table
	 var table = new Element('div');
	 var column = null
	 table.setStyle( {left: "0px" });
	 var rowClass = null;
	 var cellClass = null;
	 var leftCellClass = null;
	 var cellId = null;
	 var cellClassToUse = null;
	 var rCount = 0; this.offset;
	 var tempWeek = new Date(startDate); //used for displaying stuff
	 var fieldset = null;
	 
    // Each Column
    for (var i = 0; i < 8; i++) {
		 
		column = new Element('div');
		column.className = 'column';
		fieldset = column.appendChild(new Element('fieldset'));

		//Each Cell
		 for (var j = 0; j < 25; j++) {
		 
			//row background color
			if(j%2){ rowClass = " alt"; }else{ rowClass = " "; }
			
			if(i==0){ //left column
				
				column.className = 'column_left';
				
				if(j==0){ //first row
				
					cell = fieldset.appendChild(new Element('div'));
					cell.className = 'calendarLeftCell calendarHeader';
					cell.unselectable = 'on';

				}else{
					
					leftCellClass = 'calendarLeftCell';
					
					if(j>8){ //only after 8 am
					
						cell = fieldset.appendChild(new Element('div'));
						cell.className = leftCellClass + rowClass
						cell.unselectable = 'on';
						//cell.innerHTML = this.prefixNumber(j-1) + "h";
						cell.innerHTML = formatHour(j-1);
					
					}
					
				}
	
			}else{ //other columns
			
				column.className = 'column';
			
				//column backgound color
				cellClass = rowClass;	
				
				if(j==0){ //first row
				
					cell = fieldset.appendChild(new Element('div'));
					cell.className = 'calendarCell calendarHeader' + cellClass;
					cell.unselectable = 'on';
					cell.innerHTML = this.SHORT_DAY_NAMES[tempWeek.getDay()];				
				
				}else{
					
					if(j>8){ //only after 8 am
						//set the hour to the row
//						cellId = rCount;
						// set the id to the hour offset since monday midnight
						cellId = (((i-1)*24)+(j-1));
						
						if(this.incomingDates.indexOf(String(cellId))!=-1){

							cellClassToUse = 'calendarCell calendarCellSelected';
								
						}else{
							cellClassToUse = 'calendarCell' + cellClass;
						}
						
						if(this.mode=="edit"){
							cellClassToUse += ' hover';
						}
						
						cell = fieldset.appendChild(new Element('div', { id: cellId}));
						cell.datetime = cellId;
						cell.className = cellClassToUse;
						cell.classHolder = 'calendarCell' + cellClass;
						if(this.incomingDates.indexOf(String(cellId))!=-1){
							cell.isSelected = true;
							
						}else{
							cell.isSelected = false;
						}
						cell.calendar = this;
						cell.unselectable = 'on';
						cell.row = j;
						cell.col = i;
						//cell.innerHTML = cellId;
						
						Event.observe(cell, 'mouseover', this.handleMouseOverCell);
						Event.observe(cell, 'mousedown', this.handleMouseDownCell);
						
					}
					
					tempWeek.setHours(tempWeek.getHours()+1);
					rCount++;
					
				}
				
			}
			
			
		 }
		 
		column.appendChild(fieldset);
		table.appendChild(column);

    }

    // Append to parent element
    document.getElementById(this.parent).appendChild(table);

}

//------------------------------------------------------------------------------
// Other events coming from html page
//------------------------------------------------------------------------------

Calendar.prototype.toggleEraser = function(){
		
	var el = document.getElementById('calendar_erase');	
		
	if(this.eraserActive){
	
		this.eraserActive = false;
		el.className = "";
	
	}else{
		
		this.eraserActive = true;
		el.className = "active";
		
	}
		
}

//------------------------------------------------------------------------------
// Balloon
//------------------------------------------------------------------------------

Calendar.prototype.showBalloon = function(balloon_title_text,balloon_html_text,top,left){
	
	if(!document.getElementById('balloon')){
	
		this.balloon = new Element('div', { id: 'balloon' });
		var balloon_title =  new Element('div', { id: 'balloon_title' });
		balloon_title.innerHTML = balloon_title_text;
		var balloon_html =  new Element('div', { id: 'balloon_html' });
		balloon_html.innerHTML = balloon_html_text;
		
		this.balloon.appendChild(balloon_title);
		this.balloon.appendChild(balloon_html);
		this.balloon.setStyle( {top:top+"px",left:left+"px"} );
		
		document.getElementById(this.parent).appendChild(this.balloon);
	
		Event.observe(document.getElementById('balloon'), 'mousedown', document.calendar.handleBalloonClick);	
		
	}

}

Calendar.prototype.hideBalloon = function(){
	var el = document.getElementById('balloon');
	var el_container = document.getElementById(document.calendar.parent);
	el_container.removeChild(el); 
}

Calendar.prototype.showBalloonSmall = function(parent_object,chunkstart,chunkend){

	//only show if we're not already showing it
	if(this.currentChunkStart != chunkstart && this.currentChunkEnd != chunkend){
	
		//reset everything
		this.hideBalloonSmall();
		
		this.currentChunkStart = chunkstart;
		this.currentChunkEnd = chunkend;
		
		//create the object
		var balloon_sm = new Element('div', {id:'balloon_sm'} );

		//do we flip it if it's on the right side?
		if(parent_object.col>5){
			balloon_sm.className = "mirror";
		}
		
		//create our objects
		var balloon_sm_html = new Element('div', {id:'balloon_sm_html'} );
		//var balloon_sm_a = new Element('a');
		//balloon_sm_a.href = "javascript:;";
		//balloon_sm_a.onclick = function(){ profileCalendar.launchRequest(); } 
		//balloon_sm_btn = new Element('div', {id:'btn_tischen'} );
		//balloon_sm_a.appendChild(balloon_sm_btn);
		balloon_sm.appendChild(balloon_sm_html);
		//balloon_sm.appendChild(balloon_sm_a);
		
		//handle it's positioning, these numbers are based on the size of the balloon background
		var balloonX = 30 + (parent_object.col * 67) - 27;
		var balloonY = 15 + ((parent_object.row-7) * 15) - 60;
		
		if(parent_object.col>5){
			balloonX = balloonX - 186;
		}
		
		balloon_sm.setStyle( {left:balloonX + "px",top:balloonY + "px", display:"none"} );
		
		//add the objects together
		document.getElementById('calendar_titlebar').appendChild(balloon_sm);
		
		//fade in
		new Effect.Appear('balloon_sm', { duration: .2 });
		
		//for reference
		this.currentBalloonSmallParent = parent_object;
		var t = new Date(chunkstart*1000);
  	var chunkstartdate = t.getFullYear()+'-'+(9 > t.getMonth() ?( '0'+(t.getMonth()+1)) : (t.getMonth()+1) )+'-'+(10 > t.getDate() ? ('0'+t.getDate()) : t.getDate() ) + ' ' + (10 > t.getHours() ? ('0'+t.getHours()) : t.getHours()) + ':' + (10 > t.getMinutes() ? ('0'+t.getMinutes()) : t.getMinutes()) + ':' + (10 > t.getSeconds() ? ('0'+t.getSeconds()) : t.getSeconds());
		var t = new Date(chunkend*1000+3600000);
  	var chunkenddate = t.getFullYear()+'-'+(9 > t.getMonth() ?( '0'+(t.getMonth()+1)) : (t.getMonth()+1) )+'-'+(10 > t.getDate() ? ('0'+t.getDate()) : t.getDate() ) + ' ' + (10 > t.getHours() ? ('0'+t.getHours()) : t.getHours()) + ':' + (10 > t.getMinutes() ? ('0'+t.getMinutes()) : t.getMinutes()) + ':' + (10 > t.getSeconds() ? ('0'+t.getSeconds()) : t.getSeconds());
		
		//do an ajax request to get the correct information to fill in
		new Ajax.Request(document.base_url+'ajax/calendar', {method:'post', postBody:'action=formatchunk&chunkstart='+String(chunkstartdate)+'&chunkend='+String(chunkenddate)+'&user_id='+document.getElementById('request_user_id').value,onComplete:document.calendar.chunkAJAXGot});

	}
	
}

Calendar.prototype.chunkAJAXGot = function(t){
	document.getElementById('balloon_sm_html').innerHTML = t.responseText;
}

Calendar.prototype.hideBalloonSmall = function(){
	
	this.currentChunkStart = null;
	this.currentChunkEnd = null;	

	if(this.currentBalloonSmallParent){
		document.getElementById('calendar_titlebar').removeChild(document.getElementById('balloon_sm'));
		this.currentBalloonSmallParent = null;
	}

}

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

Calendar.prototype.prefixNumber = function(num){
	if(num<10){ return "0" + num; }else{ return num; } 	
}

//------------------------------------------------------------------------------
// Request
//------------------------------------------------------------------------------
Calendar.prototype.launchRequest = function(){
	
	showRequestBox(this.currentChunkStart,this.currentChunkEnd,this.offset);
	
}

function formatHour(hour_24){
	
	var trailer;
	
	if(hour_24>12){
		hour_24 -= 12;
		return String(hour_24)+"pm";
	}if(hour_24==12){
		return String(hour_24)+"pm";
	}else{
		return String(hour_24)+"am";
	}
	
	
}

//------------------------------------------------------------------------------
// Recurring Slider
//------------------------------------------------------------------------------
Calendar.prototype.toggleRecurring = function(){
	
	if(this.recurring){
		new Effect.Move($('repeat_slider_slider'), {
				x: -32, y: 0, duration: .2, fps:100,
				transition: Effect.Transitions.linear,
				afterFinish: this.sliderMoveDone
		});
		this.recurring = false;
	}else{
		new Effect.Move($('repeat_slider_slider'), {
				x: 32, y: 0, duration: .2, fps:100,
				transition: Effect.Transitions.linear,
				afterFinish: this.sliderMoveDone
		});
		this.recurring = true;
	}
	
}

Calendar.prototype.sliderMoveDone = function(){
	
	new Ajax.Request(document.base_url+'ajax/calendar', {method:'post', postBody:'action=updaterecurring&recurring='+String(document.calendar.recurring),onComplete:document.calendar.resetCalendar});
	
}
