function inline_dd_close(close, data){
	updateChildDependancies(close, data);
	myLightWindow.deactivate();
}

var open_menu = false;
var optionsmenu_event;

function show_options_menu(menu_id, e){

	if (e){
		elm = Event.element(e);

		if (elm.hasClassName('option_dd') || elm.up('.option_dd')){
			// Let the menu tirgger handle itself
			return;
		}
	}

	if (open_menu){
		// Hide the last open menu
		$('options_dd_' + open_menu).hide();
	}

	// Close the open menu and stop listening
	if (!menu_id){

		// Remove the document event observer
		Event.stopObserving(window, 'click', optionsmenu_event);
		open_menu = false;
		return;
	}

	// If it's the current menu, don't show it again
	if (open_menu == menu_id){
		open_menu = false;
		return;
	}

	if (!open_menu){

		optionsmenu_event = show_options_menu.bind(null, false);

		// Set a timeout to stop it being triggered when the original event is bubbled up
		setTimeout(option_menu_click, 1);
	}

	// Show the new menu
	$('options_dd_' + menu_id).show();

	// Save the current open menu
	open_menu = menu_id;
}

function option_menu_click(){
	Event.observe(window, 'click', optionsmenu_event);
}

function live_search(event, that){

}

function asset_caps_button(baseurl){

	var go = confirm('Are you sure you want to perform a CAPs lookup?');

	if (!go){
		return;
	}

	var val = '';
	var type = '';

	if ($('asset_cap_value')){
		val = $F('asset_cap_value');
		type = 'car';
	}
	else if ($('asset_cap_value_lcv')){
		val = $F('asset_cap_value_lcv');
		type = 'lcv';
	}
	else if ($('asset_cap_value_hcv')){
		val = $F('asset_cap_value_hcv');
		type = 'hcv';
	}

	window.open(baseurl + 'admin/caps_value?confirm=true&type=' + type + '&capcode=' + escape(val).replace(/\+/g, "%2B"));
}

// Creates an array of inputs
function inputArray(that){
	Event.observe(that, 'keyup', createInput.bind(that));
}

function createInput(){
	// Clone it
	this.cloneNode();
}

// I'm lazy
function GetByID(theID){
	return document.getElementById(theID);
}

var removed = new Array;
var lastinput = new Array;

function newInput(that, idlength, ownhtml){
	var input_name = that.id.substring(0, idlength);
    var nextid = input_name + (parseInt(that.id.substring(idlength)) + 1);
	var outid = input_name + "_addinput";

	if (typeof(removed[nextid]) == "undefined" && !GetByID(nextid) && that.value != ""){
		lastinput[input_name] = nextid;
		setOuterHTML(GetByID(outid), "<input type=\"text\" name=\"" + input_name + "[]\" size=\"50\" onkeyup=\"newInput(this, '" + idlength + "');\" onblur=\"removeInput(this, '" + idlength + "');\" id=\"" + nextid + "\" /><div id=\"" + outid + "\"></div>");
	}
}

function newDoubleInput(that, idlength){
	if (that.id.substring(that.id.length - 4) == "_rep"){
		var input_name = that.id.substring(0, idlength);
	    var nextid = input_name + (parseInt(that.id.substring(idlength, that.id.length - 4)) + 1);
		var outid = input_name + "_addinput";
	}
	else {
		var input_name = that.id.substring(0, idlength);
	    var nextid = input_name + (parseInt(that.id.substring(idlength)) + 1);
		var outid = input_name + "_addinput";
	}

	if (typeof(removed[nextid]) == "undefined" && !GetByID(nextid) && that.value != ""){
		lastinput[input_name] = nextid;
		setOuterHTML(GetByID(outid), "<span id=\"" + nextid + "_span\"><input type=\"text\" name=\"" + input_name + "[]\" size=\"20\" onkeyup=\"newDoubleInput(this, '" + idlength + "');\" onblur=\"removeDoubleInput(this, '" + idlength + "');\" id=\"" + nextid + "\" /> =&gt; <input type=\"text\" name=\"" + input_name + "_rep[]\" size=\"20\" onkeyup=\"newDoubleInput(this, '" + idlength + "');\" onblur=\"removeDoubleInput(this, '" + idlength + "');\" id=\"" + nextid + "_rep\" class=\"input_rep\" /><br /></span><div id=\"" + outid + "\"></div>");
	}

}

