﻿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: [],
	reservetext: '',
	waitlisttext: '',
	readmoretext: '',
	signintext: '',
	learnmoretext: '',
	onetoonetext: '',
	jointventuretext: '',
	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 = AC.Tracking.pageName() + ' - 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.reservetext = value.reservetext;
				self.waitlisttext = value.waitlisttext;
				self.readmoretext = value.readmoretext;
				self.signintext = value.signintext;
				self.learnmoretext = value.learnmoretext;
				self.onetoonetext = value.onetoonetext;
				self.jointventuretext = value.jointventuretext;
				
				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}));
		this.sendReq();
	},
	
	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) {
		var head = $$('html')[0],
			lang = head.readAttribute('lang');
		
		// sending store number in the url when requesting the JSON
		var url = '/retail/scripts/concierge_data.php?type=coe&store=' + this.storeNumber +'&locale=' + lang,
				
			send = new Ajax.Request(url, {
				method: 'POST',
				parameters: params,
				onComplete: this.acknowledgeComplete.bind(this)
		});
	},
	
	acknowledgeComplete: function(request) {
		var jsonText = request.responseText;
		var result = new Function("return "+jsonText)();

		if(result) {
			var stores = result;
			this.workshops = [];
			
			for(var i=0, category; category=stores[i]; i++) {
				if(category["category"].toLowerCase().match(/workshop|event/)) {
					for(var j=0, workshop; workshop=category["coeItemList"][j]; j++) {
						if(workshop.imageurl != null && !workshop.imageurl.toLowerCase().match(/icon_personalprojects/)) {
							if(category["category"].toLowerCase().match(/event/)) {
								workshop.tags = "specialevent," + workshop.tags;
							}
							this.workshops.push(workshop);
						} else if(workshop.imageurl == null) {
							if(category["category"].toLowerCase().match(/event/)) {
								workshop.tags = "specialevent," + workshop.tags;
							}
							this.workshops.push(workshop);
							
						}
					}
				}
			}
			
			function sortArray(a, b) {
				var aStartTimeArr = a.startTime.substring(a.startTime.indexOf(' ') + 1, a.startTime.length).split(':'),
					bStartTimeArr = b.startTime.substring(b.startTime.indexOf(' ') + 1, b.startTime.length).split(':'),
					aStartMinutes = ((parseInt(aStartTimeArr[0])*60)+parseInt(aStartTimeArr[1])),
					bStartMinutes = ((parseInt(bStartTimeArr[0])*60)+parseInt(bStartTimeArr[1]));

				return (aStartMinutes - bStartMinutes);
			}
			this.workshops = this.workshops.sort(sortArray);
			
			this.initWorkshops();
			this.displayWorkshops();
			this.displayWorkshopsOnCal();

			this.calendar.removeClassName('loading');
	
			//click tracking for calendar events
			var links = $$('#storecalendar a');
			for (var i = 0, link; (link = links[i]); i++) {
				if(link.match(/(onetoone\.apple\.com|concierge\.apple\.com)/)){
					link.observe("mousedown",function(evt){
						var elem = evt.element(),
							name;
						if (elem.href.match(/concierge/)){name='concierge';}
						else if (elem.href.match(/onetoone/)){name='one to one';}
						name = AC.Tracking.pageName() + ' - store calendar - ' + name;
						AC.Tracking.trackClick({prop3:name}, this, 'o', name);		
					})
				}
			}
		}
	},

	scopedEval: function(stringValue) {
		try {
			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 = 930,
			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.",
			truncationLength = this.getTruncationLength(this.weekviewEl, testStr, elementWidth),
			workshopsYet = false;

		this.workshops.each(function(workshop, index) {
			var startDateArr = workshop.startTime.substring(0, workshop.startTime.indexOf(' ')).split('-'),
				startTimeArr = workshop.startTime.substring(workshop.startTime.indexOf(' ') + 1, workshop.startTime.length).split(':'),
				startTime = new Date(startDateArr[0], parseInt(startDateArr[1] - 1), startDateArr[2]),
				endDateArr = workshop.endTime.substring(0, workshop.endTime.indexOf(' ')).split('-'),
				endTimeArr = workshop.endTime.substring(workshop.endTime.indexOf(' ') + 1, workshop.endTime.length).split(':'),
				endTime = new Date(endDateArr[0], parseInt(endDateArr[1] - 1), endDateArr[2]);
				
			startTime.setHours(startTimeArr[0], startTimeArr[1], startTimeArr[2]);
			endTime.setHours(endTimeArr[0], endTimeArr[1], endTimeArr[2]);

			var dateObj = new Date(startTime.getFullYear(), startTime.getMonth(), startTime.getDate());

			var workshopitem = this.inititemEl.cloneNode(true);
			var workshopclasses = "vevent " + this.firstcat;
			
			workshopclasses += ' ' + workshop.tags.toLowerCase().gsub(/\s+/, '').gsub(/,/, ' ');
			workshopitem.addClassName(workshopclasses);

			var dtstart = workshopitem.down('.dtstart'),
				dtend = workshopitem.down('.dtend');

			dtstart.innerHTML = startTime.toFormattedTime();
			dtend.innerHTML = endTime.toFormattedTime();

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

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


			if(workshop.tags.toLowerCase().match(/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.toLowerCase().match(/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 oneToOneObj = workshopitem.down('h6 span');

				var learnmoreObj = workshopitem.down('.onetoonelink');
				learnmoreObj.innerHTML = this.learnmoretext;
				head = $$('html')[0],
				lang = head.readAttribute('lang');
				switch (lang) {
					case 'it-IT':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/it/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'de-CH':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/chde/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'fr-CH':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/chfr/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'de-DE':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/de/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'fr-FR':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/fr/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'fr-CA':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/ca/fr/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'en-CA':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/ca/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'ja-JP':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/jp/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'en-GB':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/uk/retail/onetoone/', 'title': this.learnmoretext});
						break;
					case 'es-ES':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/es/retail/onetoone/', 'title': this.learnmoretext});
						break;
					default:
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com.cn/retail/onetoone/', 'title': this.learnmoretext});
						break;
				}
				
				oneToOneObj.innerHTML = this.onetoonetext;
				Element.addClassName(oneToOneObj, 'one-to-one-subhead');
				
				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 if(workshop.tags.toLowerCase().match(/joint venture/)) {
				var jointVentureObj = workshopitem.down('h6 span'),
					signinObj = workshopitem.down('.conciergelink'),
					learnmoreObj = workshopitem.down('.onetoonelink'),
					head = $$('html')[0],
					lang = head.readAttribute('lang');
				
				jointVentureObj.innerHTML = this.jointventuretext;
				signinObj.innerHTML = this.signintext;
				signinObj.writeAttribute({'href': 'http://jointventure.apple.com/', 'title': this.signintext+' '+workshop.name});
				learnmoreObj.innerHTML = 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;
				
				switch (lang) {
					case 'it-IT':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/it/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'de-CH':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/chde/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'fr-CH':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/chfr/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'de-DE':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/de/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'fr-FR':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/fr/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'fr-CA':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/ca/fr/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'en-CA':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/ca/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'ja-JP':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/jp/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'en-GB':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/uk/retail/jointventure/', 'title': this.learnmoretext});
						break;
					case 'es-ES':
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com/es/retail/jointventure/', 'title': this.learnmoretext});
						break;
					default:
						learnmoreObj.writeAttribute({'href': 'http://www.apple.com.cn/retail/jointventure/', 'title': this.learnmoretext});
						break;
				}

			} else {
				var conciergeObj = workshopitem.down('.conciergelink');

				if (workshop.status != null && (workshop.status.toLowerCase() === 'reserve' || workshop.status.toLowerCase() === 'waitlist')) {
					var conciergeObjTxt = (workshop.status.toLowerCase() === 'reserve') ? this.reservetext : this.waitlisttext;
					conciergeObj.innerHTML = conciergeObjTxt;
				
					conciergeObj.writeAttribute({'href': workshop.workshopURL, 'title': conciergeObjTxt+' '+workshop.name});
				} else {
					workshopitem.removeChild(conciergeObj);
				}

				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 startDateArr = workshop.startTime.substring(0, workshop.startTime.indexOf(' ')).split('-'),
				startTimeArr = workshop.startTime.substring(workshop.startTime.indexOf(' ') + 1, workshop.startTime.length).split(':'),
				startTime = new Date(startDateArr[0], parseInt(startDateArr[1] - 1), startDateArr[2]),
				cellid, workshopcell;
				
			startTime.setHours(startTimeArr[0], startTimeArr[1], startTimeArr[2]);

			cellid = startTime.getFullYear()+'_'+startTime.getMonth()+'_'+startTime.getDate();
			workshopcell = $(cellid) || false;

			if(workshopcell && workshop.tags.toLowerCase().match(/'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.toUSFormattedTime = function() {
// 	var hour = this.getHours();
// 	hour = (hour == 0) ? 24 : hour;
// 	
// 	return ((hour > 12) ? hour - 12 : hour)+':'+this.getMinutes().toPaddedString(2)+' '+((hour >= 12) ? 'pm' : 'am'); 
// };
// Date.prototype.toCAFRFormattedTime = function() {
// 	var hour = this.getHours();
// 	return (hour)+' h '+this.getMinutes().toPaddedString(2); 
// };
// Date.prototype.toFormattedTime = function() {
// 	var hour = this.getHours();
// 	return (hour)+':'+this.getMinutes().toPaddedString(2); 
// };

Date.prototype.toFormattedTime = function() {
	var hour = this.getHours(),
		minutes = this.getMinutes().toPaddedString(2),
		head = $$('html')[0],
		lang = head.readAttribute('lang');
		
	switch (lang) {
		case 'it-IT':
		case 'de-CH':
		case 'fr-CH':
		case 'de':
		case 'fr-FR':
		case 'de-DE':
		case 'es-ES':
			return (hour) + ':' + minutes;
			break;
		case 'fr-CA':
			return hour + ' h ' + ((minutes === '00') ? '' : minutes);
			break;
		// case 'en-CA':
		// case 'en-US':
		// case 'ja':
		default:
			hour = (hour == 0) ? 24 : hour;
			return ((hour > 12) ? hour - 12 : hour) + ':' + minutes + ' ' + ((hour >= 12) ? 'pm' : 'am');
			break;
	}
};
Element.addMethods({
	getHrefId: function(element) {
		return element.readAttribute('href').split('#')[1];
	}
});
