
window.addEvent('domready', function () {
	new ClearField('fldSearch', ['search']);
	new ClearField('fldSideSearch', ['search']);
	new ClearField('fldUsername', ['email address']);
	new ClearField('fldUsername2', ['email address']);
	new ClearField('fldPassword', ['password']);
	new ClearField('fldKeywords', ['keyword(s)']);
	var hr = new HudRss();
	var hc = new HudController();
	var hs = new HudSlider();

	// archive selector
	var es = $$('#archive-selector select', '#archive-splash-year-selector select').each(function (e) {
		new ArchiveSwitcher(e, top.baseUrl, top.siteUrl);
	});

	var labels = $$('label.replaceCB');
	if (labels) {
		labels.addClass('replaced');
		labels.each(function (label) {
			new PseudoCheckbox(label);
		});
	}

	$$('a.scroll-top-simple').each(function (e) {
		e.addEvent('click', function (evt) {
			evt.stop();
			new Fx.Scroll(window).toTop();
		});
	});

	$$('a.scroll-top').each(function (e) {
		e.addEvent('click', function (evt) {
			evt.stop();
			new Fx.Scroll(window).toTop();
			if (hc) {
				hc.open();
			}
		});
	});
	$$('a.faq-toplink', '.faq-questions a').each(function (e) {
		e.addEvent('click', function (evt) {
			evt.stop();
			var el = $(evt.target);
			var target = el.get('href');
			target = target.substr(1);
			target = document.getElement('a[name=' + target + ']');
			if (target) {
				var parent = target.getParent();
				var offset = {
					x: 0,
					y: 0
				};
				if (parent.hasClass('faq-faq')) {
					$$('.faq-selected').destroy();
					new Element('div', {'class': 'faq-selected'}).inject(parent);
					new Fx.Scroll(window, {offset: {x: 0, y: -30}}).toElement(target);
					offset.y = -60;
				}
				new Fx.Scroll(window, {offset: offset}).toElement(target);
			}
			else {
				new Fx.Scroll(window).toTop();
			}
		});
	});

	$$('a.download-denied').each(function (e) {
		e.addEvent('click', function (evt) {
			evt.stop();
			var el = $$('.download-denied-msg').pop();
			if (!el) {
				return;
			}
			el.setStyles({
				opacity: 0,
				visibility: 'hidden',
				display: 'block'
			})
			var fx = new Fx.Tween(el);
			fx.start('opacity', [0, 1]);
		});
	});

	var loginPanel = $('login-login');
	var passwordPanel = $('login-forgotpass');
	if (loginPanel && passwordPanel) {
		var elShowLogin = loginPanel.getElement('.login-options a');
		var elShowPassword = passwordPanel.getElement('.login-options a');
		elShowLogin.addEvent('click', function (evt) {
			evt.stop();
			loginPanel.toggleClass('hidden');
			passwordPanel.toggleClass('hidden');
		});
		elShowPassword.addEvent('click', function (evt) {
			evt.stop();
			loginPanel.toggleClass('hidden');
			passwordPanel.toggleClass('hidden');
		});
	}

	new Fx.SmoothScroll({
    	links: '.smooth-scroll',
    	wheelStops: false,
		offset: {
			x: -372
		}
	});

	$$('a[rel=external]').set('target', '_blank');

	$$('input.image-button').each(function (e) {
		e.addEvent('mouseover', function () {
			var src = e.get('src');
			var ext = src.substring(src.length - 4);
			src = src.substring(0, src.length - ext.length);
			src = src + '-over' + ext;
			e.set('src', src);
		});
		e.addEvent('mouseout', function () {
			var src = e.get('src');
			var ext = src.substring(src.length - 4);
			src = src.substring(0, src.length - ext.length - 5);
			src += ext;
			e.set('src', src);
		});
	});

	//search criteria
	new CriteriaSelector({fieldIdBaseName: 'v'});

	$$('table.trends').each(function (e) {
		new TableLinks(e);
	});

	// multilingual pages
	var e = document.getElement('.lang-select select');
	if (e) {
		new LanguageSwitcher(e);
	}

	var e = $('box-out-strip');
	if (e && e.hasClass('box-out-strip-scroll')) {
		new StripScroller(e);
		var wd = new InlineWinnerDisplay();
		$$('.box-out-strip-items a').addEvent('click', wd.evtClick.bindWithEvent(wd));
	}

	$$('.year-selector select', '.search-awards select').each(function (e) {
		new PseudoSelect(e);
	})
});

