$().ready(function() {
				   	
	
	$("form :input").bind("focus", function() {
		$("form ul").removeClass("active");								   
		$("form li").removeClass("active");									 
		$(this).parents("ul").addClass("active");
		$(this).parents("li").addClass("active");	
	});
	
	 $("input:text:visible:first").focus();	
	
	$("#from_country").autocomplete('/quote/api/get_countries', {
		minChars: 0,
		max: 100,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220,
		width: 186
	});

	
	$("#from_city").autocomplete('/quote/api/get_cities', {
		minChars: 0,
		max: 100,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220,
		width: 186,
		extraParams: {
			country: function() { return $("#from_country").val(); }
		}

	});
	
	$("#to_country").autocomplete('/quote/api/get_countries', {
		minChars: 0,
		max: 100,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220,
		width: 186
	});
	
	$("#to_city").autocomplete('/quote/api/get_cities', {
		minChars: 0,
		max: 100,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220,
		width: 186,
		extraParams: {
			country: function() { return $("#to_country").val(); }
		}

	});
	
	
	$('.explain').tooltip({showURL: false});
	$('.exclaim').tooltip({showURL: false, extraClass: "error-tip"});
	
	$('.calc-popup').bind('click', function() {
		window.open($(this).attr('href'),'box_calc','width=644,height=345,scrollbars=no');		
		return false;
	});
	
	
	$('.radiochoice input').bind('click', function() {
		$('.radiochoice label').removeClass('this-on');
		$(this).parent('label').addClass('this-on');
				
		if($(this).val() == 'weight') {
			$('ul#boxes-val').hide();
			$('ul#weight-val').fadeIn('fast');
			$("input:text:visible:first").focus();	
		}
		else if($(this).val() == 'box') {
			$('ul#weight-val').hide();
			$('ul#boxes-val').fadeIn('fast');
			$("input:text:visible:first").focus();	
		}
		
	});
	
	$('.checkbox input').change(function() {
		var ulName = $(this).parent('label').parent('p').attr('title');
		
		if($(this).attr('checked')) {
			$('#'+ulName).fadeIn('fast');
			$("input:text:visible:first").focus();	
		}
		else {
			$('#'+ulName).fadeOut('fast');
		}
		
	});
	
	
	function encodeHTML(s) {
   		return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
	}
	
	$('input#modal-new').click(function() {
		if ($('#item_name').val() == '') {
			setError('item_name', 'The item name field is required.');
			$('.exclaim').tooltip({showURL: false, extraClass: "error-tip"});	
			return false;
		}
		else {
			resetError('item_name', 'Enter the name of your item e.g. Ikea Wardrobe');
			$('#dialog').jqmShow();
			$("#item_dim_length").watermark("length");
			$("#item_dim_width").watermark("width");	
			$("#item_dim_height").watermark("height");		
		}
	});
	
	var dialogOpen = function(hash) {
		if ($('#dialog #item_name2').attr('value') == '')
			$('#dialog #item_name2').attr('value', $('#item_name').val());
		$('#dialog #item_quantity').focus();
		hash.w.show();		
	}
	
	$('#dialog').jqm({ 
		modal: true,
		onShow: dialogOpen
	});
	
	$('#cancelAdd').click(function() {
		$('#dialog').jqmHide();	
		$('#dialog input:text').val('');
		$('#dialog select option').attr('selected', false)		
		$("#dialog select option[value='kg']").attr('selected', 'selected');
		$('#dialog textarea').val('');
		$('#item_name').val('');
		$('#item_name').focus();
		
		$('#dialog h2').text('Add An Item');
		$('#dialog .italic').replaceWith('<p class="italic">Tell us as much as you can about your item(s).</p>');
		
		resetError('item_name2', 'Enter the name of your item e.g. Ikea Wardrobe');
		resetError('item_quantity', 'Enter the number of these items to be packed.');
		resetError('item_weight', 'Enter the weight (in kg/lb) of one of the item(s).');
		resetError('item_dim_length', 'Enter the dimensions of one of the item(s). Length x Width x Height  (in cm).');
		
		$('#dialog input#edit-confirm').hide();
		$('#dialog input#add-confirm').show();
		
		$('.explain').tooltip({showURL: false});
				
		return false;
	});	

	
	// function to set error messages and styling
	function setError(field, message) {
		$('#'+field).parent('li').addClass('error');
		$('#'+field).siblings('a').replaceWith('<a href="#" class="exclaim" title="'+message+'">!</a>');	
	}
	
	// function to reset help messages and normal field styling
	function resetError(field, message) {
		$('#'+field).parent('li').removeClass('error');
		$('#'+field).siblings('a').replaceWith('<a href="#" class="explain" title="'+message+'">?</a>');
	}
	
	//# runs on page start, if there are any rows (from sessions) then find the largest number id
	//# and make the itemId = largest ID + 1.
		
	// if the table is there
	if ($('#packing-items')) {
		// if the table has rows
		if ($('#packing-items tbody tr').length > 0) {
			var bigId = 0;
			// loop through each row, find the largest id
			$('#packing-items tbody tr').each(function() {
				var thisId = $(this).attr('id').replace('i','');
				if (thisId > bigId) bigId = thisId;
			});
			
			// largest found, set itemId as this
			itemId = bigId;
		}
	}
	else { itemId = 0; }
	
	// function inserts the items table
	function createTable() {
		var tableHtml = '<table id="packing-items"><thead><tr><th class="col-item">Item</th><th class="col-quantity">Quantity</th><th class="col-cntrl">&nbsp;</th></tr></thead><tbody></tbody></table>';
		
		var clearAllHtml = '<small id="clear-all"><a href="/quote/packing/clear">clear all items</a></small>';
						
		$('p.no-items').replaceWith(tableHtml);
		$('fieldset.blue').append(clearAllHtml);
		itemId = 0;
	}	
	
	function removeTable() {
		if (!$('#packing-items').attr('id')) return false;		
		$('input#item-check').val('');	
		$('#packing-items').fadeOut('normal', function() {
			$('#packing-items').replaceWith('<p class="no-items">You have not added any items yet. Add an item below.</p>');
		});
		$('small#clear-all').fadeOut('normal', function() {  $('small#clear-all').remove(); });	
	}
	
	// edit lini
		$('.edit-i').click(function() {
			
			var id = $(this).attr('href').replace('?edit=','');
			
			$.ajax({
				type: "POST",
				async: false,
				dataType: "json",
				url: "/quote/packing/ajax_getItem",
				data: "item_id="+id,
				success: function(data){
					$('#dialog #item_name2').val(data.name);
					$('#dialog #item_quantity').val(data.quantity);
					$('#dialog #item_weight').val(data.weight);
					$('#dialog #measurement').val(data.measurement);						
					$('#dialog #item_dim_length').val(data.length);
					$('#dialog #item_dim_width').val(data.width);
					$('#dialog #item_dim_height').val(data.height);						
					$('#dialog textarea').val(data.desc);			
					
					$('#dialog h2').text('Editing Item');
					$('#dialog p.italic').text("Edit the properties of the item '"+data.name+"'.");							
							
					$('#dialog input#add-confirm').hide();
					$('#dialog input#edit-confirm').show();
					$('#dialog input#edit-confirm').attr('class', 'save-'+id);
					
					$('#dialog').jqmShow();
					$("#item_dim_length").watermark("length");
					$("#item_dim_width").watermark("width");	
					$("#item_dim_height").watermark("height");
				},
				error: function(msg){
					alert( "Error: " + msg );	
				}
			});
						
			
			return false;
		});
		
		// remove link
		$('.remove-i').click(function() {
			var id = $(this).attr('href').replace('?remove=','');
			var name = $('tr#i'+id+ ' .col-item').html();			
			var answer = confirm("Are you sure you want to remove the item '"+name+"'");			
			if (answer)	{
				$.ajax({
					type: "POST",
					async: false,
					dataType: "text",
					url: "/quote/packing/ajax_removeItem",
					data: "item_id="+id,
					success: function(msg){
						 removeRow(id);	
					},
					error: function(msg){
					 	alert( "Error: " + msg );	
					}
				});				
			}		
					
			return false;
		});		
	
	// function to add a row to the table	
	function addRow(item_name, item_quantity) {
		// table must have been created first
		if (!$('#packing-items').attr('id')) return false;
		
		item_name = encodeHTML(item_name);
		item_quantity = encodeHTML(item_quantity);
		itemId++;
			
		var rowHtml = '<tr id="i'+itemId+'"><td class="col-item">'+item_name+'</td><td class="col-quantity">x '+item_quantity+'</td><td class="col-cntrl"><a class="edit-i" href="?edit='+itemId+'">edit</a><a class="remove-i" href="?remove='+itemId+'">remove</a></td></tr>';			
		$('#packing-items tbody').append(rowHtml).hide().fadeIn('normal');
		
		$('input#item-check').val('1');
		
		// edit lini
		$('.edit-i').click(function() {
			
			var id = $(this).attr('href').replace('?edit=','');
			
			$.ajax({
				type: "POST",
				async: false,
				dataType: "json",
				url: "/quote/packing/ajax_getItem",
				data: "item_id="+id,
				success: function(data){
					$('#dialog #item_name2').val(data.name);
					$('#dialog #item_quantity').val(data.quantity);
					$('#dialog #item_weight').val(data.weight);
					$('#dialog #measurement').val(data.measurement);					
					$('#dialog #item_dim_length').val(data.length);
					$('#dialog #item_dim_width').val(data.width);
					$('#dialog #item_dim_height').val(data.height);						
					$('#dialog textarea').val(data.desc);			
					
					$('#dialog h2').text('Editing Item');
					$('#dialog p.italic').text("Edit the properties of the item '"+ +"'");	
					
					$('#dialog input#add-confirm').hide();
					$('#dialog input#edit-confirm').show();
					$('#dialog input#edit-confirm').attr('class', 'save-'+id);		
					
					$('#dialog').jqmShow();
					$("#item_dim_length").watermark("length");
					$("#item_dim_width").watermark("width");	
					$("#item_dim_height").watermark("height");					
				},
				error: function(msg){
					alert( "Error: " + msg );	
				}
			});

			
			return false;
		});
		
		// remove link
		$('.remove-i').click(function() {
			var id = $(this).attr('href').replace('?remove=','');
			var name = $('tr#i'+id+ ' .col-item').html();			
			var answer = confirm("Are you sure you want to remove the item '"+name+"'");			
			if (answer)	{
				$.ajax({
					type: "POST",
					async: false,
					dataType: "text",
					url: "/quote/packing/ajax_removeItem",
					data: "item_id="+id,
					success: function(msg){
						 removeRow(id);	
					},
					error: function(msg){
					 	alert( "Error: " + msg );	
					}
				});				
			}		
					
			return false;
		});		
	}
	
	// function to remove a row from the table
	function removeRow(item_id) {
		// table must have been created first
		if (!$('#packing-items').attr('id')) return false;		
		// check row exists
		if (!$('#packing-items tr#i'+item_id).attr('id')) return false;
		
		//  remove the row
		$('#packing-items tr#i'+item_id).fadeOut('normal', function() {
			$('#packing-items tr#i'+item_id).remove();
			
			// if this is the only row, remove the table
			if ($('#packing-items tbody tr').length == 0) {
				removeTable();	
			}
		});		
		
		return true;			
	}
	
	// function to edit a row in the table
	function editRow(item_id, item_name, item_quantity){
		// table must have been created first
		if (!$('#packing-items').attr('id')) return false;		
		// check row exists
		if (!$('#packing-items tr#i'+item_id).attr('id')) return false;
		
		// edit the row
		$('#packing-items tr#i'+item_id+' .col-item').text(item_name);
		$('#packing-items tr#i'+item_id+' .col-quantity').text('x ' + item_quantity);
		
		return true;
	}
		
	$('#add-confirm, #edit-confirm').click(function() {
		
		var error = false;
		
		// validation checks
		if ($('#item_name2').val() == '') {
			setError('item_name2', 'The item name field is required.');
			error = true;
		}
		else {
			resetError('item_name2', 'Enter the name of your item e.g. Ikea Wardrobe');
		}
		
		if ($('#item_quantity').val() == '') {
			setError('item_quantity', 'The quantity field is required.');
			error = true;
		}
		else if ($('#item_quantity').val() != parseInt($('#item_quantity').val())) {
			setError('item_quantity', 'The quantity field can only contain whole numbers.');
			error = true;
		}
		else {
			resetError('item_quantity', 'Enter the number of these items to be packed.');
		}
		
		if ($('#item_weight').val() == '') {
			setError('item_weight', 'The weight field is required.');
			error = true;
		}
		else if ($('#item_weight').val() != parseFloat($('#item_weight').val())) {
			setError('item_weight', 'The weight field can only contain numbers.');
			error = true;
		}
		else {
			resetError('item_weight', 'Enter the weight (in kg/lb) of one of the item(s).');
		}
		
		if ($('#item_dim_length').val() == '' || $('#item_dim_width').val() == ''
		|| $('#item_dim_height').val() == '') {
			setError('item_dim_length', 'The dimensions fields (length x width x height) are required.');
			error = true;	
		}
		else if ($('#item_dim_length').val() != parseFloat($('#item_dim_length').val())
		|| $('#item_dim_width').val() != parseFloat($('#item_dim_width').val())
		|| $('#item_dim_height').val() != parseFloat($('#item_dim_height').val())) {
			setError('item_dim_length', 'The dimensions fields (Length x Width x Height) can only contain numbers.');
			error = true;	
		}
		else {
			resetError('item_dim_length', 'Enter the dimensions of one of the item(s). Length x Width x Height  (in cm).');
		}
		
		if (error) {
			// add new error tooltips (if any)
			$('.exclaim').tooltip({showURL: false, extraClass: "error-tip"});
			$('.explain').tooltip({showURL: false});
			$('#dialog .italic').replaceWith('<p class="italic error">Please check the fields in red below are fill in correctly.</p>');
			return false;
		}
		else {		
		
		
			if ($(this).attr('id') == 'add-confirm') {				
				// build table/add table row then reset form and hide modal dialog			
				if (!$('#packing-items').attr('id')) {			
					createTable();
				}
							
				var item_name = $('#dialog #item_name2').val();
				var item_quantity = $('#dialog #item_quantity').val();
				var item_weight = $('#dialog #item_weight').val();
				var measurement = $('#dialog #measurement').val();
				
				var dimensions = new Array();
				dimensions['dim_length'] = $('#dialog #item_dim_length').val();
				dimensions['dim_width'] = $('#dialog #item_dim_width').val();
				dimensions['dim_height'] = $('#dialog #item_dim_height').val();	
				
				var desc = $('#dialog textarea').val();
							
				newItemId = parseInt(itemId) + 1;
				
				var ajaxData = 'item_id='+newItemId+'&item_name='+item_name+'&item_quantity='+item_quantity+'&item_weight='+item_weight+'&measurement='+measurement+'&dim_length='+dimensions["dim_length"]+'&dim_width='+dimensions["dim_width"]+'&dim_height='+dimensions["dim_height"]+'&item_description='+desc;
				
				$.ajax({
				   type: "POST",
				   async: false,
				   dataType: "text",
				   url: "/quote/packing/ajax_addItem",
				   data: ajaxData,
				   success: function(msg){
					 addRow(item_name, item_quantity);	
				   },
				   error: function(msg){
					 alert( "Error: " + msg );	
				   }
				});			
						
							
				$('#dialog').jqmHide();	
				$('#dialog .italic').replaceWith('<p class="italic">Tell us as much as you can about your item(s).</p>');
				$('#dialog input:text').val('');
				$('#dialog select option').attr('selected', false)		
				$("#dialog select option[value='kg']").attr('selected', 'selected');
				$('#dialog textarea').val('');
				$('#item_name').val('');
				$('#item_name').focus();	
						
				return false;
			}
			else if ($(this).attr('id') == 'edit-confirm') {
				
				var item_name = $('#dialog #item_name2').val();
				var item_quantity = $('#dialog #item_quantity').val();
				var item_weight = $('#dialog #item_weight').val();
				var measurement = $('#dialog #measurement').val();
				
				var dimensions = new Array();
				dimensions['dim_length'] = $('#dialog #item_dim_length').val();
				dimensions['dim_width'] = $('#dialog #item_dim_width').val();
				dimensions['dim_height'] = $('#dialog #item_dim_height').val();	
				
				var desc = $('#dialog textarea').val();
							
				itemId = $(this).attr('class').replace('save-','');
				
				
				var ajaxData = 'item_id='+itemId+'&item_name='+item_name+'&item_quantity='+item_quantity+'&item_weight='+item_weight+'&measurement='+measurement+'&dim_length='+dimensions["dim_length"]+'&dim_width='+dimensions["dim_width"]+'&dim_height='+dimensions["dim_height"]+'&item_description='+desc;
				
				$.ajax({
				   type: "POST",
				   async: false,
				   dataType: "text",
				   url: "/quote/packing/ajax_editItem",
				   data: ajaxData,
				   success: function(msg){
					 editRow(itemId, item_name, item_quantity);	
				   },
				   error: function(msg){
					 alert( "Error: " + msg );	
				   }
				});
				
				$('#dialog').jqmHide();	
				$('#dialog .italic').replaceWith('<p class="italic">Tell us as much as you can about your item(s).</p>');
				$('#dialog input:text').val('');
				$('#dialog select option').attr('selected', false)		
				$("#dialog select option[value='kg']").attr('selected', 'selected');
				$('#dialog textarea').val('');
				$('#item_name').val('');
				$('#item_name').focus();	
						
				return false;
			}
		}
	});
	
	$('#start_date, #end_date').datepicker({
		minDate: '+1W', 
		maxDate: '+2M',
		dateFormat: 'dd/mm/yy'		
	});
	
	$('#start_date, #end_date').watermark("dd/mm/yyyy");

	
});