
var cartons = [];
cartons['WC'] = ['Wardrobe Carton', 51, 47, 99];
cartons['LC'] = ['Large Packing Carton', 47, 47, 63];
cartons['MC'] = ['Medium Packing Carton', 47, 47, 30];
cartons['SC'] = ['Small Packing Carton', 47, 32, 30];
cartons['AC'] = ['Archive Carton', 63, 47, 47];

var items = new Array();
var items_summary = "";
var current_section = "moving-details";

// Removed for facebox integration
//$(function() {

	$('#flexistore-form').ajaxForm(function(response) {
		if (response == "captcha_error")
		{
			alert("There was a problem with the captcha. Please try again.");
		}
		else
		{
			$('#flexistore-form').html('<div style="font-family:Arial, Helvetica, sans-serif; text-align:center;">Thank you for your enquiry. A Flexistore representative will contact you shortly to discuss you shipping needs.</div>');
		}
	});

	$('#moving-details').show();
	$('#personal-details, #inventory, #additional-details').hide();

	$('#sq-origin-country').change(function() {
		OriginCountryChanged();
	});

	$('#sq-dest-country').change(function() {
		DestCountryChanged();
	});

	$('#add-carton').click(function() {

		if (!parseFloat($('#carton-weight').val()))
		{
			alert('You must enter a valid weight for the item');
			return;
		}

		items[items.length] = [[cartons[$('#carton').val()][0], cartons[$('#carton').val()][1], cartons[$('#carton').val()][2], cartons[$('#carton').val()][3], $('#carton-weight').val()], $('#no_of_cartons').val()];

		generate_summary();

	});

	$('#add-owner-item').click(function() {

		if (trim($('#description').val()) == '' || !parseFloat($('#length').val()) || !parseFloat($('#width').val()) || !parseFloat($('#height').val()) || !parseFloat($('#weight').val()))
		{
			alert('You must enter a description, length, width, height and weight for the item');
			return;
		}

		items[items.length] = [[$('#description').val(), $('#length').val(), $('#width').val(), $('#height').val(), $('#weight').val()], $('#no_of_items').val()];

		generate_summary();

	});

	$('#sq-inputDate').DatePicker({
		format:'d/m/Y',
		date: new Date(),
		current: new Date(),
		starts: 1,
		position: 'bottom',
		onBeforeShow: function(){
			if ($('#sq-inputDate').val() != '')
			{
				$('#sq-inputDate').DatePickerSetDate($('#sq-inputDate').val(), true);
			}
			else
			{
				$('#sq-inputDate').DatePickerSetDate(new Date(), true);
			}
		},
		onChange: function(formated, dates){
			$('#sq-inputDate').val(formated);
			$('#sq-inputDate').DatePickerHide();
		}
	});

//});

function regexmatch(needle, haystack)
{
	var re = new RegExp(needle);

	if (haystack.match(re)) {
		return true;
	} else {
		return false;
	}
}

function switch_section(section)
{
	if (current_section == section)
	{
		return;
	}

	switch (current_section)
	{
		case 'moving-details':

			if (!regexmatch('^[A-Z]{2}$', $('#sq-origin-country').val()))
			{
				alert('Please choose the origin country.');
				return;
			}

			if (!regexmatch('^[A-Z]{2}$', $('#sq-dest-country').val()))
			{
				alert('Please choose the destination country.');
				return;
			}

			if ($('#sq-origin-city').val() == '')
			{
				alert('Please choose the origin city.');
				return;
			}

			if ($('#sq-dest-city').val() == '')
			{
				alert('Please enter the destination city.');
				return;
			}

			if (section != 'personal-details')
			{
				return;
			}

		break;

		case 'personal-details':

			if (section == 'moving-details')
			{
				break;
			}

			if ($('#sq-title').val() == '')
			{
				alert('Please choose a valid title.');
				return;
			}

			if ($('#sq-first-name').val() == '')
			{
				alert('Please enter your first name.');
				return;
			}

			if ($('#sq-last-name').val() == '')
			{
				alert('Please enter your last name.');
				return;
			}

			if (!regexmatch('^[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,4}$', $('#sq-email').val()))
			{
				alert('Please enter a valid email address.');
				return;
			}

			if ($('#sq-email').val() != $('#sq-confirm').val())
			{
				alert('Please confirm your email address.');
				return;
			}

			if ($('#sq-last-name').val() == '')
			{
				alert('Please enter your last name.');
				return;
			}

			if ($('#sq-telephone').val() == '')
			{
				alert('Please enter your telephone number.');
				return;
			}

			if ($('#sq-mobile').val() == '')
			{
				alert('Please enter your mobile number.');
				return;
			}

			if (!regexmatch('^[0-9]{2}/[0-9]{2}/[0-9]{4}$', $('#sq-inputDate').val()))
			{
				alert('Please enter a valid date. Format: DD/MM/YYYY');
				return;
			}

			if (section != 'inventory')
			{
				return;
			}

		break;

		case 'inventory':

			if (section == 'personal-details')
			{
				break;
			}

			if ($("input[name='cartons[]']").val() === undefined)
			{
				alert('Please add at least one item.');
				return;
			}

			if (section != 'additional-details')
			{
				return;
			}

		break;

		case 'additional-details':

			if (section == 'inventory')
			{
				break;
			}

			if ($("#sq-additional-info").val() == '')
			{
				alert('Please add additional information.');
				return false;
			}

			if ($("#sq-referrer").val() == '')
			{
				alert('Please choose a referrer.');
				return false;
			}

		break;
	}

	if (section == 'finish')
	{
		$('#flexistore-form').submit();
	}

	$('#moving-details, #personal-details, #inventory, #additional-details').slideUp();

	$('#' + section).slideDown();

	current_section = section;
}

function generate_summary()
{
	if (items.length == 0)
	{
		$('#item-summary').html('You have not added any items yet. Please add an item using the form above');
		$('#hidden-fields').html('');

		return;
	}

	total_weight = 0;
	total_volume = 0;
	total_volume_m3 = 0;
	total_items = 0;

	var hidden_fields = '';

	items_summary = '<table>';
	items_summary += '	<tr>';
	items_summary += '		<td>Item Description</td>';
	items_summary += '		<td>No. of Items</td>';
	items_summary += '		<td>Length</td>';
	items_summary += '		<td>Width</td>';
	items_summary += '		<td>Height</td>';
	items_summary += '		<td>Weight</td>';
	items_summary += '		<td>Volume</td>';
	items_summary += '		<td>&nbsp;</td>';
	items_summary += '	</tr>';
	items_summary += '	<tr>';


	for (i = 0; i < items.length; i++)
	{
		litres = (items[i][0][1] * items[i][0][2] * items[i][0][3]) / 1000;
		cubic_feet = convert_litres2feet(litres * items[i][1]);
		cubic_metres = convert_litres2metres(litres * items[i][1]);
		weight = items[i][0][4] * items[i][1];

		items_summary += '<tr>';
		items_summary += '	<td>' + items[i][0][0] + '</td>';
		items_summary += '	<td>' + items[i][1] + '</td>';
		items_summary += '	<td>' + items[i][0][1] + '</td>';
		items_summary += '	<td>' + items[i][0][2] + '</td>';
		items_summary += '	<td>' + items[i][0][3] + '</td>';
		items_summary += '	<td>' + weight.toFixed(2) + '</td>';
		items_summary += '	<td>' + cubic_feet.toFixed(2) + '</td>';
		items_summary += '	<td><a href="#" onclick="delete_item(' + i + '); return false">(delete)</a></td>';
		items_summary += '</tr>';

		total_weight += parseFloat(weight.toFixed(2));
		total_volume += parseFloat(cubic_feet);
		total_volume_m3 += parseFloat(cubic_metres);
		total_items += parseFloat(items[i][1]);

		hidden_fields += '<input type="hidden" name="cartons[]" value="' + items[i][0][0] + '|@|' + items[i][1]  + '|@|' + items[i][0][1] + '|@|' + items[i][0][2] + '|@|' + items[i][0][3] + '|@|' + weight.toFixed(2) + '|@|' + litres * items[i][1] + '">';
	}

	items_summary += '	</tr>';
	items_summary += '	<tr>';
	items_summary += '		<td colspan="8">Total Weight: ' + total_weight.toFixed(2) + ' kg</td>';
	items_summary += '	</tr>';
	items_summary += '	<tr>';
	items_summary += '		<td colspan="8">Total Volume: ' + total_volume.toFixed(2) + ' CuFt / ' + total_volume_m3.toFixed(2) + ' m<sup>3</sup></td>';
	items_summary += '	</tr>';
	items_summary += '	<tr>';
	items_summary += '		<td colspan="8">No. Of Items: ' + total_items + '</td>';
	items_summary += '	</tr>';
	items_summary += '</table>';

	$('#item-summary').html(items_summary);
	$('#hidden-fields').html(hidden_fields);
}

function delete_item(item)
{
	items.splice(item, 1);
	generate_summary();
}

function convert_litres2feet(litres)
{
	return litres / 28.3168466;
}

function convert_litres2metres(litres)
{
	return litres / 1000;
}

function trim (str)
{
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function formatItem(row) {
	return "<strong>" + row[0] + "</strong><br />&nbsp;&nbsp;<i>" + row[1] + "</i>";
}

function OriginCountryChanged()
{
	$('.aco_results').remove();
	$("#sq-origin-city").removeClass('ac_input');
	$("#sq-origin-city").unbind();

	$("#sq-origin-city").autocomplete("form/ajax.php", {
		delay:10,
		minChars:1,
		matchSubset:1,
		autoFill:true,
		maxItemsToShow: 9,
		cacheLength: 10,
		selectFirst: true,
		formatItem: formatItem,
		resultsClass: 'aco_results',
		extraParams: {
			country: $("#sq-origin-country").val()
		}
	});
}

function DestCountryChanged()
{
	$('.acd_results').remove();
	$("#sq-dest-city").removeClass('ac_input');
	$("#sq-dest-city").unbind();

	$("#sq-dest-city").autocomplete("form/ajax.php", {
		delay:10,
		minChars:1,
		matchSubset:1,
		autoFill:true,
		maxItemsToShow: 9,
		cacheLength: 10,
		selectFirst: true,
		formatItem:formatItem,
		resultsClass: 'acd_results',
		extraParams: {
			country: $("#sq-dest-country").val()
		}
	});
}