var quickQuoteResultsBox;
var showQuickQuoteOnLoad = false;
var parcelCounts = new Array();
parcelCounts['qq'] = 1; // quick quote
parcelCounts['sameday'] = 1; // same day delivery

function disableQuickQuoteBtn() {
	$('#qqSubmitButton').attr('disabled', true);
	$('#qqSubmitButton').addClass('actionButtonLargeDisabled');
	$('#qqSubmitButton').val('Please wait...');
}

function enableQuickQuoteBtn() {
	$('#qqSubmitButton').attr('disabled', false);
	$('#qqSubmitButton').removeClass('actionButtonLargeDisabled');
	$('#qqSubmitButton').val('Quote and Book!');
}

function validateQuickQuote() {
	var validator = new validateForm();
	selectFrom = document.getElementById( 'qq_shipFrom_country' );
	var countryFrom = selectFrom.options[ selectFrom.selectedIndex ].text;
	selectTo = document.getElementById( 'qq_shipTo_country' );
	var countryTo = selectTo.options[ selectTo.selectedIndex ].text;
	
	validator.checkSelect( 'qq_shipFrom_country', '', 'Collection Country' );
	validator.checkSelect( 'qq_shipTo_country', '', 'Destination Country' );
	
	// check all parcels have their info entered
	for ( var i = 1; i <= parcelCounts['qq']; 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(validator.numberOfErrors() > 0) {
		validator.displayErrors();
	} else {
		// disable the button to prevent multiple requests
		disableQuickQuoteBtn();
		// kick of the quote request
		searchForQuickQuotes();
	}
	
	//always return false so the form isn't submitted
	return false;
}


function searchForQuickQuotes() {
	var handleSuccess = function(o){
		enableQuickQuoteBtn();
		eval( 'var services = ' + o.responseText );
		if ( typeof services['errors'] != 'undefined' ) {
			// error occured, inform the user
			eval( 'var errors = ' + o.responseText );
			var 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...
			showQuickQuoteResultsPopup( services );
			// if we have additional services, show them too...
			if ( typeof services['availableServices'] != 'undefined' ) {
				var insuranceCost = getInsurancePriceFromAmount( document.getElementById('qq_insurance').value );
				var haveInternationalRates = false;
				var extraNotes = '';
				for ( var country in services['additionalServices'] ) {
					if ( ( typeof services['additionalServices'][country]['availableServices'] != 'undefined' ) && ( services['additionalServices'][country]['availableServices'].length > 0 ) ) {
						var cheapestPrice = 9999;
						var vatString = '';
						for ( var service in services['additionalServices'][country]['availableServices'] ) {
							// loop around each to get the cheapest price
							var thisPrice = parseFloat( services['additionalServices'][country]['availableServices'][service]['filteredTotal'] );
							thisPrice += insuranceCost;
							if ( thisPrice < cheapestPrice ) {
								cheapestPrice = thisPrice;
								vatString = ( services['additionalServices'][country]['availableServices'][service]['vatRate'] == 1 ) ? '' : '<span class="quickQuoteInternationalRateVAT"> + VAT</span>';
							}
						}
						// update the price
						$('#quickQuoteInternationalRatePrice' + country ).html( '&pound;' + cheapestPrice.toFixed(2) + '' + vatString );
						// make sure it's visible
						$('#quickQuoteInternationalRate' + country ).show();
						// set a flag
						haveInternationalRates = true;
					} else {
						// hide this country
						$('#quickQuoteInternationalRate' + country ).hide();
					}
				}
				
				// show/hide the notes area (export only)
				var availableServices = services['availableServices'];
				if(services['destination_country'] == 'Spain' || services['destination_country'] == 'Italy' || services['destination_country'] == 'Greece') {
					if(extraNotes == '') {
						extraNotes = 'Please note: Services to/from islands may take longer.'
					}
					else {
						extraNotes += '<br/>Please note: Services to / from islands may take longer.'
					}
				}
				if(extraNotes != '') {
					$('#quickQuoteExtraNotesContent').html(extraNotes);
					$('#quickQuoteExtraNotes').show();
				}
				else {
					$('#quickQuoteExtraNotes').hide();
				}
				// show the international rates if we have some
				if ( haveInternationalRates ) {
					$('#quickQuoteInternationalRates').show();
				} else {
					$('#quickQuoteInternationalRates').hide();
				}
			} else {
				// hide the international rates and notes area
				$('#quickQuoteInternationalRates').hide();
				$('#quickQuoteExtraNotes').hide();
			}
		} else {
			// errr, hopefully it will never get here...
			alert('Sorry, an error has occured.  Please try again.');
		}
		// turn on our show-popup flag
		togglePopup( true );
	};
	var handleFailure = function(o){
		enableQuickQuoteBtn();
		eval( 'var services = ' + o.responseText );
		if ( typeof services['errors'] != 'undefined' ) {
			// error occured, inform the user
			eval( 'var errors = ' + o.responseText );
			var 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.');
		}
		// turn on our show-popup flag
		togglePopup( true );
	};
	var callback = {
		success:handleSuccess,
		failure:handleFailure
	};
	
	// requestarama
	YAHOO.util.Connect.setForm( document.getElementById( 'quickQuoteForm' ) );
	YAHOO.util.Connect.asyncRequest( 'POST', '/xmlservice.php?service=customService&customService=getAvailableServices&quoteId=quick&quickQuote=1', callback );
}

function addParcel( prefix ) {
	if ( parcelCounts[ prefix ] < 20 ) {
		parcelCounts[ prefix ]++;
		document.getElementById( prefix + '_parcelRow_' + parcelCounts[ prefix ] ).style.display = '';
	}
	checkParcelCount( prefix );
}

function setParcels( prefix, quantity ) {
	if (isNaN(parseInt(quantity))) {
		alert('The number entered is invalid!');
	}
	else if (quantity > 20) {
		alert('If quoting for more than 20 parcels please contact us directly at:\n\ninfo@worldwide-parcelservices.co.uk');
	}
	else {
		while(parcelCounts[prefix] < quantity) {
			addParcel(prefix);
		}
	}
}

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

function checkParcelCount( prefix ) {
	if ( parcelCounts[ prefix ] == 1 ) {
		document.getElementById( prefix + '_addParcelImage_1' ).style.display = '';
		document.getElementById( prefix + '_removeParcelImage_1' ).style.display = 'none';
		document.getElementById( prefix + '_addParcelLink' ).style.display = 'none';
	} else {
		document.getElementById( prefix + '_addParcelImage_1' ).style.display = 'none';
		document.getElementById( prefix + '_removeParcelImage_1' ).style.display = '';
		document.getElementById( prefix + '_addParcelLink' ).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 )
		showQuickQuotePopup();
}

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:"486px",
											  height:"auto",
											  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() {
	
	var callback = {
		success: function(o){},
		failure: function(o){}
	};

	YAHOO.util.Connect.asyncRequest( 'GET', '/xmlservice.php?service=customService&customService=quickQuoteNotSelected', callback );
	
	if( typeof quickQuoteResultsBox != "undefined" )
		quickQuoteResultsBox.hide();
}

function sortByPrice(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 showQuickQuoteResultsPopup( result ) {

	/*
	if ( snowWarningMessage != '' ) {
		alert( snowWarningMessage + "\n\nClick 'OK' to receive your Quick Quote..." );
	}
	*/
	
	var title = ( result['flag_image'] ) ? '<img src="' + result['flag_image'] + '" />' : '';
	title += ( result['destination_country'] ) ? 'Your Quote to ' + result['destination_country'] : 'Your Quote...';
	$('#quickQuoteTitle').html( title );
	
	var services = result['availableServices'].sort( sortByPrice );
	
	if( typeof quickQuoteResultsBox != "undefined" ) {
		var html = '';
		var insuranceCost = getInsurancePriceFromAmount( document.getElementById('qq_insurance').value );
		for ( var i in services ) {
			var thisPrice = parseFloat( services[i]['filteredTotal'] );
			thisPrice += insuranceCost;
			var vatString = ( services[i]['vatRate'] == 1 ) ? '' : ' + VAT';
			var courier = services[i]['provider'].toLowerCase();
			var serviceCode = services[i]['serviceCode'].toLowerCase();
			if ( courier.indexOf('tnt') > -1 ) {
				courier = 'tnt';
			} else if ( courier == 'ups european' ) {
				if( serviceCode == '11_65' ) {
					courier = 'wpsexpresssaver';
				}
				else {
					courier = 'wpsstandardeuro';
				}
			} else if ( courier == 'ups export' ) {
				courier = 'wpsexpresssaver';
			} else if ( courier == 'ups dhl european' ) {
				courier = 'wpseuroeconomy';
			} else if ( courier == 'ups dhl export' ) {
				courier = 'wpsairexpress';
			} else if ( courier.indexOf('dhl') > -1 ) {
				if ( services[i]['serviceCode'].indexOf('epl') > -1 ) {
					courier = 'wpseuroeconomy';
				} else {
					courier = 'wpsairexpress';
				}
			} else {
				courier = 'dpd';
			}
			html += '<div class="quickQuoteResultsService">';
			html += '   <div style="display:none;">' + services[i]['provider'].toLowerCase() + '</div>';
			html += '	<div class="quickQuoteResultsRight">';
			html += '		<span class="quickQuoteResultsServicePrice">only <span class="quickQuoteResultsServicePricePrice">&pound;' + thisPrice.toFixed(2) + '</span>' + vatString + '</span>';
			html += '		<input type="button" value="Book This Parcel" class="actionButtonLarge button" onclick="bookQuickQuote();" />';
			html += '	</div>';
			html += '	<div class="quickQuoteResultsCourier">';
			html += '		<img src="/custom/images/' + courier + 'logopanel.png" alt="' + services[i]['provider'] + '" />';
			html += '	</div>';
			html += '	<div class="quickQuoteResultsLeft">';
			html += '		<span class="quickQuoteResultsServiceName">' + services[i]['wpsService']['name'] + ' Service</span><br />Transit Time: ' + services[i]['transitTime'];
			html += '	</div>';
			if ( courier == 'tnt' ) {
				html += '<div class="quickQuoteResultsExtraInfo">';
				html += '	Please note: TNT can only collect from commercial addresses';
				html += '</div>';
			}
			html += '	<div class="clearer"></div>';
			html += '</div>';
		}
		$('#quickQuoteResultsServices').html( html );
		quickQuoteResultsBox.show();
	}
}

function bookQuickQuote() {
	
	var handleSuccess = function(o){};
	var handleFailure = function(o){};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};

	if ( parcelAdded ) {
		var nextId = getNextRowId();
		if(document.getElementById( 'qq_document' ).checked) {
			addQuoteRow('document');
		}
		else {
			addQuoteRow('standard');
		}
	} else {
		var nextId = 1;
		parcelAdded = true;
	}
	
	var cObj = YAHOO.util.Connect.asyncRequest( 'GET', '/xmlservice.php?service=customService&customService=updateQuickQuoteToFullQuote&quoteId=' + nextId, callback );
	
	if ( quoteTableOnPage ) {
		showQuoteTable();
		populateCollectionAddresses( nextId );
		// put the information in the quick quote form into the main quote table
		for ( var i = 1; i <= parcelCounts['qq']; i++ ) {
			if ( i == 1 ) {
				if(document.getElementById( 'row_' + nextId + '_' + i + '_previousParcels' )) {
					document.getElementById( 'row_' + nextId + '_' + i + '_previousParcels' ).style.display = 'none';
					document.getElementById( 'row_' + nextId + '_' + i + '_dimensions' ).style.display = '';
				}
				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;
				if(document.getElementById( 'qq_document' ).checked) {
					$( '#cmsServicesShipping_packages_' + nextId + '_' + i + '_weight' ).attr('readonly','readonly');
					document.getElementById( 'cmsServicesShipping_packages_' + nextId + '_' + i + '_description' ).value = 'Documents';
					document.getElementById( 'cmsServicesShipping_packages_' + nextId + '_' + i + '_description' ).blur();
				}
			} 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		:	''
				};
				if(document.getElementById( 'qq_document' ).checked) {
					parcel.description = 'Documents';
					addParcelToShipment( 'document', nextId, parcel, i );
				}
				else {
					addParcelToShipment( 'standard', nextId, parcel, i );
				}
			}
		}
		// set the selected insurance
		document.getElementById( 'cmsServicesShipping_insurance_' + nextId ).value = document.getElementById('qq_insurance').value;
		if(document.getElementById( 'qq_document' ).checked) {
			document.getElementById( 'cmsServicesShipping_insurance_' + nextId ).value = '50';
			$( '#cmsServicesShipping_insurance_' + nextId ).attr('disabled','disabled');
			$( '#cmsServicesShipping_insurance_hidden_' + nextId ).removeAttr('disabled');
			$( '#cmsServicesShipping_document_' + nextId ).val('1');
		}
		// set the selected country
		document.getElementById('cmsServicesShipping_shipFrom_country').value = document.getElementById('qq_shipFrom_country').value;
		document.getElementById('cmsServicesShipping_shipTo_country').value = document.getElementById('qq_shipTo_country').value;
		shipmentDetails[ nextId ] = getEmptyAddress();
		shipmentDetails[ nextId ].from.country = document.getElementById('qq_shipFrom_country').value;
		shipmentDetails[ nextId ].to.country = document.getElementById('qq_shipTo_country').value;
		hideQuickQuoteResultsPopup();
		hideQuickQuotePopup();
		window.scrollTo(0,0);
		updateStatus( nextId );
	} else {
		// haven't got the quote table on this page, redirect to the homepage with the parcel details
		
		var url = '/?shipTo_code=' + document.getElementById('qq_shipTo_country').value;
		url += '&shipFrom_code=' + document.getElementById('qq_shipFrom_country').value;
		url += '&document=' + document.getElementById('qq_document').checked;
		for ( var i = 1; i <= parcelCounts['qq']; i++ ) {
			url += '&package[' + i + '][length]=' + document.getElementById( 'qq_package_' + i + '_length' ).value;
			url += '&package[' + i + '][width]=' + document.getElementById( 'qq_package_' + i + '_width' ).value;
			url += '&package[' + i + '][height]=' + document.getElementById( 'qq_package_' + i + '_height' ).value;
			url += '&package[' + i + '][weight]=' + document.getElementById( 'qq_package_' + i + '_weight' ).value;
		}
		Page_ShowPopOnExit = false;
		document.location = url;
		
	}
}

function toggleDocument(element) {
	if(element.checked) {
		$('#qq_insurance').val('50');
		$('#qq_insurance').attr('disabled','disabled');
		$('#qq_insurance_hidden').removeAttr('disabled');
		for(var i=1; i<=20; i++) {
			$('#qq_package_'+i+'_weight').val('0.5');
			$('#qq_package_'+i+'_weight').hide();
			$('#qq_package_'+i+'_document_weight').show();
		}
	}
	else {
		$('#qq_insurance').removeAttr('disabled');
		$('#qq_insurance_hidden').attr('disabled','disabled');
		for(var i=1; i<=20; i++) {
			$('#qq_package_'+i+'_weight').val('');
			$('#qq_package_'+i+'_document_weight').hide();
			$('#qq_package_'+i+'_weight').show();
		}
	}
}

function serviceAdded() {
	for ( var x in shipmentDetails ) {
		if ( typeof shipmentDetails[x].to != 'undefined' ) {
			return true;
		}
	}
	return false;
}

function changeDestinationSelect(countryCode) {
	if( countryCode == 'GB' || countryCode == 'IE' ) {
		$('#qq_shipTo_country_uk').attr('disabled','disabled');
		$('#qq_shipTo_country_uk').hide();
		$('#qq_shipTo_country').removeAttr('disabled');
		$('#qq_shipTo_country').show();
		$('#documentContainer').show();
	}
	else {
		document.getElementById( 'qq_shipTo_country' ).selectedIndex = 0;
		$('#qq_shipTo_country').attr('disabled','disabled');
		$('#qq_shipTo_country').hide();
		$('#qq_shipTo_country_uk').removeAttr('disabled');
		$('#qq_shipTo_country_uk').show();
		document.getElementById('qq_document').checked = false;
		toggleDocument(document.getElementById('qq_document'));
		$('#documentContainer').hide();
		$('#qq_shipTo_country_long').val('United Kingdom');
	}
}

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