dojo.provide('epages.cartridges.de_epages.calendar.widget.Schedule');
dojo.require('epages.widget.LocalizedWidget');
dojo.require('epages.io.json');
dojo.require('epages.lang.array');
dojo.require('epages.localize');
dojo.require('epages.cartridges.de_epages.calendar.widget.Datastore');
dojo.require('epages.html');

dojo.declare(
	"epages.cartridges.de_epages.calendar.widget.Schedule",
	[epages.widget.LocalizedWidget],
	{
		/**
		 * public properties
		 */
		url                :'?',
		calendarId         : 'Appointmentcalendar',
		datastoreId        : 'Datastore',
		objectId           : undefined, // id of the current business hours
		productId          : undefined, //id of the current product
		activeDate         : undefined, //current active/visible Date
		availableQuantity  : undefined, //totla quantitity of current product
		height             : '480px', //height of schedule widget
		colRatio           : '10.23', //ratio for col0 to rest of cols e.g. 1:10.23
		intervall          : '30',
		insideArea         : false,
		useDoubleHeight    : false,

		_datastore         : undefined,
		_times             : undefined,
		_appointments      : undefined,
		_now               : undefined,

		_colNode           : undefined,
		_cellNode          : undefined,
		_trNode            : undefined,
		_headThNode        : undefined,
		_hoverNode         : undefined,
		_rowsQuantity      : 0,

		_currentHoverValue : undefined,
		_currentHoverNode  : undefined,
		_startBusinessHoursMinute : undefined, 	// start time of buisness hours in minutes
		_intervallheight   : undefined,
		/**
		 * dojo widget properties
		 */
		imagePath       : epages.themeUrl('images'),
		translationName : dojo.moduleUrl('epages.cartridges.de_epages.calendar.widget','templates/translation'),
		templateString  :'<div class="Schedule Day"></div>',

		//template snippets for innerTable working with strings is in ie faster than with dom nodes
		_template: {
			'DateTableHeadTop'     : '<div class="DateTableHeadWrapper"><table class="DateTableHead"><colgroup>',
			'DateTableHeadBottomCols'  : '</colgroup>',
			'DateTableHeadBottom'  : '</table></div>',
			'ColElementTop'        : '<col ',
			'ColElementBottom'     : '></col>',
			'HeadTrTop'            : '<tr>',
			'HeadTrBottom'         : '</tr>',
			'HeadThTop'            : '<th>',
			'HeadThBottom'         : '</th>',
			'CellTop'              : '<td',
			'CellBottom'           : '</td>',
			'DateTableTop'         : '<div class="DateTableWrapper"><table class="DateTable"><colgroup>',
			'DateTableBottomCols'  : '</colgroup>',
			'DateTableBottom'      : '</table></div>',
			'TrTop'                : '<tr',
			'TrBottom'             : '</tr>',
			'ThTop'                : '<th class="Timeline">',
			'ThBottom'             : '</th>',
			'TimeTop'              : '<div class="Wrapper"><div class="Time">',
			'TimeBottom'           : '</div>',
			'WrapperBottom'        : '</div>',
			'HourTop'              : '<span class="Hour">',
			'HourBottom'           : '</span>',
			'MinutesTop'           : '<span class="Minutes">',
			'MinutesBottom'        : '</span>',
			'LockTop'              : '<div',
			'LockBottom'           : '</div>',
			'NowTop'               : '<div class="Now" style="',
			'NowBottom'            : '"></div>',
			'NewEvent'             : '', //template filled in postMixInProperties to translate language tags
			'AppointmentWrapperTop': '<div class="Wrapper" ',
			'AppointmentEventTop'  : '><div class="Event EnableHover',
			'AppointmentWrapperBottom' : '</div>',
			'AppointmentTop'       : '', //template filled in postMixInProperties to translate language tags
			'AppointmentInfoTitleTop'    : '<span class="Bold">',
			'AppointmentInfoTitleBottom'    : '</span>',
			'AppointmentInfoTop'       : '<span>',
			'AppointmentInfoBottom'    : '</span>',
			'AppointmentBottom'        : '</div></div>',
			'TTTitleTop'                    : '<tt dojoType="epages.widget.Tooltip" class="ScheduleTT" target="previous"><div class="Bold" dojoAttachPoint="ttTitleNode">',
			'TTTitleBottom'                 : '</div>',
			'TTContentTop'                  : '<div dojoAttachPoint="ttContentNode">',
			'TTContentBottom'               : '</div><br /></tt>'
		},
		_resultTable : new Array(), //table to store strings of resulting table doing only one string join at the end is faster then joining the strings every time something is added


		postMixInProperties: function () {
			this.inherited('postMixInProperties',arguments);
			this._appointments = {};
			this._times = {};
			this._now = new Date();
			this.colRatio = parseFloat(this.colRatio);
			if(this.intervall == '' || this.intervall == undefined){
				this.intervall = '30';
			}
			this.intervall = parseInt(this.intervall);
			this.connect(window, 'onresize', '_resizeWrapper');
			dojo.subscribe(this.calendarId+'/select',this,'_onCalendarSelect');
			//dojo.subscribe('Lock/change',this,'_onLockChange');
			if(this.insideArea){
				this.connect(epagesDialog,'showArea', '_onShowArea');
			}
			if(!this.useDoubleHeight && this.intervall >= 30){
				this.useDoubleHeight = true;
			}
			this._intervallheight = this.useDoubleHeight ? 40 : 20;
			//add double height classs to top of the data table
			if(this.useDoubleHeight){
				this._template['DateTableTop'] = '<div class="DateTableWrapper"><table class="DateTable IntervallDoubleHeight"><colgroup>';
			}
			//some templates need translation
			this._template['NewEvent'] = '<div class="Wrapper newAppointment"><div class="NewEvent"><div class="NewAppointmentNode">'+this.translate("NewAppointment")+'</div></div></div>';
			this._template['AppointmentTop'] = '<div class="TopLeft"><div class="TopRight"></div></div>'
									+'<div class="BottomLeft"><div class="BottomRight"></div></div>'
									+'<div class="OverlayButtons"><div class="Container">'
									+'<span class="Command DeleteButton" dojoAttachEvent="onclick:_onDeleteClick">'
									+'<img class="DeleteImage" src="'+this.imagePath+'/ico_s_delete.png" alt="'+this.translate("Delete")+'" title="'+this.translate("Delete")+'" />'+this.translate("Delete")+'</span></div></div>'
									+'<div class="Body" ><span class="StatusIcon"></span>';
		},

		_resizeWrapper:function(){
			var dateTableWrapper = epages.html.getElementsByClassName('DateTableWrapper',this.domNode);
			if(dateTableWrapper[0]){
				datetablewidth = dateTableWrapper[0].clientWidth;
				dateTableWrapper[0].style.height = this.height;
			}
			var dataTable = epages.html.getElementsByClassName('DateTable',this.domNode);
			if(dataTable[0]&& datetablewidth){
				dataTable[0].style.width = datetablewidth + "px";
			}
			var dataTableHead = epages.html.getElementsByClassName('DateTableHead',this.domNode);
			if(dataTableHead[0] && datetablewidth){
				dataTableHead[0].style.width = datetablewidth + "px";
			}
		},

		_calculateUsedRows: function(startDate,endDate){
			startDate = dojo.date.stamp.fromISOString(startDate);
			endDate = dojo.date.stamp.fromISOString(endDate);
			//check if start and end date are differnet to the active date
			var compare1 = dojo.date.compare(this.activeDate, startDate,'date');
			var compare2 = dojo.date.compare(this.activeDate, endDate,'date');
			if(compare1 != 0){
				startDate.setDate(this.activeDate.getDate());
				startDate.setMonth(this.activeDate.getMonth());
				startDate.setYear(this.activeDate.getFullYear());
				startDate.setHours(0);
				startDate.setMinutes(0);
				startDate.setSeconds(0);
			}
			if(compare2 != 0){
				endDate.setDate(this.activeDate.getDate());
				endDate.setMonth(this.activeDate.getMonth());
				endDate.setYear(this.activeDate.getFullYear());
				endDate.setHours(23);
				endDate.setMinutes(59);
				endDate.setSeconds(59);
			}
			var timeDiff = dojo.date.difference(startDate,endDate,'minute');
			var cellCount = Math.ceil(timeDiff/this.intervall);
			return cellCount;
		},

		_createInnerTable: function(){
			//this function creates the inner table of the widget
			this._startBusinessHoursMinute = undefined;
			//destroy old tooltip widget if another day is loaded
			var tooltips = epages.html.getElementsByClassName('ScheduleTT',this.domNode);
			for( var i=0,iLength=tooltips.length ; i<iLength ; i++ ){
				var widget = $$(tooltips[i].id);
				if(widget){
					widget.destroy();
				}
			}
			this.domNode.innerHTML = '';
			this._resultTable = new Array();
			this._resultTable.push(this._template['DateTableHeadTop']);

			//calculate col width with given colRatio in percentage
			var totalWidth = 100;
			var col0Width = parseFloat(totalWidth)/(this.colRatio+1);
			var remainWidth = totalWidth - col0Width;
			var colWidth = remainWidth / this._rowsQuantity;

			//create head table
			var cols = new Array;
			var headCells = new Array;
			cols.push(this._template['ColElementTop']+'style="width:'+col0Width+'%;"'+this._template['ColElementBottom']);
			for(var i = 0; i< this._rowsQuantity;i++){
				cols.push(this._template['ColElementTop']+'style="width:'+colWidth+'%;"'+this._template['ColElementBottom']);
				headCells.push(this._template['CellTop']+'>'+(i+1)+this._template['CellBottom']);
			}
			this._resultTable = this._resultTable.concat(cols);
			this._resultTable.push(this._template['DateTableHeadBottomCols']);
			this._resultTable.push(this._template['HeadTrTop']);
			this._resultTable.push(this._template['HeadThTop']);
			this._resultTable.push(this._template['HeadThBottom']);
			this._resultTable = this._resultTable.concat(headCells);
			this._resultTable.push(this._template['HeadTrBottom']);
			this._resultTable.push(this._template['DateTableHeadBottom']);
			this._resultTable.push(this._template['DateTableTop']);
			this._resultTable = this._resultTable.concat(cols);
			this._resultTable.push(this._template['DateTableBottomCols']);
			this._resultTable.push(this._template['DateTableBottomCols']);

			//create currentTime in Minutes only if acctual shown date is same as acctual date
			if(dojo.date.compare(this.activeDate,this._now,'date') == 0){
				var currentTime = this._now.getHours()*60;
				var minutes = this._now.getMinutes();
				var minutesSlotDistance = Math.floor(minutes / this.intervall) * this.intervall;
				var remainderMinutes = minutes - minutesSlotDistance;
				currentTime += minutesSlotDistance;
				minutes = remainderMinutes;
			}
			//create a table row which is not visible with the information of the width of each colum necessary for ie
			this._resultTable.push('<tr style="height:0px;">');
			this._resultTable.push('<td style="width:'+col0Width+'%;"></td>');
			for(var i = 0; i < this._rowsQuantity;i++){
					this._resultTable.push('<td style="width:'+colWidth+'%;"></td>');
			}
			this._resultTable.push('</tr>');
			//create tableRows foreach time
			for(time in this._times){
				var el = this._times[time];

				//set CSS classes for tr
				var trClasses = 'EnableHover IntervallRow';
				if(el.Minute < currentTime || dojo.date.compare(this.activeDate,this._now,'date') < 0){
					trClasses +=' Past';
				}
				if(!el.IsBookingHours){
					trClasses +=' OutsideBusinesshours';
				}
				if(el.IsBookingHours && this._startBusinessHoursMinute === undefined){
					this._startBusinessHoursMinute = el.Minute;
				}
				if(el.Minute%60 == 0 && el.Minute != 0){
					trClasses +=' Seperator';
				}
				if(el.IsOpened){
					trClasses +=' UnLocked';
				}
				if(el.IsLocked){
					trClasses +=' Locked';
				}
				this._resultTable.push(this._template['TrTop']+' class="'+trClasses+'">');

				//create cells
				//time cell
				var hour ='';
				var minute = '';
				if(el.Minute%60 == 0){
					hour = el.Minute/60;
					minute = '00';
				}
				this._resultTable.push(this._template['ThTop']);
				this._resultTable.push(this._template['TimeTop']);
				this._resultTable.push(this._template['HourTop']);
				this._resultTable.push(hour);
				this._resultTable.push(this._template['HourBottom']);
				this._resultTable.push(this._template['MinutesTop']);
				this._resultTable.push(minute);
				this._resultTable.push(this._template['MinutesBottom']);
				this._resultTable.push(this._template['TimeBottom']);

				//lock
				if(el.Minute < currentTime || dojo.date.compare(this.activeDate,this._now,'date') < 0) {
					this._resultTable.push(this._template['LockTop']+'>'+this._template['LockBottom']);
				}
				else {
					var LockingState = el.IsBusiness === 0 ? this.translate("Locked") : this.translate("Unlocked");
					this._resultTable.push(this._template['LockTop']+' class="Lock" startdate="'+el.StartDate+'" enddate="'+el.EndDate+'" isopen="'+el.IsBusiness+'" title="'+ LockingState +'">'+this._template['LockBottom']);
				}
				this._resultTable.push(this._template['WrapperBottom']);
				//now
				if(currentTime){
					if(el.Minute == currentTime){
						var height= Math.floor((minutes / this.intervall) * this._intervallheight);
						this._resultTable.push(this._template['NowTop']+(height-20)+'px;'+this._template['NowBottom']);
					}
				}
				this._resultTable.push(this._template['ThBottom']);
				//other cells
				for(var j = 0; j < this._rowsQuantity; j++){
					var cellClasses = 'Cell';
					var cellAppointment = '';
					//check if slot is valid or not
					if((j+1) > this.availableQuantity){
						cellClasses += ' Invalid';
					}
					var slotEmpty = true;
					currentSlot = 'slot'+j;
					if(el.Appointments.length != 0){
						if(this._startBusinessHoursMinute === undefined) {
							this._startBusinessHoursMinute = el.Minute;
						}
						//loop trough appointments, create items and block slots
						for(var lauf=0, iLength=el.Appointments.length; lauf<iLength; lauf++){
							var appointment = this._appointments[el.Appointments[lauf].objectId];
							if(appointment.slots == undefined){
								appointment.slots = [];
							}
							//check if currentSlot is empty
							if(slotEmpty == true){
								//check if appointment is already using this slot
								if($A(appointment.slots).exists(currentSlot)){
									slotEmpty = false;
									cellClasses += ' Used';
								}
								else{
									//check if appointment has already an item
									if(appointment.item == undefined){
										//create scheduleitem
										appointment.item = 'defined';
										cellAppointment = this._generateAppointmentCell(appointment,el);
										cellClasses +=' Used';
										slotEmpty = false;
										appointment.slots.push(currentSlot);
									}
									else{
										//block slot if appointment needs more slots
										if(appointment.slots.length == 0 || appointment.slots.length < appointment.Quantity){
											cellClasses += ' Used';
											slotEmpty = false;
											appointment.slots.push(currentSlot);
										}
									}
								}
							}
						}
					}

					if(slotEmpty == true || cellAppointment != ''){
					this._resultTable.push(this._template['CellTop']);
					if(cellAppointment != ''){
						this._resultTable.push('class="'+cellClasses+'" '+cellAppointment.cols+' '+cellAppointment.rows+'>');
						this._resultTable.push(cellAppointment.content);
					}
					if(slotEmpty == true){
						this._resultTable.push('startdate="'+el.StartDate+'" ');
						this._resultTable.push('class="'+cellClasses+'">');
					}
					this._resultTable.push(this._template['CellBottom']);
					}
				}
			this._resultTable.push(this._template['TrBottom']);
			}

			this._resultTable.push(this._template['DateTableBottom']);
			this.domNode.innerHTML= this._resultTable.join("\n");
			dojo.parser.parse(this.domNode);
			this._resizeWrapper();

			//// scroll bar position
			if(this._startBusinessHoursMinute !== undefined){
				var dateTableWrapper = epages.html.getElementsByClassName('DateTableWrapper',this.domNode);
				if(dateTableWrapper[0]){
					dateTableWrapper[0].scrollTop = Math.floor((this._startBusinessHoursMinute / this.intervall) * this._intervallheight);
				}
			}
			dojo.publish("interactionRestrictor/permit", ["ScheduleRestrictor"]);
		},

		_generateAppointmentCell:function(appointment,el){
			//generate Cell for appointment with adressinfo if defined and calculate used rows and cols
			var accepted = '';
			if(appointment.AddressInfo.AcceptedOn){
				accepted = ' Accepted';
			}
			var cellCount = this._calculateUsedRows(appointment.StartDate,appointment.EndDate);
			startDate = dojo.date.stamp.fromISOString(appointment.StartDate);
			endDate = dojo.date.stamp.fromISOString(appointment.EndDate);
			//check startMinute of appointment
			var minutesAppointment = startDate.getHours()*60 + startDate.getMinutes();

			// Are current and start date at the same day
			var isSameDay = !dojo.date.compare(startDate, endDate, 'date');

			if(cellCount != 0 || cellCount != 1){
				if(minutesAppointment > el.Minute && isSameDay){
					//block one cell more if appointment is out of standard alignment
					var cellRowspan = ' rowspan="'+(cellCount+1)+'"';
				}
				else{
					var cellRowspan = ' rowspan="'+cellCount+'"';
				}
			}
			//set Adress Info
			if(appointment.AddressInfo){
				var nameStringArray = [];
				if(appointment.AddressInfo.Company){
					nameStringArray.push(appointment.AddressInfo.Company+',');
				}
				if(appointment.AddressInfo.Title){
					nameStringArray.push(appointment.AddressInfo.Title);
				}
				if(appointment.AddressInfo.FirstName){
					nameStringArray.push(appointment.AddressInfo.FirstName);
				}
				if(appointment.AddressInfo.MiddleName){
					nameStringArray.push(appointment.AddressInfo.MiddleName);
				}
				if(appointment.AddressInfo.LastName){
					nameStringArray.push(appointment.AddressInfo.LastName);
				}

				//set infoTitleNode
				var nameString = nameStringArray.join(' ') + " ";
				//setInfoContentNode
				var addressStringArray = [];
				if(appointment.AddressInfo.EMail){
					addressStringArray.push(appointment.AddressInfo.EMail);
				}
				if(appointment.AddressInfo.Phone){
					addressStringArray.push(appointment.AddressInfo.Phone);
				}
				var addressString = addressStringArray.join(', ');
				if(appointment.AddressInfo.Comment){
					addressString += ', '+this.translate('Comment')+': '+appointment.AddressInfo.Comment;
				}

				var dayDiff = dojo.date.difference(startDate,endDate,'day');
				var startTimeHours = startDate.getHours();
				var startTimeMinutes = startDate.getMinutes();
				var endTimeHours = endDate.getHours();
				var endTimeMinutes = endDate.getMinutes();
				var _startTime = ' ';
				var _endTime = ' ';
				if(dayDiff != 0){
					_startTime = epages.localize.formatDateTime(startDate)+' ';
					_endTime = epages.localize.formatDateTime(endDate)+' ';
				}
				if(startTimeHours < 10){
					startTimeHours = '0'+startTimeHours;
				}
				if(startTimeMinutes < 10){
					startTimeMinutes = '0'+startTimeMinutes;
				}
				if(endTimeHours < 10){
					endTimeHours = '0'+endTimeHours;
				}
				if(endTimeMinutes < 10){
					endTimeMinutes = '0'+endTimeMinutes;
				}
				_startTime += startTimeHours+':'+startTimeMinutes;
				_endTime += endTimeHours+':'+endTimeMinutes;

				//set ttTitleNode
				var ttTitleString  = _startTime+' - '+_endTime;
				ttTitleString += ' '+nameStringArray.join(' ');
				//set ttContentNode
				var ttContentString = addressStringArray.join('<br />');
				if(appointment.AddressInfo.Comment){
					ttContentString += '<br />'+this.translate('Comment')+': '+appointment.AddressInfo.Comment;
				}
				if(appointment.AddressInfo.CustomerComment){
					ttContentString += '<br />'+this.translate('UserComment')+': '+appointment.AddressInfo.CustomerComment;
				}
				//set AcceptedOn CancelledOn
				if(appointment.AddressInfo.AcceptedOn) {
					if(!appointment.AddressInfo.CancelledOn){
						ttContentString += '<br />'+this.translate('Status')+': <b>'+this.translate('DateAccepted')+'</b>';
					}
				}
				if(!appointment.AddressInfo.AcceptedOn){
					ttContentString += '<br />'+this.translate('Status')+': <b>'+this.translate('DateUnconfirmed')+'</b>';
				}
			}

			//check if  is out of standard alignment and correct position
			var diffPixels = Math.floor(((minutesAppointment - el.Minute) /  (this.intervall /4)) * 10);
			if(diffPixels == undefined || diffPixels == 'NaN'){
				diffPixels = 0;
			}
			// Recalculate offset if appointment goes over more than one day
			var	diffElemPixels = isSameDay ? diffPixels : 0;

			return {
				'rows' : cellRowspan ? cellRowspan: '',
				'cols' : ' colspan="'+appointment.Quantity+'"',
				'content' : this._template['AppointmentWrapperTop']+'style="margin-top:'+diffElemPixels+'px;"'+this._template['AppointmentEventTop']+accepted+'" style="height: '
				+ (cellCount*this._intervallheight) +'px;" appointmentid="'+appointment.objectId+'">'
				+this._template['AppointmentTop']
				+this._template['AppointmentInfoTitleTop']+nameString
				+this._template['AppointmentInfoTitleBottom']
				+this._template['AppointmentInfoTop']+addressString
				+this._template['AppointmentInfoBottom']
				+this._template['AppointmentBottom']
				+this._template['TTTitleTop']+ttTitleString
				+this._template['TTTitleBottom']
				+this._template['TTContentTop']+ttContentString
				+this._template['TTContentBottom']
				+this._template['AppointmentWrapperBottom']
			};
		},

		changeDay:function(date){
			dojo.publish("interactionRestrictor/suspend", ["ScheduleRestrictor", this.domNode]);
			this._rowsQuantity = 0;
			if(this.activeDate != date){
				this.activeDate = date;
			}
			var dayList = this._datastore.getDayList(date);
			if(dayList){

				this._now = new Date( dayList[0].CurrentDateTime.replace(/-/g,'/').replace(/T/g,' ') );

				for( var i=0,iLength=dayList.length ; i<iLength ; i++ ){
					//check requested quantity for acctual Time Slot
					var quantityForTime = 0;
					//parse Appointments
					for( var j=0,jLength=dayList[i].Appointments.length ; j<jLength ; j++ ){
						quantityForTime += parseInt(dayList[i].Appointments[j].Quantity);
						if(!this._appointments[dayList[i].Appointments[j].objectId]){
							this._appointments[dayList[i].Appointments[j].objectId] = dayList[i].Appointments[j];
							if(this._appointments[dayList[i].Appointments[j].objectId].slots){
								this._appointments[dayList[i].Appointments[j].objectId].slots = undefined;
							}
							if(this._appointments[dayList[i].Appointments[j].objectId].item){
								this._appointments[dayList[i].Appointments[j].objectId].item = undefined;
							}
						}
						else{
							if(this._appointments[dayList[i].Appointments[j].objectId].slot){
								this._appointments[dayList[i].Appointments[j].objectId].slot = [];
							}
						}
					}
					if(this._rowsQuantity < quantityForTime){
						this._rowsQuantity = quantityForTime;
					}
					if(this._rowsQuantity < dayList[i].Appointments.length){
						this._rowsQuantity = dayList[i].Appointments.length;
					}
					this._times[dayList[i].Minute] = dayList[i];
				}
				if(this._rowsQuantity < this.availableQuantity){
					this._rowsQuantity = this.availableQuantity;
				}
				this._createInnerTable();
			}
			else{
				console.warn('unable to load daylist from Server');
			}
		},

		postCreate: function(){
			this.inherited('postCreate',arguments);
			if($$(this.datastoreId)){
				this._datastore = $$(this.datastoreId);
			}
			if(!this.activeDate){
				this.activeDate = new Date();
			}
			if(typeof(this.activeDate) == 'string'){
				this.activeDate = new Date(this.activeDate);
			}
			//load acctual day and appointments, but use other thread to avoid total blocking inside ie
				dojo.addOnLoad(dojo.hitch(this,function(){
					dojo.publish("interactionRestrictor/suspend", ["ScheduleRestrictor", this.domNode]);
					window.setTimeout(dojo.hitch(this,function(){
						this.changeDay(this.activeDate);
					}),10);
					this._resizeWrapper();
				}));
				this.connect(this.domNode,'onclick', '_onSchedulerClick');
				this.connect(this.domNode,'mouseover', '_onSchedulerMouseOver');
		},

		startup: function(){
			this.inherited('startup',arguments);
			this._resizeWrapper();
		},

		_onCalendarSelect: function(opt){
			//if another day on calendar was selected clear appointments and times and load day
			this._appointments = null;
			this._appointments = {};
			this._times = null;
			this._times = {};
			this.changeDay(opt.date);
		},

		_onShowArea: function(opt){
			this._resizeWrapper();
		},

		_onLockChange: function(opt){
			//if lock change was succesfull add/remove Css class on parent table row
			var lock = $$(opt.id);
			var tableRow = lock.domNode.parentNode.parentNode.parentNode.parentNode;
					if(opt.isOpen == true){
						tableRow.setAttribute('title',this.translate("Locked"));
						dojo.addClass(tableRow,'UnLocked');
						dojo.removeClass(tableRow,'Locked');
					}
					else{
						tableRow.setAttribute('title',this.translate("Unlocked"));
						dojo.addClass(tableRow,'Locked');
						dojo.removeClass(tableRow,'UnLocked');
					}
		},

		_onClickNewAppointment: function(startDate){
			epages.locationHref('?ViewAction=MBO-ViewNewAppointment&ObjectID='+this.productId +'&StartDate='+startDate);
		},

		_onSchedulerClick: function(evt){
			var targetNode = evt.target;
			if(dojo.hasClass(targetNode,'NewAppointmentNode')){
				var cell = targetNode.parentNode.parentNode.parentNode;
				this._onClickNewAppointment(cell.getAttribute('startdate'));

			}
			if(dojo.hasClass(targetNode,'Lock')){
				this._onClickLock(targetNode);
			}
			//check if a cell was clicked
			/*if(dojo.hasClass(targetNode,'Cell')){
				if(dojo.hasClass(targetNode,'Used')){
					//console.debug('appointment Clicked');
				}
				else{
					//console.debug('empty Cell Clicked');
				}
			}*/
			if(dojo.hasClass(targetNode,'BottomRight') || dojo.hasClass(targetNode,'Body') || dojo.hasClass(targetNode,'BottomLeft')
			|| dojo.hasClass(targetNode,'StatusIcon')|| dojo.hasClass(targetNode,'TopRight')|| dojo.hasClass(targetNode,'TopLeft')){
				if(dojo.hasClass(targetNode.parentNode,'Event')){
					var eventNode = targetNode.parentNode;
				}
				if(dojo.hasClass(targetNode.parentNode.parentNode,'Event')){
					var eventNode = targetNode.parentNode.parentNode;
				}
				if(eventNode){
					var appointmentId = eventNode.getAttribute('appointmentid');
					if(appointmentId){
						epages.locationHref(this.url+'ViewAction=MBO-ViewGeneral&ObjectID='+appointmentId);
					}
				}
			}
			if(dojo.hasClass(targetNode,'DeleteButton')){
				var appointmentId = targetNode.parentNode.parentNode.parentNode.getAttribute('appointmentid');
				if(appointmentId){
						epages.locationHref(this.url+'ChangeAction=Delete&ChangeObjectID='+appointmentId+'&ObjectID='+this.productId);
					}
			}
			if(dojo.hasClass(targetNode,'DeleteImage')){
				var appointmentId = targetNode.parentNode.parentNode.parentNode.parentNode.getAttribute('appointmentid');
				if(appointmentId){
						epages.locationHref(this.url+'ChangeAction=Delete&ChangeObjectID='+appointmentId+'&ObjectID='+this.productId);
					}
			}

		},

		_onSchedulerMouseOver: function(evt){
			var targetNode = evt.target;
			if(targetNode){
				if(this._currentHoverNode && !dojo.hasClass(targetNode,'NewAppointmentNode')){
					this._currentHoverNode.innerHTML = '';
				}
				if(!dojo.hasClass(targetNode,'Used') && dojo.hasClass(targetNode,'Cell')){
					targetNode.innerHTML = this._template['NewEvent'];
					this._currentHoverNode = targetNode;
				}
			}
		},

		_onClickLock: function(node){
			var isopen = node.getAttribute('isopen');
			dojo.require("epages.io.json");
			var json = new epages.io.Json();
			var output = json.loadSync(this.url, {
				ObjectID:       this.objectId,
				ChangeAction:   isopen == 1 ? 'LockPeriod' : 'UnlockPeriod',
				ViewAction:     'JSONViewResponse',
				StartDate:      node.getAttribute('startdate'),
				EndDate:        node.getAttribute('enddate')
			});
			if(!output.error){
				var tableRow = node.parentNode.parentNode.parentNode;
				if(isopen == 1){
					node.setAttribute('isopen',0);
					node.setAttribute('title',this.translate("Locked"));
					dojo.addClass(tableRow,'Locked');
					dojo.removeClass(tableRow,'UnLocked');
				}
				else{
					node.setAttribute('isopen',1);
					node.setAttribute('title',this.translate("Unlocked"));
					dojo.addClass(tableRow,'UnLocked');
					dojo.removeClass(tableRow,'Locked');
				}
			}
		}
	}
);