var numberOfParcelRows = -1;
var parcelAdded = false;
var defaultRowStatus = '- Select Additional Cover -';
var selectServiceOptionText = 'Please Select a Service...';
var prebookErrorOccured = false;
var allowedDates = new Array();
var allowedDatesOriginal = new Array();
var shipmentDetails = new Array();
var parcelTooltipContent = '<div class="parcelTooltip"><div class="parcelTooltipImg tooltipImgAdd"><img src="/custom/images/addparcel.gif" /></div> Click this icon to <strong>send another parcel to the same address</strong>.</div><div class="parcelTooltip"><div class="parcelTooltipImg tooltipImgRemove"><img src="/custom/images/removeparcel.gif" /></div> Click this icon to <strong>remove this parcel from this shipment</strong>.</div>';
var shipmentTooltipContent = '<div class="shipmentTooltip"><div class="shipmentTooltipImg tooltipImgAdd"><img src="/custom/images/addshipment.gif" /></div> Click this icon to <strong>send parcels to another address</strong>.</div><div class="shipmentTooltip"><div class="shipmentTooltipImg tooltipImgRemove"><img src="/custom/images/' + baseFolder + 'removeshipment.gif" /></div> Click this icon to <strong>remove this shipment entirely</strong>.</div>';
var lastRemoveParcelIconId = '';
var postcodesRequired = new Array();
var defaultContentsText = 'e.g Camera...';
var showShippingAddressPopupOnLoad = false;
var showShippingAddressDirection = 'from';
var quoteTableOnPage = false;
var creditInBasket = false;
var snowWarningMessage = "Important Message\n\nPlease note that DPD will not collect from any Scottish or Yorkshire postcodes until after Christmas.\n\nThere are also no DHL collections in Yorkshire and Scotland until further notice.\n\nDHL Euro Road are not currently collecting in the following areas;\n\nCHELMSFORD, CROYDON, DARTFORD, GATESHEAD, GOOLE, HULL, LINCOLN, LOUGHBOROUGH, SHEFFIELD, STOCKTON, YORK.\n\nWe apologise for the inconvenience caused.";
var exportCountries = new Array();
var europeanCountries = new Array();

function manuallyChangeShipToCountry( countryCode, countryPrefix ) {
	document.getElementById( countryPrefix + '_shipTo_country' ).value = countryCode;
	checkForCountryNotes( countryCode );
}
function manuallyChangeShipFromCountry( countryCode, countryPrefix ) {
	document.getElementById( countryPrefix + '_shipFrom_country' ).value = countryCode;
}

function showQuoteTable() {
	if ( !creditInBasket ) {
		$('#screenMask').show();
		$('#quoteTableContainer').css('z-index','4');
		$('#quoteTableContainer').show();
		$('#screenMask').height($(document).height() + 240);
		$('#screenMask').click(function(){
			hideQuoteTable();
		});
		$('#quoteClose').click(function(){
			hideQuoteTable();
		});
		if($('#cmsServicesShipping_packages_1_1_weight').val() == '') {
			$('#cmsServicesShipping_packages_1_1_weight').focus();
		}
		showReturnButton();
	} else {
		if ( confirm( "As you have credits in your basket, you must purchase these before booking shipments.\n\nClick the 'OK' button to proceed to the checkout." ) ) {
			document.location = '/checkout';
		}
	}
}

function hideQuoteTable() {
	hideShippingAddressPopup();
	$('#quoteTableContainer').hide();
	$('#quoteTableContainer').css('z-index','1');
	$('#screenMask').hide();
}

function completeShippingAddresses( surpressErrors, dir ) {
	
	// make sure we've not got United Kingdom selected when it should be one of the Channel Islands
	if ( document.getElementById('cmsServicesShipping_shipTo_country').value == 'GB' ) {
		var postcode = document.getElementById('cmsServicesShipping_shipTo_postcode').value.toUpperCase();
		var postcodeLetters = postcode.substr( 0, 2 );
		var channelIsland = '';
		if ( postcodeLetters == 'GG' ) {
			// going to guernsey, change the drop down and inform the user
			manuallyChangeShipToCountry( 'GG', 'cmsServicesShipping' );
			channelIsland = 'Guernsey';
		} else if ( postcodeLetters == 'JE' ) {
			// going to Jersey, change the drop down and inform the user
			manuallyChangeShipToCountry( 'JE', 'cmsServicesShipping' );
			channelIsland = 'Jersey';
		}
		if ( channelIsland != '' ) {
			alert( 'We have automatically changed the destination country to ' + channelIsland );
		}
	}
	
	shipmentDetails[ currentQuoteRowId ].from = new Object();
	shipmentDetails[ currentQuoteRowId ].from.name = document.getElementById('cmsServicesShipping_shipFrom_contact_name').value;
	shipmentDetails[ currentQuoteRowId ].from.houseNumber = document.getElementById('cmsServicesShipping_shipFrom_house_number').value;
	shipmentDetails[ currentQuoteRowId ].from.address1 = document.getElementById('cmsServicesShipping_shipFrom_address_1').value;
	shipmentDetails[ currentQuoteRowId ].from.address2 = document.getElementById('cmsServicesShipping_shipFrom_address_2').value;
	shipmentDetails[ currentQuoteRowId ].from.town = document.getElementById('cmsServicesShipping_shipFrom_address_3').value;
	shipmentDetails[ currentQuoteRowId ].from.county = document.getElementById('cmsServicesShipping_shipFrom_city').value;
	shipmentDetails[ currentQuoteRowId ].from.postcode = document.getElementById('cmsServicesShipping_shipFrom_postcode').value;
	shipmentDetails[ currentQuoteRowId ].from.state = document.getElementById('cmsServicesShipping_shipFrom_state').value;
	shipmentDetails[ currentQuoteRowId ].from.stateOther = document.getElementById('cmsServicesShipping_shipFrom_state_other').value;
	shipmentDetails[ currentQuoteRowId ].from.country = document.getElementById('cmsServicesShipping_shipFrom_country').value;
	shipmentDetails[ currentQuoteRowId ].from.residential = document.getElementById('cmsServicesShipping_shipFrom_residential_address').value;
	shipmentDetails[ currentQuoteRowId ].from.company = document.getElementById('cmsServicesShipping_shipFrom_company').value;
	shipmentDetails[ currentQuoteRowId ].from.telephone = document.getElementById('cmsServicesShipping_shipFrom_phone_number').value;
	shipmentDetails[ currentQuoteRowId ].from.email = document.getElementById('cmsServicesShipping_shipFrom_email_address').value;
	
	shipmentDetails[ currentQuoteRowId ].to = new Object();
	shipmentDetails[ currentQuoteRowId ].to.name = document.getElementById('cmsServicesShipping_shipTo_contact_name').value;
	shipmentDetails[ currentQuoteRowId ].to.houseNumber = document.getElementById('cmsServicesShipping_shipTo_house_number').value;
	shipmentDetails[ currentQuoteRowId ].to.address1 = document.getElementById('cmsServicesShipping_shipTo_address_1').value;
	shipmentDetails[ currentQuoteRowId ].to.address2 = document.getElementById('cmsServicesShipping_shipTo_address_2').value;
	shipmentDetails[ currentQuoteRowId ].to.town = document.getElementById('cmsServicesShipping_shipTo_address_3').value;
	shipmentDetails[ currentQuoteRowId ].to.county = document.getElementById('cmsServicesShipping_shipTo_city').value;
	shipmentDetails[ currentQuoteRowId ].to.postcode = document.getElementById('cmsServicesShipping_shipTo_postcode').value;
	shipmentDetails[ currentQuoteRowId ].to.state = document.getElementById('cmsServicesShipping_shipTo_state').value;
	shipmentDetails[ currentQuoteRowId ].to.stateOther = document.getElementById('cmsServicesShipping_shipTo_state_other').value;
	shipmentDetails[ currentQuoteRowId ].to.country = document.getElementById('cmsServicesShipping_shipTo_country').value;
	shipmentDetails[ currentQuoteRowId ].to.residential = document.getElementById('cmsServicesShipping_shipTo_residential_address').value;
	shipmentDetails[ currentQuoteRowId ].to.company = document.getElementById('cmsServicesShipping_shipTo_company').value;
	shipmentDetails[ currentQuoteRowId ].to.telephone = document.getElementById('cmsServicesShipping_shipTo_phone_number').value;
	shipmentDetails[ currentQuoteRowId ].to.email = document.getElementById('cmsServicesShipping_shipTo_email_address').value;
	
	// make sure there are no default values in the stored address
	var defaultAddress = getEmptyAddress();
	if ( shipmentDetails[ currentQuoteRowId ].from.houseNumber == defaultAddress.from.houseNumber ) {
		shipmentDetails[ currentQuoteRowId ].from.houseNumber = '';
	}
	if ( shipmentDetails[ currentQuoteRowId ].from.address2 == defaultAddress.from.address2 ) {
		shipmentDetails[ currentQuoteRowId ].from.address2 = '';
	}
	if ( shipmentDetails[ currentQuoteRowId ].from.company == defaultAddress.from.company ) {
		shipmentDetails[ currentQuoteRowId ].from.company = '';
	}
	if ( shipmentDetails[ currentQuoteRowId ].to.houseNumber == defaultAddress.to.houseNumber ) {
		shipmentDetails[ currentQuoteRowId ].to.houseNumber = '';
	}
	if ( shipmentDetails[ currentQuoteRowId ].to.address2 == defaultAddress.to.address2 ) {
		shipmentDetails[ currentQuoteRowId ].to.address2 = '';
	}
	if ( shipmentDetails[ currentQuoteRowId ].to.company == defaultAddress.to.company ) {
		shipmentDetails[ currentQuoteRowId ].to.company = '';
	}
	if ( shipmentDetails[ currentQuoteRowId ].to.postcode.replace( '*','' ) == defaultAddress.to.postcode.replace( '*','' ) ) {
		shipmentDetails[ currentQuoteRowId ].to.postcode = '';
	}
	
	var addressFromValid = true;
	var addressToValid = true;
	if(dir == 'from') {
		addressFromValid = validateShippingAddressFrom( currentQuoteRowId, surpressErrors );
		if (addressFromValid) {
			changeShippingAddressTab('to');
		}
	} else {
		addressFromValid = validateShippingAddressFrom( currentQuoteRowId, surpressErrors );
		addressToValid = validateShippingAddressTo( currentQuoteRowId, surpressErrors );
		if ( addressFromValid && addressToValid && !surpressErrors ) {
			hideShippingAddressPopup();
			// open the calendar after the addresses have been successfully entered
			$('#cmsServicesShipping_collection_date_icon_' + currentQuoteRowId ).trigger('openCalendar');
		}
	}
	
	updateStatus( currentQuoteRowId );
}

function validateShippingAddresses( rowId, surpressErrors ) {
	if(validateShippingAddressFrom(rowId,surpressErrors) && validateShippingAddressTo(rowId,surpressErrors)) {
		return true;
	}
	else {
		return false;
	}
}

function validateShippingAddressFrom(rowId, surpressErrors ) {
	if ( typeof shipmentDetails[ rowId ].from != 'undefined' ) {
		populateCollectionAddress( 'From', shipmentDetails[ rowId ].from, null );
	}
	if ( document.getElementById( 'cmsServicesShipping_shipFrom_residential_address' ).value == 1 ) {
		document.getElementById( 'cmsServicesShipping_shipFrom_company' ).value = document.getElementById( 'cmsServicesShipping_shipFrom_contact_name' ).value
	}
	var validatorFrom = checkAddressStatus( 'From', true );
	if ( validatorFrom.numberOfErrors() > 0 ) {
		if ( !surpressErrors ) {
			changeShippingAddressTab('from');
			validatorFrom.displayErrors();
		}
		return false;
	}
	else {
		return true;
	}
}
function validateShippingAddressTo(rowId, surpressErrors ) {
	if ( typeof shipmentDetails[ rowId ].to != 'undefined' ) {
		populateCollectionAddress( 'To', shipmentDetails[ rowId ].to, null );
	}
	if ( document.getElementById( 'cmsServicesShipping_shipTo_residential_address' ).value == 1 ) {
		document.getElementById( 'cmsServicesShipping_shipTo_company' ).value = document.getElementById( 'cmsServicesShipping_shipTo_contact_name' ).value
	}
	var validatorFrom = checkAddressStatus( 'To', true );
	if ( validatorFrom.numberOfErrors() > 0 ) {
		if ( !surpressErrors ) {
			changeShippingAddressTab('to');
			validatorFrom.displayErrors();
		}
		return false;
	}
	else {
		return true;
	}
}

function validateShippingAddress( direction ) {
	var validator = checkAddressStatus( direction, false );
	if ( validator.numberOfErrors() > 0 ) {
		// there were errors, set the tab color to red to indicate this
		var classToAdd = 'addressError';
		var classToRemove = 'addressValid';
	} else {
		// no errors, set the tab color to green to indicate this
		var classToAdd = 'addressValid';
		var classToRemove = 'addressError';
	}
}

function highlightAddressField( fieldId ) {
	YAHOO.util.Dom.addClass( fieldId, 'addressInputError' );
}
function lowlightAddressField( fieldId ) {
	YAHOO.util.Dom.removeClass( fieldId, 'addressInputError' );
}

function checkAddressStatus( direction, doHighlight ) {
	var validator = new validateForm();
	if ( document.getElementById( 'cmsServicesShipping_ship' + direction + '_residential_address' ).value == 0 ) {
		if ( !validator.checkText( 'cmsServicesShipping_ship' + direction + '_company', 'Ship ' + direction + ': Company Name', '- Company*' ) ) {
			if ( doHighlight ) {
				highlightAddressField( 'cmsServicesShipping_ship' + direction + '_company' );
			}
		} else {
			lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_company' );
		}
	}
	
	if ( !validator.checkText( 'cmsServicesShipping_ship' + direction + '_contact_name', 'Ship ' + direction + ': Contact Name', '- Contact Name*' ) ) {
		if ( doHighlight ) {
			highlightAddressField( 'cmsServicesShipping_ship' + direction + '_contact_name' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_contact_name' );
	}
	
	var countryCode = document.getElementById( 'cmsServicesShipping_ship' + direction + '_country' ).value;
	if ( postcodesRequired[ countryCode ] ) {
		if ( countryCode == 'GB' ) {
			var isValid = validator.validatePostCode( 'cmsServicesShipping_ship' + direction + '_postcode', 'Ship ' + direction + ': Post Code' );
		} else {
			var isValid = validator.checkText( 'cmsServicesShipping_ship' + direction + '_postcode', 'Ship ' + direction + ': Post Code', '- Postcode*' );
		}
		if ( !isValid ) {
			if ( doHighlight ) {
				highlightAddressField( 'cmsServicesShipping_ship' + direction + '_postcode' );
			}
		} else {
			lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_postcode' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_postcode' );
	}
	if ( document.getElementById('ship'+direction+'StateContainer').style.display != 'none' ) {
		if ( document.getElementById( 'cmsServicesShipping_ship'+direction+'_state' ).selectedIndex == 0 ) {
			validator.addCustomError( 'Ship '+direction+': State' );
			highlightAddressField( 'cmsServicesShipping_ship'+direction+'_state' );
		} else {
			lowlightAddressField( 'cmsServicesShipping_ship'+direction+'_state' );
			if ( document.getElementById('cmsServicesShipping_ship'+direction+'_state').value == 'other' ) {
				validator.checkText( 'cmsServicesShipping_ship'+direction+'_state_other', 'Ship '+direction+': State - other' );
				highlightAddressField( 'cmsServicesShipping_ship'+direction+'_state_other' );
			} else {
				lowlightAddressField( 'cmsServicesShipping_ship'+direction+'_state_other' );
			}
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship'+direction+'_state' );
		lowlightAddressField( 'cmsServicesShipping_ship'+direction+'_state_other' );
	}
	
	if ( !validator.validateEmailAddress( 'cmsServicesShipping_ship' + direction + '_email_address', 'Ship ' + direction + ': Email Address' ) ) {
		if ( doHighlight ) {
			highlightAddressField( 'cmsServicesShipping_ship' + direction + '_email_address' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_email_address' );
	}
	
	if ( !validator.checkText( 'cmsServicesShipping_ship' + direction + '_phone_number', 'Ship ' + direction + ': Telephone Number', '- Contact Telephone*' ) ) {
		if ( doHighlight ) {
			highlightAddressField( 'cmsServicesShipping_ship' + direction + '_phone_number' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_phone_number' );
	}
	
	if ( !validator.checkText( 'cmsServicesShipping_ship' + direction + '_address_1', 'Ship ' + direction + ': Address 1', '- Address 1*' ) ) {
		if ( doHighlight ) {
			highlightAddressField( 'cmsServicesShipping_ship' + direction + '_address_1' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_address_1' );
	}
	
	if ( !validator.checkText( 'cmsServicesShipping_ship' + direction + '_address_3', 'Ship ' + direction + ': Town', '- Town*' ) ) {
		if ( doHighlight ) {
			highlightAddressField( 'cmsServicesShipping_ship' + direction + '_address_3' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_address_3' );
	}
	
	if ( !validator.checkText( 'cmsServicesShipping_ship' + direction + '_city', 'Ship ' + direction + ': County', '- County*' ) ) {
		if ( doHighlight ) {
			highlightAddressField( 'cmsServicesShipping_ship' + direction + '_city' );
		}
	} else {
		lowlightAddressField( 'cmsServicesShipping_ship' + direction + '_city' );
	}
	
	return validator;
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function removeAllOptions( slct ) {
	slct.options.length = 0;
}

function addOptionToSelect( slct, opt ) {
	slct.options[ slct.options.length ] = opt;
}

function addToSurchargeInfo( rowId, html ) {
	if ( html != '' ) {
		html = 'The following surcharges have been applied to these services:<br /><br />' + html;
	} else {
		html = 'No surcharges apply to these services';
	}
	document.getElementById('infoIcon_' + rowId).title = html;
	addToolTipToElement( '#infoIcon_' + rowId );
}

function getFormattedSurchargeInfo( surcharges, serviceName ) {
	var infoHTML = ''
	if ( surcharges.length > 0 ) {
		infoHTML += '<p><strong>' + serviceName + '</strong></p><ul>';
	}
	for ( var surcharge in surcharges ) {
		infoHTML += '<li>' + surcharges[ surcharge ]['description'] + ' - £' + parseFloat( surcharges[ surcharge ]['price'] ).toFixed(2) + '</li>';
	}
	if ( surcharges.length > 0 ) {
		infoHTML += '</ul>';
	}
	return infoHTML;
}
function sortByPrice2(a,b){
	var result = 0;
	if( ( a['provider'].substr(0,3) == 'UPS' ) && ( a['provider'].search('DHL') == (-1) ) ){
		result --;
	}
	if( ( b['provider'].substr(0,3) == 'UPS' ) && ( b['provider'].search('DHL') == (-1) ) ){
		result ++;
	}
	if( result != 0 ){
		return result;
	}else{
		return a['filteredTotalIncInsurance'] > b['filteredTotalIncInsurance'] ? 1 : -1;  		
	}
};  
function searchForQuotes( rowId ) {
	var handleSuccess = function(o){
		eval( 'var services = ' + o.responseText );
		if ( typeof services['errors'] != 'undefined' ) {
			// error occured, inform the user
			eval( 'var errors = ' + o.responseText );
			msg = "The following errors occured:\n\n";
			for ( var e in errors.errors ) {
				msg += " - " + errors.errors[e] + "\n";
			}
			alert( msg );
		} else if ( ( typeof services['availableServices'] != 'undefined' ) && ( services['availableServices'].length > 0 ) ) {
			// we have some services to display...
			var slct = document.getElementById('cmsServicesShipping_service_' + rowId );
			removeAllOptions( slct );
			slct.disabled = false;
			var opt = new Option( selectServiceOptionText, '' );
			addOptionToSelect( slct, opt );
			var infoHTML = '';
			services['availableServices'] = services['availableServices'].sort( sortByPrice2 );
			for ( var i in services['availableServices'] ) {
				var optValue = services['availableServices'][i]['sessionVarID'];
				var opt = new Option( services['availableServices'][i]['wpsService']['name'] + ' - £' + parseFloat( services['availableServices'][i]['filteredTotalIncInsurance'] ).toFixed(2), optValue );
				addOptionToSelect( slct, opt );
				infoHTML += getFormattedSurchargeInfo( services['availableServices'][i]['surcharges'], services['availableServices'][i]['wpsService']['name'] );
			}
			addToSurchargeInfo( rowId, infoHTML );
		} else {
			// errr, hopefully it will never get here...
			alert('Sorry, an error has occured.  Please try again.');
		}
		updateSectionStatus( rowId, 'services', false );
	};
	var handleFailure = function(o){
		if ( o.responseText != '' ) {
			eval( 'var services = ' + o.responseText );
			if ( typeof services['errors'] != 'undefined' ) {
				// error occured, inform the user
				eval( 'var errors = ' + o.responseText );
				msg = "The following errors occured:\n\n";
				for ( var e in errors.errors ) {
					msg += "\t- " + errors.errors[e] + "\n";
				}
				alert( msg );
			} else {
				// errr, hopefully it will never get here either...
				alert('Sorry, an error has occured.  Please try again.');
			}
		} else {
			// errr, hopefully it will never get here either...
			alert('Sorry, an error has occured.  Please try again.');
		}
		updateSectionStatus( rowId, 'services', false );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	makeAjaxShipmentRequest( rowId, 'service=customService&customService=getAvailableServices&quoteId=' + rowId, callback );
}

function makeAjaxShipmentRequest( rowId, params, callback ) {
	// loop round all dimension, contents and value inputs, dynamically adding them to the quote form that gets submitted
	var parcelContainer = document.getElementById('quoteFormParcelContainer');
	parcelContainer.innerHTML = '';
	var table = document.getElementById( 'cmsServicesShipping_parcelDimensions_' + rowId ).getElementsByTagName('TABLE')[0];
	var rows = table.getElementsByTagName('TR');
	for ( var r = 0; r < rows.length; r++ ) {
		var inputs = rows[r].getElementsByTagName('INPUT');
		for ( var i = 0; i < inputs.length; i++ ) {
			var newInput = document.createElement('INPUT');
			var elementId = inputs[i].id;
			var idSplit = elementId.split('_');
			var elementName = idSplit[ idSplit.length - 1 ];
			newInput.type = 'hidden';
			newInput.value = inputs[i].value;
			newInput.name = 'cmsServicesShipping[packages][' + r + '][' + elementName + ']';
			parcelContainer.appendChild( newInput );
		}
	}
	document.getElementById('queryForm_insurance').value = document.getElementById('cmsServicesShipping_insurance_' + rowId ).value;
	document.getElementById('queryForm_document').value = document.getElementById('cmsServicesShipping_document_' + rowId ).value;
	document.getElementById('queryForm_selected_service').value = document.getElementById('cmsServicesShipping_service_' + rowId ).value;
	document.getElementById('queryForm_collection_date').value = document.getElementById('cmsServicesShipping_collection_date_' + rowId).value;
	// update the delivery country name for display purposes later
	selectTo = document.getElementById( 'cmsServicesShipping_shipTo_country' );
	var countryTo = selectTo.options[ selectTo.selectedIndex ].text;
	document.getElementById( 'cmsServicesShipping_shipTo_country_long' ).value = countryTo.replace('*','');

	selectFrom = document.getElementById( 'cmsServicesShipping_shipFrom_country' );
	var countryFrom = selectTo.options[ selectFrom.selectedIndex ].text;
	document.getElementById( 'cmsServicesShipping_shipFrom_country_long' ).value = countryFrom.replace('*','');
	// requestarama
	YAHOO.util.Connect.setForm( document.getElementById( 'quoteForm' ) );
	var cObj = YAHOO.util.Connect.asyncRequest( 'POST', '/xmlservice.php?' + params, callback );
}

function checkDimensions( rowId, type ) {
	var table = document.getElementById( 'cmsServicesShipping_parcelDimensions_' + rowId ).getElementsByTagName('TABLE')[0];
	var rows = table.getElementsByTagName('TR');
	var ret = true;
	var thisType = '';
	var inputId = '';
	var thisRowId = '';
	var showZeroValueAlert = false;
	for ( var r = 0; r < rows.length; r++ ) {
		var inputs = rows[r].getElementsByTagName('INPUT');
		for ( var i = 0; i < inputs.length; i++ ) {
			inputId = inputs[i].id;
			thisTypeSplit = inputId.split('_');
			thisType = thisTypeSplit[ thisTypeSplit.length - 1 ];
			// get the 1_3 part from the current input where the id = cmsServicesShipping_packages_1_3_height
			thisRowId = inputId.replace('cmsServicesShipping_packages_','');
			thisRowId = thisRowId.replace('_' + thisType,'');
			if ( thisType == type ) {
				// this is the type (ie width, length etc) we are checking
				if ( ( inputs[i].value == '' ) || ( inputs[i].value == 0 ) || ( inputs[i].value == defaultContentsText ) ) {
					updateSectionStatus( thisRowId, type, false );
					if(type == 'value' && inputs[i].value === '0') {
						showZeroValueAlert = true;
					}
					ret = false;
				} else {
					updateSectionStatus( thisRowId, type, true );
				}
			}
		}
	}
	if(showZeroValueAlert) {
		alert('Value must be greater than £0');
	}
	return ret;
}

function checkParcelValues( rowId ) {
	
	var table = document.getElementById( 'cmsServicesShipping_parcelDimensions_' + rowId ).getElementsByTagName('TABLE')[0];
	var rows = table.getElementsByTagName('TR');
	var totalValue = 0;
	// get the combined values of all parcels
	for ( var r = 0; r < rows.length; r++ ) {
		var inputs = rows[r].getElementsByTagName('INPUT');
		for ( var i = 0; i < inputs.length; i++ ) {
			var inputId = inputs[i].id;
			if ( inputId.substring( inputId.length - 5 ) == 'value' ) {
				if ( inputs[i].value == '' ) {
					return false;
				} else {
					totalValue += parseInt( inputs[i].value );
				}
			}
		}
	}
	// get insurance value
	var insuranceValue = parseInt( document.getElementById( 'cmsServicesShipping_insurance_' + rowId ).value );
	
	var ret = false;
	
	if ( totalValue <= insuranceValue ) {
		// combined parcel value is less than the selected insurance amount
		ret = true;
	} else {
		// combined parcel value is greater than the selected insurance amount
		ret = false;
	}
	
	return ret;
}

function updateSectionStatus( rowId, section, complete ) {
	YAHOO.util.Dom.removeClass( 'row_section_' + rowId + '_' + section, 'rowStatusComplete' );
	YAHOO.util.Dom.removeClass( 'row_section_' + rowId + '_' + section, 'rowStatusError' );
	YAHOO.util.Dom.addClass( 'row_section_' + rowId + '_' + section, ( complete ) ? 'rowStatusComplete' : 'rowStatusError' );
}

var populatingOnLoad = false;

function updateStatus( rowId ) {
	var rowStatus = defaultRowStatus;
	if ( document.getElementById('cmsServicesShipping_insurance_' + rowId ).selectedIndex > 0 ) {
		updateSectionStatus( rowId, 'insurance', true );
		if ( checkDimensions( rowId, 'weight' ) ) {
			// user has entered parcel weight
			if ( checkDimensions( rowId, 'length' ) ) {
				if ( checkDimensions( rowId, 'width' ) ) {
					if ( checkDimensions( rowId, 'height' ) ) {
						// user has entered all required dimensions
						if ( checkDimensions( rowId, 'description' ) ) {
							// user has entered parcel contents
							updateSectionStatus( rowId, 'description', true );
							if ( checkDimensions( rowId, 'value' ) ) {
								// user has entered parcel value
								updateSectionStatus( rowId, 'value', true );
								if ( checkParcelValues( rowId ) ) {
									// the parcel value does not exceed the insurance cover
									updateSectionStatus( rowId, 'insurance', true );
									updateSectionStatus( rowId, 'value', true );
									if ( validateShippingAddressFrom( rowId, true ) ) {
										// from address details have been entered
										updateSectionStatus( rowId, 'addressFrom', true );
										if( validateShippingAddressTo( rowId, true ) ) {
											// all shipping address details have been entered
											updateSectionStatus( rowId, 'addressTo', true );
											var selectedDate = document.getElementById('cmsServicesShipping_collection_date_' + rowId ).value;
											if ( ( selectedDate != '' ) && ( selectedDate.length == 8 ) ) {
												updateSectionStatus( rowId, 'date', true );
												// user has selected a collection date and everything is valid!
												rowStatus = 'Searching for quotes...';
												// kick off the quote search
												if ( !populatingOnLoad ) {
													searchForQuotes( rowId );
												}
											} else {
												updateSectionStatus( rowId, 'date', false );
												rowStatus = '- Select Collection Date -';
											}
										} else {
											updateSectionStatus( rowId, 'addressTo', false );
											rowStatus = '- Enter All Address Information -';
										}
									} else {
										updateSectionStatus( rowId, 'addressFrom', false );
										rowStatus = '- Enter All Address Information -';
									}
								} else {
									rowStatus = '- Parcel value must not exceed cover value -';
									showOverValuePopup();
								}
							} else {
								rowStatus = '- Enter Parcel Value -';
							}
						} else {
							rowStatus = '- Enter Parcel Contents -';
						}
					} else {
						rowStatus = '- Enter Parcel Height -';
					}
				} else {
					rowStatus = '- Enter Parcel Width -';
				}
			} else {
				rowStatus = '- Enter Parcel Length -';
			}
		} else {
			rowStatus = '- Enter Parcel Weight -';
		}
	} else {
		updateSectionStatus( rowId, 'insurance', false );
		rowStatus = defaultRowStatus;
	}
	if ( !populatingOnLoad ) {
		var slct = document.getElementById('cmsServicesShipping_service_' + rowId );
		removeAllOptions( slct );
		var opt = new Option( rowStatus, 0 );
		addOptionToSelect( slct, opt );
		slct.disabled = true;
	} else {
		updateSectionStatus( rowId, 'services', true );
	}
}

function checkDisabledDates( date ) {
	return !( Calendar.dateToInt( date ) in allowedDates );
}

function populateCollectionAddress( addressType, address, allowBlanks ) {
	var defaultAddress = getEmptyAddress();
	if ( addressType == 'from' ) {
		defaultAddress = defaultAddress.from;
	} else {
		defaultAddress = defaultAddress.to;
	}
	document.getElementById('cmsServicesShipping_ship' + addressType + '_contact_name').value = ( ( address.name ) ? address.name : ( ( allowBlanks ) ? '' : defaultAddress.name ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_house_number').value = ( ( address.houseNumber ) ? address.houseNumber : ( ( allowBlanks ) ? '' : defaultAddress.houseNumber ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_address_1').value = ( ( address.address1 ) ? address.address1 : ( ( allowBlanks ) ? '' : defaultAddress.address1 ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_address_2').value = ( ( ( address.address2 ) && ( address.address2 != defaultAddress.address2 ) ) ? address.address2 : ( ( allowBlanks ) ? '' : defaultAddress.address2 ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_address_3').value = ( ( address.town ) ? address.town : ( ( allowBlanks ) ? '' : defaultAddress.town ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_city').value = ( ( address.county ) ? address.county : ( ( allowBlanks ) ? '' : defaultAddress.county ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_postcode').value = ( ( address.postcode ) ? address.postcode : ( ( allowBlanks ) ? '' : defaultAddress.postcode ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_company').value = ( ( address.company ) ? address.company : ( ( allowBlanks ) ? '' : defaultAddress.company ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_email_address').value = ( ( address.email ) ? address.email : ( ( allowBlanks ) ? '' : defaultAddress.email ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_phone_number').value = ( ( address.telephone ) ? address.telephone : ( ( allowBlanks ) ? '' : defaultAddress.telephone ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_residential_address').value = ( ( address.residential ) ? address.residential : ( ( allowBlanks ) ? '' : defaultAddress.residential ) );
	document.getElementById('cmsServicesShipping_ship' + addressType + '_country').value = ( ( address.country ) ? address.country : ( ( allowBlanks ) ? '' : defaultAddress.country ) );
	changeResidential( address.residential, 'ship' + addressType );
	if ( addressType == 'To' ) {
		checkShipToPostcode( address.country, false );
	} else {
		checkShipFromPostcode( address.country, false );
	}
	// display any notes for this country
	if ( addressType == 'To' ) {
		checkForCountryNotes( address.country );
	}
	// show the state if necessary
	if ( ( address.country == 'EI' ) || ( address.country == 'CA' ) || ( address.country == 'US' ) || ( address.country == 'NY' ) ) {
		updateStates( address.country, 'ship'+addressType );
		if ( address.state ) {
			document.getElementById('cmsServicesShipping_ship' + addressType + '_state').value = address.state;
		}
		document.getElementById('cmsServicesShipping_ship' + addressType + '_state_other').value = address.stateOther;
		document.getElementById('ship'+addressType+'StateContainer').style.display = '';
		changeState( address.state, addressType );
	} else {
		document.getElementById('cmsServicesShipping_ship' + addressType + '_state').selectedIndex = 0;
		document.getElementById('cmsServicesShipping_ship' + addressType + '_state_other').value = '';
		document.getElementById('ship'+addressType+'StateContainer').style.display = 'none';
	}
}

function getEmptyAddress() {
	var emptyAddress = {
		to	:		{
			name		:	'- Contact Name*',
			houseNumber	:	'- Building No.',
			address1	:	'- Address 1*',
			address2	: 	'- Address 2',
			town		:	'- Town*',
			county		:	'- County*',
			postcode	:	'- Postcode*',
			country		:	$('#qq_shipTo_country').val(),
			residential	:	0,
			state		:	'',
			stateOther	:	'',
			company		:	'- Company*',
			telephone	:	'- Contact Telephone*',
			email		:	'- Contact Email*'
		},
		from	:	{
			name		:	'- Contact Name*',
			houseNumber	:	'- Building No.',
			address1	:	'- Address 1*',
			address2	: 	'- Address 2',
			town		:	'- Town*',
			county		:	'- County*',
			postcode	:	'- Postcode*',
			country		:	'GB',
			residential	:	0,
			state		:	'',
			stateOther	:	'',
			company		:	'- Company*',
			telephone	:	'- Contact Telephone*',
			email		:	'- Contact Email*'
		}
	};
	return emptyAddress;
}

function resetCollectionAddresses() {
	var emptyAddress = getEmptyAddress();
	populateCollectionAddress( 'From', emptyAddress.from, false );
	populateCollectionAddress( 'To', emptyAddress.to, false );
	$('#addressListContainer_To').hide();
	$('#addressListContainer_From').hide();
	$('#shipTo_address_fields').hide();
	$('#shipFrom_address_fields').hide();
}

function populateCollectionAddresses( num, allowBlanks ) {
	if ( typeof shipmentDetails[ num ].from != 'undefined' ) {
		populateCollectionAddress( 'From', shipmentDetails[ num ].from, allowBlanks );
		populateCollectionAddress( 'To', shipmentDetails[ num ].to, allowBlanks );
		$('#shipTo_address_fields').show();
		$('#shipFrom_address_fields').show();
	}
	else {
		resetCollectionAddresses();
	}
}

function removeQuoteRow( rowId ) {
	var answer = confirm('Are you sure you want to remove this shipment?');
	if(answer) {
		// remove the row from the UI
		var tr = document.getElementById( 'quoteRow_' + rowId );
		var trAdd = document.getElementById( 'quoteRowAdd_' + rowId );
		tr.parentNode.removeChild( trAdd );
		tr.parentNode.removeChild( tr );
		var handleSuccess = function(o) { };
		var handleFailure = function(o) { };
		var callback = {
			success:handleSuccess,
			failure:handleFailure
		};
		// ajax request to remove the item from the session
		var cObj = YAHOO.util.Connect.asyncRequest( 'POST', '/xmlservice.php?service=customService&customService=removePackage&quoteId=' + rowId, callback );
		numberOfParcelRows--;
		delete shipmentDetails[ rowId ];
		if ( numberOfParcelRows == -1 ) {
			// we've removed all rows in the table, add a brand spanking new one
			addQuoteRow('standard');
			parcelAdded = false;
		}
	}
}

function removeParcelFromShipment( tr, rowId ) {
	// remove the package from the UI
	var answer = confirm('Are you sure you want to remove this parcel?');
	if(answer) {
		var parent = tr.parentNode;
		if ( userAuthenticated ) {
			// also remove the previous parcels drop-down for this row
			var previousRow = tr.previousSibling;
			if ( previousRow && previousRow.className == 'previousParcelsRow' ) {
				parent.removeChild( previousRow );
			}
		}
		parent.removeChild( tr );
		
		var rows = parent.getElementsByTagName('TR');
		if ( rows.length == 0 ) {
			// we've just removed the last row, so add a new one
			addParcelToShipment( 'standard', rowId );
		}
		updateStatus( rowId );
	}
}

function selectPreviousParcel( quoteType, rowId, parcelNumber, previousParcelId ) {
	if ( previousParcelId == 'new' ) {
		var address = {
			weight: 0,
			length: 0,
			width: 0,
			height: 0,
			value: 0,
			description: defaultContentsText
		}
	} else {
		var address = previousParcels[0][ previousParcelId ];
	}
	if(quoteType == 'document') {
		address.weight = '0.5';
	}
	document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_weight' ).value = address.weight;
	document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_length' ).value = address.length;
	document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_width' ).value = address.width;
	document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_height' ).value = address.height;
	document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_value' ).value = parseInt( address.value );
	document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_description' ).value = address.description;
	document.getElementById( 'row_' + rowId + '_' + parcelNumber + '_previousParcels' ).style.display = 'none';
	document.getElementById( 'row_' + rowId + '_' + parcelNumber + '_dimensions' ).style.display = '';
	// change the description style
	parcelDescriptionBlur( rowId, parcelNumber );
	// validate this row
	updateStatus( rowId );
}

function parcelDescriptionBlur( rowId, parcelNumber ) {
	var input = document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_description' );
	inputBoxBlur( input, defaultContentsText );
	if ( input.value == defaultContentsText ) {
		input.className = 'formInput contentsInput contentsInputDefault';
	} else {
		input.className = 'formInput contentsInput';
	}
}
function parcelDescriptionFocus( rowId, parcelNumber ) {
	var input = document.getElementById( 'cmsServicesShipping_packages_' + rowId + '_' + parcelNumber + '_description' );
	input.className = 'formInput contentsInput';
	inputBoxFocus( input, defaultContentsText );
}

function addParcelToShipment( quoteType, thisId, parcelDetails ) {
	// get or create the table we will append the dimensions to
	var tablesFound = document.getElementById( 'cmsServicesShipping_parcelDimensions_' + thisId ).getElementsByTagName('TABLE');
	if ( tablesFound.length == 1 ) {
		// we've already created a table for this shipment, so use that
		var table = tablesFound[0];
		var tbody = table.getElementsByTagName('TBODY')[0];
		var parcelNumber = $( '.dimensionRow', $(tbody) ).length + 1;
		while( $( '#row_' + thisId + '_' + parcelNumber + '_dimensions' ).length > 0 ) {
			parcelNumber += 1;
		}
	} else {
		// no table has been created yet, so create it
		var table = document.createElement('TABLE');
		table.setAttribute( "cellspacing", 0 );
		table.setAttribute( "cellpadding", 0 );
		table.setAttribute( "border", 0 );
		var tbody = document.createElement('TBODY');
		table.appendChild( tbody );
		var parcelNumber = 1;
	}
	
	// add the previous parcel drop down if we need to
	if ( ( previousParcels.length > 0 ) && ( typeof parcelDetails == 'undefined' ) ) {
		var tr = document.createElement('TR');
			tr.className = 'previousParcelsRow';
			tr.setAttribute( 'id', 'row_' + thisId + '_' + parcelNumber + '_previousParcels' );
		var td = document.createElement('TD');
			td.colSpan = 6;
		var select = document.createElement('SELECT');
			select.className = 'formInput previousParcels';
			var opt = new Option( 'Select Parcel...', '' );
			addOptionToSelect( select, opt );
			var opt = new Option( '- Enter New Parcel -', 'new' );
			addOptionToSelect( select, opt );
			for ( var p in previousParcels[0] ) {
				var txt = previousParcels[0][p].description + ' (' + previousParcels[0][p].length + ' x ' + previousParcels[0][p].width + ' x ' + previousParcels[0][p].height + ' - ' + previousParcels[0][p].weight + 'kg)';
				var opt = new Option( txt, p );
				addOptionToSelect( select, opt );
			}
			YAHOO.util.Event.addListener( select, 'change', function(e) { selectPreviousParcel( quoteType, thisId, parcelNumber, this.value ); } );
			td.appendChild( select );
			tr.appendChild( td )
		// add the add/remove icons
		var td = document.createElement('TD');
			td.className = 'addRemoveParcelIcon';
		var img = document.createElement('IMG');
			lastRemoveParcelIconId = 'removeParcelIcon_' + thisId + '_' + parcelNumber;
			img.setAttribute( 'id', lastRemoveParcelIconId );
			img.setAttribute( 'src', '/custom/images/removeparcel.gif' );
			//img.setAttribute( 'title', 'Remove this parcel' );
			img.className = 'removeParcelIcon';
			YAHOO.util.Event.addListener( img, 'click', function() { removeParcelFromShipment( tr, thisId ) } );
			td.appendChild( img );
			tr.appendChild( td );
		tbody.appendChild( tr );
	}
	
	var tr = document.createElement('TR');
		tr.setAttribute( 'id', 'row_' + thisId + '_' + parcelNumber + '_dimensions' );
		tr.className = 'dimensionRow';
		if ( ( previousParcels.length > 0 ) && ( typeof parcelDetails == 'undefined' ) ) {
			tr.style.display = 'none';
		}
	// create weight cell
	var td = document.createElement('TD');
		td.className = 'quoteTableDimension rowStatusError';
		td.setAttribute( 'id', 'row_section_' + thisId + '_' + parcelNumber + '_weight' );
	var input4 = document.createElement('INPUT');
		input4.setAttribute( 'type', 'text' );
		input4.setAttribute( 'name', 'cmsServicesShipping[packages][' + thisId + '][' + parcelNumber + '][weight]' );
		input4.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_' + parcelNumber + '_weight' );
		if(quoteType == 'document') {
			input4.setAttribute( 'value', '0.5' );
			input4.setAttribute( 'readonly', 'readonly' );
		}
		else {
			input4.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.weight : '' ) );
		}
		input4.className = 'formInput dimensionInput';
		YAHOO.util.Event.addListener( input4, 'keyup', function(e) { checkWhole( 'kg', input4, thisId ); updateAvailableDates( thisId, quoteType ); updateStatus( thisId ); } );
		td.appendChild( input4 );
		tr.appendChild( td );
	// create length cell
	var td = document.createElement('TD');
		td.className = 'quoteTableDimension rowStatusError';
		td.setAttribute( 'id', 'row_section_' + thisId + '_' + parcelNumber + '_length' );
	var input1 = document.createElement('INPUT');
		input1.setAttribute( 'type', 'text' );
		input1.setAttribute( 'name', 'cmsServicesShipping[packages][' + thisId + '][' + parcelNumber + '][length]' );
		input1.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_' + parcelNumber + '_length' );
		input1.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.length : '' ) );
		input1.className = 'formInput dimensionInput';
		YAHOO.util.Event.addListener( input1, 'keyup', function(e) { checkWhole( 'cm', input1, thisId ); updateStatus( thisId ); } );
		td.appendChild( input1 );
		tr.appendChild( td );
	// create width cell
	var td = document.createElement('TD');
		td.className = 'quoteTableDimension rowStatusError';
		td.setAttribute( 'id', 'row_section_' + thisId + '_' + parcelNumber + '_width' );
	var input2 = document.createElement('INPUT');
		input2.setAttribute( 'type', 'text' );
		input2.setAttribute( 'name', 'cmsServicesShipping[packages][' + thisId + '][' + parcelNumber + '][width]' );
		input2.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_' + parcelNumber + '_width' );
		input2.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.width : '' ) );
		input2.className = 'formInput dimensionInput';
		YAHOO.util.Event.addListener( input2, 'keyup', function(e) { checkWhole( 'cm', input2, thisId ); updateStatus( thisId ); } );
		td.appendChild( input2 );
		tr.appendChild( td );
	// create height cell
	var td = document.createElement('TD');
		td.className = 'quoteTableDimension rowStatusError';
		td.setAttribute( 'id', 'row_section_' + thisId + '_' + parcelNumber + '_height' );
	var input3 = document.createElement('INPUT');
		input3.setAttribute( 'type', 'text' );
		input3.setAttribute( 'name', 'cmsServicesShipping[packages][' + thisId + '][' + parcelNumber + '][height]' );
		input3.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_' + parcelNumber + '_height' );
		input3.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.height : '' ) );
		input3.className = 'formInput dimensionInput';
		YAHOO.util.Event.addListener( input3, 'keyup', function(e) { checkWhole( 'cm', input3, thisId ); updateStatus( thisId ); } );
		td.appendChild( input3 );
		tr.appendChild( td );
	// create the contents cell
	var td = document.createElement('TD');
		td.className = 'quoteTableContents rowStatusError';
		td.setAttribute( 'id', 'row_section_' + thisId + '_' + parcelNumber + '_description' );
	var input5 = document.createElement('INPUT');
		input5.setAttribute( 'type', 'text' );
		input5.setAttribute( 'name', 'cmsServicesShipping[packages][' + thisId + '][' + parcelNumber + '][description]' );
		input5.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_' + parcelNumber + '_description' );
		input5.setAttribute( 'maxlength', '50' );
		if(quoteType == 'document') {
			input5.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.description : 'Documents' ) );
		}
		else {
			input5.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.description : defaultContentsText ) );
		}
		input5.className = 'formInput contentsInput' + ( ( typeof parcelDetails == 'undefined' ) ? ' contentsInputDefault' : '' );
		YAHOO.util.Event.addListener( input5, 'keyup', function(e) { updateStatus( thisId ); } );
		YAHOO.util.Event.addListener( input5, 'blur', function(e) { parcelDescriptionBlur( thisId, parcelNumber ); } );
		YAHOO.util.Event.addListener( input5, 'focus', function(e) { parcelDescriptionFocus( thisId, parcelNumber ); } );
		td.appendChild( input5 );
		tr.appendChild( td );
	// create value cell
	var td = document.createElement('TD');
		td.className = 'quoteTableValue rowStatusError';
		td.setAttribute( 'id', 'row_section_' + thisId + '_' + parcelNumber + '_value' );
	var input6 = document.createElement('INPUT');
		input6.setAttribute( 'type', 'text' );
		input6.setAttribute( 'name', 'cmsServicesShipping[packages][' + thisId + '][' + parcelNumber + '][value]' );
		input6.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_' + parcelNumber + '_value' );
		input6.setAttribute( 'value', ( ( typeof parcelDetails != 'undefined' ) ? parcelDetails.value : '' ) );
		input6.className = 'formInput valueInput';
		YAHOO.util.Event.addListener( input6, 'change', function(e) { updateStatus( thisId ); } );
		td.appendChild( input6 );
		tr.appendChild( td );
	// add the add/remove icons
	var td = document.createElement('TD');
		td.className = 'addRemoveParcelIcon';
	var img = document.createElement('IMG');
		lastRemoveParcelIconId = 'removeParcelIcon_' + thisId + '_' + parcelNumber;
		img.setAttribute( 'id', lastRemoveParcelIconId );
		img.setAttribute( 'src', '/custom/images/removeparcel.gif' );
		//img.setAttribute( 'title', 'Remove this parcel' );
		img.className = 'removeParcelIcon';
		YAHOO.util.Event.addListener( img, 'click', function() { removeParcelFromShipment( tr, thisId ) } );
		td.appendChild( img );
		tr.appendChild( td );
	tbody.appendChild( tr );
	
	// add tooltip to remove parcel icon
	// (note this is done here and in addQuoteRow because when the first package is added to a shipment (in addQuoteRow), 
	// the image hasn't been applied to the page yet and so the tooltip does not get rendered )
	// REMOVED AT WPS' REQUEST - 27/09/10
	// addToolTipToElement( '#' + lastRemoveParcelIconId, parcelTooltipContent );
	
	return table;
}

function getNextRowId() {
	var max = 0;
	for ( var i in shipmentDetails ) {
		if ( i > max ) {
			max = i;
		}
	}
	return parseInt( max ) + 1;
}

function updateAvailableDates( rowId, quoteType ) {
	var table = document.getElementById( 'cmsServicesShipping_parcelDimensions_' + rowId ).getElementsByTagName('TABLE')[0];
	try {
		// this may not yet be set...
		var countryTo = shipmentDetails[ rowId ].to.country;
	} catch( e ) {
		// ... so default to GB
		var countryTo = 'GB';
	}
	var rows = table.getElementsByTagName('TR');
	var ret = true;
	var thisType = '';
	var inputId = '';
	var thisRowId = '';
	var weight = 0;
	var secondElement = 0;
	var removedDates = 0;
	
	// reset all dates for selection
	allowedDates = new Array();
	for ( var d in allowedDatesOriginal ) {
		allowedDates[ d ] = true;
	}
	
	if(shipmentDetails[ rowId ].from.country != 'GB') {
		//If it's an import remove the next 3 days
		var dte = new Date();
		var intTodaysDate = Calendar.dateToInt( dte );
		delete allowedDates[ intTodaysDate ];
		intTodaysDate++;
		intNextDate = intTodaysDate;
		while ( removedDates < 2 ) {
			if ( intNextDate in allowedDates  ) {
				delete allowedDates[ intNextDate ];
				removedDates++;
			}
			intNextDate++;
		}
		// if past midday on a friday, make Tuesday unavailable too 
		if ( dte.getDay() == 5 && dte.getHours() >= 12 ) {
			var removedTuesday = false;
			while ( !removedTuesday ) {
				delete allowedDates[ intNextDate ];
				removedTuesday = true;
			}
		}
		document.getElementById( 'cmsServicesShipping_collection_date_' + rowId ).value = '';
		return false;
	}
	
	for ( var r = 0; r < rows.length; r++ ) {
		var inputs = rows[r].getElementsByTagName('INPUT');
		for ( var i = 0; i < inputs.length; i++ ) {
			inputId = inputs[i].id;
			thisTypeSplit = inputId.split('_');
			thisType = thisTypeSplit[ thisTypeSplit.length - 1 ];
			// get the 1_3 part from the current input where the id = cmsServicesShipping_packages_1_3_height
			thisRowId = inputId.replace('cmsServicesShipping_packages_','');
			thisRowId = thisRowId.replace('_' + thisType,'');
			if ( thisType == 'weight' ) {
				weight = inputs[i].value;
				if ( !isNaN( weight ) && ( weight < 70 ) && ( weight > 0 ) ) {
					// this package isn't "heavy"
				} else {
					// this package is "heavy", so disable the current day in the calendar
					var dte = new Date();
					var intTodaysDate = Calendar.dateToInt( dte );
					var removedSecondDate = false;
					delete allowedDates[ intTodaysDate ];
					// if it's is after 5pm, disable the next available date too
					if ( dte.getHours() >= 17 ) {
						intTodaysDate++;
						intNextDate = intTodaysDate;
						while ( !removedSecondDate ) {
							//nextDate = Calendar.intToDate( intNextDate );
							if ( intNextDate in allowedDates  ) {
								delete allowedDates[ intNextDate ];
								removedSecondDate = true;
							}
							intNextDate++;
						}
					}
					document.getElementById( 'cmsServicesShipping_collection_date_' + rowId ).value = '';
					return false;
				}
			}
		}
	}
	
	return false; // all weights are fine
}

function insuranceChanged( rowId ) {
	// update the status of the corresponding value fields
	checkParcelValues( rowId );
	// put the cursor in the next field (weight)
	if ( $('#cmsServicesShipping_packages_' + rowId + '_1_weight').is(':visible') ) {
		document.getElementById('cmsServicesShipping_packages_' + rowId + '_1_weight').focus();
	}
	// set the status of the insurance box to green
	updateSectionStatus( rowId, 'insurance', true );
	// updateStatus
	updateStatus( rowId );
}

function addQuoteRow( quoteType, rowId, collectionDate, parcelDetails, availableServices, insuranceSelected ) {
	// increment the counter
	numberOfParcelRows++;
	// clear the current shipment address information
	resetCollectionAddresses();
	// get the tbody we will append the row to
	var tbody = document.getElementById('quoteRows');
	// get the unique ID for this row
	if ( typeof rowId == 'undefined' ) {
		var thisId = getNextRowId();
	} else {
		var thisId = rowId;
		parcelAdded = true;
	}
	// create new row
	var tr = document.createElement('TR');
		tr.className = 'quoteTableShipmentRow';
		tr.setAttribute( 'id', 'quoteRow_' + thisId );
	// first blank cell
	var td = document.createElement('TD');
		td.className = 'quoteTableLeftCell';
	var space = document.createTextNode(' ');
		td.appendChild( space );
		tr.appendChild( td );
	// add the insurance options
	var td = document.createElement('TD');
		td.setAttribute( 'id', 'row_section_' + thisId + '_insurance' );
		td.className = 'quoteTableInsuranceCell'
	var insuranceSelect = document.createElement('SELECT');
		insuranceSelect.setAttribute( 'name', 'cmsServicesShipping[insurance][' + thisId + ']' );
		insuranceSelect.setAttribute( 'id', 'cmsServicesShipping_insurance_' + thisId );
		insuranceSelect.className = 'formInput insuranceInput';
		insuranceSelect = addInsuranceOptionsToSelect( insuranceSelect );
		if ( typeof insuranceSelected != 'undefined' ) {
			var insuranceValues = { '' : 1, '50' : 1, '100' : 2, '250' : 3, '500' : 4, '750' : 5, '1000' : 6 };
			insuranceSelect.selectedIndex = insuranceValues[ insuranceSelected ];
		} else {
			insuranceSelect.selectedIndex = 1;
		}
		if(quoteType == 'document') {
			insuranceSelect.setAttribute( 'disabled', 'disabled' );
		}
		YAHOO.util.Event.addListener( insuranceSelect, 'change', function() {
			insuranceChanged( thisId );
		} );
		
		td.appendChild( insuranceSelect );
		
	var insuranceHidden = document.createElement('INPUT');
		insuranceHidden.setAttribute( 'type', 'hidden' );
		insuranceHidden.setAttribute( 'name', 'cmsServicesShipping[insurance][' + thisId + ']' );
		insuranceHidden.setAttribute( 'id', 'cmsServicesShipping_insurance_hidden_' + thisId );
		insuranceHidden.setAttribute( 'value', '50' );
		if(quoteType == 'standard') {
			insuranceHidden.setAttribute( 'disabled', 'disabled' );
		}
		
		td.appendChild( insuranceHidden );
		
	var documentHidden = document.createElement('INPUT');
		documentHidden.setAttribute( 'type', 'hidden' );
		documentHidden.setAttribute( 'name', 'cmsServicesShipping[document][' + thisId + ']' );
		documentHidden.setAttribute( 'id', 'cmsServicesShipping_document_' + thisId );
		if(quoteType == 'document') {
			documentHidden.setAttribute( 'value', '1' );
		}
		else {
			documentHidden.setAttribute( 'value', '' );
		}
		
		td.appendChild( documentHidden );
		tr.appendChild( td );
		
	// add a divider cell
	tr.appendChild( addDividerCell( 'quoteTableFirstDivider' ) );
	// create cell to contain parcel dimensions
	var td = document.createElement('TD');
		td.className = 'quoteTableDimensions';
	var dimensionsDiv = document.createElement('DIV');
		dimensionsDiv.setAttribute( 'id', 'cmsServicesShipping_parcelDimensions_' + thisId );
		td.appendChild( dimensionsDiv );
		tr.appendChild( td );
	// add a divider cell
	tr.appendChild( addDividerCell() );
	// create address button cell
	var td = document.createElement('TD');
		td.setAttribute( 'id', 'row_section_' + thisId + '_addressFrom' );
		td.className = 'quoteTableAddressCell rowStatusError';
	var sendFromButton = document.createElement('INPUT');
		sendFromButton.setAttribute( 'type', 'button' );
		sendFromButton.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_addressBtn_from' );
		sendFromButton.className = 'button sendFromButton';
		sendFromButton.setAttribute( 'value', 'Send from..' );
		YAHOO.util.Event.addListener( sendFromButton, 'click', function(e) {
			setCurrentQuoteRow( thisId );
			changeShippingAddressTab('from');
		} );
		td.appendChild( sendFromButton );
		tr.appendChild( td );
	var td = document.createElement('TD');
		td.setAttribute( 'id', 'row_section_' + thisId + '_addressTo' );
		td.className = 'quoteTableAddressCell rowStatusError';
	var sendToButton = document.createElement('INPUT');
		sendToButton.setAttribute( 'type', 'button' );
		sendToButton.setAttribute( 'id', 'cmsServicesShipping_packages_' + thisId + '_addressBtn_to' );
		sendToButton.className = 'button sendToButton';
		sendToButton.setAttribute( 'value', 'Send to..' );
		YAHOO.util.Event.addListener( sendToButton, 'click', function(e) {
			setCurrentQuoteRow( thisId );
			completeShippingAddresses(false,'from');
		} );
		td.appendChild( sendToButton );
		tr.appendChild( td );
	// add a divider cell
	tr.appendChild( addDividerCell() );
	// add date selector
	var td = document.createElement('TD');
		td.setAttribute( 'id', 'row_section_' + thisId + '_date' );
		td.className = 'quoteTableDateCell rowStatusError';
	var input8 = document.createElement('INPUT');
		input8.setAttribute( 'type', 'hidden' );
		input8.setAttribute( 'name', 'cmsServicesShipping_collection_date_' + thisId );
		input8.setAttribute( 'id', 'cmsServicesShipping_collection_date_' + thisId );
		if ( ( typeof collectionDate == 'string' ) && ( collectionDate.indexOf('/') > 0 ) ) {
			var collectionDateSplit = collectionDate.split('/');
			collectionDate = collectionDateSplit[2] + '' + collectionDateSplit[1] + '' + collectionDateSplit[0];
		}
		input8.setAttribute( 'value', ( ( typeof collectionDate != 'undefined' ) ? Calendar.dateToInt(collectionDate) : '' ) );
		td.appendChild( input8 );
	var input9 = document.createElement('IMG');
		input9.setAttribute( 'src', '/custom/images/iconcalendar.jpg' );
		input9.setAttribute( 'title', 'Select collection date' );
		input9.setAttribute( 'id', 'cmsServicesShipping_collection_date_icon_' + thisId );
		td.appendChild( input9 );
		tr.appendChild( td );
	// add a divider cell
	tr.appendChild( addDividerCell() );
	// add the service select
	var td = document.createElement('TD');
		td.setAttribute( 'id', 'row_section_' + thisId + '_services' );
		td.className = 'quoteTableServicesCell rowStatusError';
	var select = document.createElement('SELECT');
		select.setAttribute( 'name', 'cmsServicesShipping[services][' + thisId + ']' );
		select.setAttribute( 'id', 'cmsServicesShipping_service_' + thisId );
		select.className = 'formInput serviceInput';
		var selectedServiceIndex = 0;
		if ( typeof availableServices != 'undefined' ) {
			// we have a list of services to add to the drop down
			var opt = new Option( selectServiceOptionText, '' );
			addOptionToSelect( select, opt );
			for ( var a in availableServices ) {
				opt = new Option( availableServices[a].name + ' - £' + parseFloat( availableServices[a].price ).toFixed(2), a );
				addOptionToSelect( select, opt );
				if ( availableServices[a].selected ) {
					selectedServiceIndex = parseInt( a ) + 1;
				}
			}
		} else {
			// no services so just add the default option
			var opt = new Option( defaultRowStatus, '' );
			addOptionToSelect( select, opt );
			// and disable the select (for now)
			select.setAttribute( 'disabled', 'disabled' );
		}
		select.selectedIndex = selectedServiceIndex;

		// christmas warning popup
		/*
		$(select).change( function() {
			var serviceName = $( 'option:selected', this ).text().toLowerCase();
			if ( ( serviceName.indexOf('dpd') > -1 ) || ( serviceName.indexOf('wps european road') > -1 ) ) {
				alert( snowWarningMessage );
			}
		} );
		*/
		
		YAHOO.util.Event.addListener( select, 'change', function(e) {
			updateSectionStatus( thisId, 'services', (this.selectedIndex == 0 ) ? false : true );
		} );
		
		td.appendChild( select );
		tr.appendChild( td );
	// add the info cell
	var td = document.createElement('TD');
		td.className = 'quoteTableInfoCell';
	var img = document.createElement('IMG');
		img.setAttribute( 'id', 'infoIcon_' + thisId );
		img.setAttribute( 'src', '/custom/images/infoicon.gif' );
		img.setAttribute( 'title', 'Surcharge information will appear here when a quote is returned' );
		td.appendChild( img );
		tr.appendChild( td );
	// add the remove shipment icon
	var td = document.createElement('TD');
		td.className = 'quoteTableAddShipmentCell';
	var img = document.createElement('IMG');
		img.setAttribute( 'id', 'removeShipmentIcon_' + thisId );
		img.setAttribute( 'src', '/custom/images/' + baseFolder + 'removeshipment.gif' );
		img.className = 'removeShipmentIcon';
		YAHOO.util.Event.addListener( img, 'click', function() { removeQuoteRow( thisId ) } );
		td.appendChild( img );
		tr.appendChild( td );
	// last blank cell
	var td = document.createElement('TD');
		td.className = 'quoteTableRightCell';
	var space = document.createTextNode(' ');
		td.appendChild( space );
		tr.appendChild( td );
	// append the new row
	tbody.appendChild( tr );
	
	if ( typeof availableServices != 'undefined' ) {
		// add any surcharge information
		var infoHTML = '';
		for ( var a in availableServices ) {
			if ( ( typeof availableServices[a].surcharges != 'undefined' ) && ( availableServices[a].surcharges.length > 0 ) ) {
				infoHTML += getFormattedSurchargeInfo( availableServices[a].surcharges, availableServices[a].name );
			}
		}
		addToSurchargeInfo( thisId, infoHTML );
	} else {
		addToolTipToElement( '#infoIcon_' + thisId );
	}
	
	if ( typeof parcelDetails != 'undefined' ) {
		for ( var p in parcelDetails ) {
			var dimensions = addParcelToShipment( quoteType, thisId, parcelDetails[p] );
			dimensionsDiv.appendChild( dimensions );
		}
	} else {
		var dimensions = addParcelToShipment( quoteType, thisId );
		dimensionsDiv.appendChild( dimensions );
	}
	
	// add tooltip to remove parcel icon
	// REMOVED AT WPS' REQUEST - 27/09/10
	// addToolTipToElement( '#' + lastRemoveParcelIconId, parcelTooltipContent );
		
	// create the calendar
	var cal = Calendar.setup({
		inputField	: input8.getAttribute('id'),
		dateFormat	: "%Y%m%d",
		trigger		: input9.getAttribute('id'),
        disabled	: checkDisabledDates,
        bottomBar	: false,
		selection	: ( ( typeof collectionDate != 'undefined' ) ? [ collectionDate ] : '' ),
		onOpen		: function() {
			if ( !validateShippingAddressTo( thisId, true ) ) {
				alert( 'Please enter the address to which your shipment is going before selecting a date.' );
				this.doOpen = false;
			} else {
				// see if we need to disable any delivery dates based on the parcel weights and the time of day
				if ( !updateAvailableDates( thisId, quoteType ) ) {
					this.selection.clear();
				}
				this.redraw();
				this.doOpen = true;
			}
		},
		dateInfo	: function() {
			return {
        		tooltip		: 'Select <strong>%d/%m/%Y</strong> as the <strong>collection</strong> date for this shipment'
			}
		},
		onSelect	: function() {
			if ( this.selection.get() != this.previousSelection ) {
				// if the date has changed, check the status
				// the 'onSelect' event gets fired on click of the trigger, so we don't
				// want to start searching for services then.
				updateStatus( thisId );
				this.previousSelection = this.selection.get();
				input9.title = Calendar.printDate( Calendar.intToDate( this.selection.get() ), '%d/%m/%Y' );
			}
			this.hide();
		},
		align		: 'Br'
	});
	cal.previousSelection = '';
	$('#' + input9.id ).bind( 'openCalendar', function() {
		// hack in the popup call so we can open it once an address has been entered
		cal.doOnClick(cal.args.trigger, cal.args.inputField, cal.args.dateFormat);
	});
	
	// create a new element in our shipment details array
	if ( typeof shipmentDetails[ thisId ] == 'undefined' ) {
		shipmentDetails[ thisId ] = new Object();
	}
	
	// add the "add another parcel" row
	tr = document.createElement('TR');
	tr.className = 'quoteTableAddParcelRow';
	tr.setAttribute( 'id', 'quoteRowAdd_' + thisId );
	// first blank cell
	var td = document.createElement('TD');
		td.className = 'quoteTableAddEndCell';
	var space = document.createTextNode(' ');
		td.appendChild( space );
		tr.appendChild( td );
	// add parcel stuff
	var td = document.createElement('TD');
		td.colSpan = 3;
	var addPackageDiv = document.createElement('DIV');
		addPackageDiv.className = 'addParcelLink';
		addPackageDiv.setAttribute( 'id', 'addParcelIcon_' + thisId );
	var addPackageText = document.createTextNode('Add another parcel to this shipment');
		addPackageDiv.appendChild( addPackageText );
	td.appendChild( addPackageDiv );
	tr.appendChild( td );
	YAHOO.util.Event.addListener( addPackageDiv, 'click', function() { addParcelToShipment( quoteType, thisId ) } );
	// first blank cell
	var td = document.createElement('TD');
		td.colSpan = 9;
		td.className = 'blank';
	var space = document.createTextNode(' ');
		td.appendChild( space );
		tr.appendChild( td );
	// append the new row
	tbody.appendChild( tr );
	
	// add the tool tip for the "add a parcel" icon
	// REMOVED AT WPS' REQUEST - 27/09/10
	//addToolTipToElement( '#addParcelIcon_' + thisId, parcelTooltipContent );
	// add the tool tip for the "remove shipment" icon
	//addToolTipToElement( '#removeShipmentIcon_' + thisId, shipmentTooltipContent );
	
	// update the status of this row
	insuranceChanged( thisId );
}

function getInsurancePriceFromAmount( amount ) {
	switch ( amount ) {
		case '100':
			return 5;
		case '250':
			return 7.5;
		case '500':
			return 12.5;
		case '750':
			return 16;
		case '1000':
			return 20;
		case '50':
		default:
			return 0;
	}
}

function addInsuranceOptionsToSelect( select ) {
	var opt = new Option( '- Select Additional Cover -', '' );
	addOptionToSelect( select, opt );
	var opt = new Option( 'Upto £50 cover (Included)', '50' );
	addOptionToSelect( select, opt );
	var opt = new Option( 'Upto £100 cover (£' + getInsurancePriceFromAmount( '100' ).toFixed(2) + ')', '100' );
	addOptionToSelect( select, opt );
	var opt = new Option( 'Upto £250 cover (£' + getInsurancePriceFromAmount( '250' ).toFixed(2) + ')', '250' );
	addOptionToSelect( select, opt );
	var opt = new Option( 'Upto £500 cover (£' + getInsurancePriceFromAmount( '500' ).toFixed(2) + ')', '500' );
	addOptionToSelect( select, opt );
	var opt = new Option( 'Upto £750 cover (£' + getInsurancePriceFromAmount( '750' ).toFixed(2) + ')', '750' );
	addOptionToSelect( select, opt );
	var opt = new Option( 'Upto £1,000 cover (£' + getInsurancePriceFromAmount( '1000' ).toFixed(2) + ')', '1000' );
	addOptionToSelect( select, opt );
	return select;
}

function addToolTipToElement( element, content ) {
	var config = {
		position: {
			target: 'mouse',
			adjust : {
				screen: true
			}
		},
		adjust : {
			mouse: true
		},
		show : {
			solo: true
		}
	};
	
	if ( typeof content != 'undefined' ) {
		config.content = content
	}

	$( element ).qtip( config );
}

function addDividerCell( tdClass ) {
	var td = document.createElement('TD');
		td.className = 'quoteTableDivider' + ( ( typeof tdClass != 'undefined' ) ? ' ' + tdClass : '' );
	var newTxt = document.createTextNode(' ');
	td.appendChild( newTxt );
	return td;
}

function setCurrentQuoteRow( rowId ) {
	currentQuoteRowId = rowId;
	populateCollectionAddresses( currentQuoteRowId, false );
}

function changeShippingAddressTab( dir ) {
	// hide both tab contents
	document.getElementById('shippingAddressTabContent_to').style.display = 'none';
	document.getElementById('shippingAddressTabContent_from').style.display = 'none';
	// limit options if showing to box and from country outside UK
	if(dir == 'to') {
		if( shipmentDetails[ currentQuoteRowId ].from.country == 'GB' || shipmentDetails[ currentQuoteRowId ].from.country == 'IE' ) {
			$('#cmsServicesShipping_shipTo_country_uk').attr('disabled','disabled');
			$('#cmsServicesShipping_shipTo_country_uk').hide();
			$('#cmsServicesShipping_shipTo_country').removeAttr('disabled');
			$('#cmsServicesShipping_shipTo_country').show();
		}
		else {
			document.getElementById( 'cmsServicesShipping_shipTo_country' ).selectedIndex = 1;
			$('#cmsServicesShipping_shipTo_country').attr('disabled','disabled');
			$('#cmsServicesShipping_shipTo_country').hide();
			$('#cmsServicesShipping_shipTo_country_uk').removeAttr('disabled');
			$('#cmsServicesShipping_shipTo_country_uk').show();
		}
	}
	// show the correct tab content
	document.getElementById('shippingAddressTabContent_' + dir).style.display = '';
	showShippingAddressPopup( document.getElementById( 'cmsServicesShipping_packages_' + currentQuoteRowId + '_addressBtn_' + dir ), dir );
}

function loadFromAddress() {
	loadAddresses( 'From' );
	$('#addressListContainer_From').show();
}

function loadToAddress() {
	loadAddresses( 'To' );
	$('#addressListContainer_To').show();
}

function loadAddresses( direction ) {
	var postcode = document.getElementById('cmsServicesShipping_ship' + direction + '_postcode').value;
	GetAddressList( direction, postcode );
}

function updatePrebookStatus( status, id, message ) {
	var html = '<div class="prebookStatusTitle">';
	var cssClass = 'prebookRow';
	switch ( status ) {
		case 'pending':
			html += 'Processing';
			cssClass += ' statusPending';
			break;
		case 'confirmed':
			html += 'Completed';
			cssClass += ' statusConfirmed';
			break;
		case 'error':
			html += 'Error';
			cssClass += ' statusError';
			break;
	}
	html += '</div>';
	if ( typeof message != 'undefined' ) {
		document.getElementById('prebook_message_' + id).innerHTML = message;
		document.getElementById('prebook_message_' + id).style.display = 'block';
	}
	document.getElementById('prebook_status_' + id).innerHTML = html;
	document.getElementById('prebook_row_' + id).className = cssClass;
}

function getQuoteRowId( index ) {
	var count = 0;
	for ( var i in shipmentDetails ) {
		if ( count == index ) {
			return i;
		}
		count++;
	}
	return false;
}

function doPrebookShipment( thisId ) {
	var id = getQuoteRowId( thisId );
	if ( id !== false ) {
		populateCollectionAddresses( id, true );
		var handleSuccess = function(o) {
			eval( 'var returned = ' + o.responseText );
			if ( typeof returned['errors'] != 'undefined' ) {
				// error occured, inform the user
				eval( 'var errors = ' + o.responseText );
				msg = '';
				var i = 1;
				for ( var e in errors ) {
					msg += i + " - " + errors[e] + '<br />';
					i++;
				}
				updatePrebookStatus( 'error', id, msg );
				// update our flag
				prebookErrorOccured = true;
			} else if ( ( typeof returned['status'] != 'undefined' ) && ( returned['status'] == 'confirmed' ) ) {
				// success!
				updatePrebookStatus( 'confirmed', id );
			} else {
				// errr, hopefully it will never get here...
				var msg = '1 - Unspecified error.  Please try again.';
				updatePrebookStatus( 'error', id, msg );
				// update our flag
				prebookErrorOccured = true;
			}
			// attempt the next shipment
			doPrebookShipment( thisId + 1 );
		};
		var handleFailure = function(o) {
			if ( o.responseText != '' ) {
				eval( 'var returned = ' + o.responseText );
				if ( typeof returned['errors'] != 'undefined' ) {
					// error occured, inform the user
					var msg = '';
					var i = 1;
					for ( var e in errors ) {
						msg += i + " - " + errors[e] + '<br />';
						i++;
					}
				} else {
					// errr, hopefully it will never get here either...
					var msg = '1 - Unspecified error.  Please try again.';
				}
			} else {
				// errr, hopefully it will never get here either...
				var msg = '1 - Unspecified error.  Please try again.';
			}
			// update status of this shipment
			updatePrebookStatus( 'error', id, msg );
			// update our flag
			prebookErrorOccured = true;
			// attempt the next shipment
			doPrebookShipment( thisId + 1 );
		};
		var callback = {
			success:handleSuccess,
			failure:handleFailure
		};
		makeAjaxShipmentRequest( id, 'service=customService&customService=prebookShipments&quoteId=' + id, callback );
	} else {
		// no more shipments to process
		if ( prebookErrorOccured ) {
			document.getElementById('prebookButtonAmend').style.display = '';
		} else {
			setTimeout( 'prebookShipmentsComplete()', 1000 );
		}
	}
}

function prebookShipmentsComplete() {
	// see if the customer has selected additional insurance
	var insuranceInputs = YAHOO.util.Dom.getElementsByClassName('insuranceInput');
	hasAdditionalInsurance = false;
	for ( var s = 0; s < insuranceInputs.length; s++ ) {
		if ( insuranceInputs[s].selectedIndex > 1 ) {
			hasAdditionalInsurance = true;
		}
	}
	if ( ( !hasAdditionalInsurance ) || ( hasAdditionalInsurance && confirm( 'Shipments Confirmed!' + "\n\n" + 'As you have purchased additional cover you MUST NOT tick the insurance box on the waybill as your cover is provided through ' + companyName + ' not the carrier. Failure to comply with this will invalidate your claim.' + "\n\n" + 'Click "OK" to agree and proceed to the checkout.') ) ) {
		document.getElementById('prebookCheckoutMessage').style.display = '';
		document.location = '/checkout';
	} else {
		hidePrebookPopup();
	}
}

function getServiceImageByName( name ) {
	var nameSplit = name.split('-');
	var serviceName = trim( nameSplit[0] );
	var src = '/custom/images/services/';
	switch ( serviceName ) {
		case 'WPS 24 (DHL)':
			src += '24-small.png';
			break;
		case 'WPS 24 (DPD)':
			src += '24dpd-small.png';
			break;
		case 'WPS Diamond':
			src += 'diamond-small.png';
			break;
		case 'WPS European Road (DPD)':
			src += 'europeanexpress-small.png';
			break;
		case 'WPS European Road (DHL)':
			src += 'europeanexpressdhl-small.png';
			break;
		case 'WPS Worldwide Express':
			src += 'worldwideexpress-small.png';
			break;
		case 'WPS European Express (TNT)':
			src += 'europeanexpresstnt-small.png';
			break;
		case 'WPS European Economy Express (TNT)':
			src += 'europeaneconomytnt-small.png';
			break;
		case 'WPS Worldwide Express (TNT)':
			src += 'worldwideexpresstnt-small.png';
			break;
		case 'WPS Worldwide Economy Express (TNT)':
			src += 'worldwideeconomytnt-small.png';
			break;
		case 'WPS Worldwide Document Express (TNT)':
			src += 'worldwideexpresstnt-small.png';
			break;
		case 'WPS Worldwide Express Import (TNT)':
			src += 'worldwideexpresstnt-small.png';
			break;
		case 'WPS Worldwide Economy Express Import (TNT)':
			src += 'worldwideeconomytnt-small.png';
			break;
		case 'WPS Worldwide Express Import (DHL)':
			src += 'worldwideexpress-small.png';
			break;
		case 'WPS European Road Import (DHL)':
			src += 'europeanexpressdhl-small.png';
			break;
		case 'WPS Express Saver':
			src += 'wpsexpresssaver-small.png';
			break;
		case 'WPS Standard Euro':
			src += 'wpsstandardeuro-small.png';
			break;
		case 'WPS Air Express (TPN)':
		case 'WPS Air Express':
			src += 'wpsairexpress-small.png';
			break;
		case 'WPS Euro Economy (TPN)':
		case 'WPS Euro Economy':
			src += 'wpseuroeconomy-small.png';
			break;
	}
	return src;
}

function prebookShipments() {
	// make sure all services have been selected
	var serviceInputs = YAHOO.util.Dom.getElementsByClassName('serviceInput');
	prebookErrorOccured = false;
	for ( var s = 0; s < serviceInputs.length; s++ ) {
		if ( serviceInputs[s].selectedIndex == 0 ) {
			showQuoteTable();
			alert('Please select all required services.  If a shipment is not required, please remove it by clicking the "Remove Shipment" icon on the right-hand side of the corresponding row.');
			return false;
		}
	}
	// hide the amend button
	document.getElementById('prebookButtonAmend').style.display = 'none';
	document.getElementById('prebookCheckoutMessage').style.display = 'none';
	// get the container we will append all rows to and clear it out
	var container = document.getElementById('prebookContainer');
	container.innerHTML = '';
	// loop through all services creating a placeholder for the various elements
	for ( var i = 0; i <= numberOfParcelRows; i++ ) {
		var id = getQuoteRowId( i );
		var slct = document.getElementById('cmsServicesShipping_service_' + id);
		var serviceName = slct.options[ slct.selectedIndex ].text;
		var rowDiv = document.createElement('DIV');
			rowDiv.className = 'prebookRow';
			rowDiv.setAttribute( 'id', 'prebook_row_' + id );
		var imgDiv = document.createElement('DIV');
			imgDiv.className = 'prebookImage';
			var imgIcon = document.createElement('IMG');
			imgIcon.src = getServiceImageByName( serviceName );
			imgDiv.appendChild( imgIcon );
		var titleDiv = document.createElement('DIV');
			titleDiv.className = 'prebookTitle';
			var slct = document.getElementById('cmsServicesShipping_service_' + id);
			titleDiv.innerHTML = serviceName;
		var statusDiv = document.createElement('DIV');
			statusDiv.className = 'prebookStatus';
			statusDiv.setAttribute( 'id', 'prebook_status_' + id );
		var msgDiv = document.createElement('DIV');
			msgDiv.setAttribute( 'id', 'prebook_message_' + id );
			msgDiv.className = 'prebookMessage';
		var clearerDiv = document.createElement('DIV');
			clearerDiv.className = 'clearer';
		rowDiv.appendChild( imgDiv );
		rowDiv.appendChild( titleDiv );
		rowDiv.appendChild( statusDiv );
		rowDiv.appendChild( msgDiv );
		rowDiv.appendChild( clearerDiv );
		container.appendChild( rowDiv );
		updatePrebookStatus( 'pending', id );
	}
	// show the panel
	showPrebookPopup();
	// kick off the actual request to confirm the shipments (without actually booking them)
	doPrebookShipment(0);		
	// don't submit the form
	return false;
}


function initShippingAddressPopup() {
	//document.getElementById('shippingAddressPopup').style.display = '';
	addressBox = new YAHOO.widget.Panel("shippingAddressPopup",  
											{
											  width:"367px", 
											  height:"413px", 
											  fixedcenter:false, 
											  close:false, 
											  draggable:false, 
											  modal:false,
											  visible:false,
											  underlay:"none",
											  zIndex: 6,
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	addressBox.render(document.body);
	if ( showShippingAddressPopupOnLoad ) {
		doShowShippingAddressPopup(showShippingAddressDirection);
	}
}

function scrollToQuoteTable() {
	window.scrollTo(0,0);
}

function doShowShippingAddressPopup(dir) {
	document.getElementById('shippingAddressPopup').style.display = '';
	// reset the postcode "results" drop-down
	var shipToResults = document.getElementById('epcAddressList_ShipTo');
	var shipFromResults = document.getElementById('epcAddressList_ShipFrom');
	removeAllOptions( shipToResults );
	removeAllOptions( shipFromResults );
	var opt1 = new Option( 'Enter postcode above...', '' );
	var opt2 = new Option( 'Enter postcode above...', '' );
	addOptionToSelect( shipToResults, opt1 );
	addOptionToSelect( shipFromResults, opt2 );
	shipToResults.disabled = true;
	shipFromResults.disabled = true;
	// validate the addresses
	validateShippingAddress('From');
	validateShippingAddress('To');
	if(dir == 'from') {
		addressBox.cfg.setProperty( 'context', [ currentQuoteRowButton, 'tr', 'tr' ] );
		$('#shippingAddressPopupTop').css('background','url("/custom/images/addresspaneltop-reversed.png") no-repeat scroll left top transparent');
		$('#shippingAddressClose').attr('class','shippingAddressCloseLeft');
	} else {
		addressBox.cfg.setProperty( 'context', [ currentQuoteRowButton, 'tl', 'tl' ] );
		$('#shippingAddressPopupTop').css('background','url("/custom/images/addresspaneltop.png") no-repeat scroll left top transparent');
		$('#shippingAddressClose').attr('class','shippingAddressCloseRight');
	}
	addressBox.show();
}

function showShippingAddressPopup( el, dir ) {
	currentQuoteRowButton = el;
	if ( typeof addressBox != "undefined" ) {
		doShowShippingAddressPopup(dir);
	} else {
		showShippingAddressPopupOnLoad = true;
		showShippingAddressDirection = dir;
	}
}

function hideShippingAddressPopup() {
	if( typeof addressBox != "undefined" ) {
		addressBox.hide();
	}
}

function checkShipFromPostcode( countryCode ) {
	if ( countryCode == 'GB' ) {
		document.getElementById('shipFrom_findAddressBtn').style.display = '';
		document.getElementById('addressListContainer_From').style.display = '';
		$('#shipFrom_address_fields').hide();
	} else {
		document.getElementById('shipFrom_findAddressBtn').style.display = 'none';
		document.getElementById('addressListContainer_From').style.display = 'none';
		$('#shipFrom_address_fields').show();
	}
}

function checkShipToPostcode( countryCode, hideFields ) {
	if ( countryCode == 'GB' ) {
		document.getElementById('shipTo_findAddressBtn').style.display = '';
		document.getElementById('addressListContainer_To').style.display = '';
		if(hideFields) {
			$('#shipTo_address_fields').hide();
		}
	} else {
		document.getElementById('shipTo_findAddressBtn').style.display = 'none';
		document.getElementById('addressListContainer_To').style.display = 'none';
		$('#shipTo_address_fields').show();
	}
}

function showAddress( dir ) {
	$('#ship'+dir+'_address_fields').show();
}

function checkForCountryNotes( countryCode ) {
	var notes = '';
	switch ( countryCode ) {
		case 'GB':
			notes = 'For bookings to the channel islands, please select Jersey or Guernsey from the list.';
			break;
		case 'ES':
			notes = 'Does not include Canary Islands, please select Canary Islands from the list for quote. Any bookings made for the Canary Islands as Spain will incur additional costs.';
			break;
		case 'PT':
			notes = 'For bookings to <strong>Madeira</strong>, please email details to <a href="mailto:info@' + domain + '">info@' + domain + '</a> and we\'ll reply with a quote as soon as possible. For <strong>Azores</strong>, please select Azores from this list. Any bookings made for <strong>Madeira</strong> or <strong>Azores</strong> as Portugal will result in additional charges.';
			break;
	}
	if ( notes != '' ) {
		notes = '<span id="notesNote">Note:</span> ' + notes;
	}
	$('#shipToNotes').html( notes );
}

function changeCountry( countryCode, countryPrefix, direction ) {
	// display any notes for this country
	if(direction == 'shipTo') {
		checkForCountryNotes( countryCode );
	}
	// hide or show the asterix for the ship-to postcode
	if ( postcodesRequired[ countryCode ] ) {
		$('#cmsServicesShipping_'+direction+'_postcode').val( '- Postcode*' );
	} else {
		$('#cmsServicesShipping_'+direction+'_postcode').val( '- Postcode' );
	}
	if ( countryCode == 'RU' ) {
		alert( 'For shipments to Russia please email details to sales@' + domain + ' and we\'ll reply with a quote as soon as possible. Most other countries can be booked online.' );
		if(direction == 'shipTo') {
			manuallyChangeShipToCountry( 'GB', countryPrefix );
		}
		else {
			manuallyChangeShipFromCountry( 'GB', countryPrefix );
		}
	} else {
		if(direction == 'shipTo') {
			shipToCountry = countryCode;
		}
		else {
			shipFromCountry = countryCode;
		}
		if ( countryPrefix != 'qq' ) {
			document.getElementById( 'cmsServicesShipping_'+direction+'_state' ).selectedIndex = 0;
			document.getElementById( 'cmsServicesShipping_'+direction+'_state_other' ).value = '';
			if ( ( countryCode == 'EI' ) || ( countryCode == 'CA' ) || ( countryCode == 'US' ) || ( countryCode == 'NY' ) ) {
				// state is required, so display it
				// hide/show the relevant options
				updateStates( countryCode, direction );
				document.getElementById( direction+'StateContainer' ).style.display = '';
			} else {
				// state not required, hide it
				document.getElementById( direction+'StateContainer' ).style.display = 'none';
			}
		} else {
			var selectBox = document.getElementById( 'qq_'+direction+'_country' );
			var countrySelected = selectBox.options[ selectBox.selectedIndex ].text;
			document.getElementById( 'qq_'+direction+'_country_long' ).value = countrySelected;
			if ( selectBox.value == 'IE' ) {
				document.getElementById('qq_'+direction+'_postcode').value = 'BT 1';
			} else if ( trim( countrySelected ) == '- Highlands and Islands' ) {
				document.getElementById('qq_'+direction+'_postcode').value = 'HS 1';
			} else {
				document.getElementById('qq_'+direction+'_postcode').value = 'M 1';
			}
		}
	}
}

function updateStates( countryCode, direction ) {
	var stateCountry = ( countryCode == 'NY' ) ? 'US' : countryCode;
	$('#cmsServicesShipping_'+direction+'_state>option').not( '.' + stateCountry ).wrap( '<span>' ).hide();
	$('#cmsServicesShipping_'+direction+'_state span option.' + stateCountry ).unwrap().show();
	$('#cmsServicesShipping_'+direction+'_state span option.xx' ).unwrap().show();
	$('#cmsServicesShipping_'+direction+'_state' ).selectedIndex = 0;
	if ( countryCode == 'NY' ) {
		document.getElementById('cmsServicesShipping_'+direction+'_state').value = 'NY';
	}
}

function changeState( val, addressType ) {
	document.getElementById( 'ship'+addressType+'StateOtherContainer' ).style.display = ( val == 'other' ) ? '' : 'none';
}

function changeResidential( val, section ) {
	var p = document.getElementById( section + '_company_section' );
	if ( val == 1 ) {
		p.style.display = 'none';
	} else {
		p.style.display = '';
	}
}


function checkPostcode( postcode, addressType ) {
	first2Characters = postcode.substr(0,2);
	if ( addressType == 'shipTo' && shipToCountry == 'NY' ) {
		// ensure New York is selected as the state
		document.getElementById('cmsServicesShipping_'+addressType+'_state').value = 'NY';
	} else
	if ( ( addressType == 'shipTo' && shipToCountry == 'US' ) || ( addressType == 'shipFrom' && shipFromCountry == 'US' ) ) {
		if ( isNaN( first2Characters ) ) {
			// they've entered a postcode like FL30091
			document.getElementById('cmsServicesShipping_'+addressType+'_state').value = first2Characters;
			if ( document.getElementById('cmsServicesShipping_'+addressType+'_state').selectedIndex > 0 ) {
				postcode = trim(postcode.substr(2,(postcode.length - 2)));
				document.getElementById('cmsServicesShipping_'+addressType+'_postcode').value = postcode;
				alert( 'Please only enter the numeric part of a US zip code.  The state has been automatically selected for you.' );
			} else {
				document.getElementById('cmsServicesShipping_'+addressType+'_state').selectedIndex = 0;
			}
		}
	} else
	if ( addressType == 'shipTo' && document.getElementById('cmsServicesShipping_shipTo_country').value == 'ES' ) {
		if ( ( first2Characters == '35' ) || ( first2Characters == '38' ) ) {
			// the user has selected spain as the country and entered a postcode beginning 35 or 35
			// which is actually the Canary Islands, so let them know
			manuallyChangeShipToCountry( 'IC', 'cmsServicesShipping' );
			alert( 'The postcode you have entered is associated with the Canary Islands, so we have selected the Canary Islands automatically for you.' );
		}
	}
}


function initPrebookPopup() {
	document.getElementById('prebookPopup').style.display = '';
	prebookBox = new YAHOO.widget.Panel("prebookPopup",  
											{
											  width:"560px", 
											  height:"296px", 
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  zIndex: 7,
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	prebookBox.render(document.body);
}

function showPrebookPopup() {
	if( typeof prebookBox != "undefined" ) {
		prebookBox.show();
	}
}

function hidePrebookPopup() {
	if( typeof prebookBox != "undefined" ) {
		prebookBox.hide();
	}
}

function initQuoteTable() {
	initShippingAddressPopup();
	initPrebookPopup();
	// REMOVED AT WPS' REQUEST - 27/09/10
	// addToolTipToElement( '#addShipmentIcon', shipmentTooltipContent );
}

function selectPreviousFromAddress( addressId ) {
	var address = previousFromAddresses[0][addressId];
	populateCollectionAddress( 'From', address, false );
	$('#shipFrom_address_fields').show();
}

function selectPreviousToAddress( addressId ) {
	var address = previousToAddresses[0][addressId];
	populateCollectionAddress( 'To', address, false );
	$('#shipTo_address_fields').show();
}


function initOverValuePopup() {
	document.getElementById('overValuePopup').style.display = '';
	overValueBox = new YAHOO.widget.Panel("overValuePopup",  
			{
			  width:"282px",
			  height:"196px",
			  fixedcenter:true, 
			  close:false, 
			  draggable:false, 
			  modal:true,
			  visible:false,
			  underlay:"none",
			  zIndex: 7,
			  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
			}
		);

	overValueBox.render(document.body);
}

function hideOverValuePopup() {
	if( typeof overValueBox != "undefined" )
		overValueBox.hide();
}

function showOverValuePopup() {
	if( typeof overValueBox != "undefined" ) {
		overValueBox.show();
	}
}

function shipToPostcodeFocus( el ) {
	var countryCode = document.getElementById( 'cmsServicesShipping_shipTo_country' ).value;
	if ( postcodesRequired[ countryCode ] ) {
		var str = '- Postcode*';
	} else {
		var str = '- Postcode';
	}
	inputBoxFocus( el, str );
}

function shipToPostcodeBlur( el ) {
	var countryCode = document.getElementById( 'cmsServicesShipping_shipTo_country' ).value;
	if ( postcodesRequired[ countryCode ] ) {
		var str = '- Postcode*';
	} else {
		var str = '- Postcode';
	}
	inputBoxBlur( el, str );
}

function showReturnButton() {
	$('#quickQuoteSmallBannerImport').hide();
	$('#quickQuoteSmallBannerContinue').show();
}

YAHOO.util.Event.addListener( window, "load", initOverValuePopup );
