site={
	init: function () {
		if ($('courses'))	new CourseMatrix('courses');
		if ($('bookshelf'))	new Bookshelf('bookshelf');
		if ($('keyword'))	new LabelInput('keyword');
		if ($('print'))		
			$('print').addEvent('click', function (e) {
				new Event(e).stop(); 
				site.print();
			});
		if ($('lostpassword'))	
			$('lostpassword').addEvent('click', function (e) {
				new Event(e).stop();
				this.getParent('ul').getPrevious('label').setStyle('display', 'none').getPrevious().getFirst().setProperty('name', 'user_login').getParent().getPrevious('h2').set('text', 'Retrieve Password').getParent('form').setProperty('action', '/wp-login.php?action=lostpassword');
				this.getParent('form').adopt(new Element('input', {type:'hidden', name:'redirect_to'}).set('value', '/login/?forgotten=true'));
				this.dispose();
			});
	},
	print: function () {
		$$('link[rel=stylesheet]').setProperty('disabled', true);
		$$('link[title=print]').setProperties({disabled:false, media:'screen, print'});
		/*
		var i, a, main;
		for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
				a.disabled = true;
				if(a.getAttribute("title") == 'print') a.disabled = false;
			}
		}
		*/
	}
}
window.addEvent('domready', site.init);

var CourseMatrix = new Class({
	initialize:function (el) {
		this.table = $$('.' + el)[0].addEvent('click', this.select.bindWithEvent(this));
		this.list = $(el);
		this.radios = this.table.getElements('input[type=radio]')
		this.courses =  $$('#'+el+' ul li');
		
		// remove any subjects with no courses
		this.list.getElements('span').each(function (subject) {
			if (subject.getNext().getChildren().length == 0)	subject.getParent().dispose();
		});
		this.subjects = this.list.getElements('span').addClass('hidden');
		
		// collate course classnames into the subjects' class name
		this.courses.each(function (course) {
			var subject = course.getParent('li');
			var classNames = course.className.split(' ');
				classNames.each(function (className) {subject.addClass(className);});
		});
		
		// loop through each radio and remove it if not subjects (and therefore courses relate to the combination of level and programme the radio represents
		this.radios.each(function (radio) {
			var classes = radio.className.split(' ');
			if (!$$('#courses li ul li').some(function (course) {return (course.hasClass(classes[0]) && course.hasClass(classes[1]));}))	radio.dispose();
		}.bind(this));
		
		this.accordion = new Fx.Accordion(this.subjects, this.list.getElements('ul'), {
			display:-1,
			onActive: function (handle, panel) {
				handle.addClass('on');
			},
			onBackground: function (handle, panel) {
				handle.removeClass('on');
			}
		});
	},
	reset: function () {
		this.courses.removeClass('hidden');
		this.subjects.addClass('hidden');
		this.accordion.display(-1);
		this.radios.each(function (radio) {radio.checked = false;});
		this.table.getElements('td').removeClass('on');
	},
	select: function(e) {
		this.reset();
		
		var target = new Event(e).stop().target;
		if (target.get('tag') != 'input')	return;
		
		this.highlight(target);
		this.showList(target.className.split(' '));
	},
	showList: function (classes) {
		// hide courses not matching selection
		this.courses.each(function (course) {
			if (!(course.className.contains(classes[0]) && course.className.contains(classes[1]))) {
				course.addClass('hidden')
			}
		});
		// hide subjects whose courses are all hidden
		this.subjects.each(function (subject) {
			var courses = subject.getNext().getChildren();
			if (!courses.every(function (course) {return course.hasClass('hidden');}))	subject.removeClass('hidden');
		});
	}, 
	highlight: function (target) {
		var pointer = target.getParent().addClass('on').getParent().getFirst().addClass('on').getNext();
		var counter = 1;
		while (!pointer.hasClass('on')) {counter++; pointer = pointer.getNext();}
		this.table.getFirst().getFirst().getChildren()[counter].addClass('on');
		target.checked = true;
	}
});

var Shelf = new Class({
	initialize: function (json, bookshelf) {
		this.bookshelf = bookshelf;
		this.name = json.name;
		this.books = json.books || new Array();
		this.booklist = new Element('ul');
		
		this.books.each(function (book) {this.addBookToShelf(book);}.bind(this));
		
		this.el = new Element('div').addClass('shelf')
			.adopt(new Element('span').set('text', json.name).addEvent('click', this.rename))
			.adopt(this.booklist)
			.injectInside(bookshelf.element)
	},
	addBookToShelf: function (book) {
		var li = new Element('li').set('text', book.name).injectInside(this.booklist);
		var deleteButton = new Element('img', {src:'/wp-content/themes/fresh/images/bullet-removeCourse.png'}).addEvent('click', function () {this.removeBookFromShelf(book, li).bind(this);}.bindWithEvent(this));
		li.adopt(deleteButton);
	},
	removeBookFromShelf: function (book, li) {
		this.books.erase(book);
		if (this.books.length == 0) {
			this.element.dispose();
		} else {
			li.dispose();
		}
	},
	rename: function () {
	
	}
});