var InlineWinnerDisplay = new Class({
	request: null,
	initialize: function () {
		this.request = new Request.HTML({
			data: 'view=entry-landing-inline',
			onSuccess: this.loaded.bind(this),
			onFailure: function () {
				alert('Request failed');
			}
		});
	},
	loaded: function (responseTree, responseElements, responseHTML, responseJavaScript) {
		var e = $('winner-display-content');
		e.empty();
		e.adopt(responseTree);

		var e = $('winner-display');
		e.setStyle('display', 'block');

	    e.getElements('a.smoothbox').each(function(el) {
	        el.onclick = TB_bind
	    });

		e.getElements('a.scroll-top-simple').each(function (el) {
			el.addEvent('click', function (evt) {
				evt.stop();
				new Fx.Scroll(window).toTop();
			});
		});

		$exec(responseJavaScript);

		var e = $('box-out-strip');
		new Fx.Scroll(window).toElement(e);
	},
	load: function (url) {
		this.request.setOptions({
			url: url
		});
		this.request.send();
	},
	evtClick: function (evt) {
		evt.stop();
		var e = $(evt.target);
		this.load(e.get('href'));
	}
});

var StripScroller = new Class({
	container: null,
	inner: null,
	next: null,
	prev: null,
	items: [],
	current: 0,
	visible: 5,
	width: 0,
	initialize: function (element) {
		this.container = $(element);
		this.inner = this.container.getElement('div.box-out-strip-items');
		this.next = this.container.getElement('a.next');
		this.prev = this.container.getElement('a.prev');

		this.next.addEvent('click', this.evtNext.bindWithEvent(this));
		this.prev.addEvent('click', this.evtPrev.bindWithEvent(this));

		// get the width of the last item including margins
		this.items = this.inner.getElements('li');
		var el = this.items.getLast();
		this.width = el.getSize().x + el.getStyle('margin-left').toInt() + el.getStyle('margin-right').toInt();
		this.inner.setStyle('width', this.width * this.items.length);
		this.setStage();
	},
	setStage: function () {
		this.next.setStyles({
			visibility: (this.current + this.visible >= this.items.length) ? 'hidden' : 'visible'
		});
		this.prev.setStyles({
			visibility: (this.current <= 0) ? 'hidden' : 'visible'
		});
		this.inner.setStyles({
			left: this.current * (0 - this.width)
		});
	},
	forward: function () {
		var i = this.current + 1;
		if (i + this.visible > this.items.lentgh) {
			return;
		}
		this.current++;
		this.setStage();
	},
	back: function () {
		var i = this.current - 1;
		if (i < 0) {
			return;
		}
		this.current--;
		this.setStage();
	},
	evtNext: function (evt) {
		evt.stop();
		this.forward();
	},
	evtPrev: function (evt) {
		evt.stop();
		this.back();
	}
});

var ArchiveSwitcher = new Class({
	element: null,
	options: [],
	baseUrl: '',
	siteUrl: '',
	initialize: function (e, baseUrl, siteUrl) {
		var options = [];
		e.getElements('option').each(function (o) {
			if (o.get('value')) {
				options.push(o.get('value'));
			}
		});

		this.baseUrl = baseUrl;
		this.siteUrl = siteUrl;
		this.options = options;
		this.select = new PseudoSelect(e);
		if (!this.options.length || !this.select) {
			return;
		}
		this.select.addEvent('change', this.changed.bind(this));
	},
	changed: function () {
		var value = this.select.get('value');
		if (!value) {
			return;
		}
		var url = this.baseUrl + '/' + value;
		if (url != this.siteUrl) {
			window.location = url;
		}
	}
});

