(function(addEvent, removeEvent){
	
	var match = /(.*?):relay\(([^)]+)\)$/,
		combinators = /[+>~\s]/,
		splitType = function(type){
			var bits = type.match(match);
			return !bits ? {event: type} : {
				event: bits[1],
				selector: bits[2]
			};
		},
		check = function(e, selector){
			var t = e.target;
			if (combinators.test(selector = selector.trim())){
				var els = this.getElements(selector);
				for (var i = els.length; i--; ){
					var el = els[i];
					if (t == el || el.hasChild(t)) return el;
				}
			} else {
				for ( ; t && t != this; t = t.parentNode){
					if (Element.match(t, selector)) return $(t);
				}
			}
			return null;
		};

	Element.implement({
		addEvent: function(type, fn){
			var splitted = splitType(type);
			if (splitted.selector){
				var monitors = this.retrieve('$moo:delegateMonitors', {});
				if (!monitors[type]){
					var monitor = function(e){
						var el = check.call(this, e, splitted.selector);
						if (el) this.fireEvent(type, [e, el], 0, el);
					}.bind(this);
					monitors[type] = monitor;
					addEvent.call(this, splitted.event, monitor);
				}
			}
			return addEvent.apply(this, arguments);
		},

		removeEvent: function(type, fn){
			var splitted = splitType(type);
			if (splitted.selector){
				var events = this.retrieve('events');
				if (!events || !events[type] || (fn && !events[type].keys.contains(fn))) return this;

				if (fn) removeEvent.apply(this, [type, fn]);
				else removeEvent.apply(this, type);

				events = this.retrieve('events');
				if (events && events[type] && events[type].keys.length == 0){
					var monitors = this.retrieve('$moo:delegateMonitors', {});
					removeEvent.apply(this, [splitted.event, monitors[type]]);
					delete monitors[type];
				}
				return this;
			}
			return removeEvent.apply(this, arguments);
		},

		fireEvent: function(type, args, delay, bind){
			var events = this.retrieve('events');
			if (!events || !events[type]) return this;
			events[type].keys.each(function(fn){
				fn.create({bind: bind || this, delay: delay, arguments: args})();
			}, this);
			return this;
		}
	});

})(Element.prototype.addEvent, Element.prototype.removeEvent);

/*
---
description: MooTools Datepicker class

authors:
  - MonkeyPhysics.com
  - Arian Stolwijk
  - MadmanMonty (Chris Baxter)
  - marfillaster (Ken Marfilla)
  - eerne (Enrique Erne)

license:
  - Attribution-Share Alike 3.0 Unported

requires:
  core/1.2.4: '*'
  more/1.2.4.4: [Date,MooTools.lang]

provides:
  - [DatePicker]

...
*/


/**
 * datepicker.js - MooTools Datepicker class
 * @version 1.19
 *
 * by MonkeyPhysics.com
 *
 * Source/Documentation available at:
 * http://www.monkeyphysics.com/mootools/script/2/datepicker
 *
 * --
 *
 * Smoothly animating, very configurable and easy to install.
 * No Ajax, pure Javascript. 4 skins available out of the box.
 *
 * --
 *
 * Some Rights Reserved
 * http://creativecommons.org/licenses/by-sa/3.0/
 *
 */

MooTools.lang.setLanguage("en-GB");

var DatePicker = new Class({

	Implements: [Options, Events],

	// working date, which we will keep modifying to render the calendars
	d: '',

	// just so that we need not request it over and over
	today: '',

	// current user-choice in date object format
	choice: {},

	// size of body, used to animate the sliding
	bodysize: {},

	// to check availability of next/previous buttons
	limit: {},

	// element references:
	picker: null,      // main datepicker container
	slider: null,      // slider that contains both oldContents and newContents, used to animate between 2 different views
	oldContents: null, // used in animating from-view to new-view
	newContents: null, // used in animating from-view to new-view
	input: null,       // original input element (used for input/output)
	visual: null,      // visible input (used for rendering)

	options: {
		pickerClass: 'datepicker',
		dayShort: 2,
		monthShort: 3,
		startDay: 1, // Sunday (0) through Saturday (6) - be aware that this may affect your layout, since the days on the right might have a different margin
		timePicker: false,
		timePickerOnly: false,
		yearPicker: true,
		yearsPerPage: 20,
		allowEmpty: true,
		animationDuration: 400,
		useFadeInOut: !Browser.Engine.trident, // dont animate fade-in/fade-out for IE
		startView: 'month', // allowed values: {time, month, year, decades}
		positionOffset: { x: 0, y: 0 },
		minDate: null, // Date object or a string
		maxDate: null, // same as minDate
		toggleElements: null, // deprecated
		toggle: null,
		draggable: true,
		timeWheelStep: 1 // 10,15,20,30
		/*,

		// i18n
		months: null,
		days: null,
		format: null,
		selectTimeTitle: null,
		timeConfirmButton: null,


		// and some event hooks:
		onShow: $empty,   // triggered when the datepicker pops up
		onClose: $empty,  // triggered after the datepicker is closed (destroyed)
		onSelect: $empty,  // triggered when a date is selected
		onNext: $empty,  // triggered when changing to next month
		onPrevious: $empty  // triggered when changing to previous month */
	},

	initialize: function(attachTo, options) {
		// MooTools.lang
		this.setOptions({
			days: MooTools.lang.get('Date', 'days'),
			months: MooTools.lang.get('Date', 'months'),
			format: MooTools.lang.get('Date', 'shortDate'),
			selectTimeTitle : MooTools.lang.get('DatePicker', 'select_a_time'),
			timeConfirmButton : MooTools.lang.get('DatePicker', 'time_confirm_button')
		});


		var oldFormat = this.options.format;
		this.setOptions(options);
		if (this.options.timePicker && this.options.format == oldFormat) {
			var timeFormat = MooTools.lang.get('Date', 'shortTime');
			this.options.format = this.options.timePickerOnly ? timeFormat : this.options.format + ' ' + timeFormat;
		}

		// Support for deprecated toggleElements
		if(this.options.toggleElements) this.options.toggle = document.getElements(this.options.toggleElements);
		
		this.attach(attachTo, this.options.toggle);

		if (this.options.timePickerOnly) {
			this.options.timePicker = true;
			this.options.startView = 'time';
		}

		if (this.options.minDate) {
			if(!(this.options.minDate instanceof Date)) this.options.minDate = Date.parse(this.options.minDate);
		}
		if (this.options.maxDate) {
			if(!(this.options.maxnDate instanceof Date)) this.options.maxDate = Date.parse(this.options.maxDate);
			this.options.maxDate = new Date( +this.options.maxDate + (24*60*60 - 1) * 1000 );
		}

		document.addEvent('mousedown', this.close.bindWithEvent(this));
	},

	attach: function(attachTo, toggle) {

		//dont bother trying to attach when not set
		if (!attachTo) return;

		// toggle the datepicker through a separate element?
		if (toggle) {
			var togglers = $type(toggle) == 'array' ? toggle : [document.id(toggle)];
			document.addEvents({
				'keydown': function(e) {
					var target = document.id(e.target);
					if (
						e.key == "tab" &&
						!target.hasClass('hour') &&
						!target.hasClass('minutes') &&
						!target.hasClass('ok')
					){
						this.close(null, true);
					}
				}.bind(this)
			});
		};

		// see what is being attached and get an array suitable for it
		var elems = $type(attachTo) == 'array' ? attachTo : [document.id(attachTo)];

		// attach functionality to the inputs
		elems.each(function(item, index) {
			// never double attach
			if (item.retrieve('datepicker')) return;

			item.store('datepicker', true); // to prevent double attachment...

			// events
			if (toggle && togglers) {
				var self = this;
				var events = {
					'click': function(e){
						if (e) e.stop();
						self.show(item, togglers[index]);
					}
				};
				var toggler = togglers[index]
					.setStyle('cursor', 'pointer')
					.addEvents(events);
				item.store('datepicker:toggler',toggler)
					.store('datepicker:events',events);
			} else {
				var events = {
					'keydown': function(e){
						// prevent the user from typing in the field
						if (this.options.allowEmpty && (e.key == "delete" || e.key == "backspace")) {
							item.set('value', '');
							this.close(null, true);
						} else if (e.key == "tab") {
							this.close(null, true);
						} else {
							e.stop();
						}
					}.bind(this),
					'focus': this.show.bind(this,[item])
				};

				item.addEvents(events).store('datepicker:events',events);
			}
		}.bind(this));

		return this;
	},

	detach: function(detach){
		var elems = $type(detach) == 'array' ? detach : [document.id(detach)];

		elems.each(function(item){
			// Only when the datepicker is attached
			if (!item.retrieve('datepicker')) return;

			var toggler = item.retrieve('datepicker:toggler');
			var events = item.retrieve('datepicker:events');
			// Detach the Events
			(toggler ? toggler : item).removeEvents(events);
		});

		return this;
	},

	show: function(input,toggler,timestamp) {
		input = document.id(input);
		// Cannot show the picker if its not attached
		if(!input.retrieve('datepicker')) return;

		// Determine the date that should be opened
		if (timestamp) {
			this.d = new Date(timestamp);
		} else {
			this.d = input.retrieve('datepicker:value') || input.get('value');
			if(!this.d){
				this.d = new Date();
			}else if(!(this.d instanceof Date)){
				this.d = Date.parse(this.d);
			}
		}
		if(!this.d.isValid()) this.d = new Date();
		// Min/max date
		if (this.options.maxDate && this.options.maxDate.isValid() && this.d > this.options.maxDate)
			this.d = this.options.maxDate;
		if (this.options.minDate && this.options.minDate.isValid() && this.d < this.options.minDate)
			this.d = this.options.minDate;

		this.input = input;
		var d = (toggler ? document.id(toggler) : input).getCoordinates();
		var position = {
			left: d.left + this.options.positionOffset.x,
			top: d.top + d.height + this.options.positionOffset.y
		};
		this.fireEvent('show');

		this.today = new Date();
		this.choice = this.d.toObject();
		this.mode = (this.options.startView == 'time' && !this.options.timePicker) ? 'month' : this.options.startView;
		this.render();
		this.position({x: position.left, y: position.top});

		if(this.options.draggable && $type(this.picker.makeDraggable) == 'function') {
			this.dragger = this.picker.makeDraggable();
			this.picker.setStyle('cursor', 'move');
		}

		if(Browser.Engine.trident) this.shim();

		return this;
	},

	close: function(e, force) {
		if (!document.id(this.picker)) return;
		if($type(e) != 'event') force = true;
		var clickOutside = e && e.target != this.picker && !this.picker.hasChild(e.target) && e.target != this.visual;
		if (force || clickOutside) {
			if (this.options.useFadeInOut) {
				this.picker.set('tween', { duration: this.options.animationDuration / 2, onComplete: this.destroy.bind(this) }).tween('opacity', 1, 0);
			} else {
				this.destroy();
			}
		}

		return this;
	},

	// Protected/Private methods

	shim: function() {
		var coords = this.picker.setStyle('zIndex', 1000).getCoordinates();
		var frame = this.frame = new Element('iframe', {
			src: 'javascript:false;document.write("");',
			styles: {
				position: 'absolute',
				zIndex: 999,
				height: coords.height, width: coords.width,
				left: coords.left, top: coords.top
			}
		}).inject(document.body);
		this.frame.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';

		this.addEvent('close', function() {frame.destroy()});

		if(this.dragger) {
			this.dragger.addEvent('drag', function() {
				var coords = this.picker.getCoordinates();
				frame.setStyles({left: coords.left, top: coords.top});
			}.bind(this));
		}
	},

	position: function(p) {
		var w = window.getSize(),
			s = window.getScroll(),
			d = this.picker.getSize(),
			max_y = (w.y + s.y) - d.y,
			max_x = (w.x + s.x) - d.x,
			i = this.input.getCoordinates();

		if(p.x > max_x) p.x = i.right - this.options.positionOffset.x - d.x;
		if(p.y > max_y) p.y = i.top - this.options.positionOffset.y - d.y;

		this.picker.setStyles({left: p.x, top: p.y});
	},

	render: function(fx) {
		if (!this.picker) {
			this.constructPicker();
		} else {
			// swap contents so we can fill the newContents again and animate
			var o = this.oldContents;
			this.oldContents = this.newContents;
			this.newContents = o;
			this.newContents.empty();
		}

		// remember current working date
		var startDate = new Date(this.d.getTime());

		// intially assume both left and right are allowed
		this.limit = { right: false, left: false };

		// render! booty!
		if (this.mode == 'decades') {
			this.renderDecades();
		} else if (this.mode == 'year') {
			this.renderYear();
		} else if (this.mode == 'time') {
			this.renderTime();
			this.limit = { right: true, left: true }; // no left/right in timeview
		} else {
			this.renderMonth();
		}

		this.picker.getElement('.previous').setStyle('visibility', this.limit.left ? 'hidden' : 'visible');
		this.picker.getElement('.next').setStyle('visibility', this.limit.right ? 'hidden' : 'visible');
		this.picker.getElement('.titleText').setStyle('cursor', this.allowZoomOut() ? 'pointer' : 'default');

		// restore working date
		this.d = startDate;

		// if ever the opacity is set to '0' it was only to have us fade it in here
		// refer to the constructPicker() function, which instantiates the picker at opacity 0 when fading is desired
		if (this.picker.getStyle('opacity') == 0) {
			this.picker.tween('opacity', 0, 1);
		}

		// animate
		if (fx) this.fx(fx);
	},

	fx: function(fx) {
		if (fx == 'right') {
			this.oldContents.setStyles({ left: 0, opacity: 1 });
			this.newContents.setStyles({ left: this.bodysize.x, opacity: 1 });
			this.slider.setStyle('left', 0).tween('left', 0, -this.bodysize.x);
		} else if (fx == 'left') {
			this.oldContents.setStyles({ left: this.bodysize.x, opacity: 1 });
			this.newContents.setStyles({ left: 0, opacity: 1 });
			this.slider.setStyle('left', -this.bodysize.x).tween('left', -this.bodysize.x, 0);
		} else if (fx == 'fade') {
			this.slider.setStyle('left', 0);
			this.oldContents.setStyle('left', 0).set('tween', { duration: this.options.animationDuration / 2 }).tween('opacity', 1, 0);
			this.newContents.setStyles({ opacity: 0, left: 0}).set('tween', { duration: this.options.animationDuration }).tween('opacity', 0, 1);
		}
	},

	constructPicker: function() {
		this.picker = new Element('div', { 'class': this.options.pickerClass }).inject(document.body);
		if (this.options.useFadeInOut) {
			this.picker.setStyle('opacity', 0).set('tween', { duration: this.options.animationDuration });
		}

		var h = new Element('div', { 'class': 'header' }).inject(this.picker);
		var titlecontainer = new Element('div', { 'class': 'title' }).inject(h);
		new Element('div', { 'class': 'previous' }).addEvent('click', this.previous.bind(this)).set('text', '«').inject(h);
		new Element('div', { 'class': 'next' }).addEvent('click', this.next.bind(this)).set('text', '»').inject(h);
		new Element('div', { 'class': 'closeButton' }).addEvent('click', this.close.bindWithEvent(this, true)).set('text', 'x').inject(h);
		new Element('span', { 'class': 'titleText' }).addEvent('click', this.zoomOut.bind(this)).inject(titlecontainer);

		var b = new Element('div', { 'class': 'body' }).inject(this.picker);
		this.bodysize = b.getSize();
		this.slider = new Element('div', { styles: { position: 'absolute', top: 0, left: 0, width: 2 * this.bodysize.x, height: this.bodysize.y }})
					.set('tween', { duration: this.options.animationDuration, transition: Fx.Transitions.Quad.easeInOut }).inject(b);
		this.oldContents = new Element('div', { styles: { position: 'absolute', top: 0, left: this.bodysize.x, width: this.bodysize.x, height: this.bodysize.y }}).inject(this.slider);
		this.newContents = new Element('div', { styles: { position: 'absolute', top: 0, left: 0, width: this.bodysize.x, height: this.bodysize.y }}).inject(this.slider);
	},

	renderTime: function(){
		var container = new Element('div', { 'class': 'time' }).inject(this.newContents);

		this.picker.getElement('.titleText').set('text', this.options.timePickerOnly ? this.options.selectTimeTitle : this.d.format('%d %B, %Y'));

		new Element('input', { type: 'text', 'class': 'hour', 'title': MooTools.lang.get('DatePicker', 'use_mouse_wheel')})
			.set('value', this.leadZero(this.d.getHours()))
			.addEvents({
				click: function(e) {
					e.target.focus();
					e.stop();
				}.bind(this),
				mousewheel: function(e) {
					var i = e.target, v = i.get('value').toInt();
					i.focus();
					if (e.wheel > 0) {
						v = (v < 23) ? v + 1 : 0;
					} else {
						v = (v > 0) ? v - 1 : 23;
					}
					i.set('value', this.leadZero(v));
					e.stop();
				}.bind(this)
			})
			.set('maxlength', 2)
			.inject(container);

		new Element('input', { type: 'text', 'class': 'minutes', 'title': MooTools.lang.get('DatePicker', 'use_mouse_wheel') })
			.set('value', this.leadZero( (this.d.getMinutes()/this.options.timeWheelStep).round() * this.options.timeWheelStep ))
			.addEvents({
				click: function(e) {
					e.target.focus();
					e.stop();
				}.bind(this),
				mousewheel: function(e) {
					var i = e.target, v = i.get('value').toInt();
					i.focus();
					if (e.wheel > 0) {
						v = (v < 59) ? v + this.options.timeWheelStep : 0;
					} else {
						v = (v > 0) ? v - this.options.timeWheelStep : (60-this.options.timeWheelStep);
					}
					if (v == 60) v = 0;

					i.set('value', this.leadZero(v));
					e.stop();
				}.bind(this)
			})
			.set('maxlength', 2)
			.inject(container);

		new Element('div', { 'class': 'separator' }).set('text', ':').inject(container);

		new Element('input', { type: 'submit', value: this.options.timeConfirmButton, 'class': 'ok' })
			.addEvents({
				click: function(e) {
					e.stop();
					this.select($merge(this.d.toObject(), { hours: this.picker.getElement('.hour').get('value').toInt(), minutes: this.picker.getElement('.minutes').get('value').toInt() }));
				}.bind(this)
			})
			.set('maxlength', 2)
			.inject(container);
	},

	renderMonth: function() {
		var month = this.d.getMonth();

		this.picker.getElement('.titleText').set('text', this.options.months[month] + ' ' + this.d.getFullYear());

		this.d.setDate(1);
		while (this.d.getDay() != this.options.startDay) {
			this.d.setDate(this.d.getDate() - 1);
		}

		var container = new Element('div', { 'class': 'days' }).inject(this.newContents);
		var titles = new Element('div', { 'class': 'titles' }).inject(container);
		var d, i, classes, e, weekcontainer;

		for (d = this.options.startDay; d < (this.options.startDay + 7); d++) {
			new Element('div', { 'class': 'title day day' + (d % 7) }).set('text', this.options.days[(d % 7)].substring(0,this.options.dayShort)).inject(titles);
		}

		var available = false;
		var t = this.today.toDateString();
		var currentChoice = Date.fromObject(this.choice).toDateString();

		for (i = 0; i < 42; i++) {
			classes = [];
			classes.push('day');
			classes.push('day'+this.d.getDay());
			if (this.d.toDateString() == t) classes.push('today');
			if (this.d.toDateString() == currentChoice) classes.push('selected');
			if (this.d.getMonth() != month) classes.push('otherMonth');

			if (i % 7 == 0) {
				weekcontainer = new Element('div', { 'class': 'week week'+(Math.floor(i/7)) }).inject(container);
			}

			e = new Element('div', { 'class': classes.join(' ') }).set('text', this.d.getDate()).inject(weekcontainer);
			if (this.limited('date')) {
				e.addClass('unavailable');
				if (available) {
					if(month == this.d.getMonth() || this.d.getDate() == 1) {
						this.limit.right = true;
					}
				} else {
					this.limit.left = true;
				}
			} else {
				available = true;
				e.addEvent('click', function(e, d) {
					if (this.options.timePicker) {
						this.d.setDate(d.day);
						this.d.setMonth(d.month);
						this.mode = 'time';
						this.render('fade');
					} else {
						this.select(d);
					}
				}.bindWithEvent(this, { day: this.d.getDate(), month: this.d.getMonth(), year: this.d.getFullYear() }));
			}
			this.d.setDate(this.d.getDate() + 1);
		}
		if (!available) this.limit.right = true;
	},

	renderYear: function() {
		var month = this.today.getMonth();
		var thisyear = this.d.getFullYear() == this.today.getFullYear();
		var selectedyear = this.d.getFullYear() == this.choice.year;

		this.picker.getElement('.titleText').set('text', this.d.getFullYear());
		this.d.setMonth(0);
		if (this.options.minDate) {
			this.d.decrement('month',1)
			this.d.set('date',this.d.get('lastdayofmonth'));
			if (this.limited('month')) {
				this.limit.left = true;
			}
			this.d.increment('month',1)
		}
		this.d.set('date',this.d.get('lastdayofmonth'))
		var i, e;
		var available = false;
		var container = new Element('div', { 'class': 'months' }).inject(this.newContents);

		for (i = 0; i <= 11; i++) {
			e = new Element('div', { 'class': 'month month'+(i+1)+(i == month && thisyear ? ' today' : '')+(i == this.choice.month && selectedyear ? ' selected' : '') })
			.set('text', this.options.monthShort ? this.options.months[i].substring(0, this.options.monthShort) : this.options.months[i]).inject(container);

			if (this.limited('month')) {
				e.addClass('unavailable');
				if (available) {
					this.limit.right = true;
				} else {
					this.limit.left = true;
				}
			} else {
				available = true;
				e.addEvent('click', function(e, d) {
					this.d.setDate(1);
					this.d.setMonth(d);
					this.mode = 'month';
					this.render('fade');
				}.bindWithEvent(this, i));
			}
			this.d.increment('month',1)
			this.d.set('date',this.d.get('lastdayofmonth'))
		}
		if (!available) this.limit.right = true;
	},

	renderDecades: function() {
		// start neatly at interval (eg. 1980 instead of 1987)
		while (this.d.getFullYear() % this.options.yearsPerPage > 0) {
			this.d.setFullYear(this.d.getFullYear() - 1);
		}

		this.picker.getElement('.titleText').set('text', this.d.getFullYear() + '-' + (this.d.getFullYear() + this.options.yearsPerPage - 1));

		var i, y, e;
		var available = false;
		var container = new Element('div', { 'class': 'years' }).inject(this.newContents);

		if (this.options.minDate && this.d.getFullYear() <= this.options.minDate.getFullYear()) {
			this.limit.left = true;
		}

		for (i = 0; i < this.options.yearsPerPage; i++) {
			y = this.d.getFullYear();
			e = new Element('div', { 'class': 'year year' + i + (y == this.today.getFullYear() ? ' today' : '') + (y == this.choice.year ? ' selected' : '') }).set('text', y).inject(container);

			if (this.limited('year')) {
				e.addClass('unavailable');
				if (available) {
					this.limit.right = true;
				} else {
					this.limit.left = true;
				}
			} else {
				available = true;
				e.addEvent('click', function(e, d) {
					this.d.setFullYear(d);
					this.mode = 'year';
					this.render('fade');
				}.bindWithEvent(this, y));
			}
			this.d.setFullYear(this.d.getFullYear() + 1);
		}
		if (!available) {
			this.limit.right = true;
		}
		if (this.options.maxDate && this.d.getFullYear() >= this.options.maxDate.getFullYear()) {
			this.limit.right = true;
		}
	},

	limited: function(type) {
		var cs = this.options.minDate;
		var ce = this.options.maxDate;
		if (!cs && !ce) return false;

		switch (type) {
			case 'year':
				return (cs && this.d.getFullYear() < this.options.minDate.getFullYear()) || (ce && this.d.getFullYear() > this.options.maxDate.getFullYear());

			case 'month':
				// todo: there has got to be an easier way...?
				var ms = ('' + this.d.getFullYear() + this.leadZero(this.d.getMonth())).toInt();
				return cs && ms < ('' + this.options.minDate.getFullYear() + this.leadZero(this.options.minDate.getMonth())).toInt()
					|| ce && ms > ('' + this.options.maxDate.getFullYear() + this.leadZero(this.options.maxDate.getMonth())).toInt()

			case 'date':
				return (cs && this.d < this.options.minDate) || (ce && this.d > this.options.maxDate);
		}
	},

	allowZoomOut: function() {
		if (this.mode == 'time' && this.options.timePickerOnly) return false;
		if (this.mode == 'decades') return false;
		if (this.mode == 'year' && !this.options.yearPicker) return false;
		return true;
	},

	zoomOut: function() {
		if (!this.allowZoomOut()) return;
		if (this.mode == 'year') {
			this.mode = 'decades';
		} else if (this.mode == 'time') {
			this.mode = 'month';
		} else {
			this.mode = 'year';
		}
		this.render('fade');
	},

	previous: function() {
		if (this.mode == 'decades') {
			this.d.setFullYear(this.d.getFullYear() - this.options.yearsPerPage);
		} else if (this.mode == 'year') {
			this.d.setFullYear(this.d.getFullYear() - 1);
		} else if (this.mode == 'month') {
			this.d.setDate(1);
			this.d.setMonth(this.d.getMonth() - 1);
		}
		this.render('left');
		this.fireEvent('previous');
	},

	next: function() {
		if (this.mode == 'decades') {
			this.d.setFullYear(this.d.getFullYear() + this.options.yearsPerPage);
		} else if (this.mode == 'year') {
			this.d.setFullYear(this.d.getFullYear() + 1);
		} else if (this.mode == 'month') {
			this.d.setDate(1);
			this.d.setMonth(this.d.getMonth() + 1);
		}
		this.render('right');
		this.fireEvent('next');
	},

	destroy: function() {
		this.picker.destroy();
		this.picker = null;
		this.fireEvent('close');
	},

	select: function(values) {
		this.choice = $merge(this.choice, values);
		var d = Date.fromObject(this.choice);

		this.input.set('value', d.format(this.options.format))
			.store('datepicker:value',d);
		this.fireEvent('select', d);

		this.close(null, true);
	},

	leadZero: function(v) {
		return v < 10 ? '0'+v : v;
	}

});


Date.implement({

	toObject: function() {
		return {
			year: this.getFullYear(),
			month: this.getMonth(),
			day: this.getDate(),
			hours: this.getHours(),
			minutes: this.getMinutes(),
			seconds: this.getSeconds()
		};
	},

	isValid: function(){
		return !isNaN(this);
	}

});

Date.extend({

	fromObject: function(values) {
		values = values || {};
		var d = new Date();
		d.setDate(1);
		['year', 'month', 'day', 'hours', 'minutes', 'seconds'].each(function(type) {
			var v = values[type];
			if (!v && v !== 0) return;
			switch (type) {
				case 'day': d.setDate(v); break;
				case 'month': d.setMonth(v); break;
				case 'year': d.setFullYear(v); break;
				case 'hours': d.setHours(v); break;
				case 'minutes': d.setMinutes(v); break;
				case 'seconds': d.setSeconds(v); break;
			}
		});
		return d;
	}

});


/**
 * Translation
 *
 */
MooTools.lang.set('en-US', 'DatePicker', {
	select_a_time: 'Select a time',
	use_mouse_wheel: 'Use the mouse wheel to quickly change value',
	time_confirm_button: 'OK'
});

MooTools.lang.set('nl-NL', 'DatePicker', {
	select_a_time: 'Selecteer een tijd',
	use_mouse_wheel: 'Gebruik uw scrollwiel om door de tijd te scrollen',
	time_confirm_button: 'OK'
});

MooTools.lang.set('cs-CZ', 'DatePicker', {
	select_a_time: 'Vyberte čas',
	use_mouse_wheel: 'Použijte kolečko myši k rychlé změně hodnoty',
	time_confirm_button: 'Potvrď'
});


String.implement({
	'toTitleCase': function() {
		var A = this.split(' '), B = [];
		for (var i = 0; A[i] !== undefined; i++) {
			B[B.length] = A[i].substr(0, 1).toUpperCase() + A[i].substr(1);
		}
		return B.join(' ');
	}
})

// JavaScript Document
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


var visibleDiv = $("headerimg1");

function toggle_header(newSrc){

    
    if(visibleDiv == $("headerimg1")){

        $("himage2").src = newSrc;

		$("headerimg1").set('tween', {duration: 'long'});
		$("headerimg2").set('tween', {duration: 'long'});

        $("headerimg1").fade(0);

        $("headerimg2").fade(1);

        visibleDiv = $("headerimg2");

    }else{

        $("himage1").src = newSrc;

		$("headerimg1").set('tween', {duration: 'long'});
		$("headerimg2").set('tween', {duration: 'long'});
        $("headerimg1").fade(1);

        $("headerimg2").fade(0);
        visibleDiv = $("headerimg1");

    }
	
    
    $('headerquote' + currlatest).setStyles({
    	display: 'none',
    	opacity: 0
    });
    currlatest = currlatest + 1;
    if(currlatest == 8)
    	currlatest = 1;
    	
    $('headerquote' + currlatest).setStyles({
    	display: 'block',
    	opacity: 0
    });
    $('headerquote' + currlatest).fade(1);
    

    
    /*
    if(newSrc == '/design/imgs/headers/Faculty_01.jpg' || newSrc == '/design/imgs/headers/Faculty_04.jpg')
    	$('headerimgcaption').set('html', 'Faculty of Education, Cambridge University');
    if(newSrc == '/design/imgs/headers/kings_college_chapel.jpg' )
    	$('headerimgcaption').set('html', 'King\'s College Chapel, Cambridge');
    if(newSrc == '/design/imgs/headers/radcliffe_camera.jpg' )
    	$('headerimgcaption').set('html', 'Radcliffe Camera, Oxford University ');
    if(newSrc == '/design/imgs/headers/gardenold.jpg' )
    	$('headerimgcaption').set('html', 'Faculty of Education, Cambridge University');
    if(newSrc == '/design/imgs/headers/introplate.jpg' )
    	$('headerimgcaption').set('html', 'Department of Education, Oxford University ');
	*/
}

           

       
function rotate_header()
{
	toggle_header(WEB_ROOT + 'design/imgs/headers/' + headerarray[currquote]);
	currquote = currquote + 1;
	if(currquote == 6)
		currquote = 0;
}

FancyUpload2.File.implement({
	render: function() {
		if (this.invalid) {
			if (this.validationError) {
				var msg = MooTools.lang.get('FancyUpload', 'validationErrors')[this.validationError] || this.validationError;
				this.validationErrorMessage = msg.substitute({
					name: this.name,
					size: Swiff.Uploader.formatUnit(this.size, 'b'),
					fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'),
					fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'),
					fileListMax: this.base.options.fileListMax || 0,
					fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b')
				});
			}
			this.remove();
			return;
		}
		
		this.addEvents({
			'start': this.onStart,
			'progress': this.onProgress,
			'complete': this.onComplete,
			'error': this.onError,
			'remove': this.onRemove
		});
		
		this.info = new Element('span', {'class': 'file-info'});
		this.element = new Element('li', {'class': 'file'}).adopt(
			new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}),
			new Element('a', {
				'class': 'file-remove',
				href: '#',
				html: MooTools.lang.get('FancyUpload', 'remove'),
				title: MooTools.lang.get('FancyUpload', 'removeTitle'),
				events: {
					click: function() {
						this.remove();
						return false;
					}.bind(this)
				}
			}),
			new Element('span', {'class': 'file-name', 'html': MooTools.lang.get('FancyUpload', 'fileName').substitute(this)}),
			this.info,
			new Element('div', {'class': 'text'}).adopt(
				new Element('label', {'html': 'Caption'}),
				new Element('input', {'class': 'caption', 'name': 'caption[]', 'type': 'text'})
			)
		).inject(this.base.list);
	},
	
	onStart: function() {
/*		var value = this.element.getElement('input.caption').get('value');
		this.base.setOptions({
			data: value
		});*/
	}
});

var Crud = new Class({
	Implements: Events,
	'initialize': function(element) {
		//Elements
		this.element = $(element);
		this.messageLog = $(this).getElement('.errorMessage');
		var self = this;
		//Classes
		if(DatePicker) {
			var dates = $(this).getElements('[data-type=date]');
			if(dates.length) {
				for(i = 0; i <= dates.length - 1; i++) {
					new DatePicker(dates[i], {
						'draggable': false,
						'onSelect': function(date) {
							this.input.set('value', date.format(this.options.format));
							self.validate(this.input);
						}
					});
				}
			}
		}
		
		//Events
		$(this).getElement('.checkAll').addEvent('click', function() {
			$$('.checkRow').set('checked', this.checked);
		});
	
		$(this).getElement('.updateGroup').addEvent('click', function(event) {
			event.stop();
			this.updateGroup(event.target);
		}.bind(this));
		
		$(this).getElement('.deleteGroup').addEvent('click', function(event) {
			event.stop();
			this.deleteGroup(event.target);
		}.bind(this));
		
		$(this).getElement('.createGroup').addEvent('click', function(event) {
			event.stop();
			this.log("Feature currently disabled");
			//this.createGroup(event.target);
		}.bind(this));
		
		if(Browser.Engine.trident) {
			$(this).getElements('.data').addEvent('change', function(event) {
				this.validate(event.target);
			}.bind(this));
		}
		else {
			$(this).addEvent('change:relay(.data)', function(event, element) {
				this.validate(element);
			}.bind(this));
		}

		$(this).addEvent('click:relay(textarea)', function(event, element) {
			element.addClass('popout').removeEvents('blur').addEvent('blur', function() {
				this.removeClass('popout');
			});
		});
		
		$(this).addEvent('click:relay(.data)', function(event, element) {
			this.showErrorMessage(element);
		}.bind(this));
		
		$(this).addEvent('click:relay(.create)', function(event, element) {
			event.stop();
			this.createRow(element);
		}.bind(this));
		
		$(this).addEvent('click:relay(.update)', function(event, element) {
			event.stop();
			this.updateRow(element);
		}.bind(this));
		
		$(this).addEvent('click:relay(.delete)', function(event, element) {
			event.stop();
			this.deleteRow(element);
		}.bind(this));
		
		//Actions
		this.validate($(this).getElements('.data'));
	},
	'toElement': function() {
		return this.element;
	},
	'validate': function(elements) {
		if($type(elements) === 'element') elements = [elements];
	
		elements.each(function(element, index) {
			var value = element.get('value'),
			attributes = element.getProperties('data-type', 'data-max-length', 'data-required'),
			error = '';
			
			if(attributes['data-required'] == 1 && value == '') {
				error = 'Cannot be empty';
			}
			else if(attributes['data-max-length'] < value.length) {
				error = "Cannot be longer than " + attributes['data-max-length'] + " characters";
			}
			else if(attributes['data-type'] === 'date') {

			}
				
			if(error !== '') {
				this.createErrorMessage(element, error);
			}
			else {
				this.deleteErrorMessage(element);
			}
		}.bind(this));
		return this;
	},
	'errorExists': function(elements) {
		if($type(elements) === 'element') elements = [elements];
		
		for(i = 0; i <= elements.length - 1; i++) {
			if(elements[i].get('data-error')) return true;
		}
		
		return false;
	},
	
	'createErrorMessage': function(element, message) {
		element.removeClass('valid').set('data-error', message).addClass('error');
		return this;
	},
	
	'deleteErrorMessage': function(element) {
		element.removeClass('error').erase('data-error').addClass('valid');
		return this;
	},
	
	'showErrorMessage': function(element) {
		this.log(element.get('data-error'));
		return this;
	},
	'log': function(message) {
		if(message) {
			this.messageLog.highlight()
		}
		this.messageLog.set('text', message);
		return this;
	},
	'createRow': function(element) {
		if(this.errorExists(element.getParent('tr').getElements('.data'))) {
			this.log('There are problems with some of the fields on this row');
			return false;
		}
		
		var parent = element.getParent('tr');
		var inputs = parent.getElements('.data');
		var request = {'data': [{}], 'ids': [parent.get('data-id')]};

		for(i = 0; i <= inputs.length - 1; i++) {
			var value = inputs[i].get('value');
			if(value === "NULL") value = null;
			request.data[0][inputs[i].get('data-name')] = value;
		}

		new Request.JSON({
			'url': element.get('href'),
			'data': request,
			'onFailure': function() {
				this.log("Could not contact server. Please contact an administrator.");
			}.bind(this),
			'onSuccess': function(response) {
				this.log(response.message);
				if(response.success) {
					var cloned = inputs.getParent().clone();
					
					if(Browser.Engine.trident) {
						cloned.addEvent('change', function(event) {
							this.validate(event.target);
						}.bind(this))
					}
					
					for(i = 0; i <= inputs.length - 1; i++) {
						cloned[i].getElements('.data').set('value', inputs[i].get('value'));
					}
					var href = WEB_ROOT + "request/" + $(this).get('data-name') + "/";
					var row = new Element("tr", { 'data-id': response.id }).adopt(
						new Element('td', {
							'html': "<input class='checkRow tiny' type='checkbox' />"
						}),
						cloned,
						new Element('td', {
							'html': "<a class='update tiny' title='Update' href='" + href + "update/" + response.id + "/'></a>"
						}),
						new Element('td', {
							'html': "<a class='delete tiny' title='Delete' href='" + href + "delete/" + response.id + "/'></a>"
						})
					)

					row.inject(element.getParent('tr'), 'after');
					inputs.set('value', '');
					this.validate(inputs);
				}
				else if(response.errors) {
					for(i = 0; i <= response.errors.length - 1; i++) {
						var el = $(response.errors[i].id).getElements("[data-name=" + response.errors[i].name + "]");
						this.createErrorMessage(el, response.errors[i].message);
					}
				}
			}.bind(this)
		}).send();
	},
	'updateRow': function(element) {
		if(this.errorExists(element.getParent('tr').getElements('.data'))) {
			this.log('There are problems with some of the fields on this row');
			return false;
		}

		var parent = element.getParent('tr');
		var inputs = parent.getElements('.data');
		var request = {'data': [{}], 'ids': [parent.get('data-id')]};
		for(i = 0; i <= inputs.length - 1; i++) {
			var value = inputs[i].get('value');
			if(value === "NULL") value = null;
			request.data[0][inputs[i].get('data-name')] = value;
		}

		new Request.JSON({
			'url': element.get('href'),
			'data': request,
			'onFailure': function() {
				this.log("Could not contact server. Please contact an administrator.");
			}.bind(this),
			'onSuccess': function(response) {
				this.log(response.message);
				if(response.errors) {
					for(i = 0; i <= response.errors.length - 1; i++) {
						var el = $(response.errors[i].id).getElements("[data-name=" + response.errors[i].name + "]");
						this.createErrorMessage(el, response.errors[i].message);
					}
				}
			}.bind(this)
		}).send();
	},
	'deleteRow': function(element) {
		new Request.JSON({
			'url': element.get('href'),
			'data': { 'ids': [element.getParent('tr').get('data-id')] },
			'onFailure': function() {
				this.log("Could not contact server. Please contact an administrator.");
			}.bind(this),
			'onSuccess': function(response) {
				this.log(response.message);
				if(response.success) {
					element.getParent('tr').destroy();
				}
			}.bind(this)
		}).send();
	},
	'updateGroup': function(element) {
		var ids = $(this).getElements('.checkRow:checked').get('value');
		if(!ids.length) {
			this.log("No rows are checked");
			return false;
		}
		
		var parents = $(this).getElements('.checkRow:checked').getParent('tr');
		var inputs = parents.getElements('.data');
		for(i = 0; i <= inputs.length - 1; i++) {
			if(this.errorExists(inputs[i])) {
				this.log('There are problems with some of the fields in selected rows');
				return false;
			}
		}
		var request = {'data': [], 'ids': ids};
		
		for(i = 0; i <= inputs.length - 1; i++) {
			request.data[i] = {};
			for(j = 0; j <= inputs[i].length - 1; j++) {
				var value = inputs[i][j].get('value');
				if(value === "NULL") value = null;
				request.data[i][inputs[i][j].get('data-name')] = value;
			}
		}
		
		new Request.JSON({
			'url': element.get('href'),
			'data': request,
			'onFailure': function() {
				this.log("Could not contact server. Please contact an administrator.");
			}.bind(this),
			'onSuccess': function(response) {
				this.log(response.message);
				if(response.errors) {
					for(i = 0; i <= response.errors.length - 1; i++) {
						var el = $(response.errors[i].id).getElements("[data-name=" + response.errors[i].name + "]");
						this.createErrorMessage(el, response.errors[i].message);
					}
				}
			}.bind(this)
		}).send();
	},
	'deleteGroup': function(element) {
		var parents = $(this).getElements('.checkRow:checked').getParent('tr');
		var ids = parents.get('data-id');

		if(!ids.length) {
			this.log("No rows are checked");
			return false;
		}
		
		new Request.JSON({
			'url': element.get('href'),
			'data': { 'ids': ids },
			'onFailure': function() {
				this.log("Could not contact server. Please contact an administrator.");
			}.bind(this),
			'onSuccess': function(response) {
				this.log(response.message);
				if(response.success) {
					parents.destroy();
				}
			}.bind(this)
		}).send();
	},
});

//var headerarray = ['Faculty_01.jpg','kings_college_chapel.jpg', 'Faculty_04.jpg', 'radcliffe_camera.jpg', 'gardenold.jpg', 'introplate.jpg'];
var headerarray = ['01.jpg','02.jpg', '03.jpg', '04.jpg', '05.jpg', '06.jpg'];
var currquote = 0;
var currlatest = 1;
function ocef_init()
{
	//Left nav accordion
	var leftnavacc = new Accordion($$('.leftnav_togg'), $$('.leftnav_ele'));
	
	$$('.leftnav_togg').each(function (el){
		el.addEvent('click', function(e) { e.stop(); });
	});
	
	if($chk($('headerquote1')))
	{
    	$('headerquote1').setStyles({
	    	display: 'block',
	    	opacity: 1
	    });
	}
	rotate_header.periodical(3000);
	
	var crud = $$('.crud');
	if(crud.length) {
		for(i = 0; i <= crud.length - 1; i++) {
			new Crud(crud[i]);
		}
	}
	
	var gallery = $$('.gallery');
	if(gallery.length >= 1) {
		gallery[0].getElements("input[type=text]").each(function(item) {
			item.addEvent('keyup', function() {
				if(this.get('value') !== '') {
					this.getParent('.container').getElements('input[type=checkbox]').set('checked', true).set('disabled', true);
				}
				else {
					this.getParent('.container').getElements('input[type=checkbox]').set('checked', false).set('disabled', false);
				}
			});
			
		});
	}
	
	if($('upload')) { 	
		var up = new FancyUpload2($('demo-status'), $('demo-list'), {
			verbose: true,
			url: $('upload').action,
			path: WEB_ROOT + 'client/js/Swiff.Uploader.swf',
			typeFilter: {
				'Images (*.jpg, *.jpeg, *.png)': '*.jpg; *.jpeg; *.png'
			},
			target: 'demo-browse',
			fileListMax: 10,			
			// graceful degradation, onLoad is only called if all went well with Flash
			onLoad: function() {
				$('demo-status').removeClass('hide'); // we show the actual UI
				$('demo-fallback').destroy(); // ... and hide the plain form
				
				// We relay the interactions with the overlayed flash to the link
				this.target.addEvents({
					click: function() {
						return false;
					},
					mouseenter: function() {
						this.addClass('hover');
					},
					mouseleave: function() {
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function() {
						this.focus();
					}
				});
	
				// Interactions for the 2 other buttons
				
				$('demo-clear').addEvent('click', function() {
					up.remove(); // remove all files
					return false;
				});
	
				$('demo-upload').addEvent('click', function() {
					up.start(); // start upload
					return false;
				});
			},
			
			// Edit the following lines, it is your custom event handling
			
			/**
			 * Is called when files were not added, "files" is an array of invalid File classes.
			 * 
			 * This example creates a list of error elements directly in the file list, which
			 * hide on click.
			 */ 
			onSelectFail: function(files) {
				files.each(function(file) {
					new Element('li', {
						'class': 'validation-error',
						html: file.validationErrorMessage || file.validationError,
						title: MooTools.lang.get('FancyUpload', 'removeTitle'),
						events: {
							click: function() {
								this.destroy();
							}
						}
					}).inject(this.list, 'top');
				}, this);
			},
			
			/**
			 * This one was directly in FancyUpload2 before, the event makes it
			 * easier for you, to add your own response handling (you probably want
			 * to send something else than JSON or different items).
			 */
			onFileSuccess: function(file, response) {
				var json = new Hash(JSON.decode(response, true) || {});
				
				if (json.get('status') == '1') {
					file.element.addClass('file-success');
					file.info.set('html', '<strong>Image was uploaded:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px, <em>' + json.get('mime') + '</em>)');
				} else {
					file.element.addClass('file-failed');
					file.info.set('html', '<strong>An error occured:</strong> ' + (json.get('error') ? (json.get('error') + ' #' + json.get('code')) : response));
				}
	
				var id = json.get('id');			
				/*$$('#update .gallery').adopt(
					new Element('div', {'class': 'image'}).adopt(
						new Element('img', {
							'height': '113px', 
							'width': '113px', 
							'src': WEB_ROOT + 'design/imgs/videoPhotos/thumbnails/' + id
							}),
						new Element('input', 
					)
				);*/

			},
			
			/**
			 * onFail is called when the Flash movie got bashed by some browser plugin
			 * like Adblock or Flashblock.
			 */
			onFail: function(error) {
				switch (error) {
					case 'hidden': // works after enabling the movie and clicking refresh
						alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
						break;
					case 'blocked': // This no *full* fail, it works after the user clicks the button
						alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
						break;
					case 'empty': // Oh oh, wrong path
						alert('A required file was not found, please be patient and we fix this.');
						break;
					case 'flash': // no flash 9+ :(
						alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
				}
			},
			
			onBeforeStart: function() {
				var listSize = this.fileList.length;
				for (var i=0; i < listSize; i++){
					var caption = this.fileList[i].element.getElement('input.caption').get('value');

					var opts = $merge(this.options.data, {
						'video_id': video_id,
						'caption': caption
						});
					this.fileList[i].setOptions({'data' : opts});
					}
			}
		});
	}
	
	if($$('.jsRequired')) {
		$$('.jsRequired').setStyle('display', 'block');
	}
	if($$('.jsDisabled')) {
		$$('.jsDisabled').setStyle('display', 'none');
	}
}

window.addEvent('domready', ocef_init);
//window.addEvent('unload', function() { eraseCookie('PHPSESSID'); });