var Bookshelf = new Class({
	initialize:function (el) {
		this.element = $(el);
		this.shelves = [];
		var json = $('json').get('text');
		if (json == '' || json == 'null')	json = '{shelves:[{name:"Your selection", books:[]}, {name:"Courses recommeded by fresh", books:[]}]}';
		this.json = JSON.decode(json);
		this.build();
		var bullet = 
		$('courses').getElements('a').each(function (a) {
			a.adopt(new Element('img', {src:'/wp-content/themes/fresh/images/bullet-addCourse.png'}).addEvent('click', this.showContextMenu.bindWithEvent(this)));
		}.bind(this));
	},
	build: function() {
		if (this.json.shelves) {
			this.json.shelves.each(function (shelf) {
				var ul = new Element('ul');
				if (shelf.books && shelf.books.length > 0) {
					shelf.books.each(function (book) {
						this.addBook(book, shelf, ul);
					}.bind(this));
				}
				this.shelves.push(new Element('div').addClass('shelf').adopt(new Element('span').set('text', shelf.name).addEvent('click', this.rename.bindWithEvent(this))).adopt(ul).injectInside(this.element));
			}.bind(this));
		}
	},
	addBook: function (book, shelf, ul) {
		var removalButton = new Element('img', {src:'/wp-content/themes/fresh/images/bullet-removeCourse.png'})
			.addEvent('click', function () {
				shelf.books.erase(book);
				if (shelf.books.length == 0) {
					var index = false;
					this.json.shelves.each(function (json_shelf, i) {
						if (json_shelf.name == shelf.name)	this.json.shelves.erase(json_shelf);
					}.bind(this));
					li.getParent().getParent().dispose();
				} else {
					li.dispose();
				}
				this.save();
			}.bind(this));
		if (!book.pdf) {
			var li = new Element('li', {rel:book.ID}).set('text', book.name).adopt(removalButton).injectInside(ul);
		} else {
			var li = new Element('li').adopt(new Element('a', {rel:book.ID, href:book.pdf}).set('text', book.name)).adopt(removalButton).injectInside(ul);
		}
	},
	showContextMenu: function (e) {
		var event = new Event(e);
		var target = $(event.target).getParent();
		if (target.get('tag') == 'a')	event.stop();
		
		var menu = new Element('ul', {id:'contextMenu'}).addEvent('mouseleave', function () {this.dispose();});
		if (!this.json.shelves)	this.json.shelves = [{name:'My first shelf', books:[]}];
		this.json.shelves.each(function (shelf, i) {
			new Element('li').set('text', shelf.name).injectInside(menu).addEvent('click', function (e) {
				var book = {ID:target.getProperty('rel'), name:target.get('text'), pdf:target.get('pdf')};
				// if not already on the shelf, add to the shelf
				var bookIDs = this.json.shelves[i].books.map(function (book) { return book.ID});
				if (!bookIDs.contains(book.ID)) {
					this.json.shelves[i].books.include(book);
					this.addBook(book, this.json.shelves[i], this.shelves[i].getElements('ul')[0]);
					this.save();
				} else {
					menu.dispose();
				}
			}.bind(this));
		}.bind(this));
		new Element('li').set('text', '...new shelf').injectInside(menu).addEvent('click', function (e) {
			var book = {ID:target.getProperty('rel'), name:target.get('text')};
			var shelf = {name:'New Shelf', books:[book]};
			this.json.shelves.push(shelf);
			var ul = new Element('ul');
			shelf.books.each(function (book) {
				this.addBook(book, shelf, ul);
			}.bind(this));
			this.shelves.push(new Element('div').addClass('shelf').adopt(new Element('span').set('text', shelf.name).addEvent('click', this.rename.bindWithEvent(this))).adopt(ul).injectInside(this.element));
			this.save();
		}.bind(this));
		menu.injectInside(document.body).setPosition(target.getFirst().getPosition());
	},
	rename: function (e) {
		var target = new Event(e).target;
		var coords = target.getCoordinates()
		new Element('input').injectAfter(target).setStyles({position:'absolute', left:5, top:0, zIndex:1}).addEvent('blur', function(e) {
			var input = new Event(e).target;
			var name = input.get('value');
			if (name == '') return alert('Please enter a shelf name');
			this.json.shelves.each(function (shelf) {
				if (shelf.name == target.get('text'))	shelf.name = name;
			});
			target.set('text', name);
			input.dispose();
			this.save();
		}.bind(this));
	},
	save: function () {
		new Request({
			url:'/wp-content/themes/fresh/save_bookshelf.php',
			data:{
				json:JSON.encode(this.json)
			},
			onComplete: function () {
				if ($('contextMenu'))	$('contextMenu').dispose();
			}
		}).send();
	}
});

var LabelInput = new Class({
	initialize:function (input) {
		this.element = $(input);
		this.label = this.element.getParent();
		this.text = this.label.get('text');
		
		this.element.addEvents({
			click: function () {
				if (this.element.value == this.text)	this.element.value = '';
			}.bindWithEvent(this),
			blur: function () {
				if (this.element.value == '')	this.element.value = this.text;
			}.bindWithEvent(this)
		});
	}
});