var LanguageSwitcher = new Class({
	current: '',
	prefix: 'lang-',
	hiddenClass: 'hidden',
	element: null,
	options: [],
	initialize: function (e) {
		var options = [];
		e.getElements('option').each(function (o) {
			if (o.get('value')) {
				options.push(o.get('value'));
			}
		});

		this.options = options;
		this.select = new PseudoSelect(e);
		if (!this.options.length || !this.select) {
			return;
		}
		this.select.addEvent('change', this.changed.bind(this));
		this.current = this.options[0];
	},
	changed: function () {
		var value = this.select.get('value');
		if (!value) {
			return;
		}
		$$('.' + this.prefix + this.current).toggleClass(this.hiddenClass);
		this.current = value;
		$$('.' + this.prefix + this.current).toggleClass(this.hiddenClass);
	}
});

var TableLinks = new Class({
	initialize: function (el) {
		el.getElements('tbody tr').each(function (e) {
			this.setup(e);
		}, this);
	},
	setup: function (tr) {
		tr.getElements('a').each(function (e) {
			e.addEvent('click', function (evt) {
				evt.stopPropagation();
			});
		});
		tr.addEvent('mouseenter', this.evtEnter.bindWithEvent(this, tr));
		tr.addEvent('mouseleave', this.evtLeave.bindWithEvent(this, tr));
		tr.addEvent('click', this.evtClick.bindWithEvent(this, tr));
	},
	evtEnter: function (evt, tr) {
		tr.addClass('hover');
	},
	evtLeave: function (evt, tr) {
		tr.removeClass('hover');
	},
	evtClick: function (evt, tr) {
		evt.stop();
		var a = tr.getElement('a');
		if (a) {
			window.location = a.get('href');
		}
	}
});

var PseudoCheckbox = new Class({
	Implements: [Options, Events],
	options: {},
	checkbox: null,
	initialize: function (label, options) {
		// make sure the label as a checkbox
		var cb = label.getElement('checkbox') || $(label.get('for'));
		if (!cb) {
			return;
		}
		this.setOptions(options);
		this.checkbox = cb;
		this.label = label;
		this.label.addEvent('click', this.mouseup.bind(this));

		if (this.checkbox.checked) {
			this.checkbox.checked = true;
			this.label.addClass('checked');
		}
	},
	mouseup: function (evt) {
		if (evt) {
			evt.stop();
		}
		if (this.checkbox.checked) {
			this.checkbox.checked = false;
			this.label.removeClass('checked');
			this.fireEvent('uncheck', [this]);
		}
		else {
			this.checkbox.checked = true;
			this.label.addClass('checked');
			this.fireEvent('check', [this]);
		}
	},
	get: function (key) {
		return this.checkbox.get(key);
	},
	check: function () {
		this.mouseup();
	},
	uncheck: function () {
		this.mouseup();
	}
});

