/* Showtimes Domready Event
------------------------------------------------------------------------------------*/
window.addEvent('domready', function(){
	// create play louder
	// but if ie6 we need some special sauce for tool tip
	if(window.ie6){
		playLouder = new PlayLouder('play-louder', 'tab-content', {
			onUpdateComplete: function(){
				// add events to show/hide tool tipe
				$$('#play-louder .special-offers-help').addEvents({
					'mouseenter': function(e){
						this.getFirst().setStyle('display', 'block');
					},
					'mouseleave': function(e){
						this.getFirst().setStyle('display', 'none');
					}
				});
			}
		});	
	}
	else{
		playLouder = new PlayLouder('play-louder', 'tab-content');
	}
	
	
	// date picker
	var picker = new DatePicker('calendar',{
		onDateChange: function(date){
			playLouder.defaultState()
			
			var url = '/play/music/includes/event-calendar.jsp?startDate=' + date;
			var ajaxRequest = new Request.HTML({	
                evalScripts:false,
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					var update = $('showtime-bucket');
					update.empty();
					update.set('html', responseHTML);
					// create togglers for days
					// create and store on element
					$$('.event-date').each(function(element, index){
						if(index == 0){
							new EventDate(element, {
								onToggle: function(){
									playLouder.defaultState();
								}
							});
						}
						else{
							new EventDate(element, {
								onToggle: function(){
									playLouder.defaultState();
								},
								startOpen:false
							});
						}
					});
					// replace headers
					sIFR.replace(univers, {
						selector: '.event-date .header h3', 
						wmode: 'transparent',
						css: [
							'.sIFR-root { font-size: 26px; color: #ffffff; font-weight: normal; }'
						],
						filters: {
							DropShadow: {
								knockout: false, distance: 1, color: '#000000', strength: 1
							}
						},
						preventWrap: false,
						fitExactly: true,
						tuneHeight: -13,
						offsetTop: -6
					});
				}				
			});
			
			ajaxRequest.get(url);
		}
	});
	
	// create and store on element
	$$('.event-date').each(function(element, index){
		if(index == 0){
			new EventDate(element, {
				onToggle: function(){
					playLouder.defaultState();
				}
			});
		}
		else{
			new EventDate(element, {
				onToggle: function(){
					playLouder.defaultState();
				},
				startOpen:false
			});
		}
	});
});


var DatePicker = new Class({
	Implements : [Options,Events],
	options:{
		onDateChange: Class.empty,
		dateRange: 5
	},
	initialize: function(container, options){
		this.setOptions(options);
				
		this.container = $(container);
		this.days = this.container.getElements('#days td').filter(function(item, index){
			if(!item.hasClass('disabled'))
				return item;
		});
		
		var tag = this.days[0].getProperty('id').split('_');
		tag = this.splitTag(tag[1]);
		this.currentMonth = tag.month;
		this.currentYear = tag.year;
		this.startMonth = this.currentMonth;
		
		// store ajax object to use later
		this.ajaxUpdate = new Request.HTML({
            evalScripts:false,
			url: '/play/music/includes/calendar.jsp',
			onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
				var update = this.container;
				update.empty();
				update.set('html', responseHTML);
			}.bind(this)
		});
		
		// start with the first available day of the month selected
		this.selectDate(this.days[0]);
		
		// history manager
		this.historyKey = 'selectedDate';
		this.history = HistoryManager.register(
			this.historyKey,
			[this.getTag()],
			function(values) {
				// split the value out in to day month year
				var date = this.splitTag(values[0]);
				// check to see if the month request is not the currently selected month
				if(date.month != this.currentMonth){
					// check to see that the month request is not before the current month
					if(date.month >= this.startMonth){
						// set the current month to the one requested
						this.currentMonth = date.month;
						this.updateMonth();
						// give the calendar some time to update
						(function(){
							// select the requested day
							this.selectDate(values[0]);
						}.bind(this)).delay(200);
					}
					else{
						// link is for a day that has already past
						alert('The link you have used is time sensitive and has expired.\nWe will take you to the nearest available date.');
					}
				}
				else{
					// requested date is in the month that is currently in view just select it
					this.selectDate(values[0]);
				}
			}.bind(this),
			function(values) {
				return this.historyKey + '(' + values[0] + ')';
			}.bind(this),
			this.historyKey + '\\(\([0123456789-]+\)\\)'
		);
		HistoryManager.start();
		
		// attach events to elements
		this.attach();
	},
	attach: function(){
		// after update
		this.ajaxUpdate.addEvent('onSuccess', function(){
			this.days = this.container.getElements('#days td').filter(function(item, index){
				if(!item.hasClass('disabled'))
					return item;
			});
			this.highlight();
		}.bind(this));
		
		// event delegation
		this.container.addEvent('click', function(e){
			e.preventDefault();
			var target = $(e.target);
			
			// if the elemnt clicked was a day (in td tags) and is not disabled
			if(target.get('tag') == 'a' && !target.hasClass('disabled') && !target.hasClass('previous') && !target.hasClass('next')){
				target = target.getParent();
				this.selectDate(target);
			}
			else if(target.hasClass('previous'))
				this.previousMonth();
			else if(target.hasClass('next'))
				this.nextMonth();				
		}.bind(this));
	},
	selectDate: function(date){
		// remove current highlighting
		this.clear();
		
		// if the date to select is being passed in from an element usually when user clicks on a day
		if($type(date) == 'element'){
			// store selected day
			this.selectedIndex = this.days.indexOf(date);
						
			var selected = this.splitTag(date.getProperty('id').split('_')[1]);
			this.selectedMonth = this.currentMonth;
			this.selectedDay = selected.day;
			this.selectedYear = selected.year;
		}
		// if the date to select is being passed in as a string 2008-06-16 usually from history manager
		else if($type(date) == 'string'){
			var selected = this.splitTag(date);
			this.selectedMonth = selected.month;
			this.selectedDay = selected.day;
			this.selectedYear = selected.year;
			
			// do a check to see if the requested day is disabled or if we have past it
			this.selectedIndex = null;
			for(var i = 0; i < this.days.length; i++){
				if(this.days[i].getFirst().get('text') == this.selectedDay && !this.days[i].hasClass('disabled')){
					this.selectedIndex = i;
					break;
				}
			}
			// if the requested day was disabled or not in the calendar
			if(this.selectedIndex == null){
				alert('The link you have used is time sensitive and has expired.\nWe will take you to the nearest available date.');
				// select the first available day of the current month
				this.selectedIndex = 0;
				var split = this.splitTag(this.days[0].getProperty('id').split('_')[1]);
				this.selectedDay = split.day;
				this.selectedMonth = split.month;
				this.selectedYear = split.year;
			}
		}
		
		// track selected date with history manager
		if(this.history != null){
			this.history.setValues([this.getTag()]);
			// fire date change event with current selected date
			this.fireEvent('onDateChange', this.getTag());
		}
		
		// calcululate and highlight the correct elements
		if((this.days.length - this.options.dateRange) < this.selectedIndex)
			this.carryForward = this.options.dateRange - (this.days.length - this.selectedIndex);
		else
			this.carryForward = 0;
			
		this.highlight();
	},
	highlight: function(){
		// highlighting days from the current month
		if(this.selectedMonth == this.currentMonth){
			for(var i = 0; i < this.options.dateRange; i++){
				if(this.selectedIndex + i < this.days.length)
					this.days[this.selectedIndex + i].addClass('highlight');
			}
		}
		else if(this.currentMonth == (this.selectedMonth + 1)){
			if(this.carryForward != 0){
				for(var i = 0; i < this.carryForward; i++){
					this.days[i].addClass('highlight');
				}
			}
		}
		else if(this.currentMonth == 1 && this.selectedMonth == 12){
			if(this.carryForward != 0){
				for(var i = 0; i < this.carryForward; i++){
					this.days[i].addClass('highlight');
				}
			}
		}
	},
	clear: function(){
		this.days.each(function(item){
			item.removeClass('highlight');
		});
	},
	nextMonth: function(){
		if(this.currentMonth < 12){
			this.currentMonth++;
		}
		else{
			this.currentMonth = 1;
			this.currentYear++;
		}
		this.updateMonth();
	},
	previousMonth: function(){
		if(this.currentMonth != 1){
			this.currentMonth--;
		}
		else{
			this.currentMonth = 12;
			this.currentYear--;
		}
		this.updateMonth();
	},
	updateMonth: function(){
		// build a data object for ajax to parse in to param string
		var state = {
			month: this.currentMonth,
			year: this.currentYear
		};
		this.ajaxUpdate.options.data = state;
		this.ajaxUpdate.get(state);
	},
	getTag: function(year, month, day){
		if(year == null || month == null || day == null)
			return this.selectedYear + '-' + this.selectedMonth + '-' + this.selectedDay;
		else
			return year.toInt() + '-' + month.toInt() + '-' + day.toInt();
	},
	splitTag: function(tag){
		var split = tag.split('-');
		return {
			year: split[0].toInt(),
			month: split[1].toInt(),
			day: split[2].toInt()
		};
	}
});