(function(){
	Object.extend(Form.Element.Methods, {
		resetInput: function (element) {
			element = $(element);
			if ($F(element) === $(element).defaultValue) {
				$(element).value = '';
			}
			
			return element;
		}
	});
	
	Element.addMethods();
	
	var clearForms = function () {
		var form_elements = $$('input[type=text]', 'textarea');
		form_elements.invoke('observe', 'focus', function () {
			this.resetInput();
		});
		
		form_elements.invoke('observe', 'blur', function () {
			if ($F(this).blank()) {
				this.value = this.defaultValue;
			}
		});
	};
	
	document.observe('dom:loaded',clearForms);
})();

Element.addMethods({
	reorder_list: function (element, column_count) {
		// this function fixes the display order of floated lists
		element = $(element);
		element.select('ul').invoke('remove');
		var old_list = $A(element.select('li')),
			new_list = $A(old_list);

		var limit = old_list.size();
		for (var i = 0, j = 0, k = 1; i < limit; i++) {
			if (j >= limit) {
				j = k;
				k++;
			}

			new_list[j] = $(old_list[i]).cloneNode(true);
			j = j + column_count;
		}

		element.update('');

		for (var i = 0; i < limit; i++) {
			element.insert({
				bottom: new_list[i]
			});
		}
		
		return element;
	},
	
	alphabetise: function (element) {
		element = $(element);
		
		// select all of the list items
		var list_items = element.select('li');
		var list = new Hash();
		
		// work out the surname for each person
		list_items.each(function (li) {
			// find the surname without Prof or Sir to confuse
			var surname = $w(li.innerHTML.stripTags()).without('Prof').without('Sir')[1] + '__' + li.innerHTML.stripTags();
			
			// return the element with surname
			list.set(surname, li.cloneNode(true));
		});
		
		// empty the list
		element.update('');
		
		// insert the ordered list items
		list.keys().sort().each(function (surname) {
			element.insert(list.get(surname));
		});
		
		return element;
	}
});