var PseudoSelect = new Class({
	Implements: [Options, Events],
	element: null,
	toggler: null,
	input: null,
	list: null,
	options: [],
	open: false,
	evtClose: null,
	initialize: function(element) {
		if (!element) {
			return;
		}

		this.replaceSelect(element);

		if (!this.element || !this.toggler || !this.input || !this.list || !this.options) {
			return;
		}

		this.open = false;
		this.list.setStyle('display', 'none');
		this.toggler.addEvent('mousedown', this.toggleClicked.bind(this));

		// populate the selected value
		var selected = this.list.getElement('.selected');
		if (!selected) {
			selected = this.options[0];
		}
		this.setSelected(selected);


		$(document.body).addEvent('mousedown', this.close.bind(this));

		// add option events
		this.options.each(function (option) {
			option.addEvent('click', this.optionClicked.bind(this));
		}, this);

		// fix the widths of the lists
		this.list.setStyles({
			display: 'block',
			visibility: 'hidden'
		});
		var width = this.toggler.getSize().x;

		var lis = this.options;
		var w = 0;
		this.options.each(function (option) {
			var size = option.getSize();
			w = (size.x > w) ? size.x : w;
		});
		var paddings = parseInt(lis[0].getStyle('paddingLeft')) + parseInt(lis[0].getStyle('paddingRight'));
		var borders = parseInt(this.list.getStyle('borderLeftWidth')) + parseInt(this.list.getStyle('borderRightWidth'));
		if (w < width) {
			w = width;
		}
		if (!isNaN(paddings)) {
			w -= paddings;
		}
		if (!isNaN(borders)) {
			w -= borders;
		}
		if (w > 0) {
			this.options.each(function (option) {
				option.setStyle('width', w);
			});
		}

		this.list.setStyles({
			display: 'none',
			visibility: ''
		});

		// add hover styles for IE6
		this.isIE6 = /MSIE\s6/.test(navigator.userAgent);
		if (this.isIE6) {
			this.options.each(function (option) {
				option.addEvent('mouseenter', function () { this.addClass('hover'); });
				option.addEvent('mouseleave', function () { this.removeClass('hover'); });
			});
		}

		this.element.set = this.set.bind(this);

		return this.element;
	},
	replaceSelect: function (select) {
		this.element = new Element('div', {
			'class': select.get('class')
		});
		this.element.addClass('pseudo-select');

		this.element.get = function (prop) {
			var property = Element.Properties.get(prop);
			var v = (property && property.get) ? property.get.apply(this.element, Array.slice(arguments, 1)) : this.element.getProperty(prop);
			return (v && $defined(v)) ? v : this.input.get(prop);
		}.bind(this);

		var value = select.get('value');

		this.input = new Element('input', {
			id: select.get('id'),
			type: 'hidden',
			name: select.get('name'),
			value: value
		}).inject(this.element);
		this.toggler = new Element('span').inject(this.element);
		this.label = new Element('em').inject(this.toggler);
		this.list = new Element('ul').inject(this.element);

		var label = '';
		select.getElements('option').each(function (option) {
			var li = new Element('li', {
				'class': option.get('class'),
				'html': option.get('text') + ' <span>' + option.value + '</span>'
			}).inject(this.list);
			this.options.push(li);
			if (option.value == value && !label) {
				li.addClass('selected');
				this.label.set('text', value);
			}
		}, this);

		// do the replacement
		if (select.getParent()) {
			this.element.replaces(select);
		}
	},
	toggleClicked: function (evt) {
		this.open = !this.open;
		this.list.setStyle('display', this.open ? 'block' : 'none');
		this.toggler.toggleClass('open');
	},
	optionClicked: function (evt) {
		var el = evt.target;
		if (!this.open || !el) {
			return false;
		}

		this.setSelected(el);

		this.toggleClicked();
	},
	setSelected: function (el) {
		if (!el) {
			return;
		}
		var value = el.getElement('span').get('text');

		var e = el.clone(true);
		e.getElement('span').destroy();
		var text = e.get('text');

		this.options.each(function (option) {
			this.element.removeClass(option.get('class'));
		}, this);
		this.element.addClass(el.get('class'));

		this.input.set('value', value);
		this.element.fireEvent('change');
		this.label.set('text', text);
	},
	close: function (evt) {
		if (this.open && !this.element.hasChild(evt.target)) {
			evt.stop();
			this.toggleClicked();
		}
	},
	set: function (prop, value) {
		if ($type(prop) == 'string' && prop == 'value') {
			this.options.each(function (option) {
				var val = option.getElement('span').get('text');
				if (val == value) {
					this.setSelected(option);
				}
			}, this);
			return this.element;
		}
		else {
			return this.element.set(arguments);
		}
	}
});

