function addPart(partID, partName, dom_container)
{
	var dom_loadingImage = document.createElement('img');
	dom_loadingImage.setAttribute('class', 'loading_image');
	dom_loadingImage.setAttribute('src', '/res/images/ajax-loader-l.gif');
	dom_container.appendChild(dom_loadingImage);
	
	jQuery.post
	(
		'/api/part/getquestions',
		{'partID':partID},
		function(data, textStatus)
		{
			processPartQuestions(data, partID, partName, dom_container.id)
		},
		'json'
	);
	
	return true;
}

function addProduct(productID, selVehicleID, dom_container)
{
	jQuery.post
	(
		'/api/basket/addproduct',
		{'productID':productID, 'selVehicleID':selVehicleID},
		function(data, textStatus)
		{
			updateBasket(data, textStatus);
			refreshBasketVehicle();
		},
		'json'
	);
	return true;
}

function removePart(partID)
{
	//$('#basket-loading').css('visibility', 'visible');
	jQuery.post('/api/basket/remove', {'partID':partID}, updateBasket, 'json');
	return true;
}
function updateBasket(data, textStatus)
{
	$('#basket-preview').html(data.data.content);
	//document.getElementById('header-basket-fields').innerHTML = data.data.headerbasket;
	$('#header-basket-fields').html(data.data.basketheader);
	
	//update number of items display
	var numItemsHTML = data.data.count + ' Items <img style="float: none; padding-top: 5px;" alt="open" src="/res/images/basket-header/basketopen.png"/>';
	$('#topbasketImage').html(numItemsHTML);
	
	window.location = '#top';
	
	if(data.data.newitem)
	{
		// Flash the new item up in red for a moment to attract the customers attention.
		$('#' + data.data.newitem).animate
		(
			{backgroundColor: '#990000'},
			'slow',
			'swing',
			function()
			{
				setTimeout(function()
				{
					$('#' + data.data.newitem).animate({backgroundColor: 'white'}, 'slow', 'swing');
				}, 500);
			}
		);
	}
}

function updateVehiclePreview(data, message)
{
	$('#vehicle-preview').html(data.data.content);
	if(message)
	{
		showHint({id:'hint_vehicle', style:'width: 190px; left: -203px; top: -27px;', html:message, directions:['right'], container: '#vehicle-preview'});
	}
}

function processPartQuestions(data, partID, partName, domID)
{
	var fields = new Array();
	var field;
	
	if(data.data.questions.fields && (data.data.questions.fields.length || data.data.isTyre))
	{
		// There are some questions that must be answered before the part can be added to the basket.
		var dom_form = createElement('div', 'partQuestions');
		
		if(data.data.isTyre)
		{
			var tp = new TyrePicker();
			
			var dom_tyrePicker = createElement('div', 'TyrePicker');
			tp.setDomRoot(dom_tyrePicker);
			dom_form.appendChild(tp.draw());
			
			if(tp.isLoading())
			{
				tp.showLoading('Loading Tyre Finder, please wait...');
			}
			var dom_side = createElement('div', '');
			dom_side.id = 'car_sides';
			tp.getDomRoot().appendChild(dom_side);
		}
		else
		{
			var dom_error = createElement('p', 'error');
			dom_error.style.display = 'none';
			dom_error.appendChild(document.createTextNode('Please select at least one of these options.'));
			dom_form.appendChild(dom_error);
			
			var dom_questions = createElement('div', 'questions');
			
			for(var x = 0; x < data.data.questions.fields.length; x++)
			{
				var dom_fieldset = createElement('div', 'fieldset');
				
				if(data.data.questions.fields[x].type == 27)
				{
					// Checkboxes
					var dom_fieldsetLabel = createElement('div', 'PartOptionsHelp');
					dom_fieldsetLabel.appendChild(document.createTextNode(data.data.questions.fields[x].label));
					dom_fieldset.appendChild(dom_fieldsetLabel);
					
					var tmpOptions = data.data.questions.fields[x].options;
					
					for(var y = 0; y < tmpOptions.length; y++)
					{
						var field = new CheckboxField();
						field.setLabel(tmpOptions[y].label);
						field.setName(data.data.questions.fields[x].name + '-' + tmpOptions[y].id);
						fields.push(field);
						
						dom_fieldset.appendChild(field.draw());
					}
				}
				else if(data.data.questions.fields[x].type == 25)
				{
					// Select field
					var select = new SelectField();
					
					var tmpOptions = data.data.questions.fields[x].options;
					var options = new Object();
					for(var y = 0; y < tmpOptions.length; y++)
					{
						options[tmpOptions[y].id] = tmpOptions[y].label;
					}
					
					select.setLabel(data.data.questions.fields[x].label);
					select.setName(data.data.questions.fields[x].name);
					select.setOptions(options);
					fields.push(select);
					
					var dom_wrapper = createElement('div', 'alloy-dropdown');
					dom_wrapper.appendChild(select.draw())
					
					dom_fieldset.appendChild(dom_wrapper);
				}
				dom_questions.appendChild(dom_fieldset);
				
				if(data.data.questions.fields[x].type == 25 && x < (data.data.questions.fields.length - 1))
				{
					dom_questions.appendChild(createElement('div', 'clear-both'));
				}
				
				var questionID = data.data.questions.fields[x].id;
			}
			
			var dom_side = createElement('div', '');
			dom_side.id = 'car_sides';
			dom_questions.appendChild(dom_side);
			
			dom_questions.appendChild(createElement('div', 'clear'));
			
			dom_form.appendChild(dom_questions);
		}
		
		var dialogOptions =
		{
			bgiframe: true,
			modal: true,
			title: 'Options for ' + partName,
			width: 580,
			height: 279,
			close: function()
			{
				$('#' + domID + ' img.loading_image').remove();
				jQuery(this).remove();
			},
			dialogClass: 'question_' + questionID+' part_'+partID
		}
		
		dialogOptions['buttons'] = new Object();
		
		dialogOptions['buttons']['Continue'] = function()
		{
			var ok = true;
			var postData = {'partID':partID, 'name':partName};
			
			var found;
			
			if(!data.data.isTyre)
			{
				// Validate the fields, based on the field type.
				// @todo At the moment this assumes all fields are of the same type.
				if(data.data.questions.fields[0].type == 27)
				{
					// Checkbox fields.
					// Make sure at least one option was picked.
					found = false;
					for(var x = 0; x < fields.length; x++)
					{
						if(fields[x].getValue())
						{
							found = true;
							postData[fields[x].getName()] = fields[x].getValue();
						}
					}
				}
				else if(data.data.questions.fields[0].type == 25)
				{
					// Select fields.
					// Make sure every field has a value.
					var found = true;
					for(var x = 0; x < fields.length; x++)
					{
						if(fields[x].getValue() == '')
						{
							$(dom_error).text('Please select all of these options');
							found = false;
							break;
						}
						else
						{
							postData[fields[x].getName() + '-' + fields[x].getValue()] = 1;
						}
					}
				}
			}
			else
			{
				found = tp.validate();
				postData['TyreCode'] = tp.getCode();
			}
			
			if(found)
			{
				jQuery(this).dialog('close');

				var dom_loadingImage = document.createElement('img');
				dom_loadingImage.setAttribute('class', 'loading_image');
				dom_loadingImage.setAttribute('src', '/res/images/ajax-loader-l.gif');
				$('#' + domID).append(dom_loadingImage);
				
				jQuery.post
				(
					'/api/basket/add',
					postData,
					function(data, textStatus)
					{
						$('#' + domID + ' img.loading_image').remove();
						updateBasket(data, textStatus);
					},
					'json'
				);
			}
			else
			{
				$(dom_error).fadeIn('slow');
			}
		}
		
		dialogOptions['buttons']['Cancel'] = function()
		{
			jQuery(this).dialog('close');
		}
		
		jQuery(dom_form).dialog(dialogOptions);
		
		$('.ui-dialog-buttonpane button:first').addClass('continue_part');
		$('.ui-dialog-buttonpane button:last').addClass('cancel_part');
	}
	else
	{
		// There are no questions for this part, we can just add it straight away.
		jQuery.post
		(
			'/api/basket/add',
			{'partID':partID, 'name':partName},
			function(data, textStatus)
			{
				updateBasket(data, textStatus);
				
				// For some reason then simply selecting the image by its class doesn't seem to work here in IE. 
				$('#' + domID + ' img:last').remove();
			},
			'json'
		);
	}
}

function emptyBasket()
{
	if(confirm('Are you sure you want to empty your basket?'))
	{
		$.get('/api/basket/empty', '', updateBasket, 'json');
	}
}

function showErrorPopup(errors)
{
	var dom_popup = createElement('div', 'popup');
	
	var dom_introduction = createElement('div', 'p');
	dom_introduction.appendChild(document.createTextNode('Sorry, but we have detected a problem with the details provided. Please click the continue button and then correct the following problems.'));
	dom_popup.appendChild(dom_introduction);

	var dom_errors = createElement('ul', 'errors');

	for(var index in errors)
	{
		var dom_error = createElement('li', 'error');
		dom_error.appendChild(document.createTextNode(errors[index]));
		dom_errors.appendChild(dom_error);
	}
	
	dom_popup.appendChild(dom_errors);
	
	$(dom_popup).dialog
	(
		{
			bgiframe: true,
			buttons: { "Continue": function() { $(this).dialog("close");}},
			modal: true,
			title: 'Submission problem',
			width: 430
		}
	);
}

function clearVRMfield()
{
	if($('#vrm').val() == 'Type reg')
	{
		$('#vrm').val('').css('color', 'black');
	}
}

function populateVRMfield()
{
	if($('#vrm').val() == '')
	{
		$('#vrm').css('color', '#DCDCDC').val('Type reg');
	}
}

function updatePartsList(obj)
{
	// Clean out the current parts list.
	var id = obj.id.split('_')[1];
	var dom_select = document.getElementById('subparts_' + id);

	while(dom_select.firstChild)
	{
		dom_select.removeChild(dom_select.firstChild);
	}

	var onreturn = function(data)
	{
		var dom_option;

		var id = obj.id.split('_')[1];
		var dom_select = document.getElementById('subparts_' + id);

		for(part in data)
		{
			dom_option = document.createElement('option');
			dom_option.value=part;
			if(part == '')
			{
				dom_option.disabled = true;
			}
			dom_option.appendChild(document.createTextNode(data[part]));
			dom_select.appendChild(dom_option);
		}
		dom_select.selectedIndex = 0;
	}
	var ticket = requestProcess.add(new Request('GET', '/res/cache/parts/'+obj.value.replace(/\//g,'-').replace(/ /g,'-').toLowerCase()+'.json','', onreturn, function(){}));
}

$(document).ready(function()
{
	$('.part_titles .help').mouseover(function()
	{
		$(this).nextAll('.help_content').fadeIn('slow');
	});
	
	$('.part_titles .help').mouseout(function()
	{
		$(this).nextAll('.help_content').fadeOut('slow');
	});
	
	$('#browse-searchform').submit(function(){
		if(!$('#browse-search').hasClass('hasValue'))
		{
			showHint({
				html: 'Oops! Type in the part name you are searching for',
				id: 'search_hint',
				container: '#browse-searchform',
				directions: ['top'],
				style: 'top: 40px; left: 60px;'
			});
			return false;
		}
	});
	
	$('#browse-search-reg').keypress(function(event){
		// Prevent insertion of spaces.
		if(event.which == 32)
		{
			return false;
		}
		
		// We shouldn't allow more than 7 characters to be inserted.
		if($('#browse-search-reg').val().length == 7)
		{
			// Even when the field is full, we still need to let delete, return and backspace work.
			// 8 is backspace
			// 13 is return
			// 0 seems to cover lots of special keys, including delete and the arrow keys.
			if(event.which != 8 && event.which != 13 && event.which != 0)
			{
				return false;
			}
		}
	});
});

function addCustomPart(categoryName, partName)
{
	var dom_fields = createElement('div', 'addCustomPart');
	
	var dom_help = createElement('div', 'help');
	var dom_p1 = document.createElement('p');
	dom_p1.appendChild(document.createTextNode('If you cannot find the part you are looking for, please use the drop down menu below to tell us what part you are looking for.'));
	dom_help.appendChild(dom_p1);
	
	var dom_list = document.createElement('ol');
	
	var dom_item1 = document.createElement('li');
	dom_item1.appendChild(document.createTextNode('Firstly select a Part Catagory that you think your part falls into e.g engines'));
	dom_list.appendChild(dom_item1);
	
	var dom_item2 = document.createElement('li');
	dom_item2.appendChild(document.createTextNode('Type the name of the part your are looking for.e.g control valve'));
	dom_list.appendChild(dom_item2);
	
	dom_help.appendChild(dom_list);
	
	dom_fields.appendChild(dom_help);
	
	var dom_error = createElement('div', 'error');
	dom_error.appendChild(document.createTextNode('Please enter the part required'));
	dom_error.style.display = 'none';
	dom_fields.appendChild(dom_error);
	
	var dom_categoryField = createElement('div', 'field');
	var dom_categoryLabel = createElement('label', 'label');
	dom_categoryLabel.setAttribute('for', 'categoryField');
	dom_categoryLabel.appendChild(document.createTextNode('Part category'));
	dom_categoryField.appendChild(dom_categoryLabel);
	
	var dom_categories = createElement('select', 'categories');
	
	// Load the category data.
	$.get
	(
		'/api/part/getcategories',
		'',
		function(data, textStatus)
		{
			var categories = data.data;
			
			for(var x = 0; x < categories.length; x++)
			{
				var dom_option = document.createElement('option');
				dom_option.setAttribute('value', categories[x]);
				dom_option.appendChild(document.createTextNode(categories[x]));
				
				if(categories[x].replace(/\//, ' ').toUpperCase() == categoryName.toUpperCase())
				{
					dom_option.selected = true;
				}
				
				dom_categories.appendChild(dom_option);
			}
		},
		'json'
	);
	
	dom_categories.id = 'categoryField';
	dom_categoryField.appendChild(dom_categories);
	
	dom_fields.appendChild(dom_categoryField);
	
	var dom_partField = createElement('div', 'field');
	
	var dom_partLabel = createElement('label', 'label');
	dom_partLabel.setAttribute('for', 'partField');
	dom_partLabel.appendChild(document.createTextNode('Part name'));
	dom_partField.appendChild(dom_partLabel);
	
	var dom_part = createElement('input', 'part');
	dom_part.setAttribute('type', 'text');
	
	if(typeof(partName) != 'undefined')
	{
		dom_part.setAttribute('value', partName);
	}
	
	dom_partField.appendChild(dom_part);
	dom_part.id = 'partField';
	
	dom_fields.appendChild(dom_partField);
	
	$(dom_fields).dialog
	(
		{
			bgiframe: true,
			buttons:
			{
				'Continue': function()
				{
					var partOptions =
					{
						category: $(dom_categories).val(),
						part: $(dom_part).val()
					};
					
					if(partOptions.part)
					{
						$.post('/api/basket/addcustom', partOptions, updateBasket, 'json');
						$(this).dialog('close');
					}
					else
					{
						$(dom_error).fadeIn('slow');
					}
				},
				'Cancel': function()
				{
					$(this).dialog('close');
				}
			},
			modal: true,
			title: 'Custom part details',
			close: function(event, ui)
			{
				// We need to remove the dialog div when it is closed so the same IDs can be used on the field elements
				// if it is displayed again.
				jQuery(this).remove();
			}
		}
	);
	
	$('.ui-dialog-buttonpane button:first').addClass('continue_part');
	$('.ui-dialog-buttonpane button:last').addClass('cancel_part');
}

function showAddPart(nextPart)
{
	var dom_form = document.createElement('form');
	dom_form.setAttribute('method', 'post');
	dom_form.setAttribute('action', '/partrequest');
	
	var dom_hidden = createElement('div', 'hidden');
	$('#partrequestform :input').each(function()
		{
			$(dom_hidden).append($(this).clone());
		});
	
	var dom_addPart = document.createElement('input');
	dom_addPart.setAttribute('name', 'addpart');
	dom_addPart.setAttribute('type', 'hidden');
	dom_addPart.setAttribute('value', '1');
	dom_hidden.appendChild(dom_addPart);
	
	dom_form.appendChild(dom_hidden);
	
	var dom_add = createElement('div', 'add-part');
	
	// Quantity field
	var dom_quantity = createElement('div', 'field');
	
	var dom_label = document.createElement('label');
	dom_label.setAttribute('for', 'part_' + nextPart + '_quantity');
	dom_label.appendChild(document.createTextNode('Quantity'));
	dom_quantity.appendChild(dom_label);
	
	var dom_input = createElement('input', 'quantity');
	dom_input.setAttribute('type', 'text');
	dom_input.id = 'part_' + nextPart + '_quantity';
	dom_input.setAttribute('name', 'part_' + nextPart + '_quantity');
	dom_quantity.appendChild(dom_input);
	
	dom_quantity.appendChild(createElement('div', 'clear'));
	
	dom_add.appendChild(dom_quantity);
	
	// Part category field
	var dom_type = createElement('div', 'field');
	
	var dom_label = document.createElement('label');
	dom_label.setAttribute('for', 'part_' + nextPart + '_quantity');
	dom_label.appendChild(document.createTextNode('Category'));
	dom_type.appendChild(dom_label);
	
	var dom_select = createElement('select', 'category');
	
	$.get('/api/part/getcategories', {}, function(data, textStatus)
	{
		for(var x = 0; x < data.data.length; x++)
		{
			var dom_option = document.createElement('option');
			dom_option.setAttribute('value', data.data[x]);
			dom_option.appendChild(document.createTextNode(data.data[x]));
			dom_select.appendChild(dom_option);
		}
	}, 'json')	
	
	dom_select.id = 'part_' + nextPart + '_type';
	dom_select.setAttribute('name', 'part_' + nextPart + '_type');
	dom_type.appendChild(dom_select);
	
	dom_type.appendChild(createElement('div', 'clear'));
	
	dom_add.appendChild(dom_type);
	
	// Part name field
	var dom_name = createElement('div', 'field');
	
	var dom_label = document.createElement('label');
	dom_label.setAttribute('for', 'part_' + nextPart + '_name');
	dom_label.appendChild(document.createTextNode('Part name'));
	dom_name.appendChild(dom_label);
	
	var dom_input = createElement('input', 'partname');
	dom_input.setAttribute('type', 'text');
	dom_input.id = 'part_' + nextPart + '_name';
	dom_input.setAttribute('name', 'part_' + nextPart + '_category');
	dom_name.appendChild(dom_input);
	
	dom_name.appendChild(createElement('div', 'clear'));
	
	dom_add.appendChild(dom_name);
	
	dom_form.appendChild(dom_add);
	$(dom_form).dialog
	(
		{
			bgiframe: true,
			buttons:
			{
				'OK': function()
				{
					$(dom_form).submit();
					$(this).dialog('close');
				},
				'Cancel': function()
				{
					$(this).dialog('close');
				}
			},
			modal: true,
			title: 'Add part'
		}
	);
}

function showBasketVehicleEntry(vrmMode, vrmText)
{
	if(vrmMode === undefined ) 
	{
		vrmMode = true;
	}
	
	if(vrmText != '') 
	{
		$('#vrm').val(vrmText);
	}
	
	if(vrmMode)
	{
		$('.vrm-lookup').show();
		$('.vehicle-details-entry').hide();
	}
	else
	{
		$('.vehicle-details-entry').show();
		$('.vrm-lookup').hide();
	}
	
	var clone = $('#basket-vrm-lookup-dialog').clone(); 

	$('.change-mode-link').click(function()
	{
		$('#basket-vrm-error').text('');
		vrmMode = !vrmMode;
		
		if(vrmMode)
		{
			$('.vrm-lookup').show();
			$('.vehicle-details-entry').hide();
		}
		else
		{
			$('.vehicle-details-entry').show();
			$('.vrm-lookup').hide();
		}
	});
	
	$('#basket-vrm-lookup-dialog').dialog
	(
		{
			bgiframe: true,
			buttons:
			{
				'OK': function()
				{
					if(vrmMode)
					{
						if(vrmText == $('#vrm').val())
						{
							vrmStep = 2;
							lookupVRMLive($('#vrm').val(), processVRMResult, $(this));
						}
						else
						{
							vrmStep = 1;
							lookupVRM($('#vrm').val(), processVRMResult, $(this));
						}
						
					}
					else
					{
						saveBasketVehicle($(this));
					} 
					$(this).dialog('close');
				},
				'Cancel': function()
				{
					$(this).dialog('close');
					}
			},
			modal: true,
			title: 'Vehicle details',
			close: function()
			{
				$(this).remove();
				$(document.body).append(clone);
				vrmDialogClose();
			},
			width: 550
		}
	);
	
	$('#basket-vrm-lookup-dialog').parent().find('button:first').addClass('continue_part');
	$('#basket-vrm-lookup-dialog').parent().find('button:last').addClass('cancel_part');
	
	return false;
}

function processBasketVehicleEntry(useVRM, dialog)
{
	if(useVRM)
	{
		lookupVRM($('#vrm').val(), processVRMResult, dialog);
	}
	else
	{
		saveBasketVehicle(dialog);
	}
}

function homeLookupVRM(form)
{
	document.getElementById('regNotFound').style.visibility = 'hidden';
	vrm = form.vrm.value;
	lookupVRM(vrm, processVRMResultHome, null);
}

function homeChangeVRM()
{
	document.getElementById('enterVehicleReg').style.display = 'block';
	document.getElementById('usingVehicleReg').style.display = 'none';
	document.getElementById('regNotFound').style.visibility = 'hidden';
}

function lookupVRM(vrm, callback, dialog)
{
	$.post('/api/vehicle/lookupvrm', {vrm: vrm}, function(data, textStatus){callback(data, textStatus, dialog);}, 'json');
}

function lookupVRMLive(vrm, callback, dialog)
{
	$.post('/api/vehicle/lookupvrmlive', {vrm: vrm}, function(data, textStatus){callback(data, textStatus, dialog);}, 'json');
}

function processVRMResultHome(data, textStatus, dialog)
{
	if(data.data.message != "Not Found")
	{
		//if found show dialog box with car summory first
		homeConfirmVRMResult(data, dialog);
	}
	else
	{
		document.getElementById('regNotFound').style.visibility = 'visible';
	}
}

function homeConfirmVRMResult(data, dialog)
{
	var dom_confirmVRM = createElement('div', 'confirmVRM');
	
	var dom_plate = createElement('div', 'ukplate');
	var dom_ybg = createElement('span', 'ybg');
	dom_ybg.appendChild(document.createTextNode(data.data.vrm));
	dom_plate.appendChild(dom_ybg);
	dom_confirmVRM.appendChild(dom_plate);
	
	var dom_table = document.createElement('table');
	var dom_tbody = document.createElement('tbody');
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Make'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.make));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Model'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.model));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Colour'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.colour));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Body type'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.body));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Engine size'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.engine + ' cc'));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Year'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.year));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	dom_table.appendChild(dom_tbody);
	dom_confirmVRM.appendChild(dom_table);
	
	$(dom_confirmVRM).dialog
	(
		{
			bgiframe: true,
			buttons:
			{
				'Yes, correct': function()
				{
					$(this).dialog('close');
					
					//if confirmed, relocate browser
					window.location='/browse/';
					
					// We should also send off another AJAX request to indicate to the server that the
					// customer has already confirmed the vehicle details are correct. This prevents them
					// seeing another vehicle confirmation dialog on the part requests form.
					// We can just send this request off and forget about it.
					$.post('/api/vehicle/confirmdetails', '', function(data, textStatus){}, 'json');
				},
				'No, incorrect': function()
				{
					$(this).dialog('close');
					// if not confirmed (wrong car) clear form and start again
					$.post('/api/vehicle/remove', '', function(data, textStatus){}, 'json');
					document.getElementById('main-vrm-plate').value = "TYPE REG.";
				}
			},
			modal: true,
			title: 'Confirm Vehicle Details',
			width: 345
		}
	);

	$(dom_confirmVRM).parent().find('button:first').addClass('vrm-correct');
	$(dom_confirmVRM).parent().find('button:last').addClass('vrm-incorrect');
}

function saveBasketVehicle(dialog)
{
	if($('#basket-make-entry').val() != 'Other' && $('#basket-model-entry').val() != 'Other' && $('#basket-year-entry').val() != 'Other')
	{
		if(!$('#basket-make-entry').val())
		{
			$('#basket-vrm-error').text('Please select your make');
			return;
		}
		
		if(!($('#basket-model-entry').val()))
		{
			$('#basket-vrm-error').text('Please select your model');
			return;
		}
		
		if(!($('#basket-year-entry').val()))
		{
			$('#basket-vrm-error').text('Please select your vehicle\'s year');
			return;
		}
		
		if(!($('#basket-body-entry').val()))
		{
			$('#basket-vrm-error').text('Please select your vehicle\'s body type');
			return;
		}
		
		if(!$('#basket-trim-entry').val())
		{
			$('#basket-vrm-error').text('Please select your vehicle\'s trim level');
			return;
		}
		
		// Still here? Good. All the data's ok then.
		var data =
		{
			make: $('#basket-make-entry').val(),
			model: $('#basket-model-entry').val(),
			year: $('#basket-year-entry').val(),
			body: $('#basket-body-entry').val(),
			trim: $('#basket-trim-entry').val()
		}
	}
	else
	{
		var customMake = '';
		var customModel = '';
		var customYear = '';		
		
		if($('#basket-make-other').val() != '')
		{
			customMake = $('#basket-make-other').val();
		}
		else
		{
			customMake = $('#basket-make-entry').val();
		}
		
		if($('#basket-model-other').val() != '')
		{
			customModel = $('#basket-model-other').val();
		}
		else
		{
			customModel = $('#basket-model-entry').val();
		}
		
		if($('#basket-year-other').val() != '')
		{
			customYear = $('#basket-year-other').val();
		}
		else
		{
			customYear = $('#basket-year-entry').val();
		}
		
		if(customMake == '' && customModel == '')
		{
			$('#basket-vrm-error').text('Please enter a make');
			return;
		}			
		
		var data =
		{
			make: customMake,
			model: customModel,
			year: customYear,
			body: '',
			trim: ''
		}
		
	}
		
	$.post
	(
		'/api/vehicle/set',
		data,
		function(data, textStatus)
		{
			$('.part-from-price').hide();
			dialog.dialog('close');
			updateVehiclePreview(data, 'Your vehicle details have been confirmed');
		},
		'json'
	);
}

function processVRMResult(data, textStatus, dialog)
{
	if(typeof(data.data.content) != 'undefined')
	{
		confirmVRMResult(data, dialog);
		vrmLookedUp = true;
	}
	else if(typeof(data.data.message) != 'undefined' && data.data.message == 'Not Found')
	{
		// VRM not found.
		showBasketVehicleEntry(false);
		$('#basket-vrm-error').text('Sorry, but we cannot find your registration number in our database.');
	}
	else
	{
		// Something's gone wrong.
		$('#basket-vrm-error').text('Sorry, but we are unable to look up your registration number at the moment.');
	}
}

function updateBasketModelOptions()
{
	var make = $('#basket-make-entry').val();
	if(make != 'Other')
	{
		$.get
		(
			'/res/cache/vehicle_model/' + make.toLowerCase().replace(/[\/ ]/, '-') + '.json',
			'',
			function(data, textStatus)
			{
				var count = updateBasketVehicleOptions(data.data, 'basket-model-entry');
				
				if(count == 1)
				{
					updateBasketYearOptions();
				}
			},
			'json'
		);
		
		$('#basket-make-other').hide();
		$('#basket-model-other').hide();
		$('#basket-year-other').hide();
	}
	else
	{		
		$('#basket-make-other').show();
		$('#basket-make-cancel').show();
		$('#basket-model-other').show();
		$('#basket-year-other').show();
		
		$('#basket-make-entry').hide();
		$('#basket-model-entry').hide();
		$('#basket-year-entry').hide();
		$('#basket-body-entry').hide();
		$('#basket-trim-entry').hide();
		$('label[for="basket-body-entry"]').hide();
		$('label[for="basket-trim-entry"]').hide();
		
	}
	
	$('#basket-year-entry').empty();
	$('#basket-body-entry').empty();
	$('#basket-trim-entry').empty();
}

function updateBasketYearOptions()
{
	var make = $('#basket-make-entry').val();
	var model = $('#basket-model-entry').val();
	
	if(model != 'Other')
	{
		$.get
		(
			'/res/cache/vehicle_year/' + make.toLowerCase().replace(/[\/ ]/, '-') + '-' + model.toLowerCase().replace(/[\/ ]/, '-') + '.json',
			'',
			function(data, textStatus)
			{
				var count = updateBasketVehicleOptions(data.data, 'basket-year-entry');
				
				if(count == 1)
				{
					updateBasketBodyOptions();
				}
			},
			'json'
		);
	}
	else
	{
		$('#basket-model-other').show();
		$('#basket-model-cancel').show();
		$('#basket-year-other').show();
		
		$('#basket-model-entry').hide();
		$('#basket-year-entry').hide();
		$('#basket-body-entry').hide();
		$('#basket-trim-entry').hide();
		$('label[for="basket-body-entry"]').hide();
		$('label[for="basket-trim-entry"]').hide();
	}
	
	$('#basket-body-entry').empty();
	$('#basket-trim-entry').empty();
}

function updateBasketBodyOptions()
{
	var make = $('#basket-make-entry').val();
	var model = $('#basket-model-entry').val();
	var year = $('#basket-year-entry').val();
	
	if(year != 'Other')
	{
		$.get
		(
			'/res/cache/vehicle_body/' + make.toLowerCase().replace(/[\/ ]/, '-') + '-' + model.toLowerCase().replace(/[\/ ]/, '-') + '-' + year.toLowerCase().replace(/[\/ ]/, '-') + '.json',
			'',
			function(data, textStatus)
			{
				var count = updateBasketVehicleOptions(data.data, 'basket-body-entry');
				
				if(count == 1)
				{
					updateBasketTrimOptions();
				}
			},
			'json'
		);
	}
	else
	{
		$('#basket-year-other').show();
		$('#basket-year-cancel').show();
		
		$('#basket-year-entry').hide();
		$('#basket-body-entry').hide();
		$('#basket-trim-entry').hide();
		$('label[for="basket-body-entry"]').hide();
		$('label[for="basket-trim-entry"]').hide();
	}
	
	$('#basket-trim-entry').empty();
}

function updateBasketTrimOptions()
{
	var make = $('#basket-make-entry').val();
	var model = $('#basket-model-entry').val();
	var year = $('#basket-year-entry').val();
	var body = $('#basket-body-entry').val();
	
	$.get
	(
		'/res/cache/vehicle_trim/' + make.toLowerCase().replace(/[\/ ]/, '-') + '-' + model.toLowerCase().replace(/[\/ ]/, '-') + '-' + year.toLowerCase().replace(/[\/ ]/, '-') + '-' + body.toLowerCase().replace(/[\/ ]/, '-') + '.json',
		'',
		function(data, textStatus)
		{
			updateBasketVehicleOptions(data.data, 'basket-trim-entry');
		},
		'json'
	);
}

function updateBasketVehicleOptions(options, field)
{
	var count = 0;
	$('#' + field).empty();
	
	var dom_field = document.getElementById(field);
	
	if(dom_field)
	{
		for(var index in options)
		{
			var dom_option = document.createElement('option');
			dom_option.value = index;
			dom_option.appendChild(document.createTextNode(options[index]));
			
			dom_field.appendChild(dom_option);
			count++;
		}
		
		if(field == 'basket-model-entry' || field == 'basket-year-entry')
		{
			var dom_option = document.createElement('option');
			dom_option.value = 'Other';
			dom_option.appendChild(document.createTextNode('Other'));
			dom_field.appendChild(dom_option);
		}
	}
	return count;
}

function showMakeOtherCancel()
{
	$('#basket-make-other').hide();
	$('#basket-make-cancel').hide();
	$('#basket-model-other').hide();
	$('#basket-year-other').hide();
	$('#basket-year-cancel').hide();
	
	$('#basket-make-entry').show();
	$('#basket-model-entry').show();
	$('#basket-year-entry').show();
	$('#basket-body-entry').show();
	$('#basket-trim-entry').show();
	$('label[for="basket-body-entry"]').show();
	$('label[for="basket-trim-entry"]').show();
	
	$('#basket-make-entry').val(0);
}

function showModelOtherCancel()
{
	$('#basket-make-other').hide();
	$('#basket-make-cancel').hide();
	$('#basket-model-other').hide();
	$('#basket-model-cancel').hide();
	$('#basket-year-other').hide();
	$('#basket-year-cancel').hide();
	
	$('#basket-make-entry').show();
	$('#basket-model-entry').show();
	$('#basket-year-entry').show();
	$('#basket-body-entry').show();
	$('#basket-trim-entry').show();
	$('label[for="basket-body-entry"]').show();
	$('label[for="basket-trim-entry"]').show();
	
	$('#basket-model-entry').val(0);
}

function showYearOtherCancel()
{
	$('#basket-make-other').hide();
	$('#basket-make-cancel').hide();
	$('#basket-model-other').hide();
	$('#basket-model-cancel').hide();
	$('#basket-year-other').hide();
	$('#basket-year-cancel').hide();
	
	$('#basket-make-entry').show();
	$('#basket-model-entry').show();
	$('#basket-year-entry').show();
	$('#basket-body-entry').show();
	$('#basket-trim-entry').show();
	$('label[for="basket-body-entry"]').show();
	$('label[for="basket-trim-entry"]').show();
	
	$('#basket-year-entry').val(0);
}

var vrmStep = 0;

function confirmVRMResult(data, dialog)
{
	var dom_confirmVRM = createElement('div', 'confirmVRM');
	dom_confirmVRM.id = 'confirm-vrm';
	
	var dom_plate = createElement('div', 'ukplate');
	var dom_ybg = createElement('span', 'ybg');
	dom_ybg.appendChild(document.createTextNode(data.data.vrm));
	dom_plate.appendChild(dom_ybg);
	dom_confirmVRM.appendChild(dom_plate);
	
	var dom_table = document.createElement('table');
	var dom_tbody = document.createElement('tbody');
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Make'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.make));
	
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Model'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.model));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Colour'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.colour));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Body type'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.body));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Engine size'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.engine + ' cc'));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	var dom_tr = document.createElement('tr');
	
	var dom_td = document.createElement('td');
	dom_td.appendChild(document.createTextNode('Year'));
	dom_tr.appendChild(dom_td);
	
	dom_td = createElement('td', 'value');
	dom_td.appendChild(document.createTextNode(data.data.year));
	dom_tr.appendChild(dom_td);
	
	dom_tbody.appendChild(dom_tr);
	
	dom_table.appendChild(dom_tbody);
	dom_confirmVRM.appendChild(dom_table);
	
	if(data.data.source == 'live')
	{
		showManualEntry = true;
	}

	if(vrmStep == 0)
	{
		$('.ui-dialog').remove();
		$(dom_confirmVRM).dialog
		(
			{
				bgiframe: true,
				buttons:
				{
					'Yes, correct': function()
					{
						$(this).dialog('close');
						
						$('.part-from-price').hide();
						dialog.dialog('close');
						
						updateVehiclePreview(data, '');
						
						if(typeof(browsePage) != 'undefined' && canShowSearchHelp())
						{
							showHint({id:'hint_search', style:'left:350px;top:55px', html:'Use our search above or<br/>browse part categories below<br/>to find parts for your vehicle', directions:['top','bottom'], duration: 10000});
						}
						
						// We should also send off another AJAX request to indicate to the server that the
						// customer has already confirmed the vehicle details are correct. This prevents them
						// seeing another vehicle confirmation dialog on the part requests form.
						// We can just send this request off and forget about it.
						$.post('/api/vehicle/confirmdetails', '', function(data, textStatus){}, 'json');
					},
					'No, incorrect': function()
					{
						$(this).dialog('close');
						// if not confirmed (wrong car) clear form and start again
						$.post('/api/vehicle/remove', '', function(data, textStatus){}, 'json');

						//if still incorrect show manual input dialog
						showBasketVehicleEntry(true, data.data.vrm);
						vrmStep = 1;
					}
				},
				modal: true,
				title: 'Confirm Vehicle Details',
				width: 345,
				open: function(){
					fixVRMDialogStyle();
				},
				close: function(){
					vrmDialogClose();
				},
				position: calculateVRMDialogPosition()
			}
		);
		showHint({id:'vrm_confirm_tooltip', style:'top: 40px; left: 360px; width: 200px;', html:'Please check the vehicle<br/>details are correct for this<br/>registration mark', directions:['left'], container: '.ui-dialog', duration: 10000});
	}
	else if(vrmStep == 1)
	{
		$('.ui-dialog').remove();
		$(dom_confirmVRM).dialog
		(
			{
				bgiframe: true,
				buttons:
				{
					'Yes, correct': function()
					{
						$(this).dialog('close');
						
						$('.part-from-price').hide();
						dialog.dialog('close');
						
						updateVehiclePreview(data, '');
						
						if(typeof(browsePage) != 'undefined' && canShowSearchHelp())
						{
							showHint({id:'hint_search', style:'left:350px;top:55px', html:'Use our search above or<br/>browse part categories below<br/>to find parts for your vehicle', directions:['top','bottom'], duration: 10000});
						}
						
						// We should also send off another AJAX request to indicate to the server that the
						// customer has already confirmed the vehicle details are correct. This prevents them
						// seeing another vehicle confirmation dialog on the part requests form.
						// We can just send this request off and forget about it.
						$.post('/api/vehicle/confirmdetails', '', function(data, textStatus){}, 'json');
					},
					'No, check again': function()
					{
						$(this).dialog('close');
						// if not confirmed (wrong car) clear form and start again
						$.post('/api/vehicle/remove', '', function(data, textStatus){}, 'json');
						
						vrmStep = 2;
						//force live lookup
						lookupVRMLive(data.data.vrm, processVRMResult, dialog);
					}
				},
				modal: true,
				title: 'Confirm Vehicle Details',
				width: 345,
				open: function(){
					fixVRMDialogStyle();
				},
				close: function(){
					vrmDialogClose();
				},
				position: calculateVRMDialogPosition()
			}
		);
		
		showHint({id:'vrm_confirm_tooltip', style:'top: 40px; left: 360px; width: 200px;', html:'Please check the vehicle<br/>details are correct for this<br/>registration mark', directions:['left'], container: '.ui-dialog', duration: 10000});
	}
	else if(vrmStep == 2)
	{
		$('.ui-dialog').remove();
		$(dom_confirmVRM).dialog
		(
			{
				bgiframe: true,
				buttons:
				{
					'Yes, correct': function()
					{
						$(this).dialog('close');
						
						$('.part-from-price').hide();
						dialog.dialog('close');
						
						updateVehiclePreview(data, '');
						if(typeof(browsePage) != 'undefined' && canShowSearchHelp())
						{
							showHint({id:'hint_search', style:'left:350px;top:55px', html:'Use our search above or<br/>browse part categories below<br/>to find parts for your vehicle', directions:['top','bottom'], duration: 10000});
						}
						
						// We should also send off another AJAX request to indicate to the server that the
						// customer has already confirmed the vehicle details are correct. This prevents them
						// seeing another vehicle confirmation dialog on the part requests form.
						// We can just send this request off and forget about it.
						$.post('/api/vehicle/confirmdetails', '', function(data, textStatus){}, 'json');
					},
					'No, incorrect': function()
					{
						$(this).dialog('close');
						// if not confirmed (wrong car) clear form and start again
						$.post('/api/vehicle/remove', '', function(data, textStatus){}, 'json');
						
						vrmStep = 2;

						//if still incorrect show manual input dialog
						showBasketVehicleEntry(false);
						vrmStep = 0;
					}
				},
				modal: true,
				title: 'Confirm Vehicle Details',
				width: 345,
				open: function(){
					fixVRMDialogStyle();
				},
				close: function(){
					vrmDialogClose();
				},
				position: calculateVRMDialogPosition()
			}
		);
		showHint({id:'vrm_confirm_tooltip', style:'top: 40px; left: 360px; width: 200px;', html:'Please check the vehicle<br/>details are correct for this<br/>registration mark', directions:['left'], container: '.ui-dialog', duration: 10000});
	}
	
	$(dom_confirmVRM).parent().find('button:first').addClass('vrm-correct');
	$(dom_confirmVRM).parent().find('button:last').addClass('vrm-incorrect');
}

function removeBasketVehicle()
{
	$.get
	(
		'/api/vehicle/remove',
		'',
		function(data, textStatus)
		{
			$('.part-from-price').show();
			updateVehiclePreview(data, 'Your vehicle details have been removed');
		},
		'json');
}

function refreshBasketVehicle()
{
	$.post
	(
		'/api/vehicle/get',
		null,
		function(data, textStatus)
		{
			updateVehiclePreview(data, 'Your vehicle details have been updated');
			if(typeof('browsePage') != 'undefined')
			{
				showHint({id:'hint_search', style:'left:350px;top:55px', html:'Use our search above or<br/>browse part categories below<br/>to find parts for your vehicle', directions:['top','bottom']});
			}
		},
		'json'
	);
}

function showPartAddConfirmation(partName)
{
	var ts = new Date().getTime();
	var div = '<div id="part-add-confirmation-' + ts + '">';
	div += '<strong>' + partName + '</strong><br/> has been added to your parts list.<br/><a href="/partrequest/">Get quotes now</a>.';
	div += '</div>';
	
	$(document.body).append(div);
	$('#part-add-confirmation-' + ts).dialog({
		modal: true,
		title: 'Thank you',
		buttons:
		{
			'Add More Parts': function()
			{
				$(this).dialog('close');
			},
			'Get Quotes': function()
			{
				window.location.href = '/partrequest/';
			}
		}
	});
}
/**
 * options = { id:unique id, x:xposition, y:yposition, html:html, directions:[up,right,left,down]}
 * */
function showHint(options)
{
	var classes = 'hint '+options.directions.join(' ');
	var html = '<div id="'+options.id+'" style="display:none;'+options.style+'" class="'+classes+'">';
	
	html+= '<div class="inner-border"><div class="inner">';
	
	for(var index in options.directions)
	{
		html += '<div class="' + options.directions[index] + '">';
	}
	
	html+= '<div class="inner-content">' + options.html + '</div>';
	
	for(var index in options.directions)
	{
		html += '</div>';
	}
	
	html+= '</div></div></div>';
	
	var container = '#container';
	if(typeof(options.container) != 'undefined')
	{
		container = options.container;
	}

	$(container).append(html);
	
	//$('#' + options.id + ' .inner-border, #' + options.id + ' .inner').corner('round 10px').corner('keep');
	$('#'+options.id).fadeIn();
	$('#'+options.id).click(function(){
		$('#'+options.id).remove();
	});
	
	DD_roundies.addRule('#' + options.id + ' .inner-border', '8px');
	DD_roundies.addRule('#' + options.id + ' .inner', '8px');

	
	var duration = 3000;
	if(typeof(options.duration) != 'undefined')
	{
		duration = options.duration;
	}
	
	setTimeout(function(){
		$('#'+options.id).fadeOut();
	}, duration);
}

function fixVRMDialogStyle(event, ui)
{
	$('.ui-dialog').css('overflow', 'visible');
}

function calculateVRMDialogPosition()
{
	var coordinates = new Array();
	var selector;
	
	// Work out what the horizontal positioning is relative to.
	if($('.body-main').length > 0)
	{
		selector = '.body-main';
	}
	else
	{
		selector = '#all_cat';
	}
	
	coordinates[0] = $(selector).offset().left + $(selector).width() / 2 - 176;
	
	coordinates[1] = $(window).height() / 2 - 152;
	return coordinates;
}

function canShowSearchHelp()
{
	var query = location.search.substr(1).split('&');
	
	for(index in query)
	{
		parts = query[index].split('=');
		
		if(parts[0] == 'stt' && parts[1] == '0')
		{
			// The search help tooltip should be suppressed.
			return false;
		}
	}
	
	// If we made it this far then the search help tooltip should be displayed.
	return true;
}

function instantAddCustomPart(category, part)
{
	var partOptions =
	{
		category: category,
		part: part
	};
	
	if(partOptions.part)
	{
		$.post('/api/basket/addcustom', partOptions, updateBasket, 'json');
		return true;
	}
	return false;
}

function quickAddCustomPart()
{
	var name = $('#custom-search-part-name').val();
	if(name)
	{
		instantAddCustomPart('', name);
	}
	else
	{
		$('#custom-search-part-error').html('Please enter a part name');
	}
}

function vrmDialogClose()
{	
	if(typeof(vrmLookedUp) != 'undefined' && vrmLookedUp)
	{
		showHint({
			id: 'hint_search_results',
			html: 'Click a part to add it to your request',
			directions: ['bottom'],
			container: '.searchresults-items',
			style: 'top: 30px; left: 250px;',
			duration: 10000
		});
	}
}
