if(typeof(AC)=="undefined")AC={};

// Retail Calendar
AC.RetailCalendar = Class.create();
Object.extend(AC.RetailCalendar.prototype, {
	
	calendar: null,
	calendarlinkEl: null,
	store: null,
	workshops: null,
	months: [],
	monthabbrs: [],
	monthLengths: [31,28,31,30,31,30,31,31,30,31,30,31],
	daynames: [],
	readmoretext: '',
	signintext: '',
	learnmoretext: '',
	moredropdownEl: null,
	firstcat: '',
	currentcat: null,
	today: {date: null, day: null, month: null, year: null},
	selectedDate: {date: null, day: null, month: null, year: null},
	currentDate: {date: null, day: null, month: null, year: null},
	endDate: {date: null, day: null, month: null, year: null},
	morecat: null,
	moretext: null,
	weekviewEl: null,
	weekviewlistsEl: null,
	inititemEl: null,
	calendarwrapperEl: null,
	calendarcellsEl: null,
	dateviewnavEl: null,
	startdatemonthEl: null,
	startdatedateEl: null,
	enddatemonthEl: null,
	enddatedateEl: null,
	enddateyearEl: null,
	dateheadersEl: null,
	monthviewmonthEl: null,
	monthviewyearEl: null,
	monthviewrowsEl: null,
	selectedcells: $A(),
	calendartitle: null,
	
	initialize: function(storenumber, calendar) {
		this.calendar = calendar;
		this.calendarlinkEl = $('storecalendar-calendarlink');
		this.storeNumber = storenumber;
		
		this.calendartitle = document.title+' - Calendar';
		
		this.moredropdownEl = this.calendar.select('#storecalendar-categories #moredropdown')[0] || null;
		
		var changeCategory = this.changeCategory.bindAsEventListener(this);
		var categories = this.calendar.select('#storecalendar-categories li a');
		this.firstcat = this.currentcat = (categories.length > 0) ? categories[0].getHrefId() : '';
		categories.each(function(category, index) {
			Event.observe(category, 'click', changeCategory);
			if(category.getHrefId() == "more") {
				this.morecat = category;
				this.moretext = category.firstChild.data;
			}
		}.bind(this));
		
		var today = new Date();
		
		this.selectedDate = this.getSelectedDate(today);
		this.currentDate = this.getSelectedDate(today);
		
		if(this.months.length === 0) {
			var self = this;
			getLang(function(value) {
				// instead of tying this to AC.RetailCalendar, I'm using "this" instead.
				self.months = value.months;
				self.monthabbrs = value.monthabbrs;
				self.daynames = value.daynames;
				self.readmoretext = value.readmoretext;
				self.signintext = value.signintext;
				self.learnmoretext = value.learnmoretext;
				
				self.localizedResourcesDidLoad();
			});
		}
		else {
			this.localizedResourcesDidLoad();
		}

	},
	
	localizedResourcesDidLoad: function() {
		this.initWeekView();
		this.createWeekView();
		this.initMonthView();
		this.createMonthView();
		this.initDateView();
		this.createDateView();
		
		this.sendReq($H({'store':this.storeNumber}));
	},
	
	initStripes: function() {
		this.weekviewEl.select('.odd').invoke('removeClassName','odd');
		this.weekviewEl.select('.even').invoke('removeClassName', 'even');
		
		this.weekviewEl.select('.noworkshops').invoke('hide');
		
		this.weekviewlistsEl.each(function(list, index) {
			this.zebraStripe(list);
			this.displayNoWorkshopsText(list);
		}.bind(this));
	},
	
	initDateView: function() {
		// getting date view elements
		this.dateviewnavEl = $('storecalendar-dateviewnav');
		this.startdatemonthEl = this.calendar.down('#storecalendar-startdate .month');
		this.startdatedateEl = this.calendar.down('#storecalendar-startdate .date');
		this.enddatemonthEl = this.calendar.down('#storecalendar-enddate .month');
		this.enddatedateEl = this.calendar.down('#storecalendar-enddate .date');
		this.enddateyearEl = this.calendar.down('#storecalendar-enddate .year');
		
		// add the events for the next and previous arrows
		var changeDateView = this.changeDateView.bindAsEventListener(this);
		this.calendar.select('#storecalendar-nav .navigation').invoke('observe', 'click', changeDateView);
		Event.observe($('storecalendar-gototoday'), 'click', changeDateView);
	},
	
	initWeekView: function() {
		// getting week view elements
		this.weekviewEl = $('storecalendar-weekview');
		this.weekviewlistsEl = this.weekviewEl.select('ul');
		this.dateheadersEl = this.calendar.select('#storecalendar-weekview h3');
		this.inititemEl = this.weekviewlistsEl[0].down(0);
		
		// removing initial list item for cloning later
		this.inititemEl.remove();
	},
	
	initMonthView: function() {
		// getting month view elements
		this.calendarwrapperEl = $('storecalendar-calendarwrapper');
		this.calendarcellsEl = this.calendar.select('#storecalendar-monthview tbody tr td');
		this.monthviewmonthEl = $('storecalendar-month');
		this.monthviewyearEl = $('storecalendar-year');
		this.monthviewrowsEl = this.calendar.select('#storecalendar-monthview tbody tr');
		
		var calendarClose = this.calendar.select('#storecalendar-monthviewclose')[0];
		Event.observe(calendarClose, 'click', function(evt) {
			Event.stop(evt);
			this.closeCalendar();
		}.bindAsEventListener(this));
		
		var dayHeaders = this.calendarwrapperEl.select('tr th');
		dayHeaders.each(function(header, index) {
			header.innerHTML = this.daynames[index].charAt(0);
		}.bind(this));
		
		Event.observe(this.calendarlinkEl, 'click', this.openCalendar.bindAsEventListener(this));
		var monthNavArrows = this.calendar.select('.storecalendar-monthnav');
		var changeMonth = this.changeMonth.bindAsEventListener(this);
		monthNavArrows.invoke('observe', 'click', changeMonth);

		this.calendarcellsEl.each(function(cell, index) {
			Event.observe(cell, 'mousedown', this.selectDate.bindAsEventListener(this));
			Event.observe(cell, 'click', this.changeDate.bindAsEventListener(this));
		}.bind(this));
	},
	
	createDateView: function() {
		this.startdatemonthEl.innerHTML = this.monthabbrs[this.selectedDate.month];
		this.startdatedateEl.innerHTML = this.selectedDate.date;

		this.enddatemonthEl.innerHTML = this.monthabbrs[this.endDate.month];
		this.enddatedateEl.innerHTML = this.endDate.date;
		this.enddateyearEl.innerHTML = this.endDate.year;
	},
	
	removeClassNamesFromEach: function(elements) {
		elements.each(function(item, index) {
			item.removeClassName(item.readAttribute('class'));
		});
	},
	
	createWeekView: function() {
		this.removeClassNamesFromEach(this.weekviewlistsEl);	
		this.weekviewlistsEl.each(function(list, index) {
			list.select('li').invoke('remove');
		});

		var selecteddaynumber = this.selectedDate.day;
		var selecteddayname = this.daynames[selecteddaynumber];
		var selectedmonth = this.selectedDate.month;
		var selectedmonthname = this.months[selectedmonth];
		var selectedyear = this.selectedDate.year;
		var selecteddate = this.selectedDate.date;
		var selectedmonthlength = this.getMonthLength(selectedmonth, selectedyear);
		
		this.dateheadersEl.each(function(header, index) {
			if(selecteddate > selectedmonthlength) {
				selectedmonth = selectedmonth + 1;
				if(selectedmonth > 11) {
					selectedyear = selectedyear + 1;
					selectedmonth = 0;
				}
			}
			if(selecteddate > selectedmonthlength) selecteddate = 1;
			header.down('.day').innerHTML = this.daynames[selecteddaynumber];
			header.down('.month').innerHTML = this.months[selectedmonth];
			header.down('.date').innerHTML = selecteddate;
			header.down('.year').innerHTML = selectedyear;
			var currentdate = new Date(selectedyear, selectedmonth, selecteddate);
			this.selectedcells[index] = selectedyear+'_'+selectedmonth+'_'+selecteddate;
			this.weekviewlistsEl[index].addClassName(currentdate.valueOf());
			selecteddaynumber = (selecteddaynumber < 6) ? selecteddaynumber + 1 : 0;
			selecteddate = selecteddate + 1;
		}.bind(this));
		
	},
	
	createMonthView: function() {
		this.monthviewmonthEl.innerHTML = this.months[this.currentDate.month];
		this.monthviewyearEl.innerHTML = this.currentDate.year;

		var first = new Date(this.currentDate.year, this.currentDate.month, 1);
		var firstDay = first.getDay();

		var prevMonth = this.getPrevMonth().month;
		var prevMonthYear = this.getPrevMonth().year;
		var prevMonthLength = this.getMonthLength(prevMonth, prevMonthYear);

		var selectedMonthLength = this.getMonthLength(this.currentDate.month, this.currentDate.year);

		this.removeClassNamesFromEach(this.monthviewrowsEl);
		this.removeClassNamesFromEach(this.calendarcellsEl);

		var date = 1;
		var onSelectedMonth = false;
		var selectingWeek = false;
		var selectedCellIdx = null;
		var todaysdate = new Date();
		var today = {
			date: todaysdate.getDate(),
			month: todaysdate.getMonth(),
			year: todaysdate.getFullYear(),
			day: todaysdate.getDay()
		};

		this.calendarcellsEl.each(function(cell, index) {
			var month = this.currentDate.month;
			var year = this.currentDate.year;
			if(index < firstDay) {
				date = (prevMonthLength - firstDay) + (index + 1);
				month = this.getPrevMonth().month;
				year = this.getPrevMonth().year;
			} else if (index >= (selectedMonthLength + firstDay)) {
				if(onSelectedMonth) {
					date = 1;
					onSelectedMonth = false;
				} else date = date + 1;
				month = this.getNextMonth().month;
				year = this.getNextMonth().year;
			} else {
				if(!onSelectedMonth) {
					date = 1;
					onSelectedMonth = true;
				} else date = date + 1;
				if(date == today.date && month == today.month && year == today.year)
					cell.addClassName('today');
				if(date == this.selectedDate.date &&
					month == this.selectedDate.month &&
					year == this.selectedDate.year) {
					cell.addClassName('selecteddate');
					selectingWeek = true;
					selectedCellIdx = index;
				}
				cell.addClassName('selectedmonth');
				var row = cell.up('tr');
				row.addClassName('viewingmonth');
			}
			
			cell.id = year+'_'+month+'_'+date;
			cell.down('.date').innerHTML = date;
		}.bind(this));

		this.selectedcells.each(function(selectedcellid, index) {
			var selectedcell = $(selectedcellid) || false;
			if(selectedcell) selectedcell.addClassName('selectedweek');
		});

		var endDate = this.selectedcells[6].split('_');
		this.endDate = {
			date: endDate[2],
			month: endDate[1],
			year: endDate[0]
		}
	},
	
	changeCategory: function(evt) {
		Event.stop(evt);
		var categorylink = Event.findElement(evt,'a');
		var categoryid = categorylink.getHrefId();
		
		if(categoryid != "more") {
			if(categorylink.up("#more")) {
				this.morecat.innerHTML = categorylink.firstChild.data;
			} else {
				this.morecat.innerHTML = this.moretext;
			}
			if(this.moredropdownEl.visible()) this.closeMore();
			
			this.calendar.removeClassName(this.currentcat);
			this.calendar.addClassName(categoryid);
		
			this.currentcat = categoryid;
		
			this.initStripes();
		} else {
			if(!this.moredropdownEl.visible()) Event.observe(document.body, 'click', this.clickOffMore.bindAsEventListener(this));
			else Event.stopObserving(document.body, 'click', this.clickOffMore.bindAsEventListener(this));

			this.moredropdownEl.toggle();
		}
	},
	
	changeDate: function(evt) {
		Event.stop(evt);
		var cell = Event.findElement(evt, 'td');
		cell.removeClassName('down');
		
		if(cell.hasClassName('selectedmonth')) {
			var cellId = cell.readAttribute('id').split('_');
			var newDate = new Date(cellId[0], cellId[1], cellId[2]);

			this.selectedDate = this.getSelectedDate(newDate);
		
			this.changeToSelectedDate();
			this.closeCalendar();
		}
	},
	
	changeDateView: function(evt) {
		Event.stop(evt);
		
		var link = Event.findElement(evt,'a');
		var direction = link.getHrefId();
		
		if(!this.dateviewnavEl.hasClassName('off') || direction == 'today') {
			switch(direction) {
				case 'prev':
					var newDate = this.selectedDate.date - 7;
					if(newDate < 1) {
						var prevMonth = this.getPrevMonth().month;
						var prevMonthYear = this.getPrevMonth().year;
						var prevMonthLength = this.getMonthLength(prevMonth, prevMonthYear);
					
						this.selectedDate.date = this.currentDate.date = prevMonthLength + newDate;
						this.selectedDate.month = this.currentDate.month = prevMonth;
						this.selectedDate.year = this.currentDate.year = prevMonthYear;
					} else this.selectedDate.date = this.currentDate.date = newDate;
					break;
				case 'next':
					var newDate = this.selectedDate.date + 7;
					var currentMonthLength = this.getMonthLength(this.selectedDate.month, this.selectedDate.year);
					if(newDate > currentMonthLength) {
						var nextMonth = this.getNextMonth().month;
						var nextMonthYear = this.getNextMonth().year;
					
						this.selectedDate.date = this.currentDate.date = newDate - currentMonthLength;
						this.selectedDate.month = this.currentDate.month = nextMonth;
						this.selectedDate.year = this.currentDate.year = nextMonthYear;
					} else this.selectedDate.date = this.currentDate.date = newDate;
					break;
				case 'today':
					var today = new Date();
					this.selectedDate = this.currentDate = this.getSelectedDate(today);
				default:
					break;
			}
		
			var newDateObj = new Date(this.selectedDate.year, this.selectedDate.month, this.selectedDate.date);
			this.selectedDate.day = newDateObj.getDay();
		
			this.changeToSelectedDate();
		
			if(direction == 'today') this.closeCalendar();
		} else { 
			this.closeCalendarQuick();
			this.calendarlinkEl.toggleClassName('activated');
		}
	},
	
	changeMonth: function(evt) {
		Event.stop(evt);
		var link = Event.findElement(evt,'a');
		var direction = link.getHrefId();
		var month = this.currentDate.month;
		var year = this.currentDate.year;
		var day = this.currentDate.day;
		var date = 1;
		var today = new Date();
		
		switch(direction) {
			case 'prev':
				month = this.getPrevMonth().month;
				year = this.getPrevMonth().year;
			
				if(month == today.getMonth() && year == today.getFullYear()) date = today.getDate();
				
				var newDate = new Date(year, month, date);
				day = newDate.getDay();
	
				break;
			case 'next':
				month = this.getNextMonth().month;
				year = this.getNextMonth().year;
				
				if(month == today.getMonth() && year == today.getFullYear()) date = today.getDate();
				
				var newDate = new Date(year, month, date);
				day = newDate.getDay();
				
				break;
			default:
				break;
		}
		
		this.currentDate.date = date;
		this.currentDate.month = month;
		this.currentDate.year = year;
		this.currentDate.day = day;
		
		this.createMonthView();
		this.displayWorkshopsOnCal();
	},
	
	selectDate: function(evt) {
		Event.findElement(evt, 'td').addClassName('down');
	},
	
	getSelectedDate: function(today) {
		return {date: today.getDate(), day: today.getDay(), month: today.getMonth(), year: today.getFullYear()};
	},
	
	clickOffMore: function(evt) {
		if($(Event.element(evt)).up('#more') != this.moredropdownEl) this.closeMore();
	},
	
	closeMore: function() {
		this.moredropdownEl.hide();
	},

	zebraStripe: function(list) {
		var visibleitems = $A();
		
		if(this.currentcat == '') {
			visibleitems = list.select('li');
		} else {
			list.select('li').each(function(listitem, index) {
				if(listitem.hasClassName(this.currentcat)) visibleitems[visibleitems.length] = listitem;
			}.bind(this));
		}
		
		visibleitems.each(function(item, index) {
			item.addClassName((index % 2 == 1) ? 'odd' : 'even');	
		});
	},
	
	displayNoWorkshopsText: function(list) {
		var workshopsvisible = false;
		var currentcat = this.currentcat;
		
		if(currentcat == '') {
			if(list.select('li').length > 0) workshopsvisible = true;
		} else {
			list.select('li').each(function(item, index) {
				if(item.hasClassName(currentcat) || item.hasClassName("specialevent")) workshopsvisible = true;
			});
		}

		if(!workshopsvisible) list.next('div.noworkshops').show();
	},

	changeToSelectedDate: function() {
		this.createWeekView();
		this.createMonthView();
		this.createDateView();
		this.displayWorkshops();
		this.displayWorkshopsOnCal();
		
		this.currentDate = this.getSelectedDate(new Date(this.selectedDate.year, this.selectedDate.month, this.selectedDate.date));
	},
	
	getPrevMonth: function() {
		var prevMonth = (this.currentDate.month > 0) ? this.currentDate.month - 1 : 11;
		var prevMonthYear = (prevMonth == 11) ? this.currentDate.year - 1: this.currentDate.year;
		return {
			month: prevMonth,
			year: prevMonthYear
		};
	},
	
	getNextMonth: function() {
		var nextMonth = (this.currentDate.month < 11) ? this.currentDate.month + 1 : 0;
		var nextMonthYear = (nextMonth == 0) ? this.currentDate.year + 1 : this.currentDate.year;
		return {
			month: nextMonth,
			year: nextMonthYear
		};
	},
	
	openCalendar: function(evt) {
		Event.stop(evt);
		this.calendarwrapperEl.show();
		this.dateviewnavEl.addClassName('off');
		this.calendarlinkEl.toggleClassName('activated');
		
		var properties = {sprop3: this.calendartitle};
		AC.Tracking.trackClick(properties, this, 'o', this.calendartitle);

		(this.calendarlinkEl.hasClassName('activated')) ? Event.observe(document.body, 'click', this.clickOffCalendar.bind(this)) : this.closeCalendarQuick();
	},
	
	clickOffCalendar: function(evt) {
		if($(Event.element(evt)).up('#storecalendar-calendarwrapper') != this.calendarwrapperEl) {
			this.closeCalendarQuick();
			this.calendarlinkEl.toggleClassName('activated');
		}
	},
	
	closeCalendarQuick: function() {
		this.calendarwrapperEl.hide();
		this.dateviewnavEl.removeClassName('off');
		Event.stopObserving(document.body, 'click');
	},
	
	closeCalendar: function() {
		setTimeout(function() {
			new Effect.Fade(this.calendarwrapperEl, {
				duration: 0.5,
				afterFinish: function() {
					this.calendarlinkEl.toggleClassName('activated');
					this.closeCalendarQuick();
				}.bind(this)
			})
		}.bind(this), 300);
	},
	
	getMonthLength: function(month, year) {
		// we need to do this for leap years
		return (month == 1 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) ? 29 : this.monthLengths[month];
	},
	
	sendReq: function(params) {
		// send request for store workshops with the R#
		var send = new Ajax.Request('/chde/retail/scripts/storewidget.php', {
			method: 'POST', 
			parameters: params,
			onComplete: this.acknowledgeComplete.bind(this)
		})
	},
	
	acknowledgeComplete: function(request) {
		var jsonText = request.responseText;
		var result = new Function("return "+jsonText)();
		//var result = this.scopedEval(jsonText);
		if(result) {
			var stores = result;
			this.store = stores[0];
			this.workshops = this.store.workshops;
			this.initWorkshops();
			this.displayWorkshops();
			this.displayWorkshopsOnCal();
			
			this.calendar.removeClassName('loading');
		}
	},

	scopedEval: function(stringValue) {
		try {
			//alert(stringValue);
			return (function() {return eval("("+stringValue+")");})();
		}
		catch(e) {
			alert('Error: '+e);
			return null;
		}
	},

	newDate: function(year, month, date) {
		return new Date(year, month, date);
	},
	
	initWorkshops: function() {

		this.workshopElements = $A();
		var image = Builder.node('img', {width:'140', height:'100'});
		
		//var elementWidth = this.inititemEl.down('.description').getStyle('width');
		var elementWidth = 930;
		var testStr = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras metus nisl, semper eget, ultrices sit amet, ultricies ut, ipsum. Integer sit amet dui. Donec nulla odio, sodales ac, malesuada nec, tristique id, lacus. Mauris nisl nulla, rhoncus id, hendrerit vel, hendrerit nec, orci. Phasellus molestie nulla id leo. Donec nec massa. Vivamus non urna vel risus aliquet accumsan. Vivamus auctor tellus id leo. Nunc euismod, nibh quis gravida ultricies, massa tortor vestibulum magna, non tristique velit lacus et pede. Fusce viverra tempus felis. Aliquam auctor. Ut ac mi in odio fermentum vulputate. Quisque ornare euismod dolor. Curabitur in magna in arcu sodales venenatis. Nullam ac magna.";
		var truncationLength = this.getTruncationLength(this.weekviewEl, testStr, elementWidth);

		var workshopsYet = false;

		this.workshops.each(function(workshop, index) {
			var dateObj = new Date(workshop.startTime.getFullYear(), workshop.startTime.getMonth(), workshop.startTime.getDate());

			var workshopitem = this.inititemEl.cloneNode(true);
			var workshopclasses = "vevent "+this.firstcat;
			workshop.tags.each(function(tag, index) {
				var tagStr = tag.toLowerCase().gsub(/\s+/, '');
				if(tagStr == 'gettingstarted' && workshop.products.length > 0) tagStr = workshop.products[0].toLowerCase().gsub(/\s+/, '')+' gettingstarted';
				workshopclasses += " "+tagStr;
			});
			workshopitem.addClassName(workshopclasses);

			var dtstart = workshopitem.down('.dtstart');
			dtstart.innerHTML = workshop.startTime.toFormattedTime();
			dtstart.writeAttribute({title: workshop.startTime.toJSON()});
			
			var dtend = workshopitem.down('.dtend');
			dtend.innerHTML = workshop.endTime.toFormattedTime();
			dtend.writeAttribute({title: workshop.endTime.toJSON()});
			
			var titleObj = workshopitem.down('.summary');
			titleObj.innerHTML = workshop.name;

			var descObj = workshopitem.down('.description');
			var description = workshop.description.unescapeHTML();

			if(workshop.tags[0] == 'specialevent') {
				descObj.innerHTML = description;
				if(workshop.imageURL != null) {
					var eventimage = image.cloneNode(true);
					Element.writeAttribute(eventimage, {src:workshop.imageURL, alt:workshop.name});
					Element.addClassName(eventimage, 'right');
					titleObj.insert({before: eventimage});
				}
			} else if(workshop.tags[0] == 'One to One') {
				var signinObj = workshopitem.down('.conciergelink');
				signinObj.innerHTML = this.signintext;
				signinObj.writeAttribute({'href': 'http://onetoone.apple.com/', 'title': this.signintext+' '+workshop.name});

				var learnmoreObj = workshopitem.down('.onetoonelink');
				learnmoreObj.innerHTML = this.learnmoretext;
				learnmoreObj.writeAttribute({'href': 'http://www.apple.com/chde/retail/onetoone/', 'title': this.learnmoretext});

				var ellipsis = '... <a class="morelink" href="#workshop_'+index+'" title="'+this.readmoretext+' '+workshop.name+'">'+this.readmoretext+'</a>';
				var ellipsisLength = ellipsis.length - (5 + this.readmoretext.length);
				truncateTo = truncationLength + ellipsisLength;
				var truncatedDesc = description.truncateDesc(truncateTo, ellipsis);

				descObj.innerHTML = truncatedDesc;
				
				var moreLink = descObj.down('.morelink') || false;
				if(moreLink) {
					Event.observe(moreLink, 'click', function(evt) {
						Event.stop(evt);
						descObj.innerHTML = workshop.description;
						var item = descObj.up('li');
						item.addClassName('open');
					}.bindAsEventListener(this));
				}
				
				workshopsYet = true;
			} else {
				var conciergeObj = workshopitem.down('.conciergelink');
				var conciergeObjTxt = conciergeObj.firstChild.data;
				conciergeObj.writeAttribute({'href': workshop.workshopURL, 'title': conciergeObjTxt+' '+workshop.name});

				var ellipsis = '... <a class="morelink" href="#workshop_'+index+'" title="'+this.readmoretext+' '+workshop.name+'">'+this.readmoretext+'</a>';
				var ellipsisLength = ellipsis.length - (5 + this.readmoretext.length);
				truncateTo = truncationLength + ellipsisLength;
				var truncatedDesc = description.truncateDesc(truncateTo, ellipsis);

				descObj.innerHTML = truncatedDesc;
				
				var moreLink = descObj.down('.morelink') || false;
				if(moreLink) {
					Event.observe(moreLink, 'click', function(evt) {
						Event.stop(evt);
						descObj.innerHTML = workshop.description;
						var item = descObj.up('li');
						item.addClassName('open');
					}.bindAsEventListener(this));
				}
				
				workshopsYet = true;
			}
			this.workshopElements[index] = {
				dateClass: dateObj.valueOf(),
				element: workshopitem
			};
		}.bind(this));
	},
	
	getTruncationLength: function(element, text, width) {
		var inSpan = document.createElement('span');
		inSpan.id = 'ellipsisSpan';
		inSpan.style.whiteSpace = 'nowrap';
		var textNode = document.createTextNode(text);
		inSpan.appendChild(textNode);
		element.appendChild(inSpan);

		var returnlength = text.length;
		if(inSpan.offsetWidth > width) {
			var i = 0;
			var guessCountFit = Math.floor((text.length * width) / inSpan.offsetWidth);
			
			textNode.deleteData(guessCountFit-1, text.length-guessCountFit);
			//Oops, too small, let's add more
			if(inSpan.offsetWidth < width) {
			   var i = guessCountFit;
			   while(inSpan.offsetWidth < (width) && i < text.length) {
					textNode.appendData(text.charAt(i));
					i++;
			   }
			}
			//We're still too big, we need to remove
			else {
			   while(inSpan.offsetWidth > width) {
					textNode.deleteData(textNode.length-1,1);
			   }
			}
			
			returnlength = textNode.length;
		}
		// using Element.remove here instead of inSpan.remove because it's buggy in IE
		Element.remove(inSpan);
		return returnlength;
	},	
	
	getTruncationLengthOriginal: function(element, text, width) {
		var inSpan = Builder.node('span', {id:'ellipsisSpan', style:'white-space:nowrap'}, [text]);
		element.insert(inSpan);

		var returnlength = text.length;
		if(inSpan.offsetWidth > width) {
			var i = 1;
		   inSpan.innerHTML = '';
		   while(inSpan.offsetWidth < (width) && i < text.length) {
				inSpan.innerHTML = text.substr(0,i);
				i++;
		   }
			returnlength = inSpan.firstChild.data.length;
		}
		// using Element.remove here instead of inSpan.remove because it's buggy in IE
		Element.remove(inSpan);
		return returnlength;
	},	
	
	displayWorkshops: function() {
		this.weekviewlistsEl.each(function(list, index) {
			var dateClass = $w(list.className)[0];
			var workshops = this.workshopElements.findAll(function(w) {
				return w.dateClass == dateClass;
			});
			workshops.each(function(workshop, index) {
				list.appendChild(workshop.element);
			});
		}.bind(this));

		this.initStripes();
	},
	
	displayWorkshopsOnCal: function() {

		this.workshops.each(function(workshop, index) {
			var workshopstarttime = workshop.startTime;
			var cellid = workshopstarttime.getFullYear()+'_'+workshopstarttime.getMonth()+'_'+workshopstarttime.getDate();
			var workshopcell = $(cellid) || false;

			if(workshopcell && workshop.tags[0] == 'specialevent') workshopcell.addClassName('event');
		}.bind(this));
	}	
});

String.prototype.truncateDesc = function(size, ellipsis) {
	ellipsis = ellipsis || "...";
	size -= ellipsis.length;

	return (this.length > size) ? this.substring(0, this.lastIndexOf(' ', size)).replace(/\W*$/, '') + ellipsis : this ;
};

Date.prototype.toFormattedTime = function() {
	var hour = this.getHours();
		return (hour)+':'+this.getMinutes().toPaddedString(2); 
	};

	Element.addMethods({
		getHrefId: function(element) {
			return element.readAttribute('href').split('#')[1];
		}
	});