var CriteriaSelector = new Class({
	Implements: Options,
	rows: [],
	nextIndex: 1,
	themes: [],
	categories: [],
	values: [],
	row: null,
	options: {
		rowClass: 'criteria-row',
		fieldIdBaseName: 'criteria-value',
		btnAdd: {
			className: 'add',
			value: 'Add'
		},
		btnRemove: {
			className: 'remove',
			value: 'Remove'
		}
	},
	initialize: function(options) {
		this.setOptions(options);

		// get all the select lists for criteria
		var elements = $$('.' + this.options.rowClass + ' .criteria-field');
		if (elements && elements.length > 0) {
			var options = elements[0].getElements('option');
			options.each(function (option) {
				var field = option.get('value');
				var select = $('criteria-field-' + field);
				if (select) {
					this.values.push({
						field: field,
						select: select
					});
				}
			}, this);
		}

		//get all rows
		this.rows = $$('.' + this.options.rowClass);
		if (!this.rows.length) {
			return;
		}

		this.row = this.rows[0].clone();

		this.rows.each(function (el) {
			this.initRow(el);
		}, this);
		this.nextIndex = this.rows.length + 1;
	},
	initRow: function (el) {
		// check the field
		el.getElements('select').each(function (el) {
			new PseudoSelect(el);
		});

		var criteria = el.getElement('.criteria-field');
		var input = el.getElement('.criteria-value');

		// sort out the fields to be displayed
		if (criteria.hasClass('ltgt')) {
			var e = el.getElement('.criteria-col-operator');
			if (e) {
				e.setStyle('display', 'block');
			}
			else {
				e = new Element('div', {
					'class': 'criteria-col-operator'
				}).inject(el.getElement('.criteria-col-field'), 'after');
				var select = new Element('select', {
					name: 'o[]'
				}).inject(e);
				new Element('option', {
					'value': 'gt',
					'text': 'Greater than'
				}).inject(select);
				new Element('option', {
					'value': 'lt',
					'text': 'Less than'
				}).inject(select);
				select = new PseudoSelect(select);
			}
			el.getElement('.criteria-col-value').addClass('criteria-col-value-short');
		}
		else {
			var e = el.getElement('.criteria-col-operator');
			if (e) {
				e.setStyle('display', 'none');
			}
			el.getElement('.criteria-col-value').removeClass('criteria-col-value-short');
		}

		var to_select = false;
		this.values.each(function (value) {
			if (value.field == criteria.get('value') && !to_select) {
				var select = value.select.clone(true, false);
				var options = select.getElements('option');
				select.set({
//					name: input.get('name'),
					name: this.options.fieldIdBaseName + '[]',
					id: input.get('id'),
					'class': input.get('class')
				});
				for (var i = 0; i < options.length; i++) {
					if (input.get('value') == options[i].get('value')) {
						select.selectedIndex = i;
						break;
					}
				}
				to_select = true;

				var p = input.getParent();
				p.empty();
				p.adopt(select);
				select = new PseudoSelect(select);
			}
		}, this);
		if (!to_select) {
			// put a text input in
			var text = new Element('input', {
				name: input.get('name'),
				id: input.get('id'),
				'class': input.get('class'),
				type: 'text',
				//value: input.get('value')
				value: (input.get('type') == 'text') ? input.get('value') : ''
			});
			text.removeClass('selected');
			text.removeClass('pseudo-select');
			var p = input.getParent().adopt(text);
			input.destroy();
		}

		criteria.removeEvents('change');
		criteria.addEvent('change', this.initRow.bind(this, el));


		// add the events
		var btnAdd = el.getElement('.' + this.options.btnAdd.className);
		btnAdd.removeEvents('click');
		btnAdd.addEvent('click', function (evt) {
			evt.stop();
			this.addRow(el);
		}.bindWithEvent(this));

		var btnRemove = el.getElement('.' + this.options.btnRemove.className);
		btnRemove.addEvent('click', function (evt) {
			evt.stop();
			this.removeRow(el);
		}.bindWithEvent(this));
	},
	addRow: function (el) {
		var row = this.row.clone();
		var input = row.getElement('.criteria-value');
		if (input) {
			input.setAttribute('id', this.options.fieldIdBaseName + this.nextIndex);
			input.value = '';
		}

		// get the current criteria value and set it in the cloned row
		var field = row.getElement('.criteria-field');
		var value = el.getElement('.criteria-field').get('value');
		if (field.nodeName == 'SELECT') {
			field.getElements('option').each(function (option, i) {
				if (option.get('value') == value) {
					option.set('selected', 'selected');
					field.selectedIndex = i;
				}
			});
		}

		row.inject(el, 'after');
		this.initRow(row);
		this.rows.push(row);

		// sort out the z-indexes for IE
		var i = this.rows.length + 1;
		$$('.' + this.options.rowClass).each(function (e) {
			e.setStyle('z-index', i--);
		});
	},
	removeRow: function(el) {
		if (this.rows.length < 2) {
			this.addRow(el);
		}
		this.rows.erase(el);
		el.destroy();
	}
});


