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

function openWindow( url, width, height ) {
	window.open( url, 'popupWindow','menubar=0,resizable=1,scrollbars=1,width='+ width +',height=' + height);
}

function addParcel( prefix ) {
	if ( parcelCounts[ prefix ] < 20 ) {
		parcelCounts[ prefix ]++;
		document.getElementById( prefix + '_parcelRow_' + parcelCounts[ prefix ] ).style.display = '';
	}
	checkParcelCount( 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 removeNonNumeric( val ) {
	return val.replace( /[^0-9]/g, '' );
}

function removeNonDecimal( val ) {
	return val.replace( /[^0-9\.]/g, '' );
}

function checkWhole( units, input, quoteRow ) {
	var isDocument = false;
	if(quoteRow == 'qq') {
		if(document.getElementById('qq_document')) {
			if(document.getElementById('qq_document').checked) {
				isDocument = true;
			}
		}
	} else {
		if(document.getElementById('cmsServicesShipping_document_' + quoteRow)) {
			if(document.getElementById('cmsServicesShipping_document_' + quoteRow).value == '1') {
				isDocument = true;
			}
		}
	}
	if(isDocument && units.toLowerCase() == 'kg') {
		var numericValue = removeNonDecimal( input.value );
	}
	else {
		var numericValue = removeNonNumeric( input.value );
	}
	if ( input.value != numericValue ) {
		input.value = numericValue;
		alert('Please only enter a whole number (ie 5.3' + units + ' would be 6' + units + ')');
	}
}

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 {
		// 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
			var msg = "The following errors occured:\n\n";
			for ( var e in services['errors'] ) {
				msg += " - " + services['errors'][e] + "\n";
			}
			alert( msg );
		} else if ( ( typeof services['availableServices'] != 'undefined' ) && ( services['availableServices'].length > 0 ) ) {
			// we have some services to display...
			showQuickQuoteResultsPopup( services['availableServices'] );
			// 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'];
				for( var j in availableServices) {
					var courier = availableServices[j]['provider'].toLowerCase();
					courier = ( courier.indexOf('dhl') > -1 ) ? 'dhl' : (( courier.indexOf('tnt') > -1 ) ? 'tnt' : 'dpd');
					if(courier == 'tnt') {
						extraNotes = 'Please note: TNT can only collect from commercial addresses';
					}
				}
				if(extraNotes != '') {
					$('#quickQuoteExtraNotesContent').text(extraNotes);
					$('#quickQuoteExtraNotes').show();
				}
				else {
					$('#quickQuoteExtraNotes').hide();
				}
			}
		} 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
			var msg = "The following errors occured:\n\n";
			for ( var e in services['errors'] ) {
				msg += " - " + services['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 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() {
	if( typeof quickQuoteResultsBox != "undefined" )
		quickQuoteResultsBox.hide();
}

function sortByPrice(a,b){  
    return a['filteredTotalIncInsurance'] > b['filteredTotalIncInsurance'] ? 1 : -1;  
};  

function showQuickQuoteResultsPopup( services ) {

	services = services.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'] == 'epl' ) {
					courier = 'wpseuroeconomy';
				} else {
					courier = 'wpsairexpress';
				}
			} else {
				courier = 'dpd';
			}
			html += '<div class="quickQuoteResultsService">';
			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>';
			html += '	<div class="clearer"></div>';
			html += '</div>';
		}
		$('#quickQuoteResultsServices').html( html );
		quickQuoteResultsBox.show();
	}
}

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 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 bookQuickQuote() {
	var numberOfParcels = document.getElementById('qq_parcelQuantity').value;
	var querystring = '?shipFrom_code=' + document.getElementById('qq_shipFrom_country').value;
	querystring += '&shipTo_code=' + document.getElementById('qq_shipTo_country').value;
	if ( document.getElementById('qq_document').checked ) {
		querystring += '&document=true';
	}
	for ( var i = 1; i <= numberOfParcels; i++ ) {
		querystring += '&package[' + i + '][width]=' + document.getElementById('qq_package_' + i + '_width').value;
		querystring += '&package[' + i + '][height]=' + document.getElementById('qq_package_' + i + '_height').value;
		querystring += '&package[' + i + '][length]=' + document.getElementById('qq_package_' + i + '_length').value;
		querystring += '&package[' + i + '][weight]=' + document.getElementById('qq_package_' + i + '_weight').value;
	}
	document.location = 'http://www.worldwide-parcelservices.co.uk/' + querystring;
}

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 addOptionToSelect( slct, opt ) {
	slct.options[ slct.options.length ] = opt;
}

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 serviceAdded() {
	for ( var x in shipmentDetails ) {
		if ( typeof shipmentDetails[x].to != 'undefined' ) {
			return true;
		}
	}
	return false;
}

function changeDestinationSelect(countryCode) {
	if(countryCode == 'GB') {
		$('#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' ).value = 'GB';
		$('#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();
	}
}

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