
Date.implement({
	startOfTheMonth: function() {
		this.set('date', 1).clearTime();
		return this;
	},
	endOfTheMonth: function() {
		this.increment('month').startOfTheMonth().decrement('minute');
		return this;
	}
});


var CalendarBrowser = new Class({
	ClassName: 'CalendarBrowser',

	initialize: function() {
		this.now    = new Date().clearTime().set('hours', 12);
		this.params = {}

		this.browser   = $('calendar-browser');
		this.form      = this.browser.getElement('form');
		this.submitBtn = this.form.getElement('#submit-btn');
		this.searchBox = this.form.getElement('#search');

		this.prevMonthBtn    = this.browser.getElements('div.month-pager span.prev');
		this.nextMonthBtn    = this.browser.getElements('div.month-pager span.next');
		this.currentMonthLbl = this.browser.getElement('div.month-pager span.current');
		this.calendarList    = this.browser.getElement('#calendar');

		this.startDate = this.now.clone().startOfTheMonth();
		this.endDate   = this.now.clone().endOfTheMonth();

		this.cat = this.browser.get('cat');
		this.params[this.cat] = true;
		switch (this.cat) {
			case 'athletes':     this.params.athleteId = this.browser.get('mid')||null; break;
			case 'monstergirls': this.params.girlId    = this.browser.get('mid')||null; break;
			case 'bands':        this.params.bandId    = this.browser.get('mid')||null; break;
		}

		this.hookEvents();
		this.findEntries();
	},

	hookEvents: function() {
		this.form.addEvent('submit', function(event) {
			event.stop();

			this.params.search = this.searchBox.get('value').trim();
			if (this.params.search) {
				this.startDate = this.now.clone().startOfTheMonth().decrement('month', 6);
				this.endDate   = this.now.clone().startOfTheMonth().increment('month', 6);
			} else {
				this.startDate = this.now.clone().startOfTheMonth();
				this.endDate   = this.now.clone().endOfTheMonth();
				this.params.search = null;
			}

			this.findEntries();
		}.bind(this));

		this.nextMonthBtn.addEvent('click', function(event) {
			event.stop();
			this.startDate.setMonth(this.startDate.getMonth()+1);
			this.endDate = this.startDate.clone().endOfTheMonth();
			this.findEntries();
		}.bind(this));

		this.prevMonthBtn.addEvent('click', function(event) {
			event.stop();
			this.startDate.setMonth(this.startDate.getMonth()-1);
			this.endDate = this.startDate.clone().endOfTheMonth();
			this.findEntries();
		}.bind(this));
	},

	findEntries: function() {
		// console.log('Finding calendar entries...');
		this.params.start = this.startDate.format('%Y%m%d');
		this.params.end   = this.endDate.format('%Y%m%d');

		new JSONPRequest({
			url: MonsterUser.switchUrl + '/tools/jsonapi/calendar-entries.js',
			parameters: this.params,
			immediate: true,
			onComplete: function(data) {
				this.calendarList.empty();

				data.items.each(function(row, index){
					var newRow = new Element('li', {'class': (index%2==0)? 'calendar-item even':'calendar-item odd'});
					newRow.grab(new Element('div', {'class': 'date'}).adopt([
						new Element('span', {'class': 'month', text: row.month }),
						new Element('span', {'class': 'day',   text: row.day   }),
						new Element('span', {'class': 'year',  text: row.year  })
					]));
					newRow.grab(new Element('h4').grab(new Element('span', {text: row.title})));
					if (row.place) newRow.grab(new Element('p', {'class':'location', text: row.place+' '+(row.time||'') }));
					newRow.grab(new Element('p', {'class':'location', text: row.location }));
					if (row.url) newRow.grab(new Element('a', {href: row.url}).adopt(newRow.getChildren()));
					this.calendarList.grab(newRow);
				}.bind(this));

				if (data.items.length == 0) {
					this.showNoItemsFound();
				}

				if (this.params.search) {
					this.prevMonthBtn.each(function(item){item.hide()});
					this.nextMonthBtn.each(function(item){item.hide()});
					this.currentMonthLbl.hide();
				} else {
					this.prevMonthBtn.each(function(item){item.show()});
					this.nextMonthBtn.each(function(item){item.show()});
					this.currentMonthLbl.show();
					this.currentMonthLbl.set('text', this.startDate.format('%B %Y'));
				}
			}.bind(this)
		});

	},

	showNoItemsFound: function() {
		var newRow = new Element('li', {'class': 'calendar-item-none'});
		newRow.grab(new Element('h4').grab(new Element('span')));
		newRow.grab(new Element('p', {'class':'location', text: 'Can you believe there is nothing going on right now? Check back soon!'}));
		this.calendarList.grab(newRow);
	}
});

new CalendarBrowser();