var ClearField = new Class({
	element: null,
	nullvalues: [],
	cleared: false,
	initialValue : '',
	initialize: function(element, nullvalues){
		this.element = $(element);
		this.nullvalues = nullvalues || [];
		if (!this.element) {
			return;
		}

		this.initialValue = this.element.value;
		this.element.addEvent('focus', function() {
			this.clearDefault();
		}.bind(this));
		this.element.addEvent('blur', function() {
			this.setToDefault();
		}.bind(this));
	},
	getValue: function(actual) {
		var value = this.element.value;
		if (!actual) {
			var i = 0;
			while (i < this.nullvalues.length) {
				if (value == this.nullvalues[i]) {
					value = '';
					break;
				}
				i++;
			}
		}
		return value;
	},
	clearDefault: function() {
		if (this.element && !this.cleared) {
			this.element.value = '';
		}
		this.cleared = true;
	},
	setToDefault: function () {
		if (this.getValue(true) == '') {
			this.element.value = this.initialValue;
			this.cleared = false;
		}
	}
});

var HudRss = new Class({
	Implements: Options,
	all: null,
	user: null,
	options: {
		cookie: 'hud-rss'
	},
	initialize: function (options) {
		this.setOptions(options);
		this.all = $('rss-all');
		this.user = $('rss-user');
		if (!this.all || !this.user) {
			return;
		}
		$$('a.rss-show-all').addEvent('click', this.setAll.bindWithEvent(this));
		$$('a.rss-show-user').addEvent('click', this.setUser.bindWithEvent(this));

		if (Cookie.read(this.options.cookie) == 'all') {
			this.setAll();
		}
	},
	setAll: function (evt) {
		if (evt) {
			evt.stop();
		}
		Cookie.write(this.options.cookie, 'all', {'path': top.baseUrl + '/'});
		this.all.setStyle('display', 'block');
		this.user.setStyle('display', 'none');
	},
	setUser: function (evt) {
		if (evt) {
			evt.stop();
		}
		Cookie.write(this.options.cookie, 'user', {'path': top.baseUrl + '/'});
		this.all.setStyle('display', 'none');
		this.user.setStyle('display', 'block');
	}
});

var HudController = new Class({
	Implements: Options,
	options: {
		id: 'hud',
		toggleClass: 'hud-toggle',
		closeClass: 'closed',
		cookie: 'hud'
	},
	togglers: [],
	element: null,
	height: 0,
	fx: null,
	initialize: function (options) {
		this.setOptions(options);
		this.element = $(this.options.id);
		if (!this.element) {
			return false;
		}

		if (!this.isOpen()) {
			this.element.setStyles({
				position: 'absolute',
				top: -4000,
				display: 'block',
				height: 'auto'
			});
			this.height = this.element.getSize().y;
			this.element.setStyles({
				position: '',
				top: '',
				display: '',
				height: ''
			});
		}
		var fx = new Fx.Tween(this.element);
		fx.addEvent('complete', this.fxCompleted.bind(this));
		this.fx = fx;

		// set the action on all the togglers
		this.togglers = $$('.' + this.options.toggleClass);
		this.togglers.each(function (toggler) {
			toggler.addEvent('click', this.toggle.bind(this));
		}, this);
	},
	open: function () {
		if (this.isOpen()) {
			return;
		}
		Cookie.write(this.options.cookie, 'open', {'path': top.baseUrl + '/'});
		this.element.setStyles({
			height: 0
		});
		this.element.removeClass(this.options.closeClass);
		this.fx.start('height', this.height);
		this.togglers.addClass(this.options.toggleClass + '-open');
		this.togglers.removeClass(this.options.toggleClass + '-closed');
	},
	close: function () {
		if (!this.isOpen()) {
			return;
		}
		Cookie.write(this.options.cookie, 'closed', {'path': top.baseUrl + '/'});
		this.height = this.element.getSize().y;
		this.element.setStyles({
			height: this.height
		});
		this.element.addClass(this.options.closeClass);
		this.fx.start('height', 0);
		this.togglers.addClass(this.options.toggleClass + '-closed');
		this.togglers.removeClass(this.options.toggleClass + '-open');
	},
	toggle: function (evt) {
		if (evt) {
			evt.stop();
		}
		this.isOpen() ? this.close() : this.open();
	},
	isOpen: function () {
		return !this.element.hasClass(this.options.closeClass);
	},
	fxCompleted: function () {
		if (this.isOpen()) {
			this.element.setStyle('height', '');
		}
	}
});


var HudSlider = new Class({
	Implements: Options,
	container: null,
	inner: null,
	prev: null,
	next: null,
	span: null,
	itemsPerSection: 0,
	sectionWidth: 0,
	status: {
		start: 0,
		end: 0,
		total: 0,
		loaded: 0
	},
	options: {

	},
	initialize: function (options) {
		this.setOptions(options);

		// get all the elements
		this.container = document.getElement('.hud-library-container');
		this.inner = document.getElement('.hud-library-inner');

		// get the prev and next links
		this.btnPrev = document.getElement('li#vp a');
		this.btnNext = document.getElement('li#vm a');

		// get the text
		this.span = document.getElement('.library_additions span');

		if (!this.container || !this.inner || !this.btnPrev || !this.btnNext || !this.span) {
			// we need all the elements to be available
			return;
		}

		this.status = this.parseStatus(this.span.get('text'));
		if (this.status.total > this.status.loaded) {
			this.itemsPerSection = this.status.loaded;
		}
		this.updateButtons();
		if (!this.itemsPerSection) {
			// nowt to do with the current number on images
			return;
		}

		this.sectionWidth = this.inner.getSize().x;
		this.inner.setStyles({
			width: this.sectionWidth * Math.ceil(this.status.total / this.itemsPerSection),
			left: 0
		});

		this.btnNext.addEvent('click', this.next.bind(this));
		this.btnPrev.addEvent('click', this.prev.bind(this));
	},
	next: function (evt) {
		if (evt) {
			evt.stop();
		}

		if (this.status.end >= this.status.total) {
			return;
		}

		var p = Math.ceil(this.status.end / this.itemsPerSection) + 1;
		this.page(p);
	},
	prev: function (evt) {
		if (evt) {
			evt.stop();
		}

		if (this.status.start <= 1) {
			return;
		}

		var p = Math.ceil(this.status.end / this.itemsPerSection) - 1;
		this.page(p);
	},
	page: function (p) {
		var n = (p * this.itemsPerSection) > this.status.total ? this.status.total : p * this.itemsPerSection;
		if (this.status.loaded < n) {
			// load
			this.inner.adopt(this.getSection(p));
			this.status.loaded = n > this.status.loaded ? n : this.status.loaded;
		}
		this.status.start = ((p - 1) * this.itemsPerSection) + 1;
		this.status.end = n;

		this.inner.tween('left', -this.sectionWidth * (p - 1));
		this.updateButtons();
		this.updateStatus();
	},
	updateButtons: function () {
		this.btnNext.setStyle('visibility', (this.status.end >= this.status.total) ? 'hidden' : 'visible');
		this.btnPrev.setStyle('visibility', (this.status.end <= this.itemsPerSection) ? 'hidden' : 'visible');
	},
	updateStatus: function () {
		var str = this.status.start + ' to ' + this.status.end + ' of ' + this.status.total;
		this.span.set('text', str);
	},
	parseStatus: function (str) {
		var regex = /(\d+) to (\d+) of (\d+)/;
		var matches = regex.exec(str);
		if (matches) {
			return {
				start: parseInt(matches[1]),
				end: parseInt(matches[2]),
				total: parseInt(matches[3]),
				loaded: parseInt(matches[2])
			}
		}
		return {
			start: 0,
			end: 0,
			total: 0,
			loaded: 0
		}
	},
	getSection: function (p) {
		var el = new Element('ul');
		var n1 = (p - 1) * this.itemsPerSection;
		var n2 = p * this.itemsPerSection;

		var lis = this.inner.getElement('ul').getElements('li');
		var n = n2 > lis.length ? lis.length : n2;
		for (var i = n1; i < n; i++) {
			var li = $(lis[i]).clone();
			el.grab(li);
		}
		return el;
	}
});
