/* version number */
var version = 'v1.0';
var projectVersion = 'v1.1';
var companyName = 'Carbon Advice Group';
/* all the flags for showing popups on load */
var showCarCalculatorOnLoad = false;
var showFlightCalculatorOnLoad = false;
var showHomeCalculatorOnLoad = false;
var showChooseProjectOnLoad = false;
var showChooseCountryOnLoad = false;
var showStartScreenOnLoad = false;
var showmidSectionExplanationOnLoad = false;
var showCheckoutSliderBoxOnLoad = false;
var showPlatformTicketsOnLoad = true;
/* name for the cookie which will store our list of transaction ids to the users browser */
var transactionCookieName = 'transactionList';
/* name for the cookie which will store our chosen project id to the users browser */
var projectIdCookieName = 'projectId';
/* name for the cookie which will store our home calculator info */
var domesticCalcCookieName = 'domesticCalcDetails';
/* name for the cookie which stores the currently selected currency */
var currencyCookieName = 'selectedCurrency';
/* name for the cookie which stores the modifier for the sliding scale at the checkout */
var checkoutTotalModifierCookieName = 'checkoutModifierPercent';
/* name for the cookie which stores whether we have previously entered details into the platform tickets */
var platformTicketCookieName = 'platformTicketCompleted';
/* default currency */
var currentCurrency = 'GBP';
/* stores the callbackFunction of the task currently being requested */
var callbackFunction = '';
/* an element to store items to be processed */
var calculatorItems = new Array();
/* no data */
var basketData = null;
/* project info */
var projectInfo = null;
/* does the chosen project have giftaid */
var giftaid = 0;
/*  temporary home units info */
var calculatorHomeInfo = '';
/* transfer protocol */
var transferProtocol = 'http';
/* custom drop down we are currently viewing */
var currentCustomDropDown = '';
/* flag to indicated whether an error has occured */
var errorOccured = false;
/* cookie name for the default country */
var defaultCountryCookieName = 'defaultCountry';
/* stores the default country we redirect the user to when first loading the site */
var defaultCountry = '';
/* dimensions of the partner schemes (default to 'safe' dimensions) */
var schemeWidth = '100%';
var schemeHeight = '100%';
var positionOverlaysCenter = true;
var transactionsAdded = new Array();
var doNotChangeCheckoutStage = false;
var partnerDetails = new Array(); // global to store all partner details
/* name of cookie which stores the keywords a user used to find the site */
var keywordsCookieName = 'keywordsUsed';
/* name of cookie which stores the keywords a user used to find the site */
var referrerCookieName = 'originalReferrer';
/* flag to denote whether this partner is a subscriber to a carboncore scheme */
var isCarbonCoreSubscriber = false;
/* currentPage denotes what page we are currently on (used in the partner scheme) */
var currentPage = '';
/* currentPartnerPageHasLinks - does the current partner page have a left hand nav we need to hide if there is custom text? */
var currentPartnerPageHasLinks = false;
/* partnerSignupURL - url to the partner signup process */
var partnerSignupURL = '';
/* showPlatformTicketPopupOnThisPage - flag to specify whether we need to work out whether to show the platform tickets on the current page */
var showPlatformTicketPopupOnThisPage = false;
/* platformTicketOnComplete - callback function that can be set to perform custom operations after a platform ticket has been entered */
var platformTicketOnComplete = false;
/* are we on dev or live? */
var apiHost = ( ( location.hostname.indexOf('carbonadvicegroup') == -1 ) || ( location.hostname.indexOf('dev') > -1 ) ) ? 'devapi.carbonadvicegroup.com' : 'api.carbonadvicegroup.com';

/**
 * 
 * General Functions
 * -----------------
 * 
 **/

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

function goToPage( page ) {
	document.location = '/' + locale + '' + basePath + '' + page;
}

function str_pad( input, pad_length, pad_string, pad_type ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'
 
    var half = '', pad_to_go;
 
    var str_pad_repeater = function(s, len) {
        var collect = '', i;
 
        while(collect.length < len) collect += s;
        collect = collect.substr(0,len);
 
        return collect;
    };
 
    input += '';
 
    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }
 
    return input;
}

/*
Sometimes we need an ID of a locale (ie 1), sometimes we need the country code (ie US),
and sometimes we need the full country name (ie United States).  Gooooooo Alan.
getLocaleId returns the numeric ID of the user's current country
*/
function getLocaleId() {
	switch ( locale ) {
		case 'us':
			return 1;
		case 'au':
			return 2;
		default:
			// uk
			return 0;
	}
}
/*
getLocaleId returns the currency symbol for the user's current country
*/
function getLocaleCurrency() {
	switch ( locale ) {
		case 'us':
			return '$';
		case 'au':
			return '$';
		default:
			// uk
			return '&pound;';
	}
}

/*
getLocaleId returns the currency iso for the user's current country
*/
function getLocaleCurrencyISO() {
	switch ( locale ) {
		case 'us':
			return 'USD';
		case 'au':
			return 'AUD';
		default:
			// uk
			return 'GBP';
	}
}

function getKeywordsUsed() {
	return getCookie( keywordsCookieName );
}

function getOriginalReferrer() {
	return getCookie( referrerCookieName );
}

function executeJSONRequest( requestURI, myCallbackFunction, localeOverride ) {
	try {
		//alert( "request = " + requestURI + "&callback=" + myCallbackFunction );
		// create a script element and add the necessary attributes
		if ( typeof localeOverride == 'undefined' ) {
			var thisLocale = getLocaleId();
		} else {
			var thisLocale = localeOverride;
		}
		var scrptE = document.createElement("script");
		scrptE.setAttribute("type", "text/javascript");
		//console.log( transferProtocol + "://" + apiHost + "/json/" + requestURI + "&callback=" + myCallbackFunction + '&LocaleID=' + getLocaleId() );
		scrptE.setAttribute("src", transferProtocol + "://" + apiHost + "/json/" + requestURI + "&callback=" + myCallbackFunction + '&LocaleID=' + thisLocale + '&Keywords=' + getKeywordsUsed() + '&Referrer=' + getOriginalReferrer() );
		// append to the head of the html page
		document.getElementsByTagName("head")[0].appendChild(scrptE);
	} catch ( e ) {
		alert( 'Error in communication: ' + e );
	}
}

/* 
sigh, this works differently again.. lets add another call  
notice no /JSON/ in the request this time
*/
function executeGeneralRequest( requestURI, myCallbackFunction ) {
	try {
		//alert( "request = " + requestURI + "&callback=" + myCallbackFunction );
		// create a script element and add the necessary attributes
		var scrptE = document.createElement("script");
		scrptE.setAttribute("type", "text/javascript");
		//alert( transferProtocol + "://" + apiHost + "/general/" + requestURI + "&callback=" + myCallbackFunction + '&LocaleID=' + getLocaleId() );
		scrptE.setAttribute("src", transferProtocol + "://" + apiHost + "/general/" + requestURI + "&callback=" + myCallbackFunction + '&LocaleID=' + getLocaleId() );
		// append to the head of the html page
		document.getElementsByTagName("head")[0].appendChild(scrptE);
	} catch ( e ) {
		alert( 'Error in communication: ' + e );
		errorOccured = true;
	}
}

function executeRSSRequest( requestURI, myCallbackFunction ) {
	try {
		//alert( "request = " + requestURI + "&callback=" + myCallbackFunction );
		// create a script element and add the necessary attributes
		var scrptE = document.createElement("script");
		scrptE.setAttribute("type", "text/javascript");
		scrptE.setAttribute("src", transferProtocol + "://" + apiHost + "/rss/" + requestURI + "&callback=" + myCallbackFunction + '&LocaleID=' + getLocaleId() );
		// append to the head of the html page
		document.getElementsByTagName("head")[0].appendChild(scrptE);
	} catch ( e ) {
		alert( 'Error in communication: ' + e );
	}
}

/* this always gets called on success of a request */
function CarbonAdviceGroupCallback( data ) {
	// check the array for an error
	if( data['root']['errornumber'] == "1" ) {
		// if its a checkout request, show the alert
		alert( "Error occurred: " + data['root']['message'] );
	} else {
		// we sent a callback with the request, ensure we call the correct results
		eval( data['root']['callback'] + "(data['root']);" );
	}
}

/* totals the tonnage for any given transaction set */
function getTransactionsTotalTonnage( data ) {
	// calculate the tonnage of the projects
	var totalTonnage = 0;
	for ( transaction in data ) {
		totalTonnage += parseFloat( data[transaction]['tonnes'] );
	}
	return round( totalTonnage, 2 );
}

/**
 * 
 * Cookie/Transaction storing Functions
 * ------------------------------------
 * 
 **/

/* get the list of transactions from the cookie */
function updateTransactionList( data ) {
	// try and get the current cookie
	var transactionIds = getTransactionList();
	// add the new id to the list
	transactionIds.push( data['transactionid'] );
	// set the list of transactions to the cookie
	setTransactionList( transactionIds );
}
/* reassigns the array of transaction ids to the cookie */
function setTransactionList( transactionIds ) {
	var newTransactionList = '';
	// recreate the array
	for( i in transactionIds ) {
		if( i > 0 ) {
			newTransactionList += ',';
		}
		newTransactionList += transactionIds[i];
	}
	// reassign the cookie
	setCookie( transactionCookieName, newTransactionList );
}
/* returns an array of transaction ids from the cookie */
function getTransactionList() {
	var cookieData = getCookie( transactionCookieName );
	// whack it into an array if its ot already
	if( typeof cookieData != 'object' && cookieData.length > 0 ) {
		return cookieData.split(',');
	} else {
		return new Array();
	}
}
/* removes the passed transactionId from the list */ 
function removeTransaction( transactionId ) {
//	alert('removeTransaction ' + transactionId);
	var newTransactionArray = new Array();
	oldTransactionArray = getTransactionList();
	// remove the one we dont want
	var count = 0;
	for( var transaction in oldTransactionArray ) {
		if( oldTransactionArray[transaction] != transactionId ) {
			// add to new array
			newTransactionArray[count] = oldTransactionArray[transaction];
			count++; // increment count
		} else {
			removeBusinessTransactionList( transactionId );
			removeBusinessTonnageList( 'additionalCarbon', transactionId );
		}
	}
	// set the updated transaction list
	setTransactionList( newTransactionArray );
}

/* gets the requested cookie info */
function getCookie( cookieName ) {
	var start = document.cookie.indexOf( cookieName + "=" );
	var len = start + cookieName.length + 1;
	if ( ( !start ) && ( cookieName != document.cookie.substring( 0, cookieName.length ) ) ) {
		return null;
	}
	if ( start == -1 ) {
		return new Array();
	}
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expireDays ) {
	var expireString = '';
	if ( typeof expireDays == 'undefined' ) {
		expireDays = 365;
	}
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + expireDays );
	expireString = ';path=/;expires=' + exdate.toGMTString()
	document.cookie = name + "=" + escape( value ) + expireString;
}

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

/* prepare the calculator for action */
function initMainCarCalculator() {
	// Initialize the temporary Panel to display while waiting for external content to load
	correctPNGBackground( 'carCalculatorPopupBg', '/custom/images/calculators/car/background.png' );
	correctPNG( 'popupCloseButton' );
	initCarCalculator( 477, 536, true );
}
function initPartnerCarCalculator() {
	// Initialize the temporary Panel to display while waiting for external content to load
	correctPNGBackground( 'carCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/carcalc.png' );
	correctPNGBackground( 'popupCloseButton', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initCarCalculator( 730, 395, positionOverlaysCenter );
}
function initCarCalculator( popupWidth, popupHeight, positionCenter ) {
	// fire off a request to get the list of manufacturers
	if ( locale != 'us' ) {
		executeJSONRequest( 'vehicle/' + version + '/manufacturers/?PartnerID=' + partnerId, 'getCarManufacturerListCallback' );
	}
	document.getElementById('carCalculatorPopup').style.display = '';
	carCalculatorBox = 
			new YAHOO.widget.Panel("carCalculatorPopup",  
											{ 
												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}
											} 
										);
	carCalculatorBox.render(document.body);
	if( showCarCalculatorOnLoad )
		carCalculatorBox.show();
}
/* populates the list of car manufacturers available */
function getCarManufacturerListCallback( data ) {
	// get the list to populate
	var manufacturerList = document.getElementById( 'optionDropDown_carManufacturers' );
	// empty the current menufacturer list 
	manufacturerList.innerHTML = '';
	// add the actual vehicles
	var html = '';
	for( manufacturer in data['details']['manufacturers'] ) {
		// use the value for both the value and the display, any requests take the manufacturers name
		html += '<a href="javascript:getManufacturerVehicleList(\'' + data['details']['manufacturers'][manufacturer]['manufacturer'] + '\');">' + data['details']['manufacturers'][manufacturer]['manufacturer'] +'</a>'
	}
	manufacturerList.innerHTML = html;
}

/* fires a query to ge all the vehicles for the current manufacturer */
function getManufacturerVehicleList( manufacturer ) {
	// setup the default panel
	document.getElementById('optionText_carManufacturer').innerHTML = manufacturer;
	document.getElementById('calculator_car_manufacturer').value = manufacturer;
	executeJSONRequest( 'vehicle/' + version + '/vehiclelist/?PartnerID=' + partnerId + '&Manufacturer=' + manufacturer, 'getManufacturerVehicleListCallback' );
}

/* populates a list of vehicles for the passed manufacturer */
function getManufacturerVehicleListCallback( data ) {
	// hide the previous drop down if one is open
	hideCustomDropDown();
	// get the list to populate
	var vehicleList = document.getElementById( 'optionDropDown_carModels' );
	// empty the current vehicle list 
	vehicleList.innerHTML = '';
	// and the actual vehicles
	var html = '';
	for( vehicle in data['details']['vehicle'] ) {
		html += '<a href="javascript:selectCarModel(\'' + data['details']['vehicle'][vehicle]['vehicleid'] + '\', \'' + data['details']['vehicle'][vehicle]['name'] + ' ' + data['details']['vehicle'][vehicle]['detail'] + '\');">' + data['details']['vehicle'][vehicle]['name'] + ' ' + data['details']['vehicle'][vehicle]['detail'] +'</a>'
	}
	vehicleList.innerHTML = html;
}

function showCustomDropDown( element, appendTo ) {
	hideCustomDropDown();
	element.style.display = '';
	var iframe = document.createElement('iframe');
	iframe.src = 'about:blank';
	iframe.style.position = 'absolute';
	iframe.frameborder = 0;
	iframe.scrolling = 'no';
	iframe.style.border = 'none';
	iframe.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
	iframe.style.MozOpacity = 0;
	iframe.style.opacity = 0;
	iframe.id = 'menuIframe';
	iframe.style.zIndex = 1000;
	element.style.zIndex = 1001;
	iframe.style.left = element.offsetLeft + 'px';
	iframe.style.top = element.offsetTop + 'px';
	iframe.style.width = element.offsetWidth + 'px';
	iframe.style.height = element.offsetHeight + 'px';
	iframe.style.display = '';
	// start listening for a click outside of this menu so we can close it
	currentCustomDropDown = element.id;
	appendTo.appendChild( iframe );
	setTimeout( 'startListening()', 1000 );
}

function startListening() {
	YAHOO.util.Event.addListener( 'mainBody', 'click', hideCustomDropDown );
}
function stopListening() {
	YAHOO.util.Event.removeListener( 'mainBody', 'click', hideCustomDropDown );
}

function hideCustomDropDown() {
	if ( currentCustomDropDown != '' ) {
		document.getElementById( currentCustomDropDown ).style.display = 'none';
		if ( document.getElementById( 'menuIframe' ) ) {
			document.getElementById( 'menuIframe' ).parentNode.removeChild( document.getElementById( 'menuIframe' ) );
		}
		stopListening();
	}
}

function showCurrencyOptions() {
	var element = document.getElementById('optionDropDown_currency');
	showCustomDropDown( element, document.getElementById('checkoutSliderPopupContent') );
}
function showCarManufacturerOptions() {
	var element = document.getElementById('optionDropDown_carManufacturers');
	showCustomDropDown( element, document.getElementById('carCalculatorPopup') );
}
function showCarModelOptions() {
	var element = document.getElementById('optionDropDown_carModels');
	showCustomDropDown( element, document.getElementById('carCalculatorPopup') );
}
function selectCarModel( modelId, model ) {
	document.getElementById('optionText_carModel').innerHTML = model;
	document.getElementById('calculator_car_model').value = modelId;
	hideCustomDropDown();
}
function selectCheckoutCurrency( currencyString, currency ) {
	document.getElementById('optionText_currency').innerHTML = currencyString;
	setCookie( currencyCookieName, currency );
	updateCurrentCurrency()
	initSliderVars( false );
	hideCustomDropDown();
}

/* hides the car calculator */
function hideCarCalculator( ) {
	if( typeof carCalculatorBox != "undefined" )
		carCalculatorBox.hide();
}
/* shows the car calculator */
function showCarCalculator() {
	// set the fields to default values
	clearCarCalculator();
	// clear the password field
	if( typeof carCalculatorBox != "undefined" )
		carCalculatorBox.show();
}
/* clear down the car calculator elements */
function clearCarCalculator() {
	document.getElementById('calculator_car_manufacturer').selectedIndex = 0;
	document.getElementById('calculator_car_model').selectedIndex = 0;
	document.getElementById('calculator_car_mileage').value = '10000';
}
/* add the current car details to the storage array */
function addCar() {
	// check if everythings been populated
	var validate = new validateForm();
	var manufacturer = document.getElementById('calculator_car_manufacturer');
	if( manufacturer.value == '-' ) {
		// unknown manufacturer
		validate.checkSelect( 'calculator_car_type', '', 'Vehicle Type' );
	} else {
		validate.checkSelect( 'calculator_car_manufacturer', '', 'Manufacturer' );
		// check unknown hasnt been selected
		validate.checkSelect( 'calculator_car_model', '', 'Model' );
	}
	validate.checkNumeric( 'calculator_car_mileage', 'Mileage' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// it has, store the details
	var carDetails = new Array();
	carDetails['vehicleId'] = document.getElementById('calculator_car_model').value;
	carDetails['mileage'] = document.getElementById('calculator_car_mileage').value;
	// add it to the array
	calculatorItems.push( carDetails );
	// update the current cars text
	// reset the calculator
	clearCarCalculator();
}

/* user clicked "Done", request the project info */
function calculateCar() {
	// validate the form first
	var validate = new validateForm();
	validate.checkSelect( 'calculator_car_manufacturer', '', 'Manufacturer' );
	// if its a manufacturer we use standard calculator
	validate.checkSelect( 'calculator_car_model', '', 'Model' );
	var unitsSelect = document.getElementById('calculator_car_unit');
	// always check distance
	validate.checkNumeric( 'calculator_car_mileage', unitsSelect.options[ unitsSelect.selectedIndex ].text );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}

	// the vehicle model id
	var vehicleId = document.getElementById('calculator_car_model').value;
	// mileage needed to send
	var distance = document.getElementById('calculator_car_mileage').value;	
	// distanc unit
	var unit = unitsSelect.value;
	// vehicle reg (NON MANDATORY, needs to be saved against the transaction)
	if( document.getElementById('calculator_car_registration').value != '' && document.getElementById('calculator_car_registration').value != '- Your Registration -' ) {
		var vehicleReg = '&VehicleReg=' + document.getElementById('calculator_car_registration').value;
	} else {
		var vehicleReg = '';
	}
	executeJSONRequest( 'vehicle/' + version + '/calculator/?PartnerID=' + partnerId + '&Distance=' + distance + '&Units=' + unit + '&VehicleID=' + vehicleId + vehicleReg, 'calculateCarCallback' );
	return false;
}
/* what do we do with the car data */
function calculateCarCallback( data ) {
	// update the saved transaction list
	updateTransactionList( data );
	// update the choose project panel
	updateChooseProject( 'car', round( data['tonnes'], 2 ), data);
	// hide the calculator
	hideCarCalculator();
	// now show the choose project panel
	showChooseProject( );
}

/**
 * 
 * Flight Functions
 * ----------------
 * 
 **/

/* prepare the calculator for action */
function initMainFlightCalculator() {
	correctPNGBackground( 'flightCalculatorPopupBg', '/custom/images/calculators/flight/background.png' );
	correctPNG( 'popupCloseButton' );
	initFlightCalculator( 677, 636, true );
}
function initPartnerFlightCalculator() {
	correctPNGBackground( 'flightCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/flightcalc.png' );
	correctPNGBackground( 'popupCloseButton', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initFlightCalculator( 730, 395, positionOverlaysCenter );
}
function initFlightCalculator( popupWidth, popupHeight, positionCenter ) {
	// IATA populated from a local js file iata_data.js (see scripts folder)
	document.getElementById('flightCalculatorPopup').style.display = '';
	flightCalculatorBox = 
			new YAHOO.widget.Panel("flightCalculatorPopup",  
											{ 
												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}
											} 
										);
	flightCalculatorBox.render(document.body);
	if( showFlightCalculatorOnLoad )
		showFlightCalculator();
}
/* hides the flight calculator */
function hideFlightCalculator( ) {
	if( typeof flightCalculatorBox != "undefined" )
		flightCalculatorBox.hide();
}
/* shows the flight calculator */
function showFlightCalculator() {
	// set the fields to default values
	if ( locale == 'us' ) {
		var fromCode = 'JFK';
		var fromValue = 'JOHN F KENNEDY INTERNATIONAL, NEW YORK';
	} else {
		var fromCode = 'LHR';
		var fromValue = 'HEATHROW, LONDON';
	}
	document.getElementById('calculator_flight_iata_from').value = fromCode;
	document.getElementById('calculator_flight_iata_from_list').value = fromValue;
	if( typeof flightCalculatorBox != "undefined" )
		flightCalculatorBox.show();
}


function getIATA( sQuery ) {
	var result = new Array();
	//search for sQuery in iataData
	for( var i in iataData ) {
		if( encodeURI(iataData[i].name.toLowerCase()).indexOf(sQuery.toLowerCase()) !== -1 || encodeURI(iataData[i].location.toLowerCase()).indexOf(sQuery.toLowerCase()) !== -1 || encodeURI(iataData[i].iata.toLowerCase()).indexOf(sQuery.toLowerCase()) !== -1 ) {
			result.push( [ iataData[i].name+', '+iataData[i].location, iataData[i].iata ] );
		}
	}
	return result;
}

/* prepares the FROM for querying */
function initFromIATASearch() {
	var userDataSource = new YAHOO.widget.DS_JSFunction( getIATA );
	userDataSource.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
	userDataSource.queryMatchContains = true;  
	var autoCompleteUser = new YAHOO.widget.AutoComplete("calculator_flight_iata_from_list","userSearchContainerFrom", userDataSource, { forceSelection : false, useShadow : false, allowBrowserAutocomplete : false, animVert : true, allowBrowserAutocomplete : false, useIFrame : true } );
	autoCompleteUser.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) {   
		searching = true;
		var pos = YAHOO.util.Dom.getXY(oTextbox);   
		pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight;   
		YAHOO.util.Dom.setXY(oContainer,pos);   
		return true;
	};  
	autoCompleteUser.itemSelectEvent.subscribe( function( oSelf , elItem , aResultItem )  {
		// assign the iata to the hidden field
		document.getElementById('calculator_flight_iata_from').value = elItem[2][1];
	})
}
/* prepares the TO for querying */
function initToIATASearch() {
	var userDataSource = new YAHOO.widget.DS_JSFunction( getIATA );
	userDataSource.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
	userDataSource.queryMatchContains = true;  
	var autoCompleteUser = new YAHOO.widget.AutoComplete("calculator_flight_iata_to_list","userSearchContainerTo", userDataSource, { forceSelection : false, useShadow : false, allowBrowserAutocomplete : false, animVert : true, allowBrowserAutocomplete : false, useIFrame : true } );
	autoCompleteUser.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) {   
		searching = true;
		var pos = YAHOO.util.Dom.getXY(oTextbox);   
		pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight;   
		YAHOO.util.Dom.setXY(oContainer,pos);   
		return true;
	};
	autoCompleteUser.itemSelectEvent.subscribe( function( oSelf , elItem , aResultItem )  {
		document.getElementById('calculator_flight_iata_to').value = elItem[2][1];
	}) 
}
	
function calculateFlight() {
	// validate the form first
	var validate = new validateForm();
	// airports
	validate.checkText( 'calculator_flight_iata_from', 'Flying from' );
	// class
	validate.checkSelect( 'calculator_flight_class_out', '', 'Class' );
	validate.checkText( 'calculator_flight_iata_to', 'Flying to' );
	// passengers
	validate.checkNumeric( 'calculator_flight_passengers', 'Passengers' );
	// quantity
	validate.checkNumeric( 'calculator_flight_qty', 'Quantity' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// data ok, get the details from the form and request the results
	var iata_from = document.getElementById('calculator_flight_iata_from').value;
	var iata_to = document.getElementById('calculator_flight_iata_to').value;
	var class_out = document.getElementById('calculator_flight_class_out').value;
	var passengers = document.getElementById('calculator_flight_passengers').value;
	var qty = document.getElementById('calculator_flight_qty').value;
	// send the request
	var travelClass = class_out;
	var iata = iata_from + ',' + iata_to;
	var noPassengers = passengers;
	// if its a return trip, add on the extra data
	if( document.getElementById('trip_type_return').checked ) {
		// according to Matthew, assume the return class is the same as out class
		travelClass += ',' + class_out;
		iata += ',' + iata_from;
		// need to send the passenger count for each leg (so comma separated)....
		noPassengers += ',' + passengers
	}
	// do that funky requesting action
	executeJSONRequest( 'flight/' + version + '/calculator/?partnerID=' + partnerId + '&class=' + travelClass + '&IATA=' + iata + '&Passengers=' + noPassengers + '&qty=' + qty, 'calculateFlightCallback' );
	return false;
}

function calculateFlightCallback( data ) {
	// update the saved transaction list
	updateTransactionList( data );
	// always have a first journey
	var totalTonnage = data['details']['journey'][0]['tonnes'];
	// check if we have a return journey
	if( data['details']['journey'][1] ) {
		// we do, add it to the first one
		totalTonnage = parseFloat( totalTonnage ) + parseFloat( data['details']['journey'][1]['tonnes'] );
	}
	// update the choose project panel
	updateChooseProject( 'flight', round( totalTonnage, 2 ), data);
	// hide the calculator
	hideFlightCalculator();
	// now show the choose project panel
	showChooseProject( );
}

/**
 * 
 * Quick Flight Functions
 * ----------------------
 * 
 **/

function quickCalculateFlight( destination ) {
	// make sure we have a valid quantity
	validate = new validateForm();
	validate.checkNumeric( 'flight_quantity', 'Number of return flights' );
	if ( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// using the main flight calculator (quick flight is used for business cal only
	// we're going to assume a certain amount of information (provided by MS)
	// class, always economy
	var travelClass = 'EC,EC';
	// 1 passenger, both directions
	var noPassengers = '1,1';
	// iata (from -> to -> from) return flight, always use London Gatwick as the base
	/// get the right destination iata
	// default to Domestic
	var iata_to = '';
	switch( destination ) {
		case 'domestic':
			iata_to = 'EDI'; // Edinburgh
			break;
		case 'european':
			iata_to = 'MAD'; // Madrid
			break;
		case 'northamericaeast':
			iata_to = 'JFK'; // New York
			break;
		case 'northamericawest':
			iata_to = 'LAX'; // Los Angeles
			break;
		case 'middleeast':
			iata_to = 'DXB'; // Dubai
			break;
		case 'asiapacific':
			iata_to = 'BKK'; // Bangkok
			break;
		case 'australasia':
			iata_to = 'SYD'; // Sydney
			break;
		default:
			iata_to = 'EDI'; // default to Edinburgh
			break;
	}
	var iata = 'LGW,' + iata_to + ',LGW';
	var qty = document.getElementById('flight_quantity').value;
	// NOTE: we'll use the main flight callback to deal with the results
	executeJSONRequest( 'flight/' + version + '/calculator/?partnerID=' + partnerId + '&class=' + travelClass + '&IATA=' + iata + '&Passengers=' + noPassengers + '&qty=' + qty, 'calculateFlightCallback' );
	return false;
}

/**
 * 
 * Home Functions
 * --------------
 * 
 **/

/* prepare the calculator for action */
function initMainHomeCalculator() {
	// initialize the temporary Panel to display while waiting for external content to load
	correctPNGBackground( 'homeCalculatorPopupBg', '/custom/images/calculators/home/background.png' );
	correctPNG( 'popupCloseButton' );
	initHomeCalculator( 492, 580, true );
}
function initPartnerHomeCalculator() {
	// initialize the temporary Panel to display while waiting for external content to load
	correctPNGBackground( 'homeCalculatorPopupBg', '/partners/scheme' + schemeId + '/images/overlays/homecalc.png' );
	correctPNGBackground( 'popupCloseButton', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initHomeCalculator( 730, 395, positionOverlaysCenter );
}
function initHomeCalculator( popupWidth, popupHeight, positionCenter ) {
	// set info back to mt string, a new one will need to be created for this calc instance
	calculatorHomeInfo = '';
	// fire off a request to get the list of dwelling types, if we're not in the us
	if ( locale == 'uk' ) {
		executeJSONRequest( 'domestic_energy/' + version + '/dwellings/?PartnerID=' + partnerId, 'getDwellingTypesCallback' );
	} else if ( locale == 'us' ) {
	// get the states for the drop-down
		getStates( 'populateHomeCalcStates' );
	}
	document.getElementById('homeCalculatorPopup').style.display = '';
	homeCalculatorBox = 
			new YAHOO.widget.Panel("homeCalculatorPopup",  
											{ 
												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}
											} 
										);
	homeCalculatorBox.render(document.body);
	if( showHomeCalculatorOnLoad )
		homeCalculatorBox.show();
}
/* hides the home calculator */
function hideHomeCalculator( ) {
	if( typeof homeCalculatorBox != "undefined" )
		homeCalculatorBox.hide();
}
/* shows the home calculator */
function showHomeCalculator() {
	if( typeof homeCalculatorBox != "undefined" )
		homeCalculatorBox.show();
}
/* populates the dwelling list */
function getDwellingTypesCallback( data ) {
	// get the list to populate
	var dwellingTypes = document.getElementById( 'calculator_home_dwelling_type' );
	for( type in data['details']['dwellings'] ) {
		var id = data['details']['dwellings'][type]['id'];
		var value = data['details']['dwellings'][type]['name'];
		// any requests take the dwelling type id
		var opt = new Option( value, id );
		dwellingTypes.options[ dwellingTypes.options.length ] = opt;
	}
	
	// get any details we have previously saved so we can repopulate the interface
	var detailString = getCookie( domesticCalcCookieName );
	if ( detailString != '' ) {
		var detailsSplit = detailString.split('|');
		document.getElementById('calculator_home_name').value = detailsSplit[0];
		document.getElementById('calculator_home_occupants').value = detailsSplit[1];
		document.getElementById('calculator_home_date').value = detailsSplit[2];
		if ( detailsSplit[2] != '' ) {
			var dateSplit = detailsSplit[2].split('/');
			document.getElementById('calculator_home_date_day').value = dateSplit[0];
			document.getElementById('calculator_home_date_month').value = dateSplit[1];
			document.getElementById('calculator_home_date_year').value = dateSplit[2];
		}
		document.getElementById('calculator_home_bedrooms').value = detailsSplit[3];
		document.getElementById('calculator_home_dwelling_type').value = detailsSplit[4];
		if ( locale == 'us' ) {
			document.getElementById('calculator_home_state').value = detailsSplit[5];
		}
	}
}

/* store home information in a cookie */
function setHomeDetails( detailString ) {
	setCookie( domesticCalcCookieName, detailString );
}

/* takes all the hme calculator info and sends it to the domestic energy calculator */
function calculateHome() {
	var validate = new validateForm();
	// name
	validate.checkText( 'calculator_home_name', 'Your Name' );
	// state
	if ( locale == 'us' ) {
		validate.checkSelect( 'calculator_home_state', '', 'State' );
		var dwellingTypeText = 'House/Apartment Type';
		var stateString = document.getElementById('calculator_home_state').value;
	} else {
		var dwellingTypeText = 'Dwelling Type';
		var stateString = '';
	}
	// bedrooms
	validate.checkSelect( 'calculator_home_dwelling_type', '', dwellingTypeText );
	// bedrooms
	validate.checkSelect( 'calculator_home_bedrooms', '', 'No. of Bedrooms' );
	// occupants
	validate.checkSelect( 'calculator_home_occupants', '', 'No. of Occupants' );
	// date (lived here since)
	validate.checkText( 'calculator_home_date', 'Lived here since' );
	// if data is missing
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
	} else {
		// save all details in a cookie so we can repopulate later
		var detailString = document.getElementById('calculator_home_name').value + '|' + document.getElementById('calculator_home_occupants').value + '|' + document.getElementById('calculator_home_date').value + '|' + document.getElementById('calculator_home_bedrooms').value + '|' + document.getElementById('calculator_home_dwelling_type').value + '|' + stateString;
		setHomeDetails( detailString );
		showHomeCalculator();
	}
	return false;
}

function calculateHomeKWH() {
	// check we have type and bedrooms
	if( document.getElementById('calculator_home_dwelling_type').value != '' && document.getElementById('calculator_home_bedrooms' ).value != '' )	 {
		// we do, kick off a request for the elec and gas usage
		executeJSONRequest( 'domestic_energy/' + version + '/dwelling_kwh_calculator/?partnerID=' + partnerId + '&DwellingID=' + document.getElementById('calculator_home_dwelling_type').value + '&Bedrooms=' + document.getElementById('calculator_home_bedrooms' ).value, 'calculateHomeKWHCallback' );
	}
}

function calculateHomeKWHCallback( data ) {
	// set the electricity KWH and set the unit to KWH
	document.getElementById('calculator_home_electricity').value = data['eleckwh'];
	document.getElementById('calculator_home_electricity_unit').value = 'kwh';
	// set the gas KWH and set the unit to KWH
	document.getElementById('calculator_home_gas').value = data['gaskwh'];
	document.getElementById('calculator_home_gas_unit').value = 'kwh';
}

function calculateHomeUsage() {
	// validate the inputs
	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('calculator_home_electricity').value != '- amount -' ) {
		usageEntered = true;
		validate.checkNumeric( 'calculator_home_electricity', 'Annual electricity usage' );
		// add data
		fuelTypes[index] = 'electricity';
		period = ( document.getElementById('calculator_home_electricity_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('calculator_home_electricity').value * period;
		units[index] = document.getElementById('calculator_home_electricity_unit').value;
		index++;
	}
	// gas
	if( document.getElementById('calculator_home_gas').value != '- amount -' ) {
		usageEntered = true;
		validate.checkNumeric( 'calculator_home_gas', 'Annual gas usage' );
		// add data
		fuelTypes[index] = 'gas';
		period = ( document.getElementById('calculator_home_gas_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('calculator_home_gas').value * period;
		units[index] = document.getElementById('calculator_home_gas_unit').value;
		index++;
	}
	// oil
	if( document.getElementById('calculator_home_oil').value != '- amount -' ) {
		usageEntered = true;
		validate.checkNumeric( 'calculator_home_oil', 'Annual oil usage' );
		// add data
		fuelTypes[index] = 'oil';
		period = ( document.getElementById('calculator_home_oil_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('calculator_home_oil').value * period;
		units[index] = document.getElementById('calculator_home_oil_unit').value;
		index++;
	}
	// wood
	if( document.getElementById('calculator_home_wood').value != '- amount -' ) {
		usageEntered = true;
		validate.checkNumeric( 'calculator_home_wood', 'Annual wood usage' );
		// add data
		fuelTypes[index] = 'wood';
		period = ( document.getElementById('calculator_home_wood_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('calculator_home_wood').value * period;
		units[index] = document.getElementById('calculator_home_wood_unit').value;
		index++;
	}
	// coal
	if( document.getElementById('calculator_home_coal').value != '- amount -' ) {
		usageEntered = true;
		validate.checkNumeric( 'calculator_home_coal', 'Annual coal usage' );
		// add data
		fuelTypes[index] = 'coal';
		period = ( document.getElementById('calculator_home_coal_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('calculator_home_coal').value * period;
		units[index] = document.getElementById('calculator_home_coal_unit').value;
		index++;
	}
	// LPG
	if( document.getElementById('calculator_home_lpg').value != '- amount -' ) {
		usageEntered = true;
		validate.checkNumeric( 'calculator_home_lpg', 'Annual LPG usage' );
		// add data
		fuelTypes[index] = 'lpg';
		period = ( document.getElementById('calculator_home_lpg_period').value == 'monthly' ) ? 12 : 1;
		quantities[index] = document.getElementById('calculator_home_lpg').value * period;
		units[index] = document.getElementById('calculator_home_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
	calculatorHomeInfo = '&FuelType=' + allFuelTypes + '&Qty=' + allQuantities + '&Unit=' + allUnits;
	
	// get the info
	var customerName = '';
	var householdQty = '';
	var dateMovedIn = '';
	var bedrooms = '';
	var dwellingType = '';
	var stateId = '';
	
	if ( locale == 'us' ) {
		stateId = document.getElementById('calculator_home_state').value;
		if ( stateId == '' ) {
			alert('Please enter the State in which you live');
			return false;
		}
	} else {
		customerName = document.getElementById('calculator_home_name').value;
		householdQty = document.getElementById('calculator_home_occupants').value;
		dateMovedIn = document.getElementById('calculator_home_date').value;
		bedrooms = document.getElementById('calculator_home_bedrooms').value;
		dwellingType = document.getElementById('calculator_home_dwelling_type').value;
	}
	
	// do that funky requesting action
	executeJSONRequest( 'domestic_energy/' + version + '/calculator/?partnerID=' + partnerId + calculatorHomeInfo + '&CustomerName=' + customerName + '&HouseholdQty=' + householdQty + '&DateMovedToAddress=' + dateMovedIn + '&BedroomQTY=' + bedrooms + '&DwellingType=' + dwellingType + '&StateID=' + stateId + '&CalculatorName=Home', 'calculateHomeCallback' );
	return false;
}

/* what happens once the home calculator has done its thang? */
function calculateHomeCallback( data ) {
	// update the saved transaction list
	updateTransactionList( data );
	// update the choose project panel
	updateChooseProject( 'home', round( data['details']['data'][0]['@attributes']['tonnes'], 2 ), data);
	// hide the calculator
	hideHomeCalculator();
	// now show the choose project panel
	showChooseProject();	
}

function updateHomeDate() {
	var str = '';
	if ( ( document.getElementById('calculator_home_date_day').value != '' ) && ( document.getElementById('calculator_home_date_month').value != '' ) && ( document.getElementById('calculator_home_date_year').value != '' ) ) {
		str += document.getElementById('calculator_home_date_day').value + '/';
		str += document.getElementById('calculator_home_date_month').value + '/';
		str += document.getElementById('calculator_home_date_year').value;
	}
	document.getElementById('calculator_home_date').value = str;
}

/**
 * 
 * Projects Functions
 * ------------------
 * 
 **/

function initMidSectionExplanation() {
	document.getElementById('midSectionExplanationPopup').style.display = '';
	midSectionExplanationBox = 
			new YAHOO.widget.Panel("midSectionExplanationPopup",  
											{ 
												width: "269px", 
												height: "160px", 
												fixedcenter: true, 
												close:false, 
												draggable:false, 
												modal:true,
												visible:false,
												underlay:"none",
												effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											}
										);
	midSectionExplanationBox.render(document.body);
	if( showmidSectionExplanationOnLoad )
		midSectionExplanationBox.show();
}

function hideMidSectionExplanation() {
	if( typeof midSectionExplanationBox != "undefined" )
		midSectionExplanationBox.hide();
}

function showMidSectionExplanation() {
	if( typeof midSectionExplanationBox != "undefined" ) {
		midSectionExplanationBox.show();
	} else {
		midSectionExplanationOnLoad = true;
	}
}
function initMainChooseProject() {
	initChooseProject( 625, 710, true );
	correctPNG('midSectionImg1');
	correctPNG('midSectionImg1a');
	if ( locale == 'us' ) {
		correctPNG('midSectionImg1b');
	}
	correctPNG('midSectionImg2');
	correctPNG('midSectionImg2a');
	correctPNG('midSectionImg3');
	correctPNG('midSectionImg4');
	correctPNG('midSectionImg5');
	correctPNG('midSectionImg6');
	correctPNG('midSectionImg7');
	correctPNG('midSectionImg8');
	correctPNG('midSectionImg9');
}
function initPartnerChooseProject( ) {
	correctPNGBackground( 'chooseProjectPopupBg', '/partners/scheme' + schemeId + '/images/overlays/midsection.png' );
	correctPNGBackground( 'remove_button', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	initChooseProject( 730, 395, true );
}
function initChooseProject( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('chooseProjectPopup').style.display = '';
	chooseProjectBox = 
			new YAHOO.widget.Panel("chooseProjectPopup",  
											{ 
												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}
											} 
										);
	chooseProjectBox.render(document.body);
	if( showChooseProjectOnLoad )
		chooseProjectBox.show();
}

/* hides the choose project */
function hideChooseProject( ) {
	if( typeof chooseProjectBox != "undefined" ) {
		document.getElementById('projectChooseItems').style.display = 'none';
		chooseProjectBox.hide();
	}
}
/* shows the choose project */
function showChooseProject(  ) {
	if( typeof chooseProjectBox != "undefined" ) {
		document.getElementById('projectChooseItems').style.display = '';
		chooseProjectBox.show();
	}
}

function updateChooseProject( type, tonnage, data ) {
	// update the choose panel
	document.getElementById('project_choose_type').innerHTML = type.replace('quick ', '') + ' produces...';
	// add the total of the last offset to the project_choose_total tag
	document.getElementById( 'project_choose_total' ).innerHTML = tonnage + 't';
	// update the lbs element for american main site
	if ( ( locale == 'us' ) && ( partnerId == 1 ) ) {
		var lbs = tonnage * 2204.622;
		document.getElementById( 'project_choose_lbs' ).innerHTML = lbs.toFixed(2);
	}
	/*
	// assign the onclick to the button that removes the item from the basket
	eval( 'var func=function(){ removeProjectItem(' + data['transactionid'] + '); }');
	YAHOO.util.Event.addListener('remove_button', "click", func );	
	*/
}

/*  removes the passed transaction from the cookie and redirects to the basket
- thus displaying the reduced basket */
function removeProjectItem( transactionId ) {
	if( confirm("Are you sure you want to remove this offset?") ) {
		// remove the transaction
		removeTransaction( transactionId );
		// refresh the current page
		document.location = document.location;
	}
}

function initProjects() {
	// fire off a request for the projects
	executeJSONRequest( 'cart/' + projectVersion + '/transactions/?partnerID=' + partnerId + '&TransactionID=' + getTransactionList(), 'initProjectsCallback' );
}

function buildProjectTable( data, allowSelect ) {
	// get the projects_table element
	var tbody = document.getElementById( 'projects_table' );
	// set the project info to an empty array
	projectInfo = new Array();
	var numberOfOffsetProjects = 0;
	var numberOfCharityProjects = 0;
	// populate the projects page
	for( project in data['details']['projects'] ) {
		projectInfo[project] = new Array();
		// set the details of this project adding the info to an array for later use as we go
		projectInfo[project]['image'] = data['details']['projects'][project]['image'];
		projectInfo[project]['title'] = data['details']['projects'][project]['name'];
		projectInfo[project]['type'] = data['details']['projects'][project]['type'];
		projectInfo[project]['location'] = data['details']['projects'][project]['location'];
		projectInfo[project]['standard'] = data['details']['projects'][project]['standard'];
		projectInfo[project]['vintage'] = data['details']['projects'][project]['vintage'];
		projectInfo[project]['description'] = decodeText( data['details']['projects'][project]['description'] );
		projectInfo[project]['id'] = data['details']['projects'][project]['id'];
		projectInfo[project]['brochure'] = data['details']['projects'][project]['brochure'];
		projectInfo[project]['video'] = data['details']['projects'][project]['video'];
		projectInfo[project]['convertedcosts'] = data['details']['projects'][project]['convertedcosts'];
		projectInfo[project]['additional'] = data['details']['projects'][project]['additional'];
		projectInfo[project]['registry_link'] = data['details']['projects'][project]['registry_link'];
		projectInfo[project]['certs'] = data['details']['projects'][project]['certs'];
		projectInfo[project]['map'] = data['details']['projects'][project]['map'];
		// build the html for the table
		var newTR = document.createElement( 'tr' );
		if ( data['details']['projects'][project]['charity'] == '1' ) {
			newTR.className = 'projectTypeCharity';
			numberOfCharityProjects++;
		} else {
			newTR.className = 'projectTypeOffset';
			numberOfOffsetProjects++;
		}
		// image td
		var newTD = document.createElement( 'td' );
		newTD.className = 'projectsTableImgTd';
		newTD.valign = 'middle';
		newTD.align = 'center';
		var newIMG = document.createElement( 'img' );
		newIMG.src = data['details']['projects'][project]['image'];
		newIMG.className = 'projectsTableImg';
		newTD.appendChild( newIMG );
		newTR.appendChild( newTD );
		// details td
		var newTD = document.createElement( 'td' );
		newTD.valign = 'top';
		var newDetailsDIV = document.createElement( 'div' );
		newDetailsDIV.className = 'projectsTableDetails';
		/* title */
		var newTitleDiv = document.createElement( 'div' );
		newTitleDiv.className = 'projectsTableTitle';
		newTitleDiv.innerHTML = data['details']['projects'][project]['name'];
		newDetailsDIV.appendChild( newTitleDiv );
		/* description */
		var newDescriptionDiv = document.createElement( 'div' );
		newDescriptionDiv.className = 'projectsTableDescription';
		newDescriptionDiv.innerHTML = data['details']['projects'][project]['description'];
		newDetailsDIV.appendChild( newDescriptionDiv );
		/* show popup */
		var newPopupDiv = document.createElement( 'div' );
		newPopupDiv.className = 'projectsTableShowPopup';
		newPopupDiv.setAttribute( 'id', 'link_showproject_' + project );
		newPopupDiv.innerHTML = 'Click here for more info...';
		newDetailsDIV.appendChild( newPopupDiv );
		/* add it to the table data */
		newTD.appendChild( newDetailsDIV );
		/* show project info */
		eval( 'var func=function(){ showProjectInfo( ' + project + ' ); }');
		YAHOO.util.Event.addListener('link_showproject_' + project, 'click', func );
		newTR.appendChild( newTD );
		// actions td
		var newTD = document.createElement( 'td' );
		newTD.align = 'right';
		newTD.className = 'chooseProjectButtonTD';
		/* button */
		if ( allowSelect ) {
			var newInput = document.createElement( 'input' );
			newInput.type = 'button';
			newInput.className = 'button chooseProjectButton';
			newInput.setAttribute( 'id', 'project_' + project + '_button' );
			newTD.appendChild( newInput );
		}
		/* cost per tonne */
		var newCostDIV = document.createElement( 'div' );
		newCostDIV.className = 'projectsTableValuesCost';
		// do some exchange ratery
		var exchangeRate = 1;
		var localeCurrency = getLocaleCurrencyISO();
		for ( var convertedCost in data['details']['projects'][project]['convertedcosts'] ) {
			if ( data['details']['projects'][project]['convertedcosts'][convertedCost]['currency'] == localeCurrency ) {
				exchangeRate = data['details']['projects'][project]['convertedcosts'][convertedCost]['exchangerate'];
			}
		}
		newCostDIV.innerHTML = getLocaleCurrency() + round( exchangeRate * data['details']['projects'][project]['cost_per_tonne'] ) + ' per tonne';
		newTD.appendChild( newCostDIV );
		/* project type */
		var newTypeDIV = document.createElement( 'div' );
		newTypeDIV.className = 'projectsTableProjectType';
		newTypeDIV.innerHTML = data['details']['projects'][project]['project_type_text'];
		newTD.appendChild( newTypeDIV );
		/* to offset */
		/*
		var newOffsetDIV = document.createElement( 'div' );
		newOffsetDIV.className = 'projectsTableValuesOffset';
		newOffsetDIV.innerHTML = 'to offset ' + getTransactionsTotalTonnage( data['details']['transactions'] ) + '<br />tonnes of CO<sub>2</sub>';
		newDiv.appendChild( newOffsetDIV );
		*/
		/* projects details link */
		var newIMG = document.createElement( 'input' );
		newIMG.title = 'Click for more project details';
		newIMG.className = 'projectsTableDetailLink';
		newIMG.setAttribute( 'id', 'img_showproject_' + project );
		newTD.appendChild( newIMG );
		eval( 'var func=function(){ showProjectInfo( ' + project + '); }');
		YAHOO.util.Event.addListener('img_showproject_' + project, 'click', func );
		/* and the click function */
		eval( 'var func=function(){ chooseProject( ' + data['details']['projects'][project]['projectid'] + '); }');
		YAHOO.util.Event.addListener('project_' + project + '_button', 'click', func );
		newTR.appendChild( newTD );
		tbody.appendChild( newTR );
		/* bunker row */
		var dividerTR = document.createElement( 'tr' );
		dividerTR.className = newTR.className;
		var newTD = document.createElement( 'td' );
		newTD.colSpan = 3;
		newTD.className = 'projectRowDivider';
		dividerTR.appendChild( newTD );
		tbody.appendChild( dividerTR );
	}
	if ( numberOfOffsetProjects == 0 ) {
		// hide the offsets tab
		document.getElementById('projectTableTabOffsets').style.display = 'none';
		// and show the charity tab by default
		changeProjecTableType('charity');
	}
	if ( numberOfCharityProjects == 0 ) {
		// hide the charity tab
		document.getElementById('projectTableTabCharity').style.display = 'none';
	}
}

/* take the projects objects and show them */
function initProjectsCallback( data ) {
	buildProjectTable( data, true );
	// hide the loading, show the panel
	document.getElementById('projects_loading').style.display = 'none';
	document.getElementById('projects_panel').style.display = '';
}

function chooseProject( id ) {
	// store the project chosen in the projectId session cookie
	setCookie( projectIdCookieName, id );
	// go to the checkout page
	goToPage( 'checkout.php' );
}

function initMainProjectInfo( ) {
	correctPNGBackground( 'projectInfoPopupBg', '/custom/images/project-info-bg-big.png' );
	correctPNG( 'popupCloseButton' );
	initProjectInfo( 820, 720, true );
}
function initPartnerProjectInfo( ) {
	correctPNGBackground( 'projectInfoPopupBg', '/partners/scheme' + schemeId + '/images/overlays/project-info-bg-big.png' );
	correctPNGBackground( 'closeWindowButton', '/partners/scheme' + schemeId + '/images/closewindow.png' );
	initProjectInfo( 820, 720, positionOverlaysCenter );
}
function initProjectInfo( popupWidth, popupHeight, positionCenter ) {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('projectInfoPopup').style.display = '';
	chooseProjectBox = 
			new YAHOO.widget.Panel("projectInfoPopup",  
											{ 
												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}
											} 
										);
	chooseProjectBox.render(document.body);
	if( showChooseProjectOnLoad )
		chooseProjectBox.show();
}

/* hides the choose project */
function hideProjectInfo( ) {
	if( typeof chooseProjectBox != "undefined" )
		chooseProjectBox.hide();
}

/* shows the choose project */
function showProjectInfo( id ) {
	// assign the correct project details to the window
	document.getElementById('project_popup_image').src = projectInfo[id]['image'];
	document.getElementById('project_popup_image').alt = projectInfo[id]['title'];
	document.getElementById('project_popup_title').innerHTML = projectInfo[id]['title'];
	document.getElementById('project_popup_type').innerHTML = projectInfo[id]['type'];
	document.getElementById('project_popup_location').innerHTML = projectInfo[id]['location'];
	document.getElementById('project_popup_description').innerHTML = projectInfo[id]['description'];

	if(document.getElementById('projectBrochureButton')) {
		
		if ( projectInfo[id]['standard'] ) {
			document.getElementById('projectInfoStandardContainer').style.display = '';
			document.getElementById('project_popup_standard').innerHTML =  projectInfo[id]['standard'];
		} else {
			document.getElementById('projectInfoStandardContainer').style.display = 'none';
		}
		
		if ( projectInfo[id]['vintage'] ) {
			document.getElementById('projectInfoVintageContainer').style.display = '';
			document.getElementById('project_popup_vintage').innerHTML =  projectInfo[id]['vintage'];
		} else {
			document.getElementById('projectInfoVintageContainer').style.display = 'none';
		}
		
		for( currency in projectInfo[id]['convertedcosts']) {
			if(projectInfo[id]['convertedcosts'][currency]['currency'] == 'EUR') {
				document.getElementById('project_popup_cost').innerHTML = projectInfo[id]['convertedcosts'][currency]['currencysymbol'] + parseFloat( projectInfo[id]['convertedcosts'][currency]['cost'] ).toFixed(2);
			}
		}
		
		document.getElementById('projectBrochureButton').style.display='none';
		document.getElementById('projectVideoButton').style.display='none';
		document.getElementById('projectImagesButton').style.display='none';
		document.getElementById('projectRegistryButton').style.display='none';
		document.getElementById('projectCertsButton').style.display='none';
		document.getElementById('projectMapButton').style.display='none';
		document.getElementById('currentImages').style.display='none';
	
		brochureLink = projectInfo[id]['brochure'];
		registryLink = projectInfo[id]['registry_link'];
		certLink = projectInfo[id]['certs'];
	
		var additionalImageSection = document.getElementById('currentImagesInner');
		additionalImageSection.innerHTML = '';
		for( additionalImage in projectInfo[id]['additional']) {
			var imagePath = projectInfo[id]['additional'][additionalImage]['thumbnail'];
	
			//var additionalImage = document.createElement('img');
			//additionalImage.setAttribute('src',imagePath);
			//additionalImageSection.appendChild(additionalImage);
			
			var newHTML = '<img src="' + imagePath + '" height="100%"/>';
			additionalImageSection.innerHTML = additionalImageSection.innerHTML + newHTML;
		}
		
		var youTubeVideoLink = '';
		var youTubeParts = projectInfo[id]['video'].split("?v=");
		if(youTubeParts[1]) {
			var youTubeParts2 = youTubeParts[1].split("&");
			var youTubeVideoId = youTubeParts2[0];
			youTubeVideoLink = 'http://www.youtube.com/v/' + youTubeVideoId + '&hl=en_GB&fs=1';
		}
		if(youTubeVideoLink != '') {
			youTubeHTML = '<object width="600" height="455">';
			youTubeHTML    += '<param name="movie" value="' + youTubeVideoLink + '"></param>';
			youTubeHTML    += '<param name="allowFullScreen" value="true"></param>';
			youTubeHTML    += '<param name="allowscriptaccess" value="always"></param>';
			youTubeHTML    += '<embed src="' + youTubeVideoLink + '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="600" height="455"/>';
			youTubeHTML    += '</object>';
		}
		
		var imageContentSection = document.getElementById('popupImageSection');
		imageContentSection.innerHTML = '';
		currentImage = 1;
		totalImages = 1;
		for( additionalImage in projectInfo[id]['additional']) {
			var imagePath = projectInfo[id]['additional'][additionalImage]['path'];
			var popupImageDiv = document.createElement('div');
			popupImageDiv.id = 'popupImage'+totalImages;
			popupImageDiv.className = 'popupImage';
			popupImageDiv.setAttribute('valign','middle');
			if(totalImages > 1) {
				popupImageDiv.style.display = 'none';
			}
			var popupImage = document.createElement('img');
			popupImage.setAttribute('src',imagePath);
			popupImageDiv.appendChild(popupImage);
			imageContentSection.appendChild(popupImageDiv);
			totalImages++;
		}
		totalImages--;
		var imageContentBottom = document.getElementById('popupImageBottom');
		imageContentBottom.innerHTML = 'Image 1 of ' + totalImages; 
		
		var mapContentSection = document.getElementById('popupMapSection');
		var mapURL = projectInfo[id]['map'];
		if(mapURL != '') {
			document.getElementById('projectInfoMapIFrame').src = mapURL.replace(/&amp;/g,'&');
		} else {
			document.getElementById('projectInfoMapIFrame').src = 'about:blank';
		}
		
		if(brochureLink != ''){document.getElementById('projectBrochureButton').style.display='';}
		if(youTubeHTML != ''){document.getElementById('projectVideoButton').style.display='';}
		if(totalImages > 0){
			document.getElementById('projectImagesButton').style.display='';
			document.getElementById('currentImages').style.display='';
		}
		if(registryLink != ''){document.getElementById('projectRegistryButton').style.display='';}
		if(certLink != ''){document.getElementById('projectCertsButton').style.display='';}
		if(mapURL != ''){document.getElementById('projectMapButton').style.display='';}
	}
	
	if( typeof chooseProjectBox != "undefined" )
		chooseProjectBox.show();
}

/*
Platform ticket popup - displayed when on a carboncore subscriber's microsite before they do their first calculation
*/
function initPlatformTicketsPanel() {
	correctPNGBackground( 'platformTicketsPopupBg', '/partners/scheme' + schemeId + '/images/overlays/projectinfobg.png' );
	//correctPNGBackground( 'platformTicketsPopupCloseButton', '/partners/scheme' + schemeId + '/images/calculator-close.png' );
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('platformTicketsPopup').style.display = '';
	platformTicketsBox = 
			new YAHOO.widget.Panel("platformTicketsPopup",
											{
												width: "790px", height: "395px", fixedcenter:true, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											}
										);
	platformTicketsBox.render(document.body);
	if( showPlatformTicketsOnLoad ) {
		platformTicketsBox.show();
	}
}

function showPlatformTicketsPanel() {
	if ( typeof platformTicketsBox != "undefined" ) {
		platformTicketsBox.show();
	} else {
		showPlatformTicketsOnLoad = true;
	}
}

function hidePlatformTicketsPanel() {
	if( typeof platformTicketsBox != "undefined" ) {
		platformTicketsBox.hide();
	}
}

function validatePlatformTicket() {
	var validator = new validateForm();
	validator.checkText( 'platformTicket_Name', 'Your Name' );
	validator.validateEmailAddress( 'platformTicket_Email', 'Your Email Address' );
	validator.checkText( 'platformTicket_Telephone', 'Your Telephone Number' );
	if ( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
	} else {
		var name = document.getElementById('platformTicket_Name').value;
		var telephone = document.getElementById('platformTicket_Telephone').value;
		var email = document.getElementById('platformTicket_Email').value;
		executeGeneralRequest( 'json/carboncore/platform_tickets/v1.0/?partnerid=' + partnerId + '&name=' + name + '&telephonenumber=' + telephone + '&emailaddress=' + email, 'submitPlatformTicketCallback' );
	}
	// always return false as we do everything via an api call above
	return false;
}

function submitPlatformTicketCallback( data ) {
	if ( data['message'] == 'success' ) {
		setCookie( platformTicketCookieName, 'true', 28 );
		if ( platformTicketOnComplete ) {
			platformTicketOnComplete();
		}
		hidePlatformTicketsPanel();
	} else {
		alert('Sorry, an error occured when saving your details. Please try again.');
	}
}

/**
 * 
 * Basket Functions
 * ----------------
 * 
 **/

function initCheckoutSliderPopup() {
	document.getElementById('checkoutSliderPopup').style.display = '';
	initCheckoutSlider();
	checkoutSliderBox = new YAHOO.widget.Panel("checkoutSliderPopup",  
											{ 
												width: "600px", height: "540px", fixedcenter:true, close:false, draggable:false, modal:true,visible:false,underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	checkoutSliderBox.render(document.body);
	if( showCheckoutSliderBoxOnLoad ) {
		doShowCheckoutSlider();
	}
}
function hideCheckoutSlider( ) {
	if( typeof checkoutSliderBox != "undefined" ) {
		checkoutSliderBox.hide();
	}
}
function showCheckoutSlider( ) {
	if( typeof checkoutSliderBox != "undefined" ) {
		doShowCheckoutSlider();
	} else {
		showCheckoutSliderBoxOnLoad = true;
	}
}
function doShowCheckoutSlider() {
	if ( ( typeof schemeId != 'undefined' ) && ( schemeId == 1 ) ) {
		correctPNGBackground( 'checkoutSliderPopupBg', '/partners/scheme1/images/checkoutsliderbg.png', 'image' );
	} else {
		correctPNGBackground( 'checkoutSliderPopupBg', '/custom/images/checkoutsliderbg.png' );
	}
	correctPNG( 'sliderButtonImg' );
	correctPNG( 'goBtn' );
	correctPNG( 'closeBtn' );
	checkoutSliderBox.show();
}

function populateCheckoutCountries( data ) {
	var slct1 = document.getElementById('checkout_country');
	var slct2 = document.getElementById('checkout_delivery_country');
	for ( var country in data['details']['country'] ) {
		// need 2 vars because IE is a piece of...
		var opt1 = new Option( data['details']['country'][country]['country'], data['details']['country'][country]['localeid'] );
		slct1.options[ slct1.options.length ] = opt1;
		if( document.getElementById('selectedCountry') != null ) {
			if( data['details']['country'][country]['localeid'] == document.getElementById('selectedCountry').value ) {
				slct1.options[ slct1.options.length-1 ].selected = true;
			}
		}
		// we dont set a selected delivery country due to the way the html is laid out, i.e. the user must click "no", my details are not
		// the same and would therefore be incorrect to be pre selected
		var opt2 = new Option( data['details']['country'][country]['country'], data['details']['country'][country]['localeid'] );
		slct2.options[ slct2.options.length ] = opt2;
	}
}

/* need to get all the basket info */
function initBasket() {
	// initialize the slider popup
	initCheckoutSliderPopup();
	// check we have something to basket first
	var transactions = getTransactionList();
	if( transactions.length == 0 ) {
		// basket is empty, stage zero 'loading' will have already shown by default	
		showStage( 'empty' );
	} else {
		// check if we already have data
		if( basketData ) {
			// using local basket
			initBasketCallback( basketData );
		} else {
			// fire off a request for the project info
			executeJSONRequest( 'cart/' + projectVersion + '/transactions/?partnerID=' + partnerId + '&TransactionID=' + getTransactionList(), 'initBasketCallback', 0 );	// force the api to return uk currency data
		}
		// also get the customers details so we can pre populate the payment stage
		if( typeof customerId != 'undefined' ) {
			//executeJSONRequest( 'cart/' + version + '/transactions/?partnerID=' + partnerId, 'populateBasketCallback' );
		} else {
			// not logged in, will be forced too by the template as the next stage
		}
	}
}

/* populate the personal details of the basket page*/
function populateBasketCallback( data ) {
	document.getElementById('checkout_firstname').value = '';
	document.getElementById('checkout_lastname').value = '';
	document.getElementById('checkout_email').value = '';
	document.getElementById('checkout_address_1').value = '';
	document.getElementById('checkout_address_2').value = '';
	document.getElementById('checkout_town').value = '';
	document.getElementById('checkout_county').value = '';
	document.getElementById('checkout_postcode').value = '';	
}

function getUnitName( unit ) {
	switch ( unit.toLowerCase() ) {
		case 'curr':
			return getLocaleCurrency();
		default:
			return unit;
	}
}

/* checkout slider stuff */
var originalCost = 0;
var originalTonnage = 0;
var checkoutCurrencyArray = new Array();
var currentSliderPercent = 100;
var currentSliderCost = 0;

function setOriginalCost( currency ) {
	originalCost = checkoutCurrencyArray[ currency ]['cost'];
	currentSliderCost = originalCost;
}
function setOriginalTonnage( tonnage ) {
	originalTonnage = tonnage;
}
function updateSliderTonnage( percent ) {
	var tonnage = ( originalTonnage * percent ).toFixed(2);
	document.getElementById('newTonnage').innerHTML = tonnage;
	document.getElementById('choose_tonnes').innerHTML = tonnage;
}
// updateSliderTotal - gets called when the user has finished sliding the scale
function updateSliderTotal() {
	if ( currentCurrency == 'AED' ) {
		var currency = 'GBP';
	    setOriginalCost( currency );
	} else {
		var currency = currentCurrency;
	}
	var currencySymbol = checkoutCurrencyArray[ currency ]['symbol'];
	var cost = ( originalCost * currentSliderPercent ).toFixed(2);
	document.getElementById('checkoutSliderNewTotal').innerHTML = currencySymbol + '' + cost;
	document.getElementById('choose_cost').innerHTML = currencySymbol + '' + cost;
	if ( document.getElementById('choose_total_initial') ) {
		document.getElementById('choose_total_initial').innerHTML = currencySymbol + '' + cost;
	}
	updateCostPerTonne( originalCost, originalTonnage );
	
	if ( currentCurrency == 'AED' ) {
	    setOriginalCost( 'AED' );
	}
}
// updateSliderValue - gets called on every 'tick' of the scale
function updateSliderValue() {
	var currencySymbol = checkoutCurrencyArray[ currentCurrency ]['symbol'];
	document.getElementById('sliderValue').innerHTML = currencySymbol + '' + ( originalCost * currentSliderPercent ).toFixed(2);
    // Update the title attribute on the background.  This helps assistive technology to communicate the state change
	document.getElementById('sliderBg').title = currencySymbol + '' + ( originalCost * currentSliderPercent ).toFixed(2);
}
// initSliderVars - update all values associated with the sliding scale
function initSliderVars( updateDropDown ) {
	updateCurrentCurrency();
	if ( updateDropDown ) {
		// get currency symbol
		var currencySymbol = checkoutCurrencyArray[ currentCurrency ]['symbol'];
		// update the drop-down
		selectCheckoutCurrency( currencySymbol + ' ' + currentCurrency, currentCurrency );
	}
	// init the original cost variable
	setOriginalCost( currentCurrency );
	// display the appropriate values
	updateSliderValue();
	// update slider total
	updateSliderTotal();
}

function updateCurrentCurrency() {
	// if currencyCookieName is set, use that as the default currency,
	// otherwise, use the current locale
	var cur = getCookie(currencyCookieName);
	if ( cur && ( cur != '' ) ) {
		currentCurrency = getCookie(currencyCookieName);
	} else {
		currentCurrency = getLocaleCurrencyISO();
	}
}

function setCurrentSliderCost( cost ) {
    currentSliderCost = checkoutCurrencyArray[ currentCurrency ]['cost'];
}

function initCheckoutSlider() {
    var Event = YAHOO.util.Event,
        Dom   = YAHOO.util.Dom,
        lang  = YAHOO.lang,
        slider, 
        bg="sliderBg",
        thumb="sliderButton", 
        textfield="sliderValue"

    var topConstraint = 0; // the number of pixels the slider can move to the left from it's original position
    var bottomConstraint = 228;	// the number of pixels the slider can move to the right from it's original position
    var scaleFactor = 1;	// Custom scale factor for converting the pixel offset into a real value
    var keyIncrement = 12;	// The amount the slider moves when the value is changed with the arrow keys
    var tickSize = 12;	// number of pixels to move every "tick"

    Event.onDOMReady(function() {

        slider = YAHOO.widget.Slider.getHorizSlider(bg, thumb, topConstraint, bottomConstraint, tickSize);

        // Sliders with ticks can be animated without YAHOO.util.Anim
        slider.animate = true;

        slider.getPercentage = function() {
        	var percent = ( this.getValue() / bottomConstraint ) * 1.9 + 0.1;
        	updateSliderTonnage( percent );
            return percent;
        }

        slider.subscribe("change", function(offsetFromStart) {
            var fld = Dom.get(textfield);
            var percent = slider.getPercentage();
            var cost = ( ( originalCost * percent ) * scaleFactor ).toFixed( 2 );
            currentSliderPercent = percent;
            setCurrentSliderCost( cost );
            // update the text box with the actual value
            updateSliderValue();
        });
        
        slider.subscribe("slideEnd", function(offsetFromStart) {
        	updateSliderTotal();
        });
        
        slider.setValue(108,true);

    });
}

function updateCostPerTonne( cost, tonnage ) {
	var currencySymbol = checkoutCurrencyArray[ currentCurrency ]['symbol'];
	var perTonnePrice = ( cost / tonnage );
	document.getElementById('choose_per_tonne').innerHTML = currencySymbol + '' + perTonnePrice.toFixed(2);
}

function submitCheckoutSlider() {
	// store the selected modifier (ie 10% to 200%)
	setCookie( checkoutTotalModifierCookieName, currentSliderPercent );
	
	// we can't process trasactions in dirhams so force the user to pay in pounds
	if ( getCookie( currencyCookieName ) == 'AED' ) {
		setCookie( currencyCookieName, 'GBP' );
	}
	
	// show the giftaid stage
	if ( client_authenticated ) {
		if ( giftaid == 1 ) {
			showStage('giftaid');
		} else {
			showStage('personal_details');
		}
//	} else {
//		document.location = 'register.php';
	}
	// hide this popup
	hideCheckoutSlider();
}
/* end checkout slider functions */

/* populate the basket as necessary */
function initBasketCallback( data ) {
	var perTonnePrice = '';
	// add the project information
	//alert( dump ( data['details'] ) );
	for( project in data['details']['projects'] ) {
		// if its the project i've chosen
		if( data['details']['projects'][project]['projectid'] == getCookie( projectIdCookieName ) ) {
			// output the details
			document.getElementById('choose_image').src = data['details']['projects'][project]['image'];
			// title
			document.getElementById('choose_title').innerHTML = data['details']['projects'][project]['name'];
			// description
			document.getElementById('choose_description').innerHTML = data['details']['projects'][project]['description'].substr( 0, 190 ) + '...';
			// more info button
			getProjectDetailsOnlyCallback( data );
			eval( 'var func=function(){ showProjectInfo( ' + project + '); }');
			YAHOO.util.Event.addListener( 'checkoutProjectDetailsInfoBtn', 'click', func );
			// cost
			var cost = round( data['details']['projects'][project]['cost'] );
			// loop round the 'convertedcosts' element and build up the currency array
			var currencyOptions = document.getElementById('optionDropDown_currency');
			for( var cur in data['details']['projects'][project]['convertedcosts'] ) {
				var curObj = data['details']['projects'][project]['convertedcosts'][cur];
				checkoutCurrencyArray[ curObj['currency'] ] = new Array();
				checkoutCurrencyArray[ curObj['currency'] ]['symbol'] = curObj['currencysymbol'];
				checkoutCurrencyArray[ curObj['currency'] ]['cost'] = curObj['cost'];
				checkoutCurrencyArray[ curObj['currency'] ]['netcost'] = curObj['netcost'];
				// build up our currency drop-down too
				currencyOptions.innerHTML += '<a href="javascript:selectCheckoutCurrency(\'' + curObj['currencysymbol'] + ' ' + curObj['currency'] + '\',\'' + curObj['currency'] + '\');">' + curObj['currencysymbol'] + ' ' + curObj['currency'] + '</a>';
			}
			// tonnes
			var tonnage = getTransactionsTotalTonnage( data['details']['transactions'] );
			document.getElementById('choose_tonnes').innerHTML = tonnage + 't';
			document.getElementById('newTonnage').innerHTML = tonnage;
			setOriginalTonnage( tonnage );
			// per tonne
			updateCostPerTonne( cost, tonnage );
			// set global variable, giftaid (will cause the user to get taken to the giftaid stage in the checkuot)
			giftaid = data['details']['projects'][project]['giftaid'];
			if( giftaid == 1 ) {
				// show the next stage (giftaid stage) button, hide the personal details stage button
				// only if authenticated (checked in the php)
				if( client_authenticated ) {
					document.getElementById( 'button_summary_next_stage' ).style.display = '';
					document.getElementById( 'button_summary_personal_details' ).style.display = 'none';
				}
				// set the giftaid panel details if necessary
				var charityName = data['details']['projects'][project]['charityname'];
				document.getElementById('giftaid_partner_1').innerHTML = charityName;
				document.getElementById('giftaid_partner_2').innerHTML = charityName;
				document.getElementById('charityText').innerHTML = data['details']['projects'][project]['giftaidtext'];
			} else {
				// only if authenticated (checked in the php)
				if( client_authenticated ) {
					// hide the next stage (giftaid stage) button, show the personal details stage button
					document.getElementById( 'button_summary_next_stage' ).style.display = 'none';
					document.getElementById( 'button_summary_personal_details' ).style.display = '';
				}
			}
		}
	}
	
	// get the table object
	var tableBody = document.getElementById( 'checkout' );
	//delete all existing rows
	var count = tableBody.childNodes.length;
	for( i = 0; i < count; i++ ) {
		tableBody.removeChild(tableBody.childNodes[0]);
	}
	var rowCount = 0;
	var rowInc = 0;
	// add the rows to the basket
	for( transaction in data['details']['transactions'] ) {
		var rowClass = 'checkoutTableRowClass';
		if( rowCount == 1 ) {
			rowCount = 0;
			rowClass = 'checkoutTableAltRowClass';
		} else {
			rowCount = 1;
		}
		// new row
		var newTR = document.createElement("tr");
		// type
		var newTD = document.createElement("td");
		newTD.className = 'checkoutTableDescriptionColumn ' + rowClass;
		var newSpan = document.createElement("div");
		newSpan.className = 'checkoutItem';
		var offsetName = data['details']['transactions'][transaction]['discipline'];
		if ( offsetName.toLowerCase() == 'us_quick_vehicle' ) {
			offsetName = 'us quick vehicle'; // ack ack ack
		}
		var offsetDescription = '<strong>' + offsetName.replace( '_', ' ' ).toCapitalCase() + '</strong>';
		offsetDescription += '<br />';
		// type details
		var discipline = String( data['details']['transactions'][transaction]['discipline'] );
		var offsetDescriptionSplit = data['details']['transactions'][transaction]['data'].split('|');
		switch ( discipline.toLowerCase() ) {
			case 'home':
				var offsetDescriptionSplit1 = data['details']['transactions'][transaction]['data'].split('#');
				if ( offsetDescriptionSplit1[1] ) {
					var offsetDescriptionSplit = offsetDescriptionSplit1[0].split('|');
					var energySplit = offsetDescriptionSplit1[1].split(',');
					energySplit.pop(); // remove last element
					offsetDescription += 'Name: ' + offsetDescriptionSplit[0] + '. Dwelling Type: ' + offsetDescriptionSplit[1] + '. Bedrooms: ' + offsetDescriptionSplit[2] + '. Occupants: ' + offsetDescriptionSplit[3] + '. Lived here since: ' + offsetDescriptionSplit[4];
					for ( var detail in energySplit ) {
						var detailSplit = energySplit[detail].split('|');
						offsetDescription += '. Energy: ' + detailSplit[0] + '. Value: ' + detailSplit[1] + ' ' + getUnitName( detailSplit[2] );
					}
				} else {
					energySplit = data['details']['transactions'][transaction]['data'].split(',');
					energySplit.pop(); // remove last element
					for ( var detail in energySplit ) {
						var detailSplit = energySplit[detail].split('|');
						offsetDescription += 'Energy: ' + detailSplit[0] + '. Value: ' + detailSplit[1] + ' ' + getUnitName( detailSplit[2] );
					}
				}
				break;
			case 'office':
				var offsetDescriptionSplit = data['details']['transactions'][transaction]['data'].split(',');
				offsetDescriptionSplit.pop();
				for ( var item in offsetDescriptionSplit ) {
					var energySplit = offsetDescriptionSplit[item].split('|');
					offsetDescription += 'Energy: ' + energySplit[0] + '. Value: ' + energySplit[1] + ' ' + energySplit[2] + '. ';
				}
				break;
			case 'car':
			case 'vehicle':
				offsetDescription += 'Manufacturer: ' + offsetDescriptionSplit[0] + '. Model: ' + offsetDescriptionSplit[1] + '. Distance: ' + offsetDescriptionSplit[2] + ' ' + offsetDescriptionSplit[3] + '. Registration: ' + offsetDescriptionSplit[4];
				break;
			case 'quick_vehicle':
			case 'us_quick_vehicle':
				offsetDescription += 'Fuel Type: ' + offsetDescriptionSplit[0] + '. Distance: ' + offsetDescriptionSplit[1] + '. Fuel Economy: ' + offsetDescriptionSplit[2] + ' ' + offsetDescriptionSplit[3];
				break;
			case 'flight':
				offsetDescriptionSplitCommas = data['details']['transactions'][transaction]['data'].split(',');
				offsetDescriptionSplit1 = offsetDescriptionSplitCommas[0].split('|');
				offsetDescription += 'Flying From: ' + offsetDescriptionSplit1[0] + '. Class: ' + offsetDescriptionSplit1[1] + '. Flying To: ' + offsetDescriptionSplit1[2] + '. Passengers: ' + offsetDescriptionSplit1[3] + '.';
				if ( offsetDescriptionSplitCommas.length > 1 ) {
					// return flight
					 offsetDescription += ' Type: Return';
				} else {
					// one-way flight
					 offsetDescription += ' Type: One-way';
				}
				offsetDescription += '. Trips: ' + offsetDescriptionSplit1[4];
				break;
			case 'quick_flight':
				offsetDescription += 'Type: ' + offsetDescriptionSplit[0];
				break;
			case 'public_transport':
				offsetDescription += 'Transport: ' + offsetDescriptionSplit[0] + '. Distance: ' + offsetDescriptionSplit[1] + ' ' + offsetDescriptionSplit[2] + '. Journeys: ' + offsetDescriptionSplit[3];
				break;
			case 'freight':
				offsetDescription += 'Transport: ' + offsetDescriptionSplit[0] + '. Distance: ' + offsetDescriptionSplit[1] + ' ' + offsetDescriptionSplit[2] + '. Freight Tonnage: ' + offsetDescriptionSplit[3];
				break;
			case 'additional':
				offsetDescription += 'Fuel Type: ' + offsetDescriptionSplit[0] + '. Amount: ' + offsetDescriptionSplit[1];
				break;
			default:
				offsetDescription += data['details']['transactions'][transaction]['data'];
				break;
		}
		
		newSpan.innerHTML = offsetDescription;
		newTD.appendChild( newSpan );
		newTR.appendChild( newTD );
		// co2 tonnes
		var newTD = document.createElement("td");
		newTD.className = 'checkoutTableTonnesColumn ' + rowClass;
		var newSpan = document.createElement("span");
		newSpan.id = 'checkoutTableTonnes_' + rowInc;
		newSpan.className = 'checkoutItem';
		var modifier = getCheckoutModifier();
		var thisTonnage = round( ( data['details']['transactions'][transaction]['tonnes'] * modifier), 2 );
		newSpan.innerHTML = thisTonnage;
		newTD.appendChild( newSpan );
		newTR.appendChild( newTD );
		// cost
		/*
		var newTD = document.createElement("td");
		newTD.style.width = '84px';
		newTD.className = 'checkoutTableCostColumn ' + rowClass;
		var newSpan = document.createElement("span");
		newSpan.className = 'checkoutItem';
		if ( perTonnePrice != '' ) {
			newSpan.innerHTML = '&pound;' + round( data['details']['transactions'][transaction]['tonnes'] * ( cost / tonnage ), 2 );
		} else {
			newSpan.innerHTML = '&nbsp;';
		}
		newTD.appendChild( newSpan );
		newTR.appendChild( newTD );
		*/
		// remove
		var newTD = document.createElement("td");
		newTD.className = 'checkoutTableRemoveColumn ' + rowClass;
		var newSpan = document.createElement("span");
		newSpan.className = 'checkoutItem checkoutRemove';
		newSpan.title = 'Click to remove';
		newSpan.setAttribute( 'id', 'checkout_remove_' + transaction );
		newSpan.innerHTML = 'remove';
		// assign the onclick to the button that removes the item from the checkout
		eval( 'var func=function(){ removeBasketItem(' + data['details']['transactions'][transaction]['transactionid'] + '); }');
		YAHOO.util.Event.addListener('checkout_remove_' + transaction, "click", func );
		newTD.appendChild( newSpan );
		newTR.appendChild( newTD );
		// add to table
		tableBody.appendChild( newTR );
		rowInc++;
	}
	
	executeGeneralRequest( 'json/countries/v1.0/?partnerid=' + partnerId, 'populateCheckoutCountries' );
	
	// show basket summary
	if ( doNotChangeCheckoutStage ) {
		if ( giftaid == 1 ) {
			showStage( 'giftaid' );
		} else {
			showStage( 'personal_details' );
		}
	} else {
		showStage( 'summary' );
		// initialise the slider
		if ( ( cost > 0 ) && ( !viewingBasket ) ) {
			initSliderVars( true );
			showCheckoutSlider();
		}
	}
}

function validateStageGiftAid() {
	// check either yes or no was selected for gift aid
	if( !document.getElementById('giftaid_yes').checked ) {
		if( !document.getElementById('giftaid_no').checked ) {
			alert( "Please select your gift aid option" );
			return;
		}
	}
	// ok, go to payment stage
	showStage( 'personal_details' );
}

function syncField( field ) {
	document.getElementById( 'checkout_delivery_' + field ).value = document.getElementById( 'checkout_' + field ).value;
}

function syncAddresses() {
	if( document.getElementById( 'same_addresses_true' ).checked ) {
		document.getElementById( 'deliveryAddress' ).style.display = 'none';
		syncField( 'address_1' );
		syncField( 'address_2' );
		syncField( 'town' );
		syncField( 'county' );
		syncField( 'postcode' );
		syncField( 'country' );
		return;
	}
	document.getElementById( 'deliveryAddress' ).style.display = '';
}

function validateCheckout() {
	syncAddresses();
	var validate = new validateForm();
	// personal details
	validate.checkText( 'checkout_firstname', 'Firstname' );
	validate.checkText( 'checkout_lastname', 'Lastname' );
	validate.validateEmailAddress( 'checkout_email', 'Email Address' );
	validate.checkText( 'checkout_address_1', 'Address 1' );
	validate.checkText( 'checkout_town', 'Town' );
	validate.checkSelect( 'checkout_country', '', 'Country' );
	validate.checkSelect( 'checkout_country', '-1', 'Country' );
//	validate.validatePostCode( 'checkout_postcode', 'Postcode' );
	validate.checkText( 'checkout_delivery_address_1', 'Delivery Address 1' );
	validate.checkText( 'checkout_delivery_town', 'Delivery Town' );
	validate.checkSelect( 'checkout_delivery_country', '', 'Delivery Country' );
	validate.checkSelect( 'checkout_delivery_country', '-1', 'Delivery Country' );
	// validate.validatePostCode( 'checkout_delivery_postcode', 'Delivery Postcode' );
	// card details
/*	validate.checkSelect( 'checkout_card_type', '', 'Card Type' );	
	validate.checkNumeric( 'checkout_card_number', 'Card Number' );
	validate.checkText( 'checkout_name_on_card', 'Name On Card' );
	validate.checkSelect( 'checkout_start_date_month', '', 'Start Date - Month' );		
	validate.checkSelect( 'checkout_start_date_year', '', 'Start Date - Year' );		
	validate.checkSelect( 'checkout_end_date_month', '', 'End Date - Month' );		
	validate.checkSelect( 'checkout_end_date_year', '', 'End Date - year' );	
		
	validate.checkNumeric( 'checkout_issue_number', 'Issue Number' );
	// check its 2 digits
	var issueNumber = document.getElementById( 'checkout_issue_number' ).value;
	// issue number required if maestro only (MS)
	if( document.getElementById( 'checkout_card_type' ).value == 'maestro' ) {
		// issue number must be 2 digits
		if( issueNumber != '' ) {
			if( issueNumber.length != 2 ) {
				validate.addCustomError( 'Issue Number must be 2 digits' );
			}
		}
	}
	validate.checkNumeric( 'checkout_cv2', 'CV2' );*/
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	
	// personal details
//	var firstname = '&Firstname=' + document.getElementById('checkout_firstname').value;
//	var lastname = '&Lastname=' + document.getElementById('checkout_lastname').value;
//	var email = '&Email=' + document.getElementById('checkout_email').value;
//	var address1 = '&Address1=' + encodeURI( document.getElementById('checkout_address_1').value );
//	var address2 = '';
//	if( document.getElementById('checkout_address_2').value != '' ) {
//		address2 = 'Address2' + encodeURI( document.getElementById('checkout_address_2').value );
//	}
//	var town = '&Town=' + encodeURI( document.getElementById('checkout_town').value );
//	var county = '&County=' + encodeURI( document.getElementById('checkout_county').value );
//	var postcode = '&PostCode=' + encodeURI( document.getElementById('checkout_postcode').value );
//	var projectid = '&ProjectID=' + getCookie( projectIdCookieName );
//	// card details
//	var cardType = '&CardType=' + document.getElementById('checkout_card_type').value;
//	var cardNumber = '&CardNo=' + document.getElementById('checkout_card_number').value;
//	var nameOnCard = '&NameOnCard=' + document.getElementById('checkout_name_on_card').value;
//	var startDate = '&StartDate=' + document.getElementById('checkout_start_date_month').value + '' + document.getElementById('checkout_start_date_year').value;
//	var endDate = '&EndDate=' + document.getElementById('checkout_end_date_month').value + '' + document.getElementById('checkout_end_date_year').value;
//	var issueNumber = '';
//	if( document.getElementById('checkout_issue_number').value != '' ) {
//		issueNumber = '&IssueNo=' + document.getElementById('checkout_issue_number').value;
//	}
//	var cv2 = '&CV2=' + document.getElementById('checkout_cv2').value;
//	// still testing
//	var test = '&Test=1';
	
	
	// everything ok, prepare the checkout request
	//executeJSONRequest( 'cart/' + version + '/checkout/?partnerID=' + partnerID + '&TransactionID=' + getTransactionList() + firstname + lastname + email + address1 + address2 + town + county + postcode + projectid + cardType + cardNumber + nameOnCard + startDate + endDate + issueNumber + cv2 + test, 'makePaymentCallback' );
	
	// dont do any of that, were now posting the data...
	var w = window.open( 'about:blank', 'basket', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=580, height=640');
	w.focus();
	return true
}

function makePaymentCallback( data ) {
	// payment successfully completed, move to the completed panel
	showStage( 'complete' );
	// and remove all transactions from session cookie
	var d = new Date();
    setCookie( transactionCookieName, '', -1 );
    // reset the minibasket
    initMiniBasket();
}

/*  removes the passed transaction from the cookie and redirects to the basket
- thus displaying the reduced basket */
function removeBasketItem( transactionId ) {
	if( confirm("Are you sure you want to remove this offset from your basket?") ) {
		var newTransactionArray = new Array();
		// user confirmed, do your worst
		oldTransactionArray = getTransactionList();
		// remove the one we dont want
		var count = 0;
		for( var transaction in oldTransactionArray ) {
			if( oldTransactionArray[transaction] != transactionId ) {
				// add to new array
				newTransactionArray[count] = oldTransactionArray[transaction];
				count++; // increment count
			}
		}
		
		// set the updated transaction list
		setTransactionList( newTransactionArray );
		
		// if its a business transaction we also need to remove it from the businessTransactionList too!!!
		// simply loop all the business transactions looking for this transactionId
		var newBusinessTransactionArray = new Array();
		var count = 0;
		var oldBusinessTransactions = getBusinessTransactionList();
		for( var businessTransaction in oldBusinessTransactions ) {
			// if its not the one we want removed
			if( oldBusinessTransactions[businessTransaction] != transactionId ) {
				// add to new array
				newBusinessTransactionArray[count] = oldBusinessTransactions[businessTransaction];
				count++; // increment count
			}
		}
		
		// set the updated business transaction list
		setBusinessTransactionList( newBusinessTransactionArray );
		
		// go to the checkout page
		document.location = '/' + locale + '' + basePath + 'checkout.php';
	}
}

/**
 * 
 * Mini-basket Functions
 * ---------------------
 * 
 **/

/* Congratulations, you've found easter egg no.5
~ extracts taken from "The Devils Dictionary" - Ambrose Bierce ( 1911 )
IAN BATCHELDOR, n. One who would exploit the dead to sell you the official t-shirt. 
*/

function initMiniBasket() {
	var transactions = getTransactionList();
	if( transactions.length == 0 ) {
		// no transactions, leave the mini basket as zeros
		document.getElementById('minibasket_offsets').innerHTML = '0';
		document.getElementById('minibasket_offsetsS').innerHTML = 's';
		document.getElementById('minibasket_tonnage').innerHTML = '0.0';	
	} else {
		executeJSONRequest( 'cart/' + projectVersion + '/transactions/?partnerID=' + partnerId + '&TransactionID=' + getTransactionList(), 'initMiniBasketCallback' );
	}
}

function getCheckoutModifier() {
	var modifier = getCookie(checkoutTotalModifierCookieName);
	if ( modifier == '' || !modifier ) {
		modifier = 1;
	}
	return modifier;
}

function initMiniBasketCallback( data ) {
	// minibasket returned data, set a variable so it doesnt have to ge called again
	basketData = data;
	var offsets = data['details']['transactions'].length;
	var offsetsDisplay = data['details']['transactions'].length;
	var offsetS = 's';
	if( offsets == 1 ) {
		offsetS = '';
	}
	// get the slider modifier percentage
	var modifier = getCheckoutModifier();
	// populate the minibasket
	document.getElementById('minibasket_offsets').innerHTML = offsetsDisplay;
	document.getElementById('minibasket_offsetsS').innerHTML = offsetS;
	document.getElementById('minibasket_tonnage').innerHTML = ( getTransactionsTotalTonnage( data['details']['transactions'] ) * modifier ).toFixed(2);
}

/**
 * 
 * Contact Form Functions
 * ----------------------
 * 
 **/

function sendContactForm( isPartner ) {
	var validate = new validateForm();
	validate.checkText( 'name', 'Name' );
	validate.validateEmailAddress( 'email', 'Email' );
	validate.checkText( 'message', 'Message' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// ok, send the details to Alan, api not written yet
	document.getElementById('contactForm').action = 'do_contact.php' + ( ( isPartner ) ? '?partner_site=1' : '' );
	// allow the form to be submitted
	return true;	
}

/**
 * 
 * Home Functions
 * --------------
 * 
 **/

function homeRSSSubscribe() {
	var validate = new validateForm();
	validate.validateEmailAddress( 'home_rss_email', 'Email Address' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// send the request
	executeRSSRequest( 'subscribe/json/?partnerID=' + partnerId + '&EmailAddress=' + document.getElementById( 'home_rss_email' ).value, 'homeRSSSubscribeCallback' );
	return false
}

function homeRSSSubscribeCallback( data ) {
	alert( 'Sign-up successful, thank you for subscribing!' );
}

/**
 * 
 * Projects Functions
 * ------------------
 * 
 **/

function getProjectList() {
	// just get a list of all projects
	executeJSONRequest( 'cart/' + projectVersion + '/projects/?PartnerID=' + partnerId, 'getProjectListCallback' );
}

function getProjectDetailsOnly() {
	executeJSONRequest( 'cart/' + projectVersion + '/projects/?PartnerID=' + partnerId, 'getProjectDetailsOnlyCallback' );
}
function getProjectDetailsOnlyCallback( data ) {
	projectInfo = new Array();
	for( var project in data['details']['projects'] ) {
		projectInfo[project] = new Array();
		// set the details of this project adding the info to an array for later use as we go
		projectInfo[project]['image'] = data['details']['projects'][project]['image'];
		projectInfo[project]['title'] = data['details']['projects'][project]['name'];
		projectInfo[project]['type'] = data['details']['projects'][project]['type'];
		projectInfo[project]['location'] = data['details']['projects'][project]['location'];
		projectInfo[project]['description'] = decodeText( data['details']['projects'][project]['description'] );
		projectInfo[project]['projectid'] = data['details']['projects'][project]['projectid'];
	}
}

function getProjectListCallback( data ) {
	buildProjectTable( data, false );
}

/**
 * 
 * Register / Login Functions
 * --------------------------
 * 
 **/

function initRegister() {
	executeGeneralRequest( 'json/countries/v1.0/?partnerid=' + partnerId, 'initRegisterCallback' );
}

function initRegisterCallback( data ) {
	var slct = document.getElementById('country');
	// if the country select is available
	if( slct != null  ) {
		for ( var country in data['details']['country'] ) {
			var opt = new Option( data['details']['country'][country]['country'], data['details']['country'][country]['localeid'] );
			slct.options[ slct.options.length ] = opt;
			if( document.getElementById('selectedCountry') != null ) {
				if( data['details']['country'][country]['localeid'] == document.getElementById('selectedCountry').value ) {
					slct.options[ slct.options.length-1 ].selected = true;
				}
			}
		}
	}
}

function validateLogin() {
	var validate = new validateForm();
	validate.checkText( 'login_email', 'Email' );
	validate.checkText( 'login_password', 'Password' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	} 
	return true;	
}

function validateRegister() {
	var validate = new validateForm();
	validate.checkSelect( 'title', '', 'Title' );
	validate.checkText( 'firstname', 'First Name' );
	validate.checkText( 'lastname', 'Last Name' );
	validate.checkText( 'address1', 'Address 1' );
	validate.checkSelect( 'country', '', 'Country' );
	validate.checkSelect( 'country', '-1', 'Country' );
	// address2 non mandatory
	validate.checkText( 'town', 'Town' );
//	validate.validatePostCode( 'postcode', 'Postcode' );
	var telephoneInput = document.getElementById( 'telephone' );
	if( telephoneInput.value == '' ) {
		// nothing entered
		validate.addCustomError( 'Telephone' );
	} else {
		// minimum length
		if( telephoneInput.value.length < 10 ) {
			validate.addCustomError( 'Telephone must be minimum 10 digits' );
		}
	}
	validate.validateEmailAddress( 'email', 'Email' );
	validate.validateEmailAddress( 'confirm_email', 'Confirm Email' );
	if( document.getElementById( 'email' ).value != document.getElementById( 'confirm_email' ).value ){
		validate.addCustomError( 'Email addresses do not match' );
	}
	validate.checkTextMinLength( 'password', 'Password', 6 );
	validate.checkTextMinLength( 'confirm_password', 'Confirm Password', 6 );
	if( document.getElementById( 'password' ).value != document.getElementById( 'confirm_password' ).value ){
		validate.addCustomError( 'Passwords do not match' );
		document.getElementById( 'password' ).value = '';
		document.getElementById( 'confirm_password' ).value = '';
	}
	
	// terms and conditions
	if( document.getElementById( 'carbonAdviceGroup_action' ).value == 'update' ){
		if( !document.getElementById( 'tandc' ).checked ) {
			validate.addCustomError( 'Accept the Terms & Conditions' );
		}
	}
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}	
	return true;
}

/**
 * 
 * Forgotten Password
 * ------------------
 * 
 **/

function forgottenPassword() {
	var validate = new validateForm();
	// must have an email address
	validate.validateEmailAddress( 'login_email', 'Email' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}	
	// send the request
	executeGeneralRequest( 'json/lost_password/' + version + '/?partnerID=' + partnerId + '&Email=' + document.getElementById( 'login_email' ).value );
	alert( "An email with your password has been sent to your email address." );
}

/**
 *
 * Partner scheme functions from the partner iframes
 * -------------------------------------------------
 *
 */
function initPartnerScheme() {
	if ( typeof partnerDetails['general'] == 'undefined' ) {
		// have not got any cached details, so get them
		getPartnerDetails( 'initPartnerSchemeCallback' );
	} else {
		// we have cached details so just call the function
		initPartnerSchemeCallback();
	}
}

function updatePartnerHomePageContent() {
	// check for any homepage content
	if ( isCarbonCoreSubscriber ) {
		executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=home&partnerID=' + partnerId, 'updateCarbonCorePartnerHomePageContentCallback' );
	} else {
		executeGeneralRequest( 'json/page_content/homepage/?partnerID=' + partnerId, 'updatePartnerHomePageContentCallback' );
	}
}

function updatePartnerClimateChangePageContent() {
	currentPartnerPageHasLinks = true;
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=climate&partnerID=' + partnerId, 'updateCarbonCorePartnerPageContent' );
}
function updatePartnerAboutPageContent() {
	currentPartnerPageHasLinks = true;
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=about&partnerID=' + partnerId, 'updateCarbonCorePartnerPageContent' );
}
function updatePartnerIndividualsPageContent() {
	currentPartnerPageHasLinks = true;
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=individuals&partnerID=' + partnerId, 'updateCarbonCorePartnerPageContent' );
}
function updatePartnerProjectsPageContent() {
	currentPartnerPageHasLinks = true;
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=projects&partnerID=' + partnerId, 'updateCarbonCorePartnerPageContent' );
}
function updatePartnerPartnerProgrammePageContent() {
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=partner&partnerID=' + partnerId, 'updatePartnerProgrammeCarbonCorePartnerPageContent' );
}

function updatePartnerProgrammeCarbonCorePartnerPageContent( data ) {
	if ( data['details']['signup_partner_name'] != '' ) {
		partnerSignupURL = 'http://microsites.carbonadvicegroup.com/signup/' + data['details']['signup_partner_name'] + '.html';
	}
	updateCarbonCorePartnerPageContent( data );
}

function updateCarbonCorePartnerPageContent( data ) {
	if ( data['details'][ currentPage + '_enabled' ] == 'True' ) {
		if ( data['details'][ currentPage + '_custom_title' ] != '' ) {
			// got a custom title to display
			document.getElementById('customTitle').innerHTML = decodeText( data['details'][ currentPage + '_custom_title' ] );
			// hide the default title
			document.getElementById('defaultTitle').style.display = 'none';
		}
		if ( data['details'][ currentPage + '_custom_text' ] != '' ) {
			// got some custom text to display
			document.getElementById('customText').innerHTML = decodeText( data['details'][ currentPage + '_custom_text' ] );
			// hide default text
			document.getElementById('defaultText').style.display = 'none';
			// and hide the default left-hand navigation if there is some
			if ( currentPartnerPageHasLinks ) {
				var navWidth = parseInt( YAHOO.util.Dom.getStyle( 'pageNav', 'width' ) );
				var navMargin = parseInt( YAHOO.util.Dom.getStyle( 'pageNav', 'marginRight' ) );
				var contentWidth = parseInt( YAHOO.util.Dom.getStyle( 'pageContent', 'width' ) );
				contentWidth += navWidth + navMargin;
				// hide the navigation
				YAHOO.util.Dom.setStyle( 'pageNav', 'display', 'none' );
				// update the width of the main content area so it spans the full available area
				YAHOO.util.Dom.setStyle( 'pageContent', 'width', contentWidth + 'px' );
			}
		}
	} else {
		// this page is not enabled on this scheme, hide the default content and redirect to the home page
		document.getElementById('defaultTitle').style.display = 'none';
		document.getElementById('defaultText').style.display = 'none';
		document.location = '/partners/';
	}
}

function updateCarbonCorePartnerHomePageContent( data ) {
	if ( data['details'][ currentPage + '_custom_title' ] != '' ) {
		// got a custom title to display
		document.getElementById('homepageContentCustomTitle').innerHTML = decodeText( data['details'][ currentPage + '_custom_title' ] );
	} else {
		// no custom title so display the default one
		document.getElementById('homepageContentCustomTitle').className = 'homeTitle';
	}
	if ( data['details'][ currentPage + '_custom_text' ] != '' ) {
		// got some custom text to display
		document.getElementById('homepageContentCustomText').innerHTML = decodeText( data['details'][ currentPage + '_custom_text' ] );
		// show custom text
		document.getElementById('homepageContentCustom').style.display = '';
		document.getElementById('homepageContentDefault').style.display = 'none';
	} else {
		// show default text
		document.getElementById('homepageContentCustom').style.display = 'none';
		document.getElementById('homepageContentDefault').style.display = '';
	}
}

function updateCarbonCorePartnerHomePageContentCallback( data ) {
	updateCarbonCorePartnerHomePageContent( data );
}

function updatePartnerPageContent( page ) {
	switch ( page.toLowerCase() ) {
		case 'home':
			updatePartnerHomePageContent();
			break;
		case 'climate':
			updatePartnerClimateChangePageContent();
			break;
		case 'about':
			updatePartnerAboutPageContent();
			break;
		case 'individuals':
			updatePartnerIndividualsPageContent();
			break;
		case 'projects':
			updatePartnerProjectsPageContent();
			break;
		case 'partner':
			updatePartnerPartnerProgrammePageContent();
			break;
		case 'contact':
			updatePartnerContactPageContent();
			break;
	}
}

function updatePartnerHomePageContentCallback( data ) {
	var showDefaultTitle = true;
	if( data['details']['page'][0]['content'] ) {
		document.getElementById('homepageContentCustomText').innerHTML = decodeText( data['details']['page'][0]['content'] );
		// show custom text
		document.getElementById('homepageContentCustom').style.display = '';
		document.getElementById('homepageContentDefault').style.display = 'none';
	} else {
		// show default text
		document.getElementById('homepageContentCustom').style.display = 'none';
		document.getElementById('homepageContentDefault').style.display = '';
	}
	if( data['details']['page'][0]['title'] ) {
		if( data['details']['page'][0]['title'] != 'What`s Your Carbon Footprint?' ) {
			// don't update the title if it's the default one
			document.getElementById('homepageContentCustomTitle').innerHTML = decodeText( data['details']['page'][0]['title'] );
			showDefaultTitle = false;
		}
	}
	if ( showDefaultTitle ) {
		// show the default title
		document.getElementById('homepageContentCustomTitle').className = 'homeTitle';
	}
}

function updatePartnerContactPageContent( data ) {
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?page=contact&partnerID=' + partnerId, 'updatePartnerContactPageContentCallback' );
}

function updatePartnerContactPageContentCallback( data ) {
	if ( data['details'][ 'contact_enabled' ] == 'True' ) {
		var customName = false;
		if ( data['details'][ 'contact_name' ] != '' ) {
			// got a custom name to display
			document.getElementById('customName').innerHTML = decodeText( data['details'][ 'contact_name' ] );
			customName = true;
			// hide the default address so avoid confusion
			document.getElementById('customAddress').innerHTML = '';
		}
		if ( data['details'][ 'contact_address' ] != '' ) {
			// got a custom address to display
			document.getElementById('customAddress').innerHTML = decodeText( data['details'][ 'contact_address' ] );
			if ( !customName ) {
				document.getElementById('customName').innerHTML = '';
			}
		}
		if ( data['details'][ 'contact_email' ] != '' ) {
			// got a custom email address to display
			document.getElementById('customEmail').innerHTML = '<a href="mailto:' + data['details'][ 'contact_email' ] + '">' + data['details'][ 'contact_email' ] + '</a>';
		}
	} else {
		// this page is not enabled on this scheme, redirect to the home page
		document.location = '/partners/';
	}
}

function getPartnerDetailsCallback( data ) {
	partnerDetails['general'] = new Array();
	partnerDetails['projects'] = new Array();
	for( details in data['details']['details'][0]['@attributes'] ) {
		// general details
		partnerDetails['general'][details] = data['details']['details'][0]['@attributes'][details];
	}
	for( details in data['details']['projects'] ) {
		// selected projects
		partnerDetails['projects'][details] = data['details']['projects'][details];
	}
}

function updatePartnerSchemeNavItem( data, prefix, navItem ) {
	if ( data['details'][ prefix + '_enabled'] == 'True' ) {
		if ( data['details'][ prefix + '_custom_link'] != '' ) {
			// got a custom title for this link, so update it
			document.getElementById('navigationLink' + navItem + 'Text').innerHTML = data['details'][ prefix + '_custom_link'];
		}
	} else {
		// hide the link as it is not enabled
		document.getElementById('navigationLink' + navItem ).style.display = 'none';
	}
}

function updatePartnerSchemeNavCallback( data ) {
	updatePartnerSchemeNavItem( data, 'home', 'Home' );
	updatePartnerSchemeNavItem( data, 'climate', 'ClimateChange' );
	updatePartnerSchemeNavItem( data, 'about', 'WhatWeDo' );
	updatePartnerSchemeNavItem( data, 'individuals', 'IndividualsBusinesses' );
	updatePartnerSchemeNavItem( data, 'partner', 'PartnerProgramme' );
	updatePartnerSchemeNavItem( data, 'projects', 'Projects' );
	if ( data['details']['partner_enabled'] != 'True' ) {
		// make sure we don't allow this user to send an affiliate link when the "Powered by CAG" logo is clicked
		// (in /partners/scripts/main.js)
		cagAffiliateID = 0;
	}
}

function updatePartnerSchemeNav() {
	// do the request to find out which pages are enabled for this partner
	executeGeneralRequest( 'json/carboncore/page_config/v1.0/?partnerID=' + partnerId, 'updatePartnerSchemeNavCallback' );
}

function initPartnerSchemeCallback( data ) {
	if ( typeof data != 'undefined' ) {
		getPartnerDetailsCallback( data );
	}
	schemeId = ( previewSchemeId == '' ) ? partnerDetails['general']['schemeid'] : previewSchemeId;
	if ( ( schemeId == 10 ) || ( schemeId == 9 ) ) {
		companyName = 'Carbon TradeXchange';
	}
	document.title = companyName;
	document.getElementById('chooseCountryPopupCompany1').innerHTML = companyName;
	document.getElementById('chooseCountryPopupCompany2').innerHTML = companyName;
	// define dimensions of scheme
	switch ( schemeId ) {
		case 2:
		case 1:
			schemeWidth = 730;
			schemeHeight = 395;
			positionOverlaysCenter = false;
			break;
		default:
			schemeWidth = '100%';
			schemeHeight = '100%';
			positionOverlaysCenter = true;
			break;
	}
	// attach our stylesheet
	var linkE = document.createElement("link");
	linkE.setAttribute("type", "text/css");
	linkE.setAttribute("rel", 'stylesheet');
	linkE.setAttribute("href", '/partners/scheme' + schemeId + '/css/main.css');
	// append to the head of the html page
	document.getElementsByTagName("head")[0].appendChild(linkE);
	if ( !errorOccured ) {
		if ( document.getElementById('validPartner') ) {
			document.getElementById('validPartner').style.display = '';
		}
	} else {
		if ( document.getElementById('invalidPartner') ) {
			document.getElementById('invalidPartner').style.display = '';
		}
	}
	
	// if this partner has platform tickets enabled show the platform tickets panel
	var showPlatformTickets = false;
	if ( partnerDetails['general']['platform_tickets_enabled'] == 'true' ) {
		if ( showPlatformTicketPopupOnThisPage ) {
			if ( getCookie( platformTicketCookieName ) !== 'true' ) {
				initPlatformTicketsPanel();
				showPlatformTickets = true;
			}
		}
	}

	// if this partner is a carboncore subscriber, update the nav with the enabled links
	if ( partnerDetails['general']['carboncore_subscriber'] == 'true' ) {
		isCarbonCoreSubscriber = true;
		updatePartnerSchemeNav();
	}
	
	if ( !showPlatformTickets && platformTicketOnComplete ) {
		platformTicketOnComplete();
	}
	updatePartnerPageContent( currentPage );
	// display the logo if we have one
	var logoHTML = '';
	var logoWidth = '';
	var logoHeight = '';
	switch( schemeId ) {
		case '1':
			logoWidth = 100;
			logoHeight = 40;
			break;
		case '2':
			logoWidth = 231;
			logoHeight = 81;
			break;
		case '3':
		case '4':
			logoWidth = 150;
			logoHeight = 90;
			break;
		case '5':
		case '9':
			logoWidth = 265;
			logoHeight = 120;
			break;
		case '6':
			logoWidth = 180;
			logoHeight = 83;
			break;
		case '7':
		case '8':
		case '10':
			logoWidth = 578;
			logoHeight = 81;
			break;
	}
	logoHTML += ( schemeId == 2 ) ? '<a href="http://www.uswitchforbusiness.com" target="_blank">' : '';
	logoHTML += '<img src="http://' + apiHost + '/general/image/client_logo/default.asp?PartnerID=' + partnerId + '&Width=' + logoWidth + '&Height=' + logoHeight + '&PreserveAspect=1" />';
	logoHTML += ( schemeId == 2 ) ? '</a>' : '';
	document.getElementById('logo').innerHTML = logoHTML;
	if ( partnerDetails['general']['bg_filename'] != '' ) {
		document.getElementById('mainBody').style.backgroundImage = 'url(http://' + apiHost + '/general/image/client_logo/default.asp?PartnerID=' + partnerId + '&Bg=1)';
	}
	// show the calculators we need to display
	if ( partnerDetails['general']['calc_car'] == '1' ) {
		document.getElementById('calculatorLinkCar').style.display = '';
		if ( document.getElementById('projectChooseCarContainer') ) {
			// show mid section link
			document.getElementById('projectChooseCarContainer').style.visibility = 'visible';
		}
	}
	if ( partnerDetails['general']['calc_home'] == '1' ) {
		document.getElementById('calculatorLinkHome').style.display = '';
		if ( document.getElementById('projectChooseHomeContainer') ) {
			// show mid section link
			document.getElementById('projectChooseHomeContainer').style.visibility = 'visible';
		}
	}
	if ( partnerDetails['general']['calc_flight'] == '1' ) {
		document.getElementById('calculatorLinkFlights').style.display = '';
		if ( document.getElementById('projectChooseFlightContainer') ) {
			// show mid section link
			document.getElementById('projectChooseFlightContainer').style.visibility = 'visible';
		}
	}
	if ( partnerDetails['general']['calc_business'] == '1' ) {
		document.getElementById('calculatorLinkBusiness').style.display = '';
		if ( document.getElementById('projectChooseBusinessContainer') ) {
			// show mid section link
			document.getElementById('projectChooseBusinessContainer').style.visibility = 'visible';
		}
	}
	// attach an onclick event to the cag logo
	if ( schemeId != 2 ) {
		YAHOO.util.Event.addListener( 'poweredByCAG', 'click', loadCAG );
	}
	// set all images with the class name 'calculateBtn' to the correct src
	var calculateBtnImages = YAHOO.util.Dom.getElementsByClassName( 'calculateBtn' );
	for ( var el in calculateBtnImages ) {
		calculateBtnImages[ el ].src = '/partners/scheme' + schemeId + '/images/btn-calculate.gif';
	}
	// set all images with the class name 'question' to the correct src
	var questionIconImages = YAHOO.util.Dom.getElementsByClassName( 'questionIcon' );
	for ( var el in questionIconImages ) {
		questionIconImages[ el ].src = '/partners/scheme' + schemeId + '/images/question.gif';
	}
	// set all images with the class name 'doneBtn' to the correct src
	var doneBtnImages = YAHOO.util.Dom.getElementsByClassName( 'doneBtn' );
	for ( var el in doneBtnImages ) {
		doneBtnImages[ el ].src = '/partners/scheme' + schemeId + '/images/btn-done.gif';
	}
	// set all images with the class name 'calculator' to the correct src
	var calendarImages = YAHOO.util.Dom.getElementsByClassName( 'calendar' );
	for ( var el in calendarImages ) {
		calendarImages[ el ].src = '/partners/scheme' + schemeId + '/images/calendar.gif';
	}
	// set all images with the class name 'addBtn' to the correct src
	var addBtnImages = YAHOO.util.Dom.getElementsByClassName( 'addBtn' );
	for ( var el in addBtnImages ) {
		addBtnImages[ el ].src = '/partners/scheme' + schemeId + '/images/btn-add.gif';
	}
	// set all images with the class name 'addOffsetBtn' to the correct src
	var addOffsetBtnImages = YAHOO.util.Dom.getElementsByClassName( 'addOffsetBtn' );
	for ( var el in addOffsetBtnImages ) {
		addOffsetBtnImages[ el ].src = '/partners/scheme' + schemeId + '/images/btn-add-offset.gif';
	}
	// set all images with the class name 'cartBarSeparator' to the correct src
	var cartBarSeparatorImages = YAHOO.util.Dom.getElementsByClassName( 'cartBarSeparator' );
	for ( var el in cartBarSeparatorImages ) {
		cartBarSeparatorImages[ el ].src = '/partners/scheme' + schemeId + '/images/cart-bar-separator.gif';
	}
	// set all images with the class name 'nextBtn' to the correct src
	var cartBarSeparatorImages = YAHOO.util.Dom.getElementsByClassName( 'nextBtn' );
	for ( var el in cartBarSeparatorImages ) {
		cartBarSeparatorImages[ el ].src = '/partners/scheme' + schemeId + '/images/btn-next.gif';
	}
	// set all images with the class name 'goBtn' to the correct src
	var cartBarSeparatorImages = YAHOO.util.Dom.getElementsByClassName( 'goBtn' );
	for ( var el in cartBarSeparatorImages ) {
		cartBarSeparatorImages[ el ].src = '/partners/scheme' + schemeId + '/images/go-small2.gif';
	}
	// show everything now we have applied the stylesheet
	document.getElementById('container').style.display = '';
}

/** START SCREEN **/

function initStartScreen() {
	startScreen = 
			new YAHOO.widget.Panel("startScreenPopup",  
											{ 
												width: "651px", 
												height: "626px", 
												fixedcenter: true, 
												close:false, 
												draggable:false, 
												modal:true,
												visible:false,
												underlay:"none",
												effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	startScreen.render(document.body);
	if( showStartScreenOnLoad )
		startScreen.show();
}

function hideStartScreen() {
	if( typeof startScreen != "undefined" ) {
		startScreen.hide();
	}
}

function showStartScreen() {
	document.getElementById('startScreenPopup').style.display = '';
	correctPNG( 'startScreenImg1' );
	correctPNG( 'startScreenImg2' );
	correctPNG( 'startScreenImg3' );
	correctPNG( 'startScreenImg4' );
	correctPNG( 'startScreenImg5' );
	correctPNG( 'startScreenImg6' );
	correctPNG( 'startScreenImg7' );
	correctPNG( 'startScreenImg8' );
	correctPNG( 'startScreenImg9' );
	if( typeof startScreen != "undefined" ) {
		startScreen.show();
	} else {
		showStartScreenOnLoad = true;
	}
}

function submitStartScreenOffset() {
	// validate the form first
	var validate = new validateForm();
	// tonnes
	validate.checkNumeric( 'startScreenInput', 'Amount' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	// the fuel type id - default to "Extra C02"
	var fuelTypeId = 25;
	// tonnes
	var quantity = document.getElementById('startScreenInput').value;
	quantity = quantity * 1000; // convert to tonnes as kg is assumed in the api
	// and make that request
	executeJSONRequest( 'additional/' + version + '/calculator/?PartnerID=' + partnerId + '&itemID=' + fuelTypeId + '&qty=' + quantity, 'submitStartScreenOffsetCallback' );
	// dont close the window yet
	return false;
}

function submitStartScreenOffsetCallback( data ) {
	// add this item to the business transactions list
	addTransaction( data['transactionid'], round( data['details']['additional'][0]['tonnes'], 2 ), 'additionalCarbon' ); // defined in business.js
	chooseProjectFromBusiness();
}

/** COUNTRY STUFF **/

function initChooseCountry() {
	// initialize the temporary Panel to display while waiting for external content to load
	document.getElementById('chooseCountryPopup').style.display = '';
	chooseCountryBox = 
			new YAHOO.widget.Panel("chooseCountryPopup",  
											{ 
												width: "269px", 
												height: "174px", 
												fixedcenter: false, 
												close:false, 
												draggable:false, 
												modal:true,
												visible:false,
												underlay:"none",
												context:['headCountry','tl','tl'],
												effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
											} 
										);
	chooseCountryBox.render(document.body);
	if( showChooseCountryOnLoad )
		doShowChooseCountry( showChooseCountryOnLoad );
}

/* hides the choose country */
function hideChooseCountry() {
	if( typeof chooseCountryBox != "undefined" )
		chooseCountryBox.hide();
	if ( document.getElementById('newsPanel') ) {
		document.getElementById('newsPanel').style.zIndex = 2;
	}
}

/* shows the choose country */
function showChooseCountry( countryCode ) {
	if( typeof chooseCountryBox != "undefined" ) {
		doShowChooseCountry( countryCode );
	} else {
		showChooseCountryOnLoad = countryCode;
	}
}

function doShowChooseCountry( countryCode ) {
	switch ( countryCode ) {
		case 'uk':
			var country = 'United Kingdom';
			break;
		case 'us':
			var country = 'United States';
			break;
		case 'au':
			var country = 'Australian';
			break;
	}
	if ( document.getElementById('newsPanel') ) {
		document.getElementById('newsPanel').style.zIndex = 0;
	}
	document.getElementById('chooseCountryPopupCountry').innerHTML = country;
	defaultCountry = countryCode;
	chooseCountryBox.show();
}

function selectCountry( makeDefault ) {
	if ( makeDefault ) {
		selectDefaultCountry();
	} else {
		document.location = '/' + defaultCountry + '' + basePath;
	}
}

function selectDefaultCountry() {
	// set the cookie
	setCookie( defaultCountryCookieName, defaultCountry, 9999 ); // store for 9999 days
	// now redirect to selected country
	document.location = '/' + defaultCountry + '' + basePath;
}

function getCurrentCountryName() {
	switch ( locale ) {
		case 'us':
			return 'United States';
		case 'au':
			return 'Australia';
		default:
			return 'United Kingdom';
	}
}

function getStates( callbackFunction ) {
	executeJSONRequest( 'domestic_energy/' + version + '/statelist/?Country=' + getCurrentCountryName() + '&PartnerID=' + partnerId, callbackFunction );
}

function populateHomeCalcStates( data ) {
	populateStatesDropDown( data, 'calculator_home_state' );
}

function populateStatesDropDown( data, selectId, callbackFunction ) {
	// get the list to populate
	var stateDropDown = document.getElementById( selectId );
	for( state in data['details']['states'] ) {
		var opt = new Option( data['details']['states'][state]['name'], data['details']['states'][state]['id'] );
		stateDropDown.options[ stateDropDown.options.length ] = opt;
	}
	if ( typeof callbackFunction != 'undefined' ) {
		eval( callbackFunction + '();' );
	}
}

/** UNSUBSCRIBE USERS **/

function unsubscribeUser() {
	var validator = new validateForm();
	validator.validateEmailAddress( 'unsubscribe_email_address', 'Email Address' );
	if ( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		// fire off api call
		var emailAddress = document.getElementById('unsubscribe_email_address').value;
		executeGeneralRequest( 'json/mailing_list/v1.0/?OptOut=1&email=' + emailAddress, 'unsubscribeUserCallback' );
		return false;
	}
}

function unsubscribeUserCallback() {
	// if we got here, we have unsubscribed.  hoorah!
	alert('You have been successfully unsubscribed from future emails.');
}

function getPartnerDetails( callback ) {
	// get all details for a partner, including name, contact details, calculators selected, and projects selected
	executeGeneralRequest( 'json/register_partner/' + version + '/details/?PartnerID=' + registeredPartnerId, callback );
}

function openPartnerWindow( url ) {
	// default open to the US version of the site
	if ( partnerSignupURL != '' ) {
		window.open( partnerSignupURL, 'partnerProgrammeWindow', 'width=1000,height=600,toolbars=no,resizable=no' );
	} else {
		window.open( 'http://www.carbonadvicegroup.com/us/' + url, 'partnerProgrammeWindow', 'width=1000,height=600,toolbars=no,resizable=no' );
	}
}

function decodeText( txt) {
	return strReplace( txt, '`', '"' );
}

function changeProjecTableType( type ) {
	// change tab styles
	document.getElementById('projectTableTabCharity').className = ( type == 'charity' ) ? 'projectTableTabOn' : 'projectTableTab';
	document.getElementById('projectTableTabOffsets').className = ( type == 'offsets' ) ? 'projectTableTabOn' : 'projectTableTab';
	doChangeProjectTableType( type );
}

function doChangeProjectTableType( type ) {
	// hide/show appropriate rows
	var charityRows = YAHOO.util.Dom.getElementsByClassName( 'projectTypeCharity' );
	var offsetRows = YAHOO.util.Dom.getElementsByClassName( 'projectTypeOffset' );
	var charityDisplay = ( type == 'charity' ) ? 'table-row' : 'none';
	var offsetDisplay = ( type == 'offsets' ) ? 'table-row' : 'none';
	/* start ie7 hackage */
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	if ( version <= 7 ) {
		if ( charityDisplay == 'table-row' ) {
			charityDisplay = 'block';
		}
		if ( offsetDisplay == 'table-row' ) {
			offsetDisplay = 'block';
		}
	}
	/* end ie7 hackage */
	for ( var row in charityRows ) {
		YAHOO.util.Dom.setStyle( charityRows[ row ], 'display', charityDisplay );
	}
	for ( var row in offsetRows ) {
		YAHOO.util.Dom.setStyle( offsetRows[ row ], 'display', offsetDisplay );
	}
}

/** project info popup **/

var youTubeHTML = '';
var brochureLink = '';
var registryLink = '';
var certLink = '';
var currentImage = 1;
var totalImages = 1;
var viewingVideo = 0;
var subPopOpen = 0;

function openProjectInfoWindow( url, name ) {
	window.open( url, name, 'width=600,height=400' );
}

function showProjectBrochure() {
	openProjectInfoWindow(brochureLink,"Brochure");
}
function showProjectVideo() {
	subPopOpen = 1;
	viewingVideo = 1;
	document.getElementById('mainPopupBox').style.display='none';
	document.getElementById('popupVideoSection').innerHTML = youTubeHTML;
	document.getElementById('videoPopupBox').style.display='';
}
function showProjectImages() {
	subPopOpen = 1;
	document.getElementById('mainPopupBox').style.display='none';
	document.getElementById('imagePopupBox').style.display='';
}
function showProjectRegistry() {
	openProjectInfoWindow(registryLink,"Registry");
}
function showProjectCerts() {
	openProjectInfoWindow(certLink,"Certificates");
}
function showProjectMap() {
	subPopOpen = 1;
	document.getElementById('mainPopupBox').style.display='none';
	document.getElementById('mapPopupBox').style.display='';
}
function doHideProjectInfo() {
	if(subPopOpen == 1) {
		if ( viewingVideo ) {
			document.getElementById('popupVideoSection').innerHTML = '';
			viewingVideo = 0;
		}
		document.getElementById('imagePopupBox').style.display='none';
		document.getElementById('videoPopupBox').style.display='none';
		document.getElementById('mapPopupBox').style.display='none';
		document.getElementById('mainPopupBox').style.display='';
		subPopOpen = 0;
	}
	else {
		hideProjectInfo();		
	}
}
function changeImage(direction) {
	switch(direction) {
		case 'left':
			if (currentImage > 1) {
				var currentImageBox = 'popupImage' + currentImage;
				document.getElementById(currentImageBox).style.display = 'none';
				currentImage--;
				var newImageBox = 'popupImage' + currentImage;
				document.getElementById(newImageBox).style.display = '';
			}
			break;
		case 'right':
			if (currentImage < totalImages) {
				var currentImageBox = 'popupImage' + currentImage;
				document.getElementById(currentImageBox).style.display = 'none';
				currentImage++;
				var newImageBox = 'popupImage' + currentImage;
				document.getElementById(newImageBox).style.display = '';
			}
			break;
	}
	var imageContentBottom = document.getElementById('popupImageBottom');
	imageContentBottom.innerHTML = 'Image ' + currentImage + ' of ' + totalImages; 
}
/** end project info popup **/


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