function removeDoubleInput(that, idlength){
	if (that.id.substring(that.id.length - 4) == "_rep"){
    	var rep = that;
    	var that = GetByID(rep.id.substring(0, that.id.length - 4));
		var span = GetByID(that.id + '_span');
	}
	else {
		var rep = GetByID(that.id + '_rep');
		var span = GetByID(that.id + '_span');
	}

	if (that.value == "" && rep.value == "" && lastinput[that.id.substring(0, idlength)] != that.id && lastinput[that.id.substring(0, idlength)] != ""){
		removed[that.id] = true;
		setTimeout("GetByID('" + span.id + "').parentNode.removeChild(GetByID('" + span.id + "'));", 10);
	}
}

function removeInput(that, idlength){
	if (that.value == "" && lastinput[that.id.substring(0, idlength)] != that.id && lastinput[that.id.substring(0, idlength)] != ""){//GetByID(that.id.substring(0, idlength) + (parseInt(that.id.substring(idlength)) + 1))){
		removed[that.id] = true;
		that.parentNode.removeChild(that);
		setTimeout("GetByID('" + that.id + "').parentNode.removeChild(GetByID('" + that.id + "'));", 10);
	}
}

function setOuterHTML(element, toValue){
	if (typeof(element.outerHTML) != 'undefined'){
		element.outerHTML = toValue;
	}
	else {
		var range = document.createRange();
		range.setStartBefore(element);
		element.parentNode.replaceChild(range.createContextualFragment(toValue), element);
	}
}

function checkSelected(theForm, FieldName){
	// Get the element(s)
	var objCheckBoxes = theForm.elements[FieldName];

	// Nope?
	if (!objCheckBoxes){
		return false;
	}

	var countCheckBoxes = objCheckBoxes.length;

	if (!countCheckBoxes){

		if (objCheckBoxes.checked){
			return true;
		}

	}
	else {

		// set the check value for all check boxes
		for (var i = 0; i < countCheckBoxes; i++){

			if (objCheckBoxes[i].checked){
				return true;
			}

		}

	}

	return false;
}

// Gets the selected checkboxes
function getSelected(theForm, FieldName){
	// Get the element(s)
	var objCheckBoxes = theForm.elements[FieldName];

	// Nope?
	if (!objCheckBoxes){
		return [];
	}

	var countCheckBoxes = objCheckBoxes.length;

	if (!countCheckBoxes){

		if (objCheckBoxes.checked){
			return [objCheckBoxes.value];
		}

	}
	else {

		checked = [];

		// set the check value for all check boxes
		for (var i = 0; i < countCheckBoxes; i++){

			if (objCheckBoxes[i].checked){
				checked.push(objCheckBoxes[i].value);
			}

		}


		return checked;
	}

	return [];
}


function ToggleCheckAll(theForm, FieldName, CheckValue){

	// Get the element(s)
	var objCheckBoxes = theForm.elements[FieldName];

	// Nope?
	if (!objCheckBoxes){
		return false;
	}

	var countCheckBoxes = objCheckBoxes.length;

	if (!countCheckBoxes){

		if (CheckValue == null){
			CheckValue = (objCheckBoxes.checked == false) ? true : false;
		}

		objCheckBoxes.checked = CheckValue;
	}
	else {

		// set the check value for all check boxes
		for (var i = 0; i < countCheckBoxes; i++){

			if (CheckValue == null){
				CheckValue = (objCheckBoxes[i].checked == false) ? true : false;
			}

			objCheckBoxes[i].checked = CheckValue;
		}

	}
}

function updateGUIforms(that){
	var elements = that.getElementsByTagName('input');

	// Loop through all the lists
	for (var i = 0; i < elements.length; i++){

		if (elements[i].name.indexOf('column_n_') != 0){
			continue;
		}

		var theID = elements[i].name.substr(9);

		// Update the form elements
		that.elements['column_n_' + theID].value = Sortable.serialize('gui_dnd_live_' + theID, {'name' : 'n'});
	}

}


function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function keyDate(e, obj){
	var key;
	var isCtrl = false;
	var keychar;
	var reg;

	// MSIE
	if (window.event){
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	// Gecko
	else if (e.which){
		key = e.which;
		isCtrl = e.ctrlKey;
	}

	// Not a number?
	if (isNaN(key)){
		return true;
	}

	keychar = String.fromCharCode(key);

	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl){
		return true;
	}

	// It's a valid character
	if (/[\d\/]/.test(keychar)){

		if ((/^\d{2}$/.test(obj.value) || /^\d{2}\/\d{2}$/.test(obj.value)) && keychar != '/'){
			obj.value = obj.value + '/';
		}

		return true;
	}

	Event.stop(e);
	return false;
}

/* Made by Mathias Bynens <http://mathiasbynens.be/> */
function number_format(a, b, c, d, empty){
console.log(a);
console.log(empty);
	if (a == 0){
		return (!empty) ? '0' : '';
	}

	if (a === Infinity || a === -Infinity){
		return 'Infinity';
	}

	if (b !== null){
		a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	}

	e = a + '';
	f = e.split('.');

	if (!f[0]){
		f[0] = '0';
	}

	if (!f[1]){
		f[1] = '';
	}

	if (f[1].length < b){
		g = f[1];
		for (i=f[1].length + 1; i <= b; i++){
			g += '0';
		}
		f[1] = g;
	}

	var pref = '';

	if(d != '' && f[0].length > 3){
		h = f[0];

		if (h[0] == '-'){
			h = h.substring(1);
			pref = '-';
		}

		f[0] = '';

		for(j = 3; j < h.length; j+=3){
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}

		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}

	c = ((b !== null && b <= 0) || (b === null && f[1] <= 0)) ? '' : c;

	return pref + f[0] + c + f[1];
}

function keyNumber(obj, e){
	var key;
	var isCtrl = false;
	var keychar;
	var reg;

	// MSIE
	if (window.event){
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	// Gecko
	else if (e.which){
		key = e.which;
		isCtrl = e.ctrlKey;
	}

	// Not a number?
	if (isNaN(key)){
		return true;
	}

	keychar = String.fromCharCode(key);

	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl){
		return true;
	}

	// It's a valid character
	if (/[\d,.]/.test(keychar)){

		if ((/^\d{2}$/.test(obj.value) || /^\d{2}\/\d{2}$/.test(obj.value)) && keychar != '/'){
			obj.value = obj.value + '/';
		}

		return true;
	}

	return false;
}

function deincrement(id, amount, min){

	if ($(id).disabled == true){
		return false;
	}

	var elem = $F(id);
	var num = parseFloat(elem);

	if (isNaN(num)){
		num = 0;
	}

	var newnum = num - parseFloat(amount);

	if (min !== null && newnum < min){
		newnum = min;
	}

	$(id).value = newnum;
}

function increment(id, amount, max){

	if ($(id).disabled == true){
		return false;
	}

	var elem = $F(id);
	var num = parseFloat(elem);

	if (isNaN(num)){
		num = 0;
	}

	var newnum = num + parseFloat(amount);

	if (max !== null && newnum > max){
		newnum = max;
	}

	$(id).value = newnum;
}

function togglesearch(){
	Element.toggle('search_hide');
	Element.toggle('search_show');
	Element.toggle('search_main');
	Element.toggle('search_buttons');
}

function showsearch(){
	Effect.BlindDown('search_main', {afterFinish: function(){
		Element.toggle('search_hide');
		Element.toggle('search_show');
	}});

	Effect.BlindDown('search_buttons');
}