document.observe('dom:loaded', function () {
	var body_class = $(document.body).className;
	$$('#main_menu li').each(function (li) {
		if (li.hasClassName(body_class)) {
			// console.log(li.inspect());
			li.down('a').addClassName('selected');
			li.addClassName('selected');
		}
	});
	
	$$('.submenu li', '.menu li').each(function (link) {
		
	});
	
	$$('.border .text.content', '.span-12 .text.content').each(function (element) {
		if (element.down('p:not(:empty)')) { element.down('p:not(:empty)').addClassName('border'); }
	});
	
	$$('.submenu.alphabetise ul').invoke('alphabetise');
	$$('.submenu.two_column ul').invoke('reorder_list', 2);
	$$('.submenu.three_column ul').invoke('reorder_list', 3);
	
	$$('.menu.limit ul li').slice(2).invoke('remove');
	
	$$('a.popup').invoke('observe', 'click', function (event) {
		event.stop();
		window.open(this.readAttribute('href', 'LAYTONS_popupwindow'));
	});
	
	var bottom_boxes, max_height;
	
	bottom_boxes = $$('body.home .box');
	bottom_boxes.invoke('setStyle', { height: 'auto' });

	max_height = bottom_boxes.invoke('getHeight').max();
	bottom_boxes.invoke('setStyle', { height: max_height-18 + 'px' });
	
	if ($('solicitor_search_name')) {
		var auto = new Ajax.Autocompleter('solicitor_search_name', 'solicitor_search_name_results', '../_search/solicitor_quick.asp', {
			paramName: 'name',
			minChars: 1,
			afterUpdateElement : function (text, li) {
				var value = li.readAttribute('id').replace(/^result\-/, '');
				$('solicitor_search_id').setValue(value);
				window.location.href = value;
			}
		});
	}
	
	$$('#content .span-11 .image', '.bottom_image').each(function (image) {
		var height = image.setStyle({ marginTop: 'auto' }).getHeight();
		var available_height = $('content').getHeight();
		var difference = available_height - height;
		if (difference > 0) {
			image.setStyle({ marginTop: difference + 'px' });
		}
	});
	
	$$('#tools a[class] img').invoke('setOpacity', 1);
	
	$$('#tools a.add').invoke('observe', 'click', function (event) {
		event.stop();
		var ajax = new Ajax.Request(this.readAttribute('href'), {
			method: 'get',
			onSuccess: function (t) {
				this.setStyle({ backgroundColor: '#94a593' });
				$$('#tools a.clear', '#tools a.view').invoke('setOpacity', 1);
			}.bindAsEventListener(this)
		});
	});
	
	$$('#tools a.clear').invoke('observe', 'click', function (event) {
		event.stop();
		var ajax = new Ajax.Request(this.readAttribute('href'), {
			method: 'get',
			onSuccess: function (t) {
				$$('#tools a.clear', '#tools a.view').invoke('setOpacity', 0.5);
				$$('#tools a.add').invoke('setStyle', { backgroundColor: '' });
			}.bindAsEventListener(this)
		});
	});
	
	$$('#tools a.bookmark').invoke('observe', 'click', function (event) {
		event.stop();
		Try.these(
			function () { window.external.AddFavorite(window.location.href, document.title); },
			function () { window.sidebar.addPanel(document.title, window.location.href, ''); },
			function () { alert('Please add this page to your favourites.'); }
		);
	});
	
	$$('#tools a.print').invoke('observe', 'click', function (event) {
		event.stop();
		window.print();
	});
	
	$$('#tools a.email').invoke('observe', 'click', function (event) {
		event.stop();
		window.open(this.readAttribute('href')+'&title=' + document.title.replace(/^[^\|]+?\|\s/, ''), 'LAYTONS_send_page', 'width=400,height=400');
	});
	
	$$('.accessibility a[href^=#]').invoke('observe', 'click', function (event) {
		event.stop();
		switch(this.readAttribute('href')) {
			case '#small':
				$(document.body).removeClassName('medium');
				$(document.body).removeClassName('large');
				
				$(document.body).addClassName('small');
				break;
			case '#medium':
				$(document.body).removeClassName('small');
				$(document.body).removeClassName('large');
				
				$(document.body).addClassName('medium');
				break;
			case '#large':
				$(document.body).removeClassName('small');
				$(document.body).removeClassName('medium');
				
				$(document.body).addClassName('large');
				break;
		}
	});
	
	var Timer = {
		counter: null,
		start: function (fn) { this.counter = setTimeout(fn, 1000); },
		stop: function () {
			if (this.counter !== null) clearInterval(this.counter);
			this.counter = null;
		}
	};
	
	$$('#tools .add').each(function (element) {
		return element;
		var box = new Element('div', { className: 'info_bubble' })
			.update(new Element('a', { href: '../_shortlist/about.asp' })
				.observe('click', function (e) { e.stop(); window.open(this.href, 'LAYTONS_popup', 'width=400,height=400'); })
				.update(element.readAttribute('title')));
				
		element.writeAttribute('title', '');
		var options = { duration: 0.3 };
		
		element.insert(box);
		box.hide();
		
		element.observe('mouseover', function () {
			Timer.stop();
			if (!$(box).visible()) {
				var parallel = new Effect.Parallel([
					new Effect.Move(box, { sync: true, x: 0, y: 20, mode: 'absolute' }),
					Effect.Appear(box, { sync: true })
				], { duration: 0.5 });
			}
		});
		
		element.observe('mouseout', function () {
			Timer.start(function () {
				var parallel = new Effect.Parallel([
					new Effect.Move(box, { sync: true, x: 0, y: 10, mode: 'absolute' }),
					Effect.Fade(box, { sync: true })
				], { duration: 0.3 });
			});
		});
	});
	
	if ($('back_button')) {
		$('back_button').observe('click', function () {
			var href = window.location.href;
			href.sub(/([^\/]+?)([0-9])\.asp/, function (match) {
				var number = match[2];
				var location = match[0].replace(number, parseInt(number, 10)-1);
				window.location.href = location;
			});
		});
	}
	
	$$('#breadcrumbs ul').each(function (ul) {
		ul.select('li a').each(function (a) {
			a.update(a.innerHTML.truncate(25, '…'));
		});
		var title = document.title.split(' | ').slice(1).join(' | ').truncate(30, '…');
		ul.insert(new Element('li').update(title));
	});
	
	$$('#breadcrumbs ul li:last-child').invoke('addClassName', 'last');
	
	$$('#what-we-do-search-options').invoke('observe', 'change', function () {
		if (!$F(this).blank()) {
			this.up('form').submit();
		}
	});
	
	$$('a[href^=../_contact/email.asp?name=]').each(function (email_link) {
		email_link.writeAttribute('target', 'LAYTONS_email');
		
		email_link.observe('click', function (e) {
			e.stop();
			var email_address = email_link.readAttribute('href').replace(/^\.\.\/_contact\/email\.asp\?name=/, '');
			window.location.href = 'mailto:#{address}@laytons.com?subject=Contact from the Laytons Website'.interpolate({ address: email_address });
		});
	});
	
	$$('#barristers_practising').invoke('observe', 'change', function () {
		if (typeof Vx === 'undefined') {
			if (!this.value.blank()) { window.location.href = this.value; }
		}
	});
	
	$$('#barrister-name').each(function (name_search) {
		var full_list = null,
			results_holder = new Element('ul'),
			result_template = new Template('<' + 'li><' + 'a href="#{url}">#{name}<' + '/a><' + '/li>');
			
		name_search.observe('focus', function () {
			if (!full_list) {
				new Ajax.Request('../_search/barristers.asp', {
					method: 'get',
					onSuccess: function (transport, json) {
						full_list = json;
						$('barrister-results').insert(results_holder.hide());
						
						name_search.observe('keyup', function (event) {
							var search = $F(this);
							if (search.blank()) {
								results_holder.hide();
							} else {
								results_holder.show().update('');
								search = $A(search.replace(/([\.\^\$\-\*\+])/, '\\$1')).join('.*');
								search = new RegExp(search, 'ig');
								$A(full_list).each(function (barrister) {
									if (search.test(barrister.name)) {
										results_holder.insert(result_template.evaluate(barrister));
									}
								});
							}
						});
					}
				});
			}
		});
	});
});