(function () {
	var resetInput = function () {
		var element = (typeof $(this).hasClassName === 'function') ? $(this) : $(arguments[0]);
		if (!element.hasClassName('prefilled') && element.getValue() === element.defaultValue) {
			element.setValue('');
		}
		return element;
	};
	var clearForms = function () {
		var form_elements = $$('input[type=text]', 'input[type=password]', 'textarea');
		form_elements.invoke('observe', 'focus', resetInput);
		form_elements.invoke('observe', 'blur', function () {
			if ($F(this).blank()) {
				this.setValue(this.defaultValue);
			}
		});
		$$('form').invoke('observe', 'submit', function () {
			this.select('input[type=text]', 'input[type=password]', 'textarea').map(resetInput);
		});
	};

	document.observe('dom:loaded', clearForms);
})();

// Element.Storage API
// each element contains an ID attribute, which is the key of the Element.Storage hash
// storing separate pseudo-attributes on each element can cause memory leaks in IE,
// but by only holding the element's ID with the element, and then a hash of all the
// element's pseudo-attributes with the ID as a key we can reduce the memory leaks
// and only have one unique point of access for all elements, even if they have been
// removed from the document.
var Storage = {
	create: function (element) {
		if (typeof window.Element.Storage === 'undefined') {
			Element.Storage = new Hash();
		}
 
		element = $(element);
		var storage = Element.Storage,
		id = element.identify();
 
		if (!storage.keys().include(id)) {
			storage.set(id, new Hash());
		}
 
		return element;
	}
};
 
Element.addMethods({
	store: function (element, rules, value) {
		element = Storage.create(element);
		var storage = Element.Storage.get(element.identify()),
			attributes = {};
 
		if (typeof rules === 'object') {
			attributes = rules;
		} else {
			attributes[rules] = value;
		}
 
		for (var key in attributes) {
			if (attributes.hasOwnProperty(key) && typeof attributes[key] !== 'undefined') {
				storage.set(key, attributes[key]);
			}
		}
 
		return element;
	},
 
	retrieve: function (element, property_name, property_default_value) {
		element = Storage.create(element);
		var storage = Element.Storage.get(element.identify());
 
		if (!storage.keys().include(property_name)) {
			element.store(property_name, property_default_value);
		}
 
		return storage.get(property_name);
	},
 
	eliminate: function (element, property_name) {
		element = Storage.create(element);
		var storage = Element.Storage.get(element.identify());
 
		if (storage.keys().include(property_name)) {
			storage.unset(property_name);
		}
 
		return element;
	}
});

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);
		
		if (element.retrieve('sorted_order')) {
			// if we have already sorted this column, use a shortcut
			element.innerHTML = element.retrieve('sorted_order');
		} else {
			// otherwise, store the original order
			element.store('original_order', element.innerHTML);
			
			// 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().replace(/\sQC$/, '')).last() + '__' + 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));
			});
			
			// ensure we re-order the lists into columns
			element.reorder_list(4);
			
			// save the new order to speed up next time
			element.store('sorted_order', element.innerHTML);
		}
		
		return element;
	},
	
	seniority: function (element) {
		element = $(element);
		element.update(element.retrieve('original_order', element.innerHTML));
		return element;
	}
});

var GL = {};

document.observe('dom:loaded', function () {
	try {
		var location_sub = /([^\/]+?)\/([^\/]+?)\.asp/;
		var folder_name, file_name, window_location;
		window.location.href.gsub(location_sub, function (match) {
			window_location = match[0];
			folder_name = match[1];
			file_name = match[2];
		});


		$$('.vx_menu a').each(function (element) {
			$(element).readAttribute('href').gsub(location_sub, function (match) {
				if (match[0] === window_location) {
					element.addClassName('selected').ancestors().each(function (li) {
						if (li.tagName.toUpperCase() === 'LI') { li.addClassName('selected'); }
					});
				}

				if (match[1] !== folder_name && match[2] === folder_name) {
					element.addClassName('selected').ancestors().each(function (li) {
						if (li.tagName.toUpperCase() === 'LI') { li.addClassName('selected'); }
					});
				}
			});
		});
	} catch (err) {}
	
	$$('.dropdown li').each(function (li) {
		var Timer = {
			counter: null,
			start: function (fn) { this.counter = setTimeout(fn, 150); },
			stop: function () {
				if (this.counter !== null) clearInterval(this.counter);
				this.counter = null;
			}
		};
		
		li.observe('mouseover', function () {
			Timer.stop();
			li.addClassName('hover');
		});
		
		li.observe('mouseout', function () {
			Timer.start(function () {
				li.removeClassName('hover');
			});
		});
	});
	
	if (typeof Vx === 'undefined') {
		$$('.members_search input[type=text]').invoke('observe', 'focus', function () {
			var input = $(this),
				container = input.up().next();
			
			if (!GL.members_list) {
				new Ajax.Request('../_inc/people.asp', {
					method: 'get',
					onSuccess: function (t) {
						GL.members_list = $A(eval(t.responseText));
					
						input.observe('keyup', function (e) {
							container.update('');
						
							var value = this.value;
							if (value.blank()) return;
						
							value = value.replace(/([\.\-\[\]\(\)\^\$\*\?])/, "\\$1");
						
							var results = GL.members_list.inject($A(), function (results, list) {
								if (list && (new RegExp(value, 'i')).test(list[0])) {
									results.push(list);
								}
							
								return $A(results);
							
							});
						
							if (e.keyCode === Event.KEY_RETURN && results[0] && results[0][1]) {
								window.location.href = results[0][1];
							}
						
							results.each(function (result) {
								var a = new Element('a', { href: result[1] }).update(result[0]),
									li = new Element('li').update(a);
							
								container.insert(li);
							});
						});
					}
				});
			}
		});
	}
});