function hidesearch(){
	Effect.BlindUp('search_main', {afterFinish: function(){
		Element.toggle('search_hide');
		Element.toggle('search_show');
	}});

	Effect.BlindUp('search_buttons');
}

function check_row(area, id){

	if (!$(area + '_id_' + id) || !$(area + '_tr_' + id)){
		return;
	}

	if ($(area + '_id_' + id).checked == true){
		$(area + '_tr_' + id).addClassName('alt_select');
	}
	else {
			$(area + '_tr_' + id).removeClassName('alt_select');
	}
}

function get_child_table(button, area, id){

	if (button.firstDescendant().alt == 'Expand'){

		// Show the row
		$($(area + '_more_' + id).parentNode).show();

		// Change the button
		button.firstDescendant().src = 'images/collapse_button.gif';
		button.firstDescendant().alt = 'Collapse';

		// Use cached results?
		if ($(area + '_more_' + id).hasClassName('found_results')){
			return;
		}

		// Show the loading text
		$(area + '_more_' + id).update('Loading...');
		$(area + '_more_' + id).setStyle({textAlign: 'center', padding: '10px'});
		$(area + '_more_' + id).addClassName('child_td');

		// Make the AJAX call
		AJAX.request('get_child_table', [area, id], {onComplete: get_child_table_init});
	}
	else {
		// Change the button back
		button.firstDescendant().alt = 'Expand';
		button.firstDescendant().src = 'images/expand_button.gif';

		$(area + '_more_' + id).parentNode.hide();
	}

	return false;
}

function update_search (data){
	var area = data['area'];

	if (data['table']){
		val = data['table'];
		num_results = data['num_results'];
	}
	else {
		val = data['no_results'];
		num_results = 0;
	}

	if (data['pagination']){
		$('pagination1').update('Page(s): ' + data['pagination']);
		$('pagination2').update('Page(s): ' + data['pagination']);

		$('pagination1').show();
		$('pagination2').show();
	}
	else {
		$('pagination2').show();
		$('pagination2').show();
	}

	$('num_results1').update(num_results);
	$('num_results2').update(num_results);

	$('search_spinner').hide();
	$('main_results').show();

	$(area + '-list-contents').update(val);
}

// TODO: Cache results.
function get_child_table_init(data){

	if (data['table']){
		$(data['area'] + '_more_' + data['id']).update(data['table']);
	}
	else {
		$(data['area'] + '_more_' + data['id']).update('No information found...');
	}

	// Add a class so we know we can use cached results
	$(data['area'] + '_more_' + data['id']).addClassName('found_results');
}

menutimer = false;

changeMenu = function(event, menu){

	if (!menu || !$(menu + '_child')){
	//	return;
	}

	//console.log(menu);

	if (menu == lastMenu){
	//	return;
	}

	if ($(lastMenu)){
		$(lastMenu).removeClassName('selected');
		//$(lastMenu + '_child').hide();
	}

	lastMenu = menu;
	$(menu).addClassName('selected');
	//$(menu + '_child').show();
	//return;

	var sub_menu = menu_array[menu];

//	if (!sub_menu){
//		sub_menu = '<a href="' + $('menu_' + menu).href + '">' + $('menu_' + menu).innerHTML + '</a>';
//	}

	$('menu_second').update(sub_menu);

/*	var dimensions = Position.cumulativeOffset(elm);
	var width = parseFloat($('menu_second').getWidth());
	var elmleft = dimensions[0];

	var left = (elmleft - (width / 2));

	if (left < 20){
		return;
	}

	$('menu_second').setStyle({
		left: left + 'px'
	});*/

}

changedMenu = function(){

	//$('menu_' + lastMenu).addClassName('selected');
}

function selectValue(elm, value){

	if (!value || !elm || !elm.options){
		return;
	}

	theOption = $A(elm.options).find(
		function(opt){
			return opt.value == value;
		}
	);

	if (!theOption){
		show_alert('Sorry but that operative ID doesn\'t exist.');
	}

	elm.selectedIndex = theOption.index;
	elm.selectedIndex = theOption.index;
}

function inline_edit(that, area, inputname, row_id){

	if (!$(area + '_' + inputname + '_' + row_id + '_loader')){
		var loader = document.createElement('img');
		loader.alt = 'Loading...';
		loader.src = 'images/inline_loader.gif';
		loader.id = area + '_' + inputname + '_' + row_id + '_loader';

		// Add the trendy loader image
		that.appendChild(loader);
	}
	else {
		$(area + '_' + inputname + '_' + row_id + '_loader').show();
	}

	// Make the AJAX call
	AJAX.request('inline_edit', [area, inputname, that.id, row_id], {onComplete: inline_edit_init});
}

function inline_edit_init(data){

	//console.log();

	$(data.id).innerHTML = data.input;

	data.input.extractScripts().each(function(data){
		console.log(data);
		eval(data);
	});

}

function save_inline_edit(that, area, id){
	that.parentNode.update(that.value);

	// Make the AJAX call
	AJAX.request('inline_edit_save', [area, that.name, id, that.value]);
}

function getChildDependancies(area, child, parent, fields){
	value = $F(parent);

	// No children?
	if (!value || value == '--select--'){

		if ($(child + '_dd_loader')){
			// Remove the loader
			var loader = $(child + '_dd_loader');
			loader.parentNode.removeChild(loader);
		}

		child = $(child);

		// Remove all the options
		child.options.length = 1;

		// I'm a genius
		Event.triggerObserve(child, 'change');
		return;
	}

	var where = {};

	// Reverse the input's values
	fields.each(function(obj){
		where[obj.name] = rev(obj);
	});

	// Make the AJAX call
	AJAX.request('get_child_dd', [area, child, value, where], {onComplete: updateChildDependancies.bind(null, child)});

	if (!$(child + '_dd_loader')){
		new Insertion.After(parent, '<img src="images/inline_loader.gif" class="inlineloader" id="' + child + '_dd_loader" alt=".." />');
	}
}

function updateChildDependancies(child, data){
	child = $(child);
	var orig_value = child.options[child.selectedIndex].value;

	if (data['value']){
		orig_value = data.value;
	}

	// Remove all the options
	child.options.length = 1;

	if (child.options[0].value == '--select--' && child.options[0].innerHTML != '-- None --'){
		// Keep the first option
		var start = 1;
	}
	else {
		// Overwrite the first option
		var start = 0;
	}

	// Add the new ones
	$H(data.options).each(function(vv){

		key = vv[0];
		value = vv[1];

		if (!value){
			return;
		}

		if (start !== null){
			optkey = start;
		}
		else {
			optkey = child.options.length;
		}

		if (key.toString() == orig_value){
			var selected = true;
		}
		else {
			var selected = false;
		}

		child.options[optkey] = new Option(value, key, false, selected);

		start = null;
	});

	if ($(child.id + '_dd_loader')){
		// Remove the loader
		var loader = $(child.id + '_dd_loader');
		loader.parentNode.removeChild(loader);
	}

	// I'm a genius
	Event.triggerObserve(child, 'change');
}

function rev(inputName, type){
	input = $(inputName);

	if (!input){
		console.log(inputName + ' - Doesn\'t exist');
		val = '';
	}
	else {
		val = $F(input);
	}

	if (val == '--select--' && input.nodeName.toLowerCase() == 'select'){
			return '';
	}

	// Number
	if (/^(-?)(((\d{1,3})(,\d{3})*)|(\d+))(.\d+)?$/.test(val) || type == 'number'){
			num = parseFloat(val.replace(/,/g, ''));

			if (isNaN(num)){
				return 0.00;
			}

			return num;
	}

	// Date
	if ((parts = val.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{2,4})/))){
		return parts[3] + '-' + parts[2] + '-' + parts[1];
	}

	return val;
}

