var showQuickQuoteOnLoad = false;
var parcelCount = 1;

function validateQuickQuote() {

	var validator = new validateForm();
		
	selectTo = document.getElementById( 'qq_shipTo_country' );
	var countryTo = selectTo.options[ selectTo.selectedIndex ].text;
	
	// check all parcels have their info entered
	for ( var i = 1; i <= parcelCount; i++ ) {
		validator.checkNumeric( 'qq_package_' + i + '_width' , 'Package ' + i + ' Width' );
		validator.checkNumeric( 'qq_package_' + i + '_height' , 'Package ' + i + ' Height' );
		validator.checkNumeric( 'qq_package_' + i + '_length' , 'Package ' + i + ' Length' );
		validator.checkNumeric( 'qq_package_' + i + '_weight' , 'Package ' + i + ' Weight' );
	}
	
	if ( document.getElementById( 'qq_emailQuote' ).checked ) {
		validator.validateEmailAddress( 'qq_email_address' , 'Email Address so we can email you your quote' );
	}
	
	if(validator.numberOfErrors() > 0) {
		validator.displayErrors();
	} else {
		// kick of the quote request
		searchForQuickQuotes();
	}
	
	//always return false so the form isn't submitted
	return false;
}


function searchForQuickQuotes() {
	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 ) {
				msg += " - " + errors[e] + "\n";
			}
			alert( msg );
		} else if ( ( typeof services['availableServices'] != 'undefined' ) && ( services['availableServices'].length > 0 ) ) {
			// we have some services to display...
			var msg = '';
			var cheapestPrice = 99999;
			var cheapestService = '';
			var vatRate = 1;
			for ( var i in services['availableServices'] ) {
				var thisPrice = parseFloat( services['availableServices'][i]['filteredTotalIncVAT'] );
				if ( thisPrice < cheapestPrice ) {
					cheapestPrice = thisPrice;
					cheapestService = services['availableServices'][i]['wpsService']['name'];
					vatRate = services['availableServices'][i]['vatRate'];
				}
			}
			if ( cheapestPrice < 99999 ) {
				if ( document.getElementById('qq_insurance').selectedIndex > 1 ) {
					// user has selected insurance, so include that in the total price
					cheapestPrice += getInsurancePriceFromAmount( document.getElementById('qq_insurance').value ) * vatRate;
				}
				showQuickQuoteResultsPopup( cheapestService, cheapestPrice );
			}
		} else {
			// errr, hopefully it will never get here...
			alert('Sorry, an error has occured.  Please try again.');
		}
	};
	var handleFailure = 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 ) {
				msg += "\t- " + errors[e] + "\n";
			}
			alert( msg );
		} else {
			// errr, hopefully it will never get here either...
			alert('Sorry, an error has occured.  Please try again.');
		}
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	
	// requestarama
	YAHOO.util.Connect.setForm( document.getElementById( 'quickQuoteForm' ) );
	var cObj = YAHOO.util.Connect.asyncRequest( 'POST', '/xmlservice.php?service=customService&customService=getAvailableServices&quoteId=quick&quickQuote=1', callback );
}

function addParcel() {
	if ( parcelCount < 20 ) {
		parcelCount++;
		document.getElementById( 'parcelRow_' + parcelCount ).style.display = '';
	}
	checkParcelCount();
}

function removeParcel( num ) {
	document.getElementById( 'parcelRow_' + parcelCount ).style.display = 'none';
	for ( i = num; i < 20; i++ ) {
		// loop round all the dimensions, weights, etc and move the values up
		document.getElementById( 'qq_package_' + i + '_width' ).value = document.getElementById( 'qq_package_' + ( i + 1 ) + '_width' ).value;
		document.getElementById( 'qq_package_' + i + '_height' ).value = document.getElementById( 'qq_package_' + ( i + 1 ) + '_height' ).value;
		document.getElementById( 'qq_package_' + i + '_length' ).value = document.getElementById( 'qq_package_' + ( i + 1 ) + '_length' ).value;
		document.getElementById( 'qq_package_' + i + '_weight' ).value = document.getElementById( 'qq_package_' + ( i + 1 ) + '_weight' ).value;
		document.getElementById( 'qq_package_' + ( i + 1 ) + '_width' ).value = '';
		document.getElementById( 'qq_package_' + ( i + 1 ) + '_height' ).value = '';
		document.getElementById( 'qq_package_' + ( i + 1 ) + '_length' ).value = '';
		document.getElementById( 'qq_package_' + ( i + 1 ) + '_weight' ).value = '';
	}
	
	parcelCount--;
	checkParcelCount();
}

function checkParcelCount() {
	if ( parcelCount == 1 ) {
		document.getElementById( 'addParcelImage_1' ).style.display = '';
		document.getElementById( 'removeParcelImage_1' ).style.display = 'none';
		document.getElementById( 'qqAddParcelLink' ).style.display = 'none';
	} else {
		document.getElementById( 'addParcelImage_1' ).style.display = 'none';
		document.getElementById( 'removeParcelImage_1' ).style.display = '';
		document.getElementById( 'qqAddParcelLink' ).style.display = '';
	}
}

function changeQuickQuoteEmail( bool ) {
	document.getElementById('qqEmailContainer').style.display = ( bool ) ? '' : 'none';
}

function initQuickQuotePopup() {
	document.getElementById('quickQuotePopup').style.display = '';
	quickQuoteBox = 
			new YAHOO.widget.Panel("quickQuotePopup",  
											{
											  width:"353px",
											  height:"376px",
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	quickQuoteBox.render(document.body);
	if( showQuickQuoteOnLoad )
		quickQuoteBox.show();
}

function hideQuickQuotePopup() {
	if( typeof quickQuoteBox != "undefined" )
		quickQuoteBox.hide();
}

function showQuickQuotePopup() {
	if( typeof quickQuoteBox != "undefined" )
		quickQuoteBox.show();
	else
		showQuickQuoteOnLoad = true
}

function initQuickQuoteResultsPopup() {
	document.getElementById('quickQuoteResultsPopup').style.display = '';
	quickQuoteResultsBox = 
			new YAHOO.widget.Panel("quickQuoteResultsPopup",  
											{
											  width:"250px",
											  height:"200px",
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	quickQuoteResultsBox.render(document.body);
}

function hideQuickQuoteResultsPopup() {
	if( typeof quickQuoteResultsBox != "undefined" )
		quickQuoteResultsBox.hide();
}

function showQuickQuoteResultsPopup( service, price ) {
	if( typeof quickQuoteResultsBox != "undefined" ) {
		document.getElementById('quickQuoteResultsService').innerHTML = service;
		document.getElementById('quickQuoteResultsPrice').innerHTML = '&pound;' + price.toFixed(2);
		var country = document.getElementById('qq_shipTo_country');
		document.getElementById('quickQuoteResultsCountry').innerHTML = country.options[ country.selectedIndex ].text;
		quickQuoteResultsBox.show();
	}
}

function bookQuickQuote() {
	if ( parcelAdded ) {
		var nextId = getNextRowId();
		addQuoteRow();
	} else {
		var nextId = 1;
	}
	populateCollectionAddresses( nextId );
	// put the information in the quick quote form into the main quote table
	for ( var i = 1; i <= parcelCount; i++ ) {
		if ( i == 1 ) {
			document.getElementById( 'cmsServicesShipping_packages_' + nextId + '_' + i + '_length' ).value = document.getElementById( 'qq_package_' + i + '_length' ).value;
			document.getElementById( 'cmsServicesShipping_packages_' + nextId + '_' + i + '_width' ).value = document.getElementById( 'qq_package_' + i + '_width' ).value;
			document.getElementById( 'cmsServicesShipping_packages_' + nextId + '_' + i + '_height' ).value = document.getElementById( 'qq_package_' + i + '_height' ).value;
			document.getElementById( 'cmsServicesShipping_packages_' + nextId + '_' + i + '_weight' ).value = document.getElementById( 'qq_package_' + i + '_weight' ).value;
		} else {
			var parcel = {
				length		: 	document.getElementById( 'qq_package_' + i + '_length' ).value,
				width		:	document.getElementById( 'qq_package_' + i + '_width' ).value,
				height		:	document.getElementById( 'qq_package_' + i + '_height' ).value,
				weight		:	document.getElementById( 'qq_package_' + i + '_weight' ).value,
				description	:	'',
				value		:	''
			};
			addParcelToShipment( nextId, parcel, i );
		}
	}
	// set the selected insurance
	document.getElementById( 'cmsServicesShipping_insurance_' + nextId ).value = document.getElementById('qq_insurance').value;
	// set the selected country
	document.getElementById('cmsServicesShipping_shipTo_country').value = document.getElementById('qq_shipTo_country').value;
	shipmentDetails[ nextId ] = getEmptyAddress();
	shipmentDetails[ nextId ].to.country = document.getElementById('qq_shipTo_country').value;
	hideQuickQuoteResultsPopup();
	hideQuickQuotePopup();
}

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