// business calcs */
var officeEnergyCalculatorBox = null;
var showOfficeEnergyCalculatorOnLoad = false;
var quickCarCalculatorBox = null;
var showQuickCarCalculatorOnLoad = false;
var publicTransportCalculatorBox = null;
var showPublicTransportCalculatorOnLoad = false;
var quickFlightCalculatorBox = null;
var showQuickFlightCalculatorOnLoad = false;
var freightRoadCalculatorBox = null;
var showFreightRoadCalculatorOnLoad = false;
var freightAirCalculatorBox = null;
var showFreightAirCalculatorOnLoad = false;
var freightSeaCalculatorBox = null;
var showFreightSeaCalculatorOnLoad = false;
var additionalCarbonCalculatorBox = null;
var showAdditionalCarbonCalculatorOnLoad = false;
/* name for the cookie which will store our list of transacition ids to the users browser */
var businessTransactionCookieName = 'businessTransactionList';
var businessTonnageCookieName = 'businessTonnageList';
var businessReportPeriodCookieName = 'businessDates';
var transactionsAdded = new Array();
var currentBusinessStateId = 0;

/**
 * 
 * Cookie Stuff
 * ------------
 * 
 **/

/* reassigns the array of transaction ids and tonnages to the cookie */
function setBusinessTonnageList( businessTransactionData ) {
	// reassign the cookie
	//alert( "setting cookie data to : " + businessTransactionData );
	document.cookie = businessTonnageCookieName + '=' + businessTransactionData + ';path=/;';
}

/* loops through all transactions and check if this one has been added previously */
function checkIfTransactionExists( transactionId ) {
	var transactionIds = getTransactionList();
	if ( transactionIds instanceof Array ) {
		for ( var i in transactionIds ) {
			if ( transactionIds[i] == transactionId ) {
				return true;
			}
		}
	}
	return false;
}

function addTransaction( transactionId, tonnes, type ) {
	// flag that we have added an item for this type so we don't add offsets previously add every time we open the calculator
	transactionsAdded[ type ] = true;
	// add the transaction to the cookie
	updateBusinessTransactionList( transactionId );
	// update the business tonnage totals
	updateBusinessTonnageList( type, transactionId, tonnes );
}

function updateBusinessTransactionList( transactionId ) {
	// try and get the current cookie
	var transactionIds = getBusinessTransactionList();
	// add the new id to the list if it hasn't been added previously
	if ( !checkIfTransactionExists( transactionId ) ) {
		transactionIds.push( transactionId );
	}
	// set the list of transactions to the cookie
	setBusinessTransactionList( transactionIds );
}

/* reassigns the array of transaction ids to the cookie */
function setBusinessTransactionList( transactionIds ) {
	var newTransactionList = '';
	// recreate the array
	for( i in transactionIds ) {
		if( i > 0 ) {
			newTransactionList += ',';
		}
		newTransactionList += transactionIds[i];
	}
	// reassign the cookie
	document.cookie = businessTransactionCookieName + '=' + newTransactionList + ';path=/;';
}
/* returns an array of transaction ids from the cookie */
function getBusinessTransactionList() {
	var cookieData = getCookie( businessTransactionCookieName );
	// whack it into an array if its ot already
	if( typeof cookieData != 'object' && cookieData.length > 0 ) {
		return cookieData.split(',');
	} else { 
		return new Array();
	}
}

/**
 * 
 * Helper Functions
 * ----------------
 * 
 **/

/* adds " Miles" onto the end of a value */
function appendMiles( id ) {
	var object = document.getElementById( id );
	var myValue = object.value;
	if( isNumeric( myValue )) {
		object.value = myValue + ' Miles';	
	} else {
		if( object.value != '' ) {
			alert( 'Distance must be a numeric value' );
		}
		object.value = '0 Miles';
	}
}

/* removes " Miles" from the end of a value */
function removeMiles( id ) {
	var object = document.getElementById( id );
	var myValue = object.value;
	if( object.value == '0 Miles' ) {
		// if its zero, set the value to nothing
		object.value = '';
	} else {
		// just replace the " Miles"
		object.value = myValue.replace(' Miles', '' );
	}
}

/* removes a particular transaction based on the type passed in */
function removeBusinessItem( type, transactionId ) {
	// sure?
	if( confirm("Are you sure you want to remove this offset?") ) {
		// remove the row from the correct table
		var tbody = document.getElementById( type + 'CalculatorTable' );	
		tbody.removeChild( document.getElementById( type + '_' + transactionId ));
		// remove the transaction from the cookie
		removeBusinessTransactionList( transactionId );
		// and remove the co2 from the appropriate list too
		removeBusinessTonnageList( type, transactionId );
		// update the offset counter
		var offsetCount = document.getElementById( type + '_offset_count' ).innerHTML;
		document.getElementById( type + '_offset_count' ).innerHTML = parseInt( offsetCount ) - 1;
	}
}

/* remove a transaction from the business transaction list */
function removeBusinessTransactionList( transactionId ) {
	var businessTransactions = getBusinessTransactionList();
	var newArray = new Array();
	if ( businessTransactions instanceof Array ) {
		for ( var i in businessTransactions ) {
			if ( businessTransactions[i] != transactionId ) {
				newArray.push( businessTransactions[i] );
			}
		}
	}
	removeTransaction( transactionId );
	setBusinessTransactionList( newArray );
}

function removeBusinessTonnageList( type, transactionId ) {
	var currentBusinessData = getBusinessTonnageArray();
	var newBusinessData = new Array();
	// make sure the type array exists
	if( typeof currentBusinessData[type] == 'object' ) {
		for ( var transaction in currentBusinessData[type] ) {
			// if this is the transaction toremove
			if( transaction != transactionId ) {
				// remove it from the array
				newBusinessData.push( currentBusinessData[type][transactionId] );
				break;
			}
		}
	}
	// reassign the updated cookie info
	setBusinessTonnageArray( newBusinessData );	
}

function getBusinessTonnageArray( ) {
	// breakdown the existing cookie data
	var cookieData = getCookie( businessTonnageCookieName );
	// whack it into an array if its own already
	if( typeof cookieData != 'object' && cookieData.length > 0 ) {
		var businessTonnageData = cookieData.split('#');
	} else {
		var businessTonnageData = new Array();
	}
	var businessDataArray = new Array();
	for( var transactionType in businessTonnageData ) {
		// split the transaction type from its associated data pairs
		var businessTypeInfo = businessTonnageData[transactionType].split('|');
		// create a new array element if it doesn't exist
		businessDataArray[businessTypeInfo[0]] = new Array();
		// get the transaction data into a loopable array
		var transactionInfo = businessTypeInfo[1].split(',');
		// loop it
		for( transaction in transactionInfo ){
			// split the transactionId from the tonnage
			var transactionData = transactionInfo[transaction].split(':');
			businessDataArray[businessTypeInfo[0]][transactionData[0]] = transactionData[1];
		}
	}
	//alert( dump( businessDataArray ));
	return businessDataArray;
}

function setBusinessTonnageArray( businessDataArray ) {
	// something like this hopefully
	// type#transId:tonnes,transId:tonnes|type#transId:tonnes, etc...
	
	var dataString = '';
	if( typeof businessDataArray == 'object' ) {
		for( var businessData in businessDataArray ) {
			if( dataString != '' ) {
				dataString += '#';
			}
			transactionString = '';
			var loopCount = 0;
			for( var transactionData in businessDataArray[businessData] ) {
				loopCount++;
				if( loopCount == 1 ) {
					// only add the key (i.e. quickCar) if we have transactions
					dataString += businessData + '|';
				}				
				if( transactionString != '' ) {
					transactionString += ','
				}
				transactionString += transactionData + ':' + businessDataArray[businessData][transactionData];
			}
			
			dataString += transactionString;
		}
	}
	// and set it to the cookie
	setBusinessTonnageList( dataString );
}

function updateBusinessTonnageList( type, transactionId, tonnes ) {
	// get the existing business data in array format
	var currentBusinessData = getBusinessTonnageArray();
	// make sure the type array exists
	if( typeof currentBusinessData[type] == 'undefined' ) {
		currentBusinessData[type] = new Array();
	}
	// add the new tonnage
	currentBusinessData[type][transactionId] = tonnes;
	// update the cookie info
	setBusinessTonnageArray( currentBusinessData );
}

/* adds the passed info to the correct business type transaction list and
adds a row to the correct table with the correct info correctly */
function addBusinessItem( type, transactionId, tonnes, offsetType, offsetDescription, offsetModifier ) {
	// add this transaction
	addTransaction( transactionId, tonnes, type );	// defined in interface.js
	// add the item to the correct table
	var tbody = document.getElementById( type + 'CalculatorTable' );	
	var newTR = document.createElement("tr");
	newTR.setAttribute( 'id', type + '_' + transactionId );
	// detail
	var newTD = document.createElement("td");
	newTD.style.width = '209px';
	var newSpan = document.createElement("div");
	newSpan.style.marginLeft = '4px';
	newSpan.innerHTML = '<strong>' + offsetType + '</strong><br />' + offsetDescription
	// only if we have a modifier
	if( offsetModifier != ''  ) {
		if ( offsetDescription != '' ) {
			newSpan.innerHTML += ', '
		}
		newSpan.innerHTML += ( ( offsetModifier.toUpperCase() == 'CURR' ) ? getLocaleCurrency() : offsetModifier );
	}
	newTD.appendChild( newSpan );
	newTR.appendChild( newTD );
	// co2 tonnes
	var newTD = document.createElement("td");
	newTD.style.width = '75px';
	newTD.style.paddingLeft = '3px';
	var newDiv = document.createElement("div");
	newDiv.className = 'generalBusinessPopupTableCO2';
	newDiv.innerHTML = round( tonnes, 2 );
	newTD.appendChild( newDiv );
	// remove
	var newIMG = document.createElement("img");
	newIMG.src = '/custom/images/calculators/business/btn-close.gif';
	newIMG.alt = 'Click here to remove this offset';
	newIMG.className = 'clickable';
	newTD.appendChild( newIMG );
	newTR.appendChild( newTD );
	newIMG.setAttribute( 'id', type + '_img_' + transactionId );
	// assign the onclick to the button that removes the item from the business - public transport table
	eval( 'var func=function(){ removeBusinessItem( "' + type + '", ' + transactionId + '); }');
	YAHOO.util.Event.addListener( type + '_img_' + transactionId, "click", func );
	// add to table
	tbody.appendChild( newTR );	
	// update the offset counter
	var offsetCount = document.getElementById( type + '_offset_count' ).innerHTML;
	document.getElementById( type + '_offset_count' ).innerHTML = parseInt( offsetCount ) + 1;
}

function loadBusinessCalcStates() {
	getStates('populateBusinessCalcStates');
}

function populateBusinessReportingPeriod() {
	var strDates = getCookie( businessReportPeriodCookieName );
	if ( strDates != '' ) {
		var datesSplit = strDates.split(',');
		document.getElementById('business_name').value = datesSplit[0];
		document.getElementById('business_email').value = datesSplit[1];
		document.getElementById('business_from_month').value = datesSplit[2];
		document.getElementById('business_from_year').value = datesSplit[3];
		document.getElementById('business_to_month').value = datesSplit[4];
		document.getElementById('business_to_year').value = datesSplit[5];
		if ( locale == 'us' ) {
			currentBusinessStateId = datesSplit[6];
		}
	} else {
		// auto-populate with current month/year
		var today = new Date();
		document.getElementById('business_from_month').selectedIndex = today.getMonth() + 1;
		document.getElementById('business_from_year').value = today.getFullYear();
		nextMonth = today.getMonth() + 1;
		nextYear = today.getFullYear() + 1;
		document.getElementById('business_to_month').selectedIndex = nextMonth;
		document.getElementById('business_to_year').value = nextYear;
	}
}

function populateBusinessCalcStates( data ) {
	populateStatesDropDown( data, 'business_state', 'updateBusinessCalcState' );
}

function updateBusinessCalcState() {
	if ( currentBusinessStateId > 0 ) {
		document.getElementById('business_state').value = currentBusinessStateId;
	}
}

/* shows the choosen calculator */
function showCalculator( myCalculator, stringVal ) {
	
	// check reporting stuff has been completed first
	var validate = new validateForm();
	// company name
	validate.checkText( 'business_name', 'Company Name' );
	// company email address
	validate.validateEmailAddress( 'business_email', 'Company Email' );
	// from month
	validate.checkSelect( 'business_from_month', '', 'From Month' );
	// from year
	validate.checkSelect( 'business_from_year', '', 'From Year' );
	// to month
	validate.checkSelect( 'business_to_month', '', 'To Month' );
	// to year
	validate.checkSelect( 'business_to_year', '', 'To Year' );
	// state
	if ( locale == 'us' ) {
		validate.checkSelect( 'business_state', '', 'State' );
		var stateString = document.getElementById('business_state').value;
	} else {
		var stateString = '';
	}
	
	// if none have been selected
	if( validate.numberOfErrors() > 0 ) {
		validate.displayBusinessErrors();
		return false;
	}
	// store reporting period info in a cookie so we can populate them again later
	var strVals = document.getElementById('business_name').value + ',' + document.getElementById('business_email').value + ',' + document.getElementById('business_from_month').value + ',' + document.getElementById('business_from_year').value + ',' + document.getElementById('business_to_month').value + ',' + document.getElementById('business_to_year').value + ',' + stateString;
	document.cookie = businessReportPeriodCookieName + '=' + strVals + ';path=/;';	
	
	if( typeof myCalculator != "undefined" && myCalculator != null ) {
		myCalculator.show();
	} else {
		switch( stringVal ) {
			case 'officeEnergy':
				showOfficeEnergyCalculatorOnLoad = true;
				break;
			case 'quickCar':
				showQuickCarCalculatorOnLoad = true;
				break;
			case 'publicTransport':
				showPublicTransportCalculatorOnLoad = true;
				break;
			case 'quickFlight':
				showQuickFlightCalculatorOnLoad = true;
				break;
			case 'freightRoad':
				showFreightRoadCalculatorOnLoad = true;
				break;
			case 'freightAir':
				showFreightAirCalculatorOnLoad = true;
				break
			case 'freightSea':
				showFreightSeaCalculatorOnLoad = true;
				break;
			case 'additionalCarbon':
				showAdditionalCarbonCalculatorOnLoad = true;
				break;
		}
	}
}

/* only called from the business calculator currently, adds all the business calulcations to the main transaction list
so they can be inluded in the shopping cart call */
function chooseProjectFromBusiness() {
	var transactionIds = getTransactionList();
	var businessTransactions = getBusinessTransactionList();
	var businessTransactionCount = 0;
	// associative array, check if we have any business transactions
	for( var transaction in businessTransactions ) {
		businessTransactionCount++;
	}
	// must have a transaction of either type before we can leave the page
	if( transactionIds.length > 0 || businessTransactionCount > 0 ) {
		// add all the businessTransactions to the main transaction list
		for( var transaction in businessTransactions ) {
			// add the new id to the list (if it is not already in it)
			if ( !checkIfTransactionExists( businessTransactions[ transaction ] ) ) {
				transactionIds.push( businessTransactions[transaction] );
			}
		}
		// set the list of transactions to the cookie
		setTransactionList( transactionIds );
		// unset the business transaction list so they cant get re added
		businessTransactions = new Array();
		// redirect to the project choosing page
		goToPage( 'choose_project.php' );
		// cheers thanks bye
	} else {
		// no transactions added, simply alert to that fact
		alert( 'You currently have no offsets in your basket.' );
	}
}
/* hides the choosen calculator */
function hideCalculator( myCalculator ) {
	if( typeof myCalculator != "undefined" )
		myCalculator.hide();
}

/* totals all the offsets for any given calculator */
function totalOffsets( calculatorName ) {
	var totalCO2 = 0.0;
	// get the existing business data in array format
	var currentBusinessData = getBusinessTonnageArray();
	// loop all the ones of the type
	if( typeof currentBusinessData[calculatorName] != 'undefined' ) {
		for( var i in currentBusinessData[calculatorName] ) {
			totalCO2 += parseFloat( currentBusinessData[calculatorName][i] );
		}
	}
	return round( totalCO2, 2 ) + ' ' + tonnesString;	
}

function getFreightListCallback( data, elementType, type ) {
	// get the list to populate
	var itemList = document.getElementById( elementType + '_type' );
	// remove all the items first
	// empty the current vehicle list 
	for( var oldItem in itemList ){
		// remove it
		itemList.remove( oldItem );
	}
	// add the new options starting with 
	var opt = new Option( '- Type -', '' );
	itemList.options[ itemList.options.length ] = opt;
	for( var item in data['details']['freight'] ) {
		if( data['details']['freight'][item]['type'] == type ) {
			var value = data['details']['freight'][item]['detail'];
			var id = data['details']['freight'][item]['freightid'];
			var opt = new Option( value, id );
			itemList.options[ itemList.options.length ] = opt;
		}
	}	
}

function getReportingPeriodInfo() {
	var name = document.getElementById( 'business_name' ).value;
	// company email address
	var email = document.getElementById( 'business_email' ).value;
	// from month
	var fromMonth = document.getElementById( 'business_from_month' ).value;
	// from year
	var fromYear = document.getElementById( 'business_from_year' ).value;
	// to month
	var toMonth = document.getElementById( 'business_to_month' ).value;
	// to year
	var toYear = document.getElementById( 'business_to_year' ).value;
	// return the url params, dont know any better so add 01 as the day.
	return '&CompanyEmail=' + email + '&CompanyName=' + name + '&AccountingFrom=01/' + fromMonth + '/' + fromYear + '&AccountingTo=01/' + toMonth + '/' + toYear;
}

/**
 * 
 * Office Energy Functions
 * -----------------------
 * 
 **/
function initMainOfficeEnergyCalculator() {
	correctPNGBackground( 'officeEnergyCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonOfficeEnergy' );
	initOfficeEnergyCalculator( 492, 576, true );
}
function initPartnerOfficeEnergyCalculator() {
	correctPNGBackground( 'officeEnergyCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/officecalc.png' );
	correctPNGBackground( 'popupCloseButtonOfficeEnergy', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initOfficeEnergyCalculator( 730, 395, positionOverlaysCenter );
}
function initOfficeEnergyCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('officeEnergyCalculatorPopup').style.display = '';
	officeEnergyCalculatorBox = 
			new YAHOO.widget.Panel("officeEnergyCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	officeEnergyCalculatorBox.beforeShowEvent.subscribe( loadPreviousOfficeEnergyTransactions, this );
	officeEnergyCalculatorBox.render(document.body);
	if( showOfficeEnergyCalculatorOnLoad )
		officeEnergyCalculatorBox.show();
}

function calculateOfficeEnergy() {
	// validate the form first
	var validate = new validateForm();
	
	// prepare some arrays so we don't have to check twice
	var fuelTypes = new Array();
	var quantities = new Array();
	var units = new Array();
	var index = 0;
	var usageEntered = false;
	// electricity
	if ( ( document.getElementById('office_electricity').value != '' ) && ( document.getElementById('office_electricity').value != '- amount -' ) ) {
		usageEntered = true;
		validate.checkNumeric( 'office_electricity', 'Annual electricity usage' );
		// add data
		fuelTypes[index] = 'electricity';
		period = ( document.getElementById('office_electricity_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('office_electricity').value * period;
		units[index] = document.getElementById('office_electricity_unit').value;
		index++;
	}
	// gas
	if ( ( document.getElementById('office_gas').value != '' ) && ( document.getElementById('office_gas').value != '- amount -' ) ) {
		usageEntered = true;
		validate.checkNumeric( 'office_gas', 'Annual gas usage' );
		// add data
		fuelTypes[index] = 'gas';
		period = ( document.getElementById('office_gas_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('office_gas').value * period;
		units[index] = document.getElementById('office_gas_unit').value;
		index++;
	}
	// oil
	if ( ( document.getElementById('office_oil').value != '' ) && ( document.getElementById('office_oil').value != '- amount -' ) ) {
		usageEntered = true;
		validate.checkNumeric( 'office_oil', 'Annual oil usage' );
		// add data
		fuelTypes[index] = 'oil';
		period = ( document.getElementById('office_oil_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('office_oil').value * period;
		units[index] = document.getElementById('office_oil_unit').value;
		index++;
	}
	// wood
	if ( ( document.getElementById('office_wood').value != '' ) && ( document.getElementById('office_wood').value != '- amount -' ) ) {
		usageEntered = true;
		validate.checkNumeric( 'office_wood', 'Annual wood usage' );
		// add data
		fuelTypes[index] = 'wood';
		period = ( document.getElementById('office_wood_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('office_wood').value * period;
		units[index] = document.getElementById('office_wood_unit').value;
		index++;
	}
	// coal
	if ( ( document.getElementById('office_coal').value != '' ) && ( document.getElementById('office_coal').value != '- amount -' ) ) {
		usageEntered = true;
		validate.checkNumeric( 'office_coal', 'Annual coal usage' );
		// add data
		fuelTypes[index] = 'coal';
		period = ( document.getElementById('office_coal_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('office_coal').value * period;
		units[index] = document.getElementById('office_coal_unit').value;
		index++;
	}
	// LPG
	if ( ( document.getElementById('office_lpg').value != '' ) && ( document.getElementById('office_lpg').value != '- amount -' ) ) {
		usageEntered = true;
		validate.checkNumeric( 'office_lpg', 'Annual LPG usage' );
		// add data
		fuelTypes[index] = 'lpg';
		period = ( document.getElementById('office_lpg_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('office_lpg').value * period;
		units[index] = document.getElementById('office_lpg_unit').value;
		index++;
	}
	if( !usageEntered ) {
		validate.addCustomError( 'You must enter at least one usage' );
	}
	// if none have been selected
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// add the fuel types into a comma separated string
	var allFuelTypes = '';
	for( fuelType in fuelTypes ) {
		if( fuelType > 0 ) {
			allFuelTypes += ',';
		}
		allFuelTypes += fuelTypes[fuelType];
	}
	// add the quantities into a comma separated string
	var allQuantities = '';
	for( quantity in quantities ) {
		if( quantity > 0 ) {
			allQuantities += ',';
		}
		allQuantities += quantities[quantity];
	}
	// add the units into a comma separated string
	var allUnits = '';
	for( unit in units ) {
		if( unit > 0 ) {
			allUnits += ',';
		}
		allUnits += units[unit];
	}
	
	// assign the details to the temp variable, we need it later
	var calculatorHomeInfo = '&FuelType=' + allFuelTypes + '&Qty=' + allQuantities + '&Unit=' + allUnits;
	// and make that request
	executeJSONRequest( 'domestic_energy/' + version + '/calculator/?partnerID=' + partnerId + calculatorHomeInfo + '&CalculatorName=Office&CustomerName=&HouseholdQty=&DateMovedToAddress=' + getReportingPeriodInfo(), 'calculateOfficeEnergyCallback' );
	// dont close the window
	return false;
}

function calculateOfficeEnergyCallback( data ) {
	//api call with trans id
	// add this item to the business transactions list
	var fuelTypes = '';
	for ( var i in data['details']['energy'] ) {
		fuelTypes += ( ( i == 0 ) ? '' : ', ' ) + data['details']['energy'][i]['fueltype'] + ' (' + data['details']['energy'][i]['unit'] + ')';
	}
	addBusinessItem( 'officeEnergy', data['transactionid'], round( data['details']['data'][0]['@attributes']['tonnes'], 2 ), 'Office Energy', fuelTypes, '' );
	// set the fields back to their default
	// modifier is miles
	//document.getElementById( 'quick_car_unit' ).selectedIndex = 0;
}

/* finalise any changes made to the main window */
function completeOfficeEnergy( ) {
	// assign it to the main window
	document.getElementById('office_energy_co2').value = totalOffsets( 'officeEnergy' );
	// lastly, hide the freezeover
	hideCalculator( officeEnergyCalculatorBox );
}

/* populate the tonnage inputs (on page load) */
function populateBusinessTonnage() {
	var suffix = ' ' + tonnesString;
	var items = getBusinessTonnageArray();
	// office
	var tonnage = getBusinessTonnageByType( items, 'officeEnergy' );
	document.getElementById('office_energy_co2').value = tonnage + suffix;
	// quick car
	tonnage = getBusinessTonnageByType( items, 'quickCar' );
	document.getElementById('quick_car_co2').value = tonnage + suffix;
	// public transport
	tonnage = getBusinessTonnageByType( items, 'publicTransport' );
	document.getElementById('public_transport_co2').value = tonnage + suffix;
	// quick flight
	tonnage = getBusinessTonnageByType( items, 'quickFlight' );
	document.getElementById('flights_co2').value = tonnage + suffix;
	// freight road
	tonnage = getBusinessTonnageByType( items, 'freightRoad' );
	document.getElementById('freight_road_co2').value = tonnage + suffix;
	// freight air
	tonnage = getBusinessTonnageByType( items, 'freightAir' );
	document.getElementById('freight_air_co2').value = tonnage + suffix;
	// freight sea
	tonnage = getBusinessTonnageByType( items, 'freightSea' );
	document.getElementById('freight_sea_co2').value = tonnage + suffix;
	// additional carbon
	tonnage = getBusinessTonnageByType( items, 'additionalCarbon' );
	document.getElementById('additional_carbon_co2').value = tonnage + suffix;
}

function getBusinessTonnageByType( items, type ) {
	var tonnage = 0.0;
	if ( items instanceof Array ) {
		for ( var i in items[ type ] ) {
			tonnage += parseFloat( items[ type ][i] );
		}
	}
	return tonnage.toFixed(2);
}

/**
 * 
 * Quick Car Functions
 * -------------------
 * 
 **/

function loadPreviousTransactionsByTypeCallback_officeEnergy( data ) {
	addBusinessItem( 'officeEnergy', data['transactionid'], round( data['details']['energy'][0]['tonnes'], 2 ), 'Office Energy', data['details']['energy'][0]['fueltype'], data['details']['energy'][0]['unit'] );
}
function loadPreviousTransactionsByTypeCallback_quickCar( data ) {
	addBusinessItem( 'quickCar', data['transactionid'], round( data['details']['vehicle'][0]['tonnes'], 2 ), data['details']['vehicle'][0]['type'], data['details']['vehicle'][0]['description'], data['details']['vehicle'][0]['miles'] );
}
function loadPreviousTransactionsByTypeCallback_publicTransport( data ) {
	addBusinessItem( 'publicTransport', data['transactionid'], round( data['details']['transport'][0]['tonnes'], 2 ), data['details']['transport'][0]['type'], data['details']['transport'][0]['description'], data['details']['transport'][0]['miles'] );
}
function loadPreviousTransactionsByTypeCallback_quickFlight( data ) {
	addBusinessItem( 'quickFlight', data['transactionid'], round( data['details']['flight'][0]['tonnes'], 2 ), data['details']['flight'][0]['type'], 'x' + data['details']['flight'][0]['qty'], '' );
}
function loadPreviousTransactionsByTypeCallback_freightRoad( data ) {
	addBusinessItem( 'freightRoad', data['transactionid'], round( data['details']['freight'][0]['tonnes'], 2 ), data['details']['freight'][0]['type'], data['details']['freight'][0]['description'], data['details']['freight'][0]['miles'] );
}
function loadPreviousTransactionsByTypeCallback_freightAir( data ) {
	addBusinessItem( 'freightAir', data['transactionid'], round( data['details']['freight'][0]['tonnes'], 2 ), data['details']['freight'][0]['type'], data['details']['freight'][0]['description'], data['details']['freight'][0]['miles'] );
}
function loadPreviousTransactionsByTypeCallback_freightSea( data ) {
	addBusinessItem( 'freightSea', data['transactionid'], round( data['details']['freight'][0]['tonnes'], 2 ), data['details']['freight'][0]['type'], data['details']['freight'][0]['description'], data['details']['freight'][0]['miles'] );
}
function loadPreviousTransactionsByTypeCallback_additionalCarbon( data ) {
	addBusinessItem( 'additionalCarbon', data['transactionid'], round( data['details']['additional'][0]['tonnes'], 2 ), data['details']['additional'][0]['item'], data['details']['additional'][0]['qty'], '' );
}

function loadPreviousOfficeEnergyTransactions() {
	loadPreviousTransactionsByType( 'officeEnergy' );
}
function loadPreviousQuickCarTransactions() {
	loadPreviousTransactionsByType( 'quickCar' );
}
function loadPreviousPublicTransportTransactions() {
	loadPreviousTransactionsByType( 'publicTransport' );
}
function loadPreviousQuickFlightTransactions() {
	loadPreviousTransactionsByType( 'quickFlight' );
}
function loadPreviousFreightRoadTransactions() {
	loadPreviousTransactionsByType( 'freightRoad' );
}
function loadPreviousFreightAirTransactions() {
	loadPreviousTransactionsByType( 'freightAir' );
}
function loadPreviousFreightSeaTransactions() {
	loadPreviousTransactionsByType( 'freightSea' );
}
function loadPreviousAdditionalCarbonTransactions() {
	loadPreviousTransactionsByType( 'additionalCarbon' );
}

function loadPreviousTransactionsByType( type ) {
	if ( !transactionsAdded[ type ] ) {
		var allPreviousTransactions = getBusinessTonnageArray();
		var previousTransactions = allPreviousTransactions[ type ];
		if ( previousTransactions instanceof Array ) {
			for ( var i in previousTransactions ) {
				var url = 'json/wayback/v1.0/?partnerid=' + partnerId + '&transactionID=' + i;
				executeGeneralRequest( url, 'loadPreviousTransactionsByTypeCallback_' + type );
			}
		}
	}
}

function initMainQuickCarCalculator() {
	correctPNGBackground( 'quickCarCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonQuickCar' );
	initQuickCarCalculator( 492, 576, true );
}
function initPartnerQuickCarCalculator() {
	correctPNGBackground( 'quickCarCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonQuickCar', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initQuickCarCalculator( 730, 395, positionOverlaysCenter );
}
function initQuickCarCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('quickCarCalculatorPopup').style.display = '';
	quickCarCalculatorBox = 
			new YAHOO.widget.Panel("quickCarCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	quickCarCalculatorBox.beforeShowEvent.subscribe( loadPreviousQuickCarTransactions, this );
	quickCarCalculatorBox.render(document.body);
	if( showQuickCarCalculatorOnLoad )
		quickCarCalculatorBox.show();
}

/* requests the quick vehicle sizes data based on the fuel type selected on screen */
function getQuickCarSizes( fuelType ) {
	// get all the car sizes
	executeJSONRequest( 'quick_vehicle/' + version + '/vehiclelist/?PartnerID=' + partnerId + '&VehicleType=Car&FuelType=' + fuelType, 'getQuickCarSizesCallback' );	
}

/* creates the list of quick vehicle sizes */
function getQuickCarSizesCallback( data ) {
	var quickCarSizeList = document.getElementById( 'quick_car_size' );
	// clear it down
	for( oldCarSize in quickCarSizeList ){
		// remove it
		quickCarSizeList.remove( oldCarSize );
	}
	// add a please select
	var opt = new Option( '- Please select -', '' );
	quickCarSizeList.options[ quickCarSizeList.options.length ] = opt;
	// and add the new car sizes
	for( vehicle in data['details']['vehicle'] ) {
		var value = data['details']['vehicle'][vehicle]['vehicleid'];
		var text = data['details']['vehicle'][vehicle]['detail'];
		var opt = new Option( text, value );
		quickCarSizeList.options[ quickCarSizeList.options.length ] = opt;
	}	
}

function calculateQuickCar() {
	// validate the form first
	var validate = new validateForm();
	// fuel type
	if( !document.getElementById('quick_car_fuel_petrol').checked && !document.getElementById('quick_car_fuel_diesel').checked && !document.getElementById('quick_car_fuel_hybrid').checked ) {
		validate.addCustomError( 'Fuel Type' );
	}
	if ( locale == 'us' ) {
		validate.checkNumeric( 'quick_calculator_car_fuel_economy', 'Fuel Economy' );
		validate.checkSelect( 'quick_calculator_car_fuel_economy_units', '', 'Fuel Economy Units' );
	} else {
		// engine size
		validate.checkSelect( 'quick_car_size', '', 'Engine Size' );
		var unitsSelect = document.getElementById('quick_car_unit');
		// always check distance
		validate.checkNumeric( 'quick_car_distance', unitsSelect.options[ unitsSelect.selectedIndex ].text );
	}
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// mileage needed to send
	var distance = document.getElementById('quick_car_distance').value;	
	// and make that request
	if ( locale == 'us' ) {
		var unit = document.getElementById('quick_calculator_car_fuel_economy').value;
		var unitsType = document.getElementById('quick_calculator_car_fuel_economy_units').value;
		var distanceType = document.getElementById('quick_car_unit').value;
		if ( document.getElementById('quick_car_fuel_petrol').checked ) {
			var fuelType = 'petrol';
		} else if ( document.getElementById('quick_car_fuel_diesel').checked ) {
			var fuelType = 'diesel';
		} else if ( document.getElementById('quick_car_fuel_hybrid').checked ) {
			var fuelType = 'lpg';
		}
		executeJSONRequest( 'us_quick_vehicle/' + version + '/calculator/?PartnerID=' + partnerId + '&Distance=' + distance + '&DistanceType=' + distanceType + '&Units=' + unit + '&UnitType=' + unitsType + '&FuelType=' + fuelType, 'calculateQuickCarCallback' );
	} else {
		// distance unit
		var unit = document.getElementById('quick_car_unit').value;
		// the vehicle type id
		var vehicleId = document.getElementById('quick_car_size').value;
		executeJSONRequest( 'quick_vehicle/' + version + '/calculator/?PartnerID=' + partnerId + '&Distance=' + distance + '&Units=' + unit + '&VehicleID=' + vehicleId + getReportingPeriodInfo(), 'calculateQuickCarCallback' );
	}
	// dont close the window yet
	return false;
}

function calculateQuickCarCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'quickCar', data['transactionid'], round( data['details']['vehicle'][0]['tonnes'], 2 ), data['details']['vehicle'][0]['type'], data['details']['vehicle'][0]['description'], data['details']['vehicle'][0]['miles'] );
	// set the fields back to their default
	document.getElementById('quick_car_fuel_petrol').checked = false;
	document.getElementById('quick_car_fuel_diesel').checked = false;
	document.getElementById('quick_car_fuel_hybrid').checked = false;
	// the engine size list
	var quickCarSizeList = document.getElementById( 'quick_car_size' );
	// clear it down
	for( oldCarSize in quickCarSizeList ){
		// remove it
		quickCarSizeList.remove( oldCarSize );
	}
	// add a please select
	var opt = new Option( '- Please select -', '' );
	quickCarSizeList.options[ quickCarSizeList.options.length ] = opt;
	// distance = zero
	document.getElementById( 'quick_car_distance' ).value = '0';
	// modifier is miles
	document.getElementById( 'quick_car_unit' ).selectedIndex = 0;
}

/* finalise any changes made to the main window */
function completeQuickCar( ) {
	// assign it to the main window
	document.getElementById('quick_car_co2').value = totalOffsets( 'quickCar' );
	// lastly, hide the freezeover
	hideCalculator( quickCarCalculatorBox );
}

/**
 * 
 * Public Transport Functions
 * -----------------------------
 * 
 **/

function initMainPublicTransportCalculator() {
	correctPNGBackground( 'publicTransportCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonPublicTransport' );
	initPublicTransportCalculator( 492, 576, true );
}
function initPartnerPublicTransportCalculator() {
	correctPNGBackground( 'publicTransportCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonPublicTransport', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initPublicTransportCalculator( 730, 395, positionOverlaysCenter );
}
function initPublicTransportCalculator( popupWidth, popupHeight, positionCenter ) {
	// fire off a request to get the list of public transport types
	executeJSONRequest( 'public_transport/' + version + '/transportlist/?PartnerID=' + partnerId, 'getPublicTransportListCallback' );
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('publicTransportCalculatorPopup').style.display = '';
	publicTransportCalculatorBox = 
			new YAHOO.widget.Panel("publicTransportCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	publicTransportCalculatorBox.beforeShowEvent.subscribe( loadPreviousPublicTransportTransactions, this );
	publicTransportCalculatorBox.render(document.body);
	if( showPublicTransportCalculatorOnLoad )
		publicTransportCalculatorBox.show();
}

function getPublicTransportListCallback( data ) {
	// get the list to populate
	var publicTransportList = document.getElementById( 'public_transport_type' );
	for( transport in data['details']['transport'] ) {
		var value = data['details']['transport'][transport]['type'] + ( ( data['details']['transport'][transport]['detail'] == '' ) ? '' : ' (' + data['details']['transport'][transport]['detail'] + ')' );
		var id = data['details']['transport'][transport]['transportid'];
		// use the value for both the "value and the display, any requests take the manufcaturers name
		var opt = new Option( value, id );
		publicTransportList.options[ publicTransportList.options.length ] = opt;
	}
}

function calculatePublicTransport() {
	// validate the form
	var validate = new validateForm();
	// transport
	validate.checkSelect( 'public_transport_type', '', 'Transport' );
	// distance
	distance = document.getElementById( 'public_transport_distance' ).value;
	if( !isNumeric( distance )) {
		validate.addCustomError( 'Distance must be a numeric value' );
	} else {
		if( distance <= 0 ) {
			validate.addCustomError( 'Distance must be greater than 0' );
		}
	}
	// no of journeys
	validate.checkNumeric( 'public_transport_journeys', '', 'No. of journeys' );
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	
	// get the details, already got the validated "distance" value from earlier
	var transportId = document.getElementById( 'public_transport_type' ).value;
	var qty = document.getElementById( 'public_transport_journeys' ).value;
	var unit = document.getElementById( 'public_transport_unit' ).value;
	// all ok, lets prepare the request
	executeJSONRequest( 'public_transport/' + version + '/calculator/?partnerID=1&TransportID=' + transportId + '&Distance=' + distance + '&Qty=' + qty + '&Units=' + unit + getReportingPeriodInfo(), 'calculatePublicTransportCallback' );
	// dont close the window yet
	return false;
}

function calculatePublicTransportCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'publicTransport', data['transactionid'], round( data['details']['transport'][0]['tonnes'], 2 ), data['details']['transport'][0]['type'], data['details']['transport'][0]['description'], data['details']['transport'][0]['miles'] );
	// set the fields back to their default
	document.getElementById( 'public_transport_type' ).selectedIndex = 0;
	document.getElementById( 'public_transport_distance' ).value = '1';
	document.getElementById( 'public_transport_unit' ).selectedIndex = 0;
	document.getElementById( 'public_transport_journeys' ).value = '1';	
}

/* finalise any changes made to the main window */
function completePublicTransport( ) {
	// assign it to the main window
	document.getElementById('public_transport_co2').value = totalOffsets( 'publicTransport' );
	// lastly, hide the freezeover
	hideCalculator( publicTransportCalculatorBox );
}


/**
 * 
 * Quick Flight Functions
 * ----------------------
 * 
 **/
function initMainQuickFlightCalculator() {
	correctPNGBackground( 'quickFlightCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonQuickFlight' );
	initQuickFlightCalculator( 492, 576, true );
}
function initPartnerQuickFlightCalculator() {
	correctPNGBackground( 'quickFlightCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonQuickFlight', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initQuickFlightCalculator( 730, 395, positionOverlaysCenter );
}
function initQuickFlightCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('quickFlightCalculatorPopup').style.display = '';
	quickFlightCalculatorBox = 
			new YAHOO.widget.Panel("quickFlightCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	quickFlightCalculatorBox.beforeShowEvent.subscribe( loadPreviousQuickFlightTransactions, this );
	quickFlightCalculatorBox.render(document.body);
	if( showQuickFlightCalculatorOnLoad )
		quickFlightCalculatorBox.show();
}

function calculateQuickFlight( haul ) {
	// validate the qty for the chosen flight type is numeric
	var validate = new validateForm();
	validate.checkNumeric( 'quick_flight_' + haul + '_quantity', '', 'Quantity' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	var qty = document.getElementById( 'quick_flight_' + haul + '_quantity' ).value;
	executeJSONRequest( 'quick_flight/' + version + '/calculator/?PartnerID=' + partnerId + '&Haul=' + haul + '&Qty=' + qty + getReportingPeriodInfo(), 'calculateQuickFlightCallback' );
	// dont close the window
	return false;
}

function calculateQuickFlightCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'quickFlight', data['transactionid'], round( data['details']['flight'][0]['tonnes'], 2 ), data['details']['flight'][0]['type'], 'x' + data['details']['flight'][0]['qty'], '' );
	// set the fields back to their default
	document.getElementById('quick_flight_do_quantity').value = '1';
	document.getElementById('quick_flight_sh_quantity').value = '1';
	document.getElementById('quick_flight_lo_quantity').value = '1';
}

/* finalise any changes made to the main window */
function completeQuickFlight( ) {
	// assign it to the main window
	document.getElementById('flights_co2').value = totalOffsets( 'quickFlight' );
	// lastly, hide the freezeover
	hideCalculator( quickFlightCalculatorBox );
}

/**
 * 
 * Freight Road Functions
 * ----------------------
 * 
 **/

function initMainFreightRoadCalculator() {
	correctPNGBackground( 'freightRoadCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonFreightRoad' );
	initFreightRoadCalculator( 492, 576, true );
}
function initPartnerFreightRoadCalculator() {
	correctPNGBackground( 'freightRoadCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonFreightRoad', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initFreightRoadCalculator( 730, 395, positionOverlaysCenter );
}
function initFreightRoadCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('freightRoadCalculatorPopup').style.display = '';
	freightRoadCalculatorBox = 
			new YAHOO.widget.Panel("freightRoadCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	freightRoadCalculatorBox.beforeShowEvent.subscribe( loadPreviousFreightRoadTransactions, this );
	freightRoadCalculatorBox.render(document.body);
	if( showFreightRoadCalculatorOnLoad )
		freightRoadCalculatorBox.show();
}

function getFreightRoadList() {
	// fire off a request to get the list of public transport types
	executeJSONRequest( 'freight/' + version + '/freightlist/?PartnerID=' + partnerId + '&type=Road', 'getFreightRoadListCallback' );
}

function getFreightRoadListCallback( data ) {
	getFreightListCallback( data, 'freight_road','Road' );
}

function calculateFreightRoad() {
	// validate the form first
	var validate = new validateForm();
	// freight type
	validate.checkSelect( 'freight_road_type', '', 'Transport' );
	// distance
	distance = document.getElementById( 'freight_road_distance' ).value.replace(' Miles', '' );
	if( !isNumeric( distance )) {
		validate.addCustomError( 'Distance must be a numeric value' );
	} else {
		if( distance <= 0 ) {
			validate.addCustomError( 'Distance must be greater than 0' );
		}
	}
	// freight weight
	validate.checkNumeric( 'freight_road_weight', 'Freight Weight' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// the freight id
	var freightId = document.getElementById('freight_road_type').value;
	// and weight
	var weight = document.getElementById('freight_road_weight').value;
	// and unit 
	var unit = document.getElementById('freight_road_unit').value;
	// and make that request
	executeJSONRequest( 'freight/' + version + '/calculator/?PartnerID=' + partnerId + '&FreightID=' + freightId + '&Distance=' + distance + '&Units=' + unit + '&qty=' + weight + getReportingPeriodInfo(), 'calculateFreightRoadCallback' );
	// dont close the window yet
	return false;
}

function calculateFreightRoadCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'freightRoad', data['transactionid'], round( data['details']['freight'][0]['tonnes'], 2 ), data['details']['freight'][0]['type'], data['details']['freight'][0]['description'], data['details']['freight'][0]['miles'] );
	// set the fields back to their default
	document.getElementById( 'freight_road_type' ).selectedIndex = 0;
	document.getElementById( 'freight_road_distance' ).value = '1';
	document.getElementById( 'freight_road_weight' ).value = '1';	
}

/* finalise any changes made to the main window */
function completeFreightRoad( ) {
	// assign it to the main window
	document.getElementById('freight_road_co2').value = totalOffsets( 'freightRoad' );
	// lastly, hide the freezeover
	hideCalculator( freightRoadCalculatorBox );
}

/**
 * 
 * Freight Air Functions
 * ---------------------
 * 
 **/
function initMainFreightAirCalculator() {
	correctPNGBackground( 'freightAirCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonFreightAir' );
	initFreightAirCalculator( 492, 576, true );
}
function initPartnerFreightAirCalculator() {
	correctPNGBackground( 'freightAirCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonFreightAir', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initFreightAirCalculator( 730, 395, positionOverlaysCenter );
}
function initFreightAirCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('freightAirCalculatorPopup').style.display = '';
	freightAirCalculatorBox = 
			new YAHOO.widget.Panel("freightAirCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	freightAirCalculatorBox.beforeShowEvent.subscribe( loadPreviousFreightAirTransactions, this );
	freightAirCalculatorBox.render(document.body);
	if( showFreightAirCalculatorOnLoad )
		freightAirCalculatorBox.show();
}

function getFreightAirList( ) {
	// fire off a request to get the list of public transport types
	executeJSONRequest( 'freight/' + version + '/freightlist/?PartnerID=' + partnerId + '&type=Air', 'getFreightAirListCallback' );
}

function getFreightAirListCallback( data ) {
	getFreightListCallback( data, 'freight_air','Air' );
}

function calculateFreightAir() {
	// validate the form first
	var validate = new validateForm();
	// freight type
	validate.checkSelect( 'freight_air_type', '', 'Transport' );
	// distance
	distance = document.getElementById( 'freight_air_distance' ).value.replace(' Miles', '' );
	if( !isNumeric( distance )) {
		validate.addCustomError( 'Distance must be a numeric value' );
	} else {
		if( distance <= 0 ) {
			validate.addCustomError( 'Distance must be greater than 0' );
		}
	}
	// freight weight
	validate.checkNumeric( 'freight_air_weight', 'Freight Weight' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// the freight id
	var freightId = document.getElementById('freight_air_type').value;
	// and weight
	var weight = document.getElementById('freight_air_weight').value;
	// and unit 
	var unit = document.getElementById('freight_air_unit').value;
	// and make that request
	executeJSONRequest( 'freight/' + version + '/calculator/?PartnerID=' + partnerId + '&FreightID=' + freightId + '&Distance=' + distance + '&Units=' + unit + '&qty=' + weight + getReportingPeriodInfo(), 'calculateFreightAirCallback' );
	// dont close the window yet
	return false;
}

function calculateFreightAirCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'freightAir', data['transactionid'], round( data['details']['freight'][0]['tonnes'], 2 ), data['details']['freight'][0]['type'], data['details']['freight'][0]['description'], data['details']['freight'][0]['miles'] );
	// set the fields back to their default
	document.getElementById( 'freight_air_type' ).selectedIndex = 0;
	document.getElementById( 'freight_air_distance' ).value = '1';
	document.getElementById( 'freight_air_weight' ).value = '1';	
}

/* finalise any changes made to the main window */
function completeFreightAir( ) {
	// assign it to the main window
	document.getElementById('freight_air_co2').value = totalOffsets( 'freightAir' );
	// lastly, hide the freezeover
	hideCalculator( freightAirCalculatorBox );
}

/**
 * 
 * Freight Sea Functions
 * ---------------------
 * 
 **/
function initMainFreightSeaCalculator() {
	correctPNGBackground( 'freightSeaCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonFreightSea' );
	initFreightSeaCalculator( 492, 576, true );
}
function initPartnerFreightSeaCalculator() {
	correctPNGBackground( 'freightSeaCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonFreightSea', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initFreightSeaCalculator( 730, 395, positionOverlaysCenter );
}
function initFreightSeaCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('freightSeaCalculatorPopup').style.display = '';
	freightSeaCalculatorBox = 
			new YAHOO.widget.Panel("freightSeaCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	freightSeaCalculatorBox.beforeShowEvent.subscribe( loadPreviousFreightSeaTransactions, this );
	freightSeaCalculatorBox.render(document.body);
	if( showFreightSeaCalculatorOnLoad )
		freightSeaCalculatorBox.show();
}

function getFreightSeaList( ) {
	// fire off a request to get the list of public transport types
	executeJSONRequest( 'freight/' + version + '/freightlist/?PartnerID=' + partnerId + '&type=Sea', 'getFreightSeaListCallback' );
}

function getFreightSeaListCallback( data ) {
	getFreightListCallback( data, 'freight_sea','Sea' );
}

function calculateFreightSea() {
	// validate the form first
	var validate = new validateForm();
	// freight type
	validate.checkSelect( 'freight_sea_type', '', 'Transport' );
	// distance
	distance = document.getElementById( 'freight_sea_distance' ).value.replace(' Miles', '' );
	if( !isNumeric( distance )) {
		validate.addCustomError( 'Distance must be a numeric value' );
	} else {
		if( distance <= 0 ) {
			validate.addCustomError( 'Distance must be greater than 0' );
		}
	}
	// freight weight
	validate.checkNumeric( 'freight_sea_weight', 'Freight Weight' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// the freight id
	var freightId = document.getElementById('freight_sea_type').value;
	// and weight
	var weight = document.getElementById('freight_sea_weight').value;
	// and unit 
	var unit = document.getElementById('freight_sea_unit').value;
	// and make that request
	executeJSONRequest( 'freight/' + version + '/calculator/?PartnerID=' + partnerId + '&FreightID=' + freightId + '&Distance=' + distance + '&Units=' + unit + '&qty=' + weight + getReportingPeriodInfo(), 'calculateFreightSeaCallback' );
	// dont close the window yet
	return false;
}

function calculateFreightSeaCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'freightSea', data['transactionid'], round( data['details']['freight'][0]['tonnes'], 2 ), data['details']['freight'][0]['type'], data['details']['freight'][0]['description'], data['details']['freight'][0]['miles'] );
	// set the fields back to their default
	document.getElementById( 'freight_sea_type' ).selectedIndex = 0;
	document.getElementById( 'freight_sea_distance' ).value = '1';
	document.getElementById( 'freight_sea_weight' ).value = '1';	
}

/* finalise any changes made to the main window */
function completeFreightSea( ) {
	// assign it to the main window
	document.getElementById('freight_sea_co2').value = totalOffsets( 'freightSea' );
	// lastly, hide the freezeover
	hideCalculator( freightSeaCalculatorBox );
}


/**
 * 
 * Additional Carbon Functions
 * ---------------------------
 * 
 **/
function initMainAdditionalCarbonCalculator() {
	correctPNGBackground( 'additionalCarbonCalculatorPopupBg', '/custom/images/calculators/business/general.png' );
	correctPNG( 'popupCloseButtonAdditionalCarbon' );
	initAdditionalCarbonCalculator( 492, 576, true );
}
function initPartnerAdditionalCarbonCalculator() {
	correctPNGBackground( 'additionalCarbonCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/businesscalc.png' );
	correctPNGBackground( 'popupCloseButtonAdditionalCarbon', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initAdditionalCarbonCalculator( 730, 395, positionOverlaysCenter );
}
function initAdditionalCarbonCalculator( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('additionalCarbonCalculatorPopup').style.display = '';
	additionalCarbonCalculatorBox = 
			new YAHOO.widget.Panel("additionalCarbonCalculatorPopup",  
											{ 
												width: popupWidth + "px", height: popupHeight + "px", fixedcenter:positionCenter, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	additionalCarbonCalculatorBox.beforeShowEvent.subscribe( loadPreviousAdditionalCarbonTransactions, this );
	additionalCarbonCalculatorBox.render(document.body);
	if( showAdditionalCarbonCalculatorOnLoad )
		additionalCarbonCalculatorBox.show();
}

function getAdditionalList() {
	executeJSONRequest( 'additional/' + version + '/itemlist/?PartnerID=' + partnerId, 'getAdditionalListCallback' );	
}

function getAdditionalListCallback( data ) {
	// get the list to populate
	var itemList = document.getElementById( 'additional_carbon_type' );
	// remove all the items first
	// empty the current vehicle list 
	for( var oldItem in itemList ){
		// remove it
		itemList.remove( oldItem );
	}
	// add the new options starting with 
	var opt = new Option( '- Type -', '' );
	itemList.options[ itemList.options.length ] = opt;
	for( var item in data['details']['items'] ) {
		var value = data['details']['items'][item]['name'];
		var id = data['details']['items'][item]['itemid'];
		var opt = new Option( value, id );
		itemList.options[ itemList.options.length ] = opt;
	}	
}


function calculateAdditionalCarbon() {
	// validate the form first
	var validate = new validateForm();
	// fuel type
	validate.checkSelect( 'additional_carbon_type', '', 'Fuel Type' );
	// tonnes
	validate.checkNumeric( 'additional_carbon_amount', 'Amount' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// the fuel type id
	var fuelTypeId = document.getElementById('additional_carbon_type').value;
	// tonnes
	var quantity = document.getElementById('additional_carbon_amount').value;
	// and make that request
	executeJSONRequest( 'additional/' + version + '/calculator/?PartnerID=' + partnerId + '&itemID=' + fuelTypeId + '&qty=' + quantity + getReportingPeriodInfo(), 'calculateAdditionalCarbonCallback' );
	// dont close the window yet
	return false;
}

function calculateAdditionalCarbonCallback( data ) {
	// add this item to the business transactions list
	addBusinessItem( 'additionalCarbon', data['transactionid'], round( data['details']['additional'][0]['tonnes'], 2 ), data['details']['additional'][0]['item'], data['details']['additional'][0]['qty'], '' );
	// set the fields back to their default
	document.getElementById( 'additional_carbon_type' ).selectedIndex = 0;
	document.getElementById( 'additional_carbon_amount' ).value = '0';
}

/* finalise any changes made to the main window */
function completeAdditionalCarbon( ) {
	// assign it to the main window
	document.getElementById('additional_carbon_co2').value = totalOffsets( 'additionalCarbon' );
	// lastly, hide the freezeover
	hideCalculator( additionalCarbonCalculatorBox );
}