// Create a date object from UK date
function to_date(date){

	if (!date){
		return '';
	}

	// Date
	if ((parts = date.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{2,4})/))){

		date = parts[1];
		months = parts[2];
		years = parts[3];

		if (years < 70){
			years = parseInt(years) + 2000;
		}
		else if (years < 1000){
			years = parseInt(years) + 1900;
		}

		// Months run from 0-11
		months = parseInt(months) - 1;

		return new Date(years, months, date);
	}
	else if ((parts = date.match(/([0-9]{2,4})-([0-9]{2})-([0-9]{2})/))){

		date = parts[3];
		months = parts[2];
		years = parts[1];

		if (years < 70){
			years = parseInt(years) + 2000;
		}
		else if (years < 1000){
			years = parseInt(years) + 1900;
		}

		// Months run from 0-11
		months = parseInt(months, 10) - 1;

		return new Date(years, months, date);
	}

	return '';
}


function from_date(date){

	if (typeof(date) != 'object' || !date){
		return '';
	}

	date_year = date.getYear();
	date_month = date.getMonth();
	date_days = date.getDate();

	// Add 1 to make it normal
	date_month += 1;

	if (date_year < 70){
		date_year = parseInt(date_year) + 2000;
	}
	else if (date_year < 1000){
		date_year = parseInt(date_year) + 1900;
	}

	if (date_days < 10){
		date_days = '0' + date_days;
	}

	if (date_month < 10){
		date_month = '0' + date_month;
	}

	return date_days + '/' + date_month + '/' + date_year;
}

// How many days in a month?
function days_in_month (year, month) {
	return 32 - new Date(year, month, 32).getDate();
}

// Add/Substract something from a date
function date_add(date, days, months, years){

	// Using an array?
	if (date.constructor.toString().indexOf("Array") != -1){
		date = new Date(date[0], date[1] - 1, date[2]);
	}
	// Using an element ID?
	if (typeof(date) != 'object'){
		date = to_date(date);
	}

	if (!date){
		return;
	}

	// Work out one day in miliseconds
	var one_day = 1000 * 60 * 60 * 24;
	// Current time in miliseconds
	milliseconds = date.getTime();

	// Add the days
	newdate = milliseconds + (one_day * days);
	// Make a new date out of it
	newdate = new Date(newdate);

	date_year = newdate.getYear();
	date_month = newdate.getMonth();
	date_days = newdate.getDate();

	// Make it a full year
	if (date_year < 70){
		date_year = parseInt(date_year) + 2000;
	}
	else if (date_year < 1000){
		date_year = parseInt(date_year) + 1900;
	}

	// Do months?
	if (months){

		months += date_month;

		// How many years do the months make up?
		new_years = (months / 12);

		// Remove the remainder
		if (new_years < 0){
			// When subtracting months
			new_years = Math.ceil(new_years);
		}
		else {
			// When adding months
			new_years = Math.floor(new_years);
		}

		// Remove the years from those months
		months = months - (12 * new_years);

		// Add the extra years
		years = ((years) ? years : 0) + new_years;

		// Set the month
		newdate.setMonth(months);
	}

	// Do years?
	if (years){
		newdate.setYear(date_year + years);
	}

	return newdate;
}

function date_diff(start, end){
    var difference = end.getTime() - start.getTime();

    var daysDifference = Math.floor(difference/1000/60/60/24);
    difference -= daysDifference*1000*60*60*24
    var hoursDifference = Math.floor(difference/1000/60/60);
    difference -= hoursDifference*1000*60*60
    var minutesDifference = Math.floor(difference/1000/60);
    difference -= minutesDifference*1000*60
    var secondsDifference = Math.floor(difference/1000);

    return [daysDifference, hoursDifference, minutesDifference, secondsDifference];
}

function input_mask(field, mask, e){
	field = $(field);

	value = $F(field);

	var new_value = '';
	var j = 0;

	mask = mask.split('');

	if (typeof(mask[value.length]) == 'undefined'){
		return true;
	}

	// Character at
	//charAt = getSelectionStart(field);

	var key;
	var isCtrl = false;
	var keychar;
	var reg;

	// MSIE
	if (window.event){
		key = e.keyCode;
		isCtrl = window.event.ctrlKey;
	}
	// Gecko
	else if (e.which){
		key = e.which;
		isCtrl = e.ctrlKey;
	}

	keychar = String.fromCharCode(key);

	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl){
		return true;
	}

	lmask = mask[value.length];

	if (lmask == '#'){
		// Do nout
	}
	else if (lmask == 'A'){

		//if (/[A-Z]/i.test(value[value.length - 1])){
			// Remove it
		//	field.value.substring(0, value.length - 1);
		//}

	}
	// Do the next character
	else if (lmask){
		field.value += mask[value.length];

		// Don't continue adding it
		if (mask[value.length] == keychar){
			Event.stop(e);
		}
	}

	return new_value;
}

function input_mask_change(field, mask){
	field = $(field);

	value = $F(field);

	if (!value){
		return value;
	}

	var new_value = '';
	var j = 0;

	var mlen = mask.length;

	mask = mask.split('');
	value = value.split('');

	for (var i = 0; i < mlen; i++){

		if (typeof(value[j]) != 'undefined' && mask[i] == '#'){

			// Use the actual value
			new_value += value[j];
			j++;
		}
		/*else if (typeof(value[j]) != 'undefined' && mask[i] == 'A'){

			if (/[A-Z]/i.test(value[j])){
				// Use the actual value
				new_value += value[j];
				j++;
			}
			else {
				new_value += '#';
			}

		}*/
		else if (typeof(mask[i]) != 'undefined'){

			new_value += mask[i];

			if (typeof(value[j]) != 'undefined' && value[j] == mask[i]){
				j++;
			}

		}
		else {
alert(mask +'-' + i);
		}


	}

	return new_value;

	//field.value =
}

/*
function input_mask(e, field, mask){
	field = $(field);

	value = $F(field);

	// Character at
	charAt = getSelectionStart(field);

	var key;
	var isCtrl = false;
	var keychar;
	var reg;

	// MSIE
	if (window.event){
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	// Gecko
	else if (e.which){
		key = e.which;
		isCtrl = e.ctrlKey;
	}

	keychar = String.fromCharCode(key);

	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl){
		return true;
	}

	/*if (typeof(mask[charAt + 1] != 'undefined') && (mask[charAt + 1] == 'A' || mask[charAt] == '0')){
		console.log(keychar);
		value[charAt + 1] = keychar;
		console.log(keychar);
		console.log(value);
		field.value = value;
		return false;
	}

	len = value.length - 1;
console.log(mask);
console.log(mask[len]);
	if (typeof(mask[len]) == 'undefined'){
		console.log('limit');
		return false;
	}

	// Number mask?
	if (mask[len] == '0'){

		// Not number?
		if (!/[0-9]/.test(keychar)){
			console.log('not number');
			return false;
		}

	}

	// Letter mask?
	if (mask[len] == 'A'){

		// Not letter?
		if (!/[a-z]/i.test(keychar)){
			console.log('not character: '+ keychar);
			return false;
		}

	}

	var nextlen = len + 1;

	// Do the next character autofill
	if (typeof(mask[nextlen]) != 'undefined'){
		nextChar = mask[nextlen];
console.log(nextChar);
		if (nextChar != '0' && nextChar != 'A'){
			field.value += nextChar;
		}
	}

	return true;
}*/

// Author: Mihai Bazon, 2006
// http://www.bazon.net/mishoo/
// This code is (c) Dynarch.com, 2006.
//
// Permission is hereby granted to use this code
// under the terms of the GNU LGPL. (www.gnu.org/licenses/lgpl.html)

var is_gecko = /gecko/i.test(navigator.userAgent);
var is_ie    = /MSIE/.test(navigator.userAgent);

function setSelectionRange(input, start, end) {
	if (is_gecko) {
		input.setSelectionRange(start, end);
	} else {
		// assumed IE
		var range = input.createTextRange();
		range.collapse(true);
		range.moveStart("character", start);
		range.moveEnd("character", end - start);
		range.select();
	}
};

function getSelectionStart(input) {
	if (is_gecko)
		return input.selectionStart;
	var range = document.selection.createRange();
	var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
	if (!isCollapsed)
		range.collapse(true);
	var b = range.getBookmark();
	return b.charCodeAt(2) - 2;
};

function getSelectionEnd(input) {
	if (is_gecko)
		return input.selectionEnd;
	var range = document.selection.createRange();
	var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
	if (!isCollapsed)
		range.collapse(false);
	var b = range.getBookmark();
	return b.charCodeAt(2) - 2;
};


Event.observe(window, 'load', function(){
	// Textareas
	$A(document.getElementsByTagName('textarea')).each(function (elm){
			Event.observe(elm, 'keydown', keyDown.bindAsEventListener(elm));
	});
	// Inputs - slightly more complicated
	$A(document.getElementsByTagName('input')).each(function (elm){
		if (elm.type != 'text'){
			return;
		}

		Event.observe(elm, 'keydown', keyDown.bindAsEventListener(elm));
	});

});

var alt_down = false;
var ctrl_down = false;

// For darley
function keyDown(e){
	var key;
	var isCtrl = false;
	var keychar;
	var reg;

	// MSIE
	if (window.event){
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	// Gecko
	else if (e.which){
		key = e.which;
		isCtrl = e.ctrlKey;
	}

	// Not a number?
	if (isNaN(key)){
		return true;
	}

	keychar = String.fromCharCode(key);

	if (key == 18){
		alt_down = true;
		return true;
	}
	else if (key == 17){
		ctrl_down = true;
		return true;
	}

	if (!alt_down){
		ctrl_down = false;
		alt_down = false;
		return;
	}

	alt_down = false;
	ctrl_down = false;

	newchar = false;

	switch(keychar.toUpperCase()){
		case 'U':
			newchar = 'ü';
		break;
		case 'O':
			newchar = 'ö';
		break;
		case 'S':
			newchar = 'ß';
		break;
		case 'E':
			newchar = 'é';
		break;
		case 'A':
			newchar = 'ä';
		break;
	}


	if (newchar){
		sel_start = getSelectionStart(this);
		sel_end = getSelectionEnd(this);
		this.value = this.value.substring(0, sel_start) + newchar + this.value.substring(sel_end);

		// Set the selection back
		setSelectionRange(this, sel_start + 1, sel_start + 1);

		Event.stop(e);
		return false;
	}

}

function visit_link(event, prefix){

	if (!prefix){
		prefix = '';
	}

	if (!this.value){
		$(this.id + '_vlink').hide();
	}
	else {
		$(this.id + '_vlink').show();

		if (prefix + this.value != $(this.id + '_vlink').href){
			$(this.id + '_vlink').href = prefix + this.value;
			new Effect.Highlight(this.id + '_vlink');
		}

	}

}

function updateMapLink(id, value){
	var maplink = $(id + '_maplink');


	if (!value){
		$(maplink).hide();
	}
	else {
		$(maplink).show();

		// Update the map link
		maplink.href = 'http://www.multimap.com/maps/?hloc=GB|' + escape(value);
		new Effect.Highlight(maplink);
	}

}

function setOpacity(testObj, value) {
	testObj.style.opacity = value/10;
	testObj.style.filter = 'alpha(opacity=' + value*10 + ')';

	return testObj;
}

function toggleDeleteFile(id){

	if ($F('file_' + id + '_delete') == 'nodelete'){
		$('file_' + id + '_delete').value = 'deletefile';

		setOpacity($('filetoggle_' + id), 4);
	}
	else {
		$('file_' + id + '_delete').value = 'nodelete';

		setOpacity($('filetoggle_' + id), 10);
	}

}

function percentage_of(percent){
	return percent / 100;
}