CriteriaCompleter = Class.create(Ajax.Autocompleter, {
	onClick: function(event) {
		var element = Event.findElement(event, 'LI');
		this.index = element.autocompleteIndex;
		this.selectEntry();
		//this.hide();
	},
	updateElement: function(selectedElement) {
		if (this.options.updateElement) {
			this.options.updateElement(selectedElement);
			return;
		}
		var value = '';
		if (this.options.select) {
			var nodes = $(selectedElement).select('.' + this.options.select) || [];
			if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
		} else {
			value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
	    }/*
		var bounds = this.getTokenBounds();
		if (bounds[0] != -1) {
			var newValue = this.element.value.substr(0, bounds[0]);
			var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
			if (whitespace) {
				newValue += whitespace[0];
			}
			this.element.value = newValue + value + this.element.value.substr(bounds[1]);
		} else {
			this.element.value = value;
		}*/
		this.element.value = value; // new bit
		this.oldElementValue = this.element.value;
		this.element.focus();
	    
		if (this.options.afterUpdateElement) {
			this.options.afterUpdateElement(this.element, selectedElement);
		}
	},
	onBlur: function(event) {
		// needed to make click events working
		//setTimeout(this.hide.bind(this), 250);
		//this.hasFocus = false;
		//this.active = false;     
	}
});

PostcodeCompleter = Class.create(Ajax.Autocompleter, {
	getUpdatedChoices: function(force_dig) {
		if (force_dig === undefined) {
			force_dig = 'no';
		}
		
		this.startIndicator();
    
		var entry = encodeURIComponent(this.options.paramName) + '=' + 
			encodeURIComponent(this.getToken());

		this.options.parameters = this.options.callback ?
			this.options.callback(this.element, entry) : entry;

		if(this.options.defaultParams) { 
			this.options.parameters += '&' + this.options.defaultParams;
		}
    	
    	if (force_dig == 'no') {
			new Ajax.Request(this.url, this.options);
		} else {
			new Ajax.Request(this.url + '&force_dig=yes', this.options);
		}
	},
	onClick: function(event) {
		if (Event.findElement(event, 'IMG')) {
			var img = Event.findElement(event, 'IMG');
			var li = Event.findElement(event, 'LI');
			this.index = li.autocompleteIndex;
			var oldValue = this.element.value;
			this.element.value = li.lastChild.nodeValue;
			this.tokenBounds = null;
			if (oldValue.toLowerCase() == this.element.value.toLowerCase()) {
				// Don't just repeat the same search, try going down a level
				this.getUpdatedChoices('yes');
			} else {
				this.getUpdatedChoices('no');
			}
		} else {
			var element = Event.findElement(event, 'LI');
			this.index = element.autocompleteIndex;
			this.selectEntry();
			//this.hide();
		}
	},
	updateElement: function(selectedElement) {
		if (this.options.updateElement) {
			this.options.updateElement(selectedElement);
			return;
		}
		var value = '';
		if (this.options.select) {
			var nodes = $(selectedElement).select('.' + this.options.select) || [];
			if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
		} else {
			value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
	    }/*
		var bounds = this.getTokenBounds();
		if (bounds[0] != -1) {
			var newValue = this.element.value.substr(0, bounds[0]);
			var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
			if (whitespace) {
				newValue += whitespace[0];
			}
			this.element.value = newValue + value + this.element.value.substr(bounds[1]);
		} else {
			this.element.value = value;
		}*/
		this.element.value = value; // new bit
		this.oldElementValue = this.element.value;
		this.element.focus();
	    
		if (this.options.afterUpdateElement) {
			this.options.afterUpdateElement(this.element, selectedElement);
		}
	},
	onBlur: function(event) {
		// needed to make click events working
		//setTimeout(this.hide.bind(this), 250);
		//this.hasFocus = false;
		//this.active = false;     
	}
});

ListLogic.rules = {
	'#search_criteria ul': function(ul) {
		new ListLogic.SearchCriteriaLoader(ul);
	},
	'li.business_type_popup': function(li) {
		li.observe('click', function(e) {
			$('business_type_menu').toggle();
		});
	},
	'a.u_sure': function(a) {
		a.observe('click', function(e) {
			var choice = confirm('Are you sure?');
			if (choice == false) {
				e.stop();
				return false;
			}
		});
	},
	'a#logout_link': function(a) {
		a.observe('click', function(e) {
			var choice = confirm('Are you sure you wish to log out? Your cart will be emptied any unsaved searches will be lost.');
			if (choice == false) {
				e.stop();
				return false;
			}
		});
	},
	'a.load_search': function(a) {
		a.observe('click', function(e) {
			var choice = confirm('Are you sure you wish to load this search? Any unsaved searches in your session will be lost.');
			if (choice == false) {
				e.stop();
				return false;
			}
		});
	},
	'a.license_terms_link': function(a) {
		a.observe('click', function(e) {
			e.stop();
			window.open(a.href, '', 'width=800,height=600');
		});
	},
	'input#purchase_data': function(input) {
		input.observe('click', function(e) {
			if($('records_count').innerHTML == '0') {
				alert("You have no criteria selected or haven't updated the count");
				e.stop();
				return false;
			}
			if ($('count_name')) {
				if ($('count_name').value == '' || $('count_name').value == 'Enter a name...') {
					alert('You must save your selection before purchasing.');
					e.stop();
					return false;
				} else {
					//new ListLogic.unt(input).update();
					//e.stop();
					//return false;
				}
			}
		});
	},
	'input#count_name': function(input) {
		new Ajax.Autocompleter('count_name',
			'count_name_autocomplete',
			'/searches/request/?request=autocomplete_count_name',
			{
				paramName: 'value',
				minChars: 2
			}
		);
	},
	'input.autocomplete': function(input) {
		ListLogic.Autocomplete.Criteria = $F(input.next('input.autocomplete_criteria'));
		new CriteriaCompleter(input, input.next('div.autocomplete'), $F(input.next('input.autocomplete_url'))+'&criteria='+$F(input.next('input.autocomplete_criteria')), {
			paramName: "value",
			minChars: 2,
			indicator: input.next('span.indicator'),
			afterUpdateElement: function(t, li) {
				ListLogic.Autocomplete.AddToSession(li.id, input.value);
			}
		});
	},
	'input.autocomplete_postcodes': function(input) {
		new PostcodeCompleter(input, input.next('div.autocomplete'), $F(input.next('input.autocomplete_url'))+'&criteria='+$F(input.next('input.autocomplete_criteria')), {
			paramName: "value",
			minChars: 1,
			indicator: input.next('span.indicator'),
			afterUpdateElement: function(t, li) {
				ListLogic.AutocompletePostcode.AddToSession(li.id, input.value);
			}
		});
	},
	'div.li_expand img': function(img) {
		img.observe('click', function(e) {
			e.stop();
		});
	},
	'input.ajax_checkbox': function(input) {
		input.observe('click', function(e) {
			ListLogic.Autocomplete.Criteria = input.id.replace(/_.+$/, '');
			// Ticked or not ticked?
			if (input.checked) {
				// Now we are ticked
				ListLogic.Autocomplete.AddToSession(input.value, input.previous('label').innerHTML);
			} else {
				// Now we are unticked
				ListLogic.Autocomplete.RemoveFromSession(input.value);
			}
		});
	},
	'img.delete_img': function(img){
		img.observe('click', function(e) {
			ListLogic.Autocomplete.Criteria = img.up('ul').id;
			var selected_criteria = new RegExp('selected_' + ListLogic.Autocomplete.Criteria + '_');
			ListLogic.Autocomplete.RemoveFromSession(img.up('li').id.replace(selected_criteria, ''));
		});
	},
	'#update_count': function(input){
		new ListLogic.UpdateCount(input);
	},
	'#edit_mailing_address a.copy_address': function(a){
		a.observe('click', function(e) {
			var fields = new Array('street1', 'street2', 'locality', 'town', 'county', 'postcode', 'country');
			fields.each(function(f) {
				$('customer_mailing_' + f).setValue($F('customer_invoice_' + f));
			});
		});
	},
	'#edit_delivery_address a.copy_address': function(a){
		a.observe('click', function(e) {
			var fields = new Array('street1', 'street2', 'locality', 'town', 'county', 'postcode', 'country');
			fields.each(function(f) {
				$('customer_delivery_' + f).setValue($F('customer_invoice_' + f));
			});
		});
	},
	'input.checkbox_data_type, input.extra': function(input) {
		input.observe('click', function(e) {
			ListLogic.Purchase.getTotals();
		});
	},
	'input#save_search, #name_cancel a': function(input) {
		input.observe('click', function(e) {
			$('count_name_container').toggle();
			e.stop();
		});
	},
	'#go_to_cart_fields': function(button) {
		button.observe('click', function(e) {
			ListLogic.Purchase.getTotals();
		});
	},
	'#go_to_cart_payment': function(button) {
		button.observe('click', function(e) {
			ListLogic.Purchase.getTotals();
		});
	},
	'#go_to_cart_summary': function(button) {
		button.observe('click', function(e) {
			ListLogic.Purchase.getTotals();
		});
	},
	'input#save_name': function(input) {
		input.observe('click', function(e) {
			e.stop();
			var options = {
				parameters: {
					name: $F('count_name')
				},
				onComplete: function(xhr) {
					var response = xhr.responseText;
					var sure = true;
					if(response == 'taken') {
						var sure = confirm("Using the same name as an existing search that has not been ordered will save over the existing search.");
					}
					if(sure) {
						$('count_name_container').toggle();
						new ListLogic.UpdateCount(input).update();
					}
				}
			};
			new Ajax.Request('/searches/checkname', options);
			
		});
	},
	/*
	'input#count_name': function(input) {
		if (input.value == '') {
			input.addClassName('type_here');
			input.value = 'Enter a name...';
		}
		input.observe('focus', function(e) {
			if (input.value == 'Enter a name...') {
				input.value = '';
				input.removeClassName('type_here');
			}
		});
		input.observe('blur', function(e) {
			if (input.value == '') {
				input.addClassName('type_here');
				input.value = 'Enter a name...';
			}
		});
	},
	*/
	'a#reset_criteria': function(a) {
		a.observe('click', function(e) {
			var choice = confirm('Are you sure?');
			if (choice == false) {
				e.stop();
				return false;
			}
			// Get selected criteria
			var criteria = $$('#search_criteria ul li.selected').first().id.replace(/^criteria_/,'');
			// Remove criteria data from session
			new Ajax.Request('/searches/request', {
				method: 'post',
				parameters: {
					request: 'rem_session',
					criteria: criteria
				},
				onSuccess: function(transport) {
					// Remove critera list
					if ($(criteria)) {
						$(criteria).up('li').fade({afterFinish:function(){
							if ($(criteria)) {
								$(criteria).up('li').remove();
							}
						}});
					}
					// Any checkboxes to untick?
					switch (criteria) {
						case 'turnover':
						case 'employees':
						case 'headoffice':
						case 'regions':
						case 'group':
							$$('ul#checkboxes_' + criteria + ' input.checkbox').each(function(cb){cb.checked=false});
							break;
					}
					// Un-Highligh sidebar option
					$('criteria_' + criteria).removeClassName('highlight');
					if ($$('ul#business_type_menu li.highlight').size() == 0) {
						$('business_type_menu_parent').removeClassName('highlight');
					}
				}
			});
			e.stop();
		});
	},
	/*'#cart_options li': function(li) {
		li.observe('click', function(e) {
			var fieldset = li.id.replace(/view_/,'');
			$$('#form_purchase fieldset').invoke('hide');
			$$('#cart_options li').each(function(li){
				li.removeClassName('selected');
				if (li.id == 'view_'+fieldset) {
					li.addClassName('selected');
				}
			});
			if ($(fieldset)) {
				$(fieldset).appear();
			}
		});
	},*/
	'input.skip_to_payment': function(input) {
		input.observe('click', function(e) {
			$$('#form_purchase fieldset').invoke('hide');
			$('cart_payment').appear();
			$$('#cart_options li').each(function(li){
				li.removeClassName('selected');
			});
			$('view_cart_payment').addClassName('selected');
			e.stop();
		});
	},
	'input.edit_save': function(button) {
		button.up('form').observe('submit', function(e) {
			if(button.up('fieldset').visible()) {
				var fields = button.up('fieldset').getElementsBySelector('input').reject(function(field) {
					return field.name.match(/password/);
				});
				if(!validateFields(fields, button.up('fieldset').id)) {
					e.stop();
				}
			}
		});
	},
	'#register_button': function(button) {
		button.up('form').observe('submit', function(e) {
			if(button.up('fieldset').visible()) {
				var fields = button.up('fieldset').getElementsBySelector('input');
				if(!validateFields(fields, button.id)) {
					e.stop();
				}
			}
		});
	},
	'input.go_to': function(input) {
		input.observe('click', function(e) {
			e.stop();
			var fields = input.up('fieldset').getElementsBySelector('input');
			
			if(!validateFields(fields, input.id)) {
				return false;
			}
		
			var go_to = input.id.replace(/^go_to_/,'');
			$$('fieldset').invoke('hide');
			$(go_to).appear({duration:0.2});
			$$('div.right_side li').each(function(li){
				li.removeClassName('selected');
			});
			$('view_' + go_to).addClassName('selected');
		});
	},
	'input.go_back': function(input) {
		input.observe('click', function(e) {
			e.stop();
			var fields = input.up('fieldset').getElementsBySelector('input');
			
			if(!validateFields(fields, input.id)) {
				return false;
			}
		
			var go_to = input.id.replace(/^go_back_/,'');
			$$('fieldset').invoke('hide');
			$(go_to).appear({duration:0.2});
			$$('div.right_side li').each(function(li){
				li.removeClassName('selected');
			});
			$('view_' + go_to).addClassName('selected');
		});
	},	
	'#search_cart': function(div) {
		// Trigger total calculation on load
		ListLogic.Purchase.getTotals();
	},
	'#customers_new #customer_edit_nav a': function(a) {
		a.observe('click', function(e) {
			var go_to = a.up('li').id.replace(/^view_/,'');
			$$('fieldset').invoke('hide');
			$(go_to).appear();
			$$('div.right_side li').each(function(li){
				li.removeClassName('selected');
			});
			$('view_' + go_to).addClassName('selected');
			e.stop();
		});
	},
	'#save_search_guest': function(button) {
		button.observe('click', function(e) {
			e.stop();
			window.location = '/searches/guestsave';
		});
	},
	'#extra_confirm input': function(checkbox) {
		checkbox.observe('change', function(e) {
			this.up('p').toggleClassName('confirmed');
		});
	},
	'#customers_new #register_button': function(button) {
		button.observe('click', function(e) {
			e.stop();
			var form = this.up('form');
			var container = new Element('fieldset').update('<legend>Confirm Your Details</legend>');
			container.update('<div class="form_desc">Check your details below and click "Save" if they\'re ok, or "Go Back" if not.</div>');
			form.getElementsBySelector('fieldset').each(function(fs) {
				fs.hide();
				var sub = new Element('div', {className: 'customer_details'});
				var title = new Element('h2').update(fs.down('legend').innerHTML);
				sub.insert({top: title});
				fs.getElementsBySelector('input[type=text]').each(function(input) {
					if($F(input)) {
						sub.insert($F(input) + '<br />');
					}
				});
				container.insert(sub);
			});
			container.insert('<div class="customer_details preview"><input type="submit" value="Save" type="submit" />'
			+'<input type="button" class="go_back" id="go_back_edit_delivery_address" value="Go Back" /></div>');
			form.insert(container);
			container.down('input.go_back').observe('click', function(e) {
				setTimeout(function() {
					container.remove();
				}, 500);
			});
			ListLogic.Behaviour.go(container);
		});
	},
	'form.home_confirm': function(form) {
		form.observe('submit', function(e) {
			var sure = confirm("Creating a new search will clear any existing criteria, are you sure you want to do that?");
			if(!sure) {
				e.stop();
			}
		});
	},
	'#price_explain_trigger': function(link) {
		link.observe('click', function(e) {
			e.stop();
			$('price_explain').show();
		});
	},
	'#explain-close': function(link) {
		link.observe('click', function(e) {
			e.stop();
			$('price_explain').hide();
		});
	},
	'#smax_limit': function(radio) {
		radio.observe('click', smax_toggling);
	},
	'#smax_all': function(radio) {
		radio.observe('click', smax_toggling);
	},
	'#smax_limit_value': function(input) {
		new Form.Element.Observer(
			input,
			0.2,
			function(el, value) {
				if(value) {
					$('smax_all').checked = false;
					$('smax_limit').checked = true;
				}
			}
		);
		
	},
	'#checkout_form': function(form) {
		form.observe('submit', function(e) {
			if(!$F('extra_confirm_box')) {
				e.stop();
				if (!$('errors')) {
					$('flash').insert(
						new Element('ul', {id: 'errors'})
					);
				}
				else {
					$('errors').update();
				}
				$('errors').insert(
					new Element('li').update('You must tick to confirm you understand our Terms & conditions, and that refunds/reruns are not possible.')
				);
				$('errors').scrollTo();
			}
		});
	}
}

function smax_toggling(e) {
	if($('smax_limit').checked) {
		$('smax_limit_value').activate();
	}
	else {
		$('smax_limit_value').setValue('');
	}
}

ListLogic.Behaviour.add(ListLogic.rules);

function validateFields(fields, key) {
	var errors = [];
	fields.each(function(field) {
		if(field.up().previous() && field.up().previous().down('label')) {
			var label = field.up().previous().down('label').innerHTML;
			if((field.hasClassName('required') || label.match(/\*$/)) && $F(field) == '') {
				var tag = label.replace(' *','');
				errors.push( tag + ' is a required field');
			}
		}
	});
	switch(key) {
		case 'go_to_edit_customer': //the button on the Account Details section
			var email = $F('customer_email_address');
			if(email) {
				var options = {
					method: 'get',
					parameters: {
						email: email
					},
					asynchronous: false,
					onComplete: function(xhr) {
						if(xhr.responseText == 'taken') {
							errors.push('Someone has already registered with that email address, <a href="/login">click to login</a>');
						}
						else if(xhr.responseText == 'invalid') {
							errors.push('The email address you entered is invalid');
						}
					}
				};
				new Ajax.Request('/customers/checkemail', options);
			}
			//fall-through
		case 'edit_account': 
			['email_address', 'password'].each(function(fieldname) {
				var one = $F('customer_' + fieldname);
				var two = $F('customer_' + fieldname + '_confirm');
				if(one != two) {
					errors.push("The " + fieldname.replace('_',' ') + " fields must be identical");
				}
			});
		break;
		case 'go_to_edit_invoice_address':
			var phone = $F('customer_telephone');
			if(phone.match(/^[\d- #+]*$/) == null) {
				errors.push("Invalid characters in your telephone number");
			}
			var mobile = $F('customer_mobile');
			if(mobile.match(/^[\d- #+]*$/) == null) {
				errors.push("Invalid characters in your mobile number");
			}
		break;
	}
	if(errors.length > 0) {
		if(!$('errors')) {
			var list = new Element('ul',{id:'errors'});
			$('flash').update(list);
		}
		$('errors').update();
		errors.each(function(text) {
			$('errors').insert('<li>' + text + '</li>');
		});
		return false;
	}
	if($('errors')) {
		$('errors').remove();
	}
	return true;
}

ListLogic.SearchCriteriaLoader = Class.create();
ListLogic.SearchCriteriaLoader.prototype = {
	current: 'yell_classification_desc',
	initialize: function(ul){
		this.ul = $(ul);
		this.countSection = $('left_column');
		this.selectedClass = 'selected';
		this.ul.childElements().each(function(li) {
			li.observe('click', this.switchSearch.bindAsEventListener(this));
			if (li.hasClassName(this.selectedClass)) {
				this.selectedLi = li;
			}
		}.bind(this));
	},
	switchSearch: function(e) {
		var li = Event.element(e);
		if (!li.hasClassName(this.selectedClass) && li.id != 'business_type_menu_parent') {
			$$('ul#main_criteria_list li').invoke('removeClassName', 'selected');
			$$('ul#business_type_menu li').invoke('removeClassName', 'selected');
			if (li.hasClassName('child') && li.hasClassName('business_type_popup')) {
				$('business_type_menu_parent').addClassName('selected');
			} else {
				if ($('business_type_menu').visible()) {
					$('business_type_menu').hide();
				}
			}
			// Switch the selected class from the current selected li to this one
			if(this.selectedLi) {
				this.selectedLi.removeClassName(this.selectedClass);
			}
			li.addClassName(this.selectedClass);
			this.selectedLi = li;
			// Replace contents of #count_section with loading image
			this.countSection.update(new Element('img', {src:'/graphics/ajax-loader.gif',className:'ajax_loading'}));
			// Get the html for this section
			new Ajax.Updater(this.countSection, '/searches/request', {
				parameters:{request:'template',criteria:li.id},
				onComplete:this.complete.bind(this)
			});
			this.current = li.id.replace('criteria_','');
			
			// Show only the relevant criteria list
			$$('#selected_criteria li').invoke('hide');
			if ($(this.current)) {
				$$('ul#' + this.current + ' li').invoke('show');
				$(this.current).up('li').show();
				$$('ul#' + this.current).invoke('show');
			}
			
			// Hide criteria summary if shown
			if ($('selected-criteria-summary-content')) {
				$('selected-criteria-summary-content').hide();
				$('selected-criteria-summary-toggle').innerHTML = 'more';
			}
		}
	},
	complete: function(xhr){
		ListLogic.Behaviour.go(this.countSection);
	}
}

ListLogic.Autocomplete = {
	Criteria: '',
	AddToList: function(transport){
		if (transport.responseJSON) {
			// Create parent list first?
			if (!$(transport.responseJSON.criteria)) {
				var label = '';
				var isChild = false;
				switch (transport.responseJSON.criteria) {
					case 'group':
						label = 'Business Group';
						isChild = true;
						break;
					case 'sector':
						label = 'Business Sector';
						isChild = true;
						break;
					case 'yell':
						label = 'Business Classification';
						isChild = true;
						break;
					case 'sicuk':
						label = 'SIC (UK)';
						isChild = true;
						break;
					case 'sicnace':
						label = 'SIC (NACE)';
						isChild = true;
						break;
					case 'headoffice':
						label = 'Head Office / Principle Location';
						break;
					default:
						label = transport.responseJSON.criteria.capitalize();
						break;
				}
				$('selected_criteria').insert(
					new Element('li').insert(
						new Element('h2').update('Selected ' + label)
					).insert(
						new Element('ul', {id:transport.responseJSON.criteria})
					)
				);
				// Highligh sidebar option
				$('criteria_' + transport.responseJSON.criteria).addClassName('highlight');
				if (isChild) {
					$('business_type_menu_parent').addClassName('highlight');
				}
			}
			// Add the item itself
			$(transport.responseJSON.criteria).insert(
				new Element('li', {id: 'selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key}).update(
					new Element('img', {className: 'delete_img', src:'/graphics/delete_list.png'})).insert(
						transport.responseJSON.value
					).insert(transport.responseJSON.name).observe('click', function(e) {
						var img = Event.element(e);
						ListLogic.Autocomplete.Criteria = img.up('ul').id;
						var selected_criteria = new RegExp('selected_' + ListLogic.Autocomplete.Criteria + '_');
						ListLogic.Autocomplete.RemoveFromSession(img.up('li').id.replace(selected_criteria,''));
					}).hide().appear()
			);
		}
	},
	RemoveFromList: function(transport){
		// Last item in list?
		if ($$('ul#' + transport.responseJSON.criteria + ' li').length == 1 &&
			$('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key)) {
			// Remove list parent
			$(transport.responseJSON.criteria).up('li').fade({afterFinish:function(){
				if ($(transport.responseJSON.criteria)) {
					$(transport.responseJSON.criteria).up('li').remove();
				}
			}});
			// Un-Highligh sidebar option
			$('criteria_' + transport.responseJSON.criteria).removeClassName('highlight');
			if ($$('ul#business_type_menu li.highlight').size() == 0) {
				$('business_type_menu_parent').removeClassName('highlight');
			}
		} else {
			// Just remove the list item
			$('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key).fade({afterFinish:function(){
				if ($('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key)) {
					$('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key).remove();
				}
			}});
		}
		// Checkbox to untick too?
		if ($(transport.responseJSON.criteria + '_' + transport.responseJSON.key)) {
			$(transport.responseJSON.criteria + '_' + transport.responseJSON.key).checked = false;
		}
	},
	AddToSession: function(key, value){
		new Ajax.Request('/searches/request', {
			method: 'post',
			parameters: {
				request: 'add_session',
				criteria: ListLogic.Autocomplete.Criteria,
				key: key,
				value: value
			},
			onSuccess: ListLogic.Autocomplete.AddToList
		});
	},
	RemoveFromSession: function(key){
		new Ajax.Request('/searches/request', {
			method: 'post',
			parameters: {
				request: 'rem_session',
				criteria: ListLogic.Autocomplete.Criteria,
				key: key
			},
			onSuccess: ListLogic.Autocomplete.RemoveFromList
		});
	}
}

ListLogic.AutocompletePostcode = {
	Criteria: 'postcodes',
	AddToList: function(transport) {
		if (transport.responseJSON) {
			// Create parent list first?
			if (!$(transport.responseJSON.criteria)) {
				var label = 'Postcodes';
				$('selected_criteria').insert(
					new Element('li').insert(
						new Element('h2').update('Selected ' + label)
					).insert(
						new Element('ul', {id:transport.responseJSON.criteria})
					)
				);
				// Highligh sidebar option
				$('criteria_postcodes').addClassName('highlight');
			}
			$(transport.responseJSON.criteria).insert(
				new Element('li', {id: 'selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key}).update(
					new Element('img', {className: 'delete_img', src:'/graphics/delete_list.png'})).insert(
						transport.responseJSON.value
					).insert(transport.responseJSON.name).observe('click', function(e) {
						var img = Event.element(e);
						var selected_criteria = new RegExp('selected_' + ListLogic.AutocompletePostcode.Criteria + '_');
						ListLogic.AutocompletePostcode.RemoveFromSession(img.up('li').id.replace(selected_criteria,''));
					}).hide().appear()
			);
		}
	},
	RemoveFromList: function(transport){
		// Last item in list?
		if ($$('ul#' + transport.responseJSON.criteria + ' li').length == 1 &&
			$('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key)) {
			// Remove list parent
			$(transport.responseJSON.criteria).up('li').fade({afterFinish:function() {
				if ($(transport.responseJSON.criteria)) {
					$(transport.responseJSON.criteria).up('li').remove();
				}
			}});
			// Un-Highligh sidebar option
			$('criteria_postcodes').removeClassName('highlight');
			if ($$('ul#business_type_menu li.highlight').size() == 0) {
				$('business_type_menu_parent').removeClassName('highlight');
			}
		} else {
			// Just remove the list item
			$('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key).fade({afterFinish:function(){
				if ($('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key)) {
					$('selected_' + transport.responseJSON.criteria + '_' + transport.responseJSON.key).remove();
				}
			}});
		}
	},
	AddToSession: function(key, value){
		new Ajax.Request('/searches/request', {
			method: 'post',
			parameters: {
				request: 'add_session',
				criteria: ListLogic.AutocompletePostcode.Criteria,
				key: key,
				value: value
			},
			onSuccess: ListLogic.AutocompletePostcode.AddToList
		});
	},
	RemoveFromSession: function(key){
		new Ajax.Request('/searches/request', {
			method: 'post',
			parameters: {
				request: 'rem_session',
				criteria: ListLogic.AutocompletePostcode.Criteria,
				key: key
			},
			onSuccess: ListLogic.AutocompletePostcode.RemoveFromList
		});
	}
}

ListLogic.UpdateCount = Class.create();
ListLogic.UpdateCount.prototype = {
	params: {},
	initialize: function(input) {
		this.input = $(input);
		this.input.observe('click', this.inputClickListener.bindAsEventListener(this));
		this.loadingImg = $('loading_div_img');
		this.summaryContainer = $('selected-criteria-summary');
		this.summaryContent = $('selected-criteria-summary-content');
		this.summaryToggle = $('selected-criteria-summary-toggle');
		this.summaryToggle.observe('click', this.summaryToggleClickListener.bindAsEventListener(this));
		if (location.href.match(/\/post/) && input.id == 'update_count') {
			// Trigger update on load
			this.update();
		}
		this.updateSummary();
	},
	inputClickListener: function(e) {
		e.stop();
		this.update();
	},
	update: function() {
		if($('ajax_form')){
			this.params = $('ajax_form').serialize(true);
		}
		this.params.request = 'update_count';
		if ($('count_name')) {
			this.params.name = $('count_name').getValue();
		}
		new Ajax.Request('/searches/request', {
			method: 'get',
			onCreate: this.start.bind(this),
			parameters: this.params,
			onSuccess: this.success.bind(this),
			onFailure: function() {
				window.location = window.location;
			}
		});
	},
	start: function() {
		// Hide errors
		if ($('errors')) {
			$('errors').remove();
		}
		// Logged in, another field to cover
		this.loadingImg.addClassName('logged_in');
		this.loadingImg.appear();
	},
	success: function(transport) {
		this.loadingImg.fade();
		if (transport.responseJSON) {
			var errors = transport.responseJSON.errors;
			var purchase_ok = transport.responseJSON.purchase_ok;
			if (errors.size()) {
				if (!$('errors')) {
					$('flash').insert(
						new Element('ul', {id: 'errors'})
					);
				}
				errors.each(function(err) {
					$('errors').insert(
						new Element('li').update(err)
					);
				});
			} else {
				$('records_count').update(transport.responseJSON.count);
				$('records_count_price').update(transport.responseJSON.price);
				if (purchase_ok) {
					$('purchase_data').writeAttribute('src', '/graphics/purchase_data.png');
				}
				this.updateSummary();
			}
		}
	},
	summaryToggleClickListener: function(e) {
		e.stop();
		if (this.summaryToggle.innerHTML == 'more') {
			this.summaryContent.show();
			this.summaryToggle.innerHTML = 'close';
		} else {
			this.hideSummary();
			this.summaryToggle.innerHTML = 'more';
		}
	},
	updateSummary: function() {
		new Ajax.Updater(this.summaryContent, '/searches/request', {
			parameters:{request:'summary'},
			onComplete:this.summaryComplete.bind(this)
		});
	},
	hideSummary: function() {
		this.summaryContent.hide();
	},
	summaryComplete: function() {
		if (this.summaryContent.down('ul')) {
			this.summaryToggle.innerHTML = 'close';
			this.summaryContainer.show();
			this.summaryContent.show();
		} else {
			this.summaryContainer.hide();
		}
	}
}

ListLogic.Purchase = {
	updateTotals: function(transport) {
		$('total_ppr').innerHTML = transport.responseJSON.total_ppr;
		$('summary_total_ppr').innerHTML = 'x ' + transport.responseJSON.total_ppr;
		$('subtotal').innerHTML = transport.responseJSON.subtotal;
		$('selected_format').innerHTML = transport.responseJSON.format_name;
		$('summary_format_price').innerHTML = '+ ' + transport.responseJSON.format_price;
		$('selected_license').innerHTML = transport.responseJSON.license_name;
		$('summary_license_multiplier').innerHTML = 'x ' + transport.responseJSON.license_multiplier;
		$('selected_shipping').innerHTML = transport.responseJSON.shipping_name;
		$('summary_shipping_price').innerHTML = '+ ' + transport.responseJSON.shipping_price;
		$('total_price').innerHTML = transport.responseJSON.total_price;
		$('records_count_price').innerHTML = transport.responseJSON.total_price;
		if(transport.responseJSON.smax_value) {
			var total_str = '#{smax_value} of #{total_count}'.interpolate(transport.responseJSON);
		}
		else {
			var total_str = '#{total_count}'.interpolate(transport.responseJSON);
		}
		switch (transport.responseJSON.dedupe) {
			case '':
			case 'NONE':
				$('selected_deduplication').innerHTML = 'None';
				break;
			case 'ALL':
				$('selected_deduplication').innerHTML = 'All previous orders';
				break;
			default:
				$('selected_deduplication').innerHTML = 'Order ' + transport.responseJSON.dedupe;
				break;
		}
		$('summary_deduplication_price').update(transport.responseJSON.dedupe_price);
		$('records_count').update(total_str);
		$('summary_count').update(total_str);
		
		if (transport.responseJSON.below_minimum) {
			// Alert the user
			if (!$('messages')) {
				$('flash').insert(
					new Element('ul', {id: 'messages'})
				);
			}
			else {
				$('messages').update();
			}
			$('messages').insert(
				new Element('li').update('The minimum order value of ' + transport.responseJSON.subtotal + ' has been applied to your order.')
			);
		}
		else if($('messages')){
			$('messages').remove();
		}
	},
	getTotals: function() {
		var fields = $$('input.checkbox_data_type').findAll(function(cb){return cb.checked}).pluck('value');
		if ($('form_purchase')) {
			var form = $('form_purchase');
			var selected_format = form.getInputs('radio', 'order[format]').find(function(rb){return rb.checked}).getValue();
			var selected_license = form.getInputs('radio', 'order[license]').find(function(rb){return rb.checked}).getValue();
			var selected_shipping = form.getInputs('radio', 'order[shipping_method]').find(function(rb){return rb.checked}).getValue();
			
			var params = {
				request: 'get_totals',
				fields: fields.toJSON(),
				format: selected_format,
				license: selected_license,
				shipping: selected_shipping
			};
			if($F('smax_limit')) {
				params.smax_value = $F('smax_limit_value');
			}
			if($F('order_dedupe')) {
				params.dedupe = $F('order_dedupe');
			}
			if ($F('order_discount_code')) {
				params.discount_code = $F('order_discount_code');
			}
			new Ajax.Request('/orders/request', {
				method: 'post',
				parameters: params,
				onSuccess: ListLogic.Purchase.updateTotals				
			});
		}
	}
}