// hook into loaded event
var myUIRunner = null;
document.observe("dom:loaded", function() { myUIRunner = new UIRunner() } )

// prototype functions
String.prototype.trim = function() 
{
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};

/*
	questions contains a map of all question items
	and properties in order to drive the javascript
	validation, scrolling and calculations
*/

var maxDays = 40;
var maxActivities = 40;
var maxKm = 4000;

var allQuestions = {
	'Field_Holiday_WhoIsGoing' :
	{
		name: 'Holiday Who Is Going',
		type: 'slider',
		value: 2,
		group: undefined,
		slider: undefined,
		slider_range: $R(1, 20),
		slider_values: undefined
	},
	'Field_Holiday_HolidayDuration' : 
	{
		name: 'Holiday Duration',
		type: 'slider',
		value: 1,
		group: undefined,
		slider: undefined,
		slider_range: $R(1, maxDays),
		slider_values: $R(1, maxDays)
	},
	'Field_Holiday_Name' : 
	{
		name: 'Holiday Name',
		type: 'text',
		value: 'My Great Holiday',
		group: undefined
	},
	'Field_Holiday_HomeLocation' :
	{
		name: 'Holiday Home Location',
		type: 'select',
		value: 'Australia',
		group: undefined
	},
	'Field_Transport_InternationalAir' :
	{
		name: 'Transport International Air',
		type: 'button',
		value: undefined, // gets saved and loaded seperately
		
		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value;
		},
		calcValuePerGroup: function(value){
			return value * peopleCount();
		}
	},
	'Field_Transport_DomesticAir' :
	{
		name: 'Transport Domestic Air',
		type: 'button',
		value: undefined, // gets saved and loaded seperately
		
		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value;
		},
		calcValuePerGroup: function(value){
			return value * peopleCount();
		}
	},
	'Field_Transport_Car' :
	{
		name: 'Transport Car',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxKm),
		slider_values: undefined,

		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 0.2550;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value);
		}
	},
	'Field_Transport_Bus' :
	{
		name: 'Transport Bus',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxKm),
		slider_values: undefined,

		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 0.087;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Transport_Train' :
	{
		name: 'Transport Train',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxKm),
		slider_values: undefined,

		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 0.1240;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Transport_Boat' :
	{
		name: 'Transport Boat',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0,maxKm),
		slider_values: undefined,

		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 0.3010;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Transport_Motorhome' :
	{
		name: 'Transport Motorhome',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxKm),
		slider_values: undefined,

		group : 'Page_Transport',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 0.3010;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Accomodation_BedBreakfast' :
	{
		name: 'Accommodation Bed-breakfast',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxDays),
		slider_values: undefined,

		group : 'Page_Accommodation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 5;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Accomodation_HotelVacation' :
	{
		name: 'Accommodation Hotel Vacation',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxDays),
		slider_values: undefined,

		group : 'Page_Accommodation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 24;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Accomodation_Hostel' :
	{
		name: 'Accommodation Hostel',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxDays),
		slider_values: undefined,

		group : 'Page_Accommodation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 3;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Accomodation_Motel' :
	{
		name: 'Accommodation Motel',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxDays),
		slider_values: undefined,

		group : 'Page_Accommodation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 8;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Accomodation_Private' :
	{
		name: 'Accommodation Private Home',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxDays),
		slider_values: undefined,

		group : 'Page_Accommodation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 8.9589;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Accomodation_Camping' :
	{
		name: 'Accommodation Camping',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxDays),
		slider_values: undefined,

		group : 'Page_Accommodation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return value * 1.3600;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value) * peopleCount();
		}
	},
	'Field_Recreation_SportingActivities' :
	{
		name: 'Recreation Sporting Activities',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxActivities),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return this.calcValuePerGroup(value) / peopleCount();
		},
		calcValuePerGroup: function(value){
			return value * 17;
		}
	},
	'Field_Recreation_VisitAttractions' :
	{
		name: 'Recreation Visit Attractions',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxActivities),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return this.calcValuePerGroup(value) / peopleCount();
		},
		calcValuePerGroup: function(value){
			return value * 1;
		}
	},
	'Field_Recreation_VisitorCentres' :
	{
		name: 'Recreation Visitor Centres',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxActivities),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return this.calcValuePerGroup(value) / peopleCount();
		},
		calcValuePerGroup: function(value){
			return value * 1;
		}
	},
	'Field_Recreation_SpaTreatments' :
	{
		name: 'Recreation Spa Treatments',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxActivities),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return this.calcValuePerGroup(value) / peopleCount();
		},
		calcValuePerGroup: function(value){
			return value * 14;
		}
	},
	'Field_Recreation_EatOut' :
	{
		name: 'Recreation Eat Out',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, maxActivities),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return this.calcValuePerGroup(value) / peopleCount();
		},
		calcValuePerGroup: function(value){
			return value * 2;
		}
	},
	'Field_Recreation_Vegetarian' :
	{
		name: 'Recreation Vegetarian',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, 100),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return -1 * (0.01*value) * 3 * allQuestions.Field_Holiday_HolidayDuration.value;
		},
		calcValuePerGroup: function(value){
			return this.calcValuePerPerson(value);
		}
	},
	'Field_Recreation_Shopping' :
	{
		name: 'Recreation Shopping',
		type: 'slider',
		value: 0,
		
		slider: undefined,
		slider_range: $R(0, 5000),
		slider_values: undefined,

		group : 'Page_Recreation',
		emissionsPerPerson : 0,
		emissionsPerGroup : 0,
		calcValuePerPerson: function(value){
			return this.calcValuePerGroup(value) / peopleCount();
		},
		calcValuePerGroup: function(value){
			return value * 1.5;
		}
	}
};

/*
	Helper function for html tag getting and setting
*/
function getEmission(emission)
{
	var p = $(emission).down('p');
	return parseInt($(p).innerHTML.substring(0,$(p).innerHTML.indexOf('kg')).trim());
}
function getEmissionFromPage(page)
{
	return getEmission($(page).down('.emissions'));
}
function setEmission(emission, value)
{
	$(emission).down('p').update(roundNumber(value) + '<span>kg</span>');
}
function setEmissionFromPage(page,value)
{
	setEmission($(page).down('.emissions'),value);
}
function getResult(result)
{
	return roundNumber($(result).innerHTML.substring(0,$(result).innerHTML.indexOf('kg')).trim());
}
function setResultFromQuestion(question, value)
{
	$(question).down('.result').update(roundNumber(value).toString() + ' kg*');
	$(question).down('.result').title = value.toString() + ' kg CO2-e per person (' + allQuestions[question.id].emissionsPerGroup + ' kg for group of '+ peopleCount() +' people)';
}
function getInput(question)
{
	return $(question).down('input').value;
}
function setInput(question, value)
{
	$(question).down('input').value = value;
}
function doCalcEmission(questions, question, value)
{
	// per person
	questions[question].emissionsPerPerson = questions[question].calcValuePerPerson(value);
	// per group
	questions[question].emissionsPerGroup = questions[question].calcValuePerGroup(value);
}

/*
 main class/function which will do all js processing
*/
var UIRunner = Class.create({
	initialize : function()
{	

	// private properties
	var currentQuestion = undefined;
	this.currentlyOpenQuestion = undefined;
	this.questions = allQuestions;
	this.updatingQuestion = false;

	this.emailAddress = '';
	
	var self = this;
		
	// loop through all questions
	$$('.question').each(function(question) 
	{
		currentQuestion = question;

		// setup listeners
		self.setQuestionEventListeners(currentQuestion);

		// create the sliders
		self.generateSliders(currentQuestion);
		
		// update the question values
		// NOT SURE THIS IS NEEDED HERE
		self.updateQuestionValue(currentQuestion);
	});
	// setup listeners for everything else
	this.setOverallEventListeners();
	
	this.grapher = new Grapher(this.questions);
	
	// setup the wizard
	this.wizard = new Wizard(function(oldSection, newSection)
	{
		// check if we're at the last page
		if( newSection.id == 'Page_Results')
		{
			// call the Grapher to update the graphs
			self.grapher.refresh();
		}
	});
	
	// setup the flights
	this.flights = new Flights(function(domesticEmissions, internationalEmissions)
	{
		self.updateFlights(domesticEmissions, internationalEmissions)
	});
	
	// hide the popups
	$$('.popup-wrapper').each( function(obj){
		obj.hide()
	});
	$('popups').show();
	
	// hide the loading page
	$('loading').fade();
	
},
updateFlights : function(domesticEmissions, internationalEmissions)
{
	var domDiv = 'Field_Transport_DomesticAir';
	var intDiv = 'Field_Transport_InternationalAir';

	// domestic
	doCalcEmission(this.questions, domDiv, domesticEmissions);
	setResultFromQuestion($(domDiv),this.questions[domDiv].emissionsPerPerson.toString());
	shouldUpdate = true;

	// international
	doCalcEmission(this.questions, intDiv, internationalEmissions);
	setResultFromQuestion($(intDiv),this.questions[intDiv].emissionsPerPerson.toString());
	shouldUpdate = true;

	this.updateEmissionsSection('Page_Transport');	
},
updateQuestionValue: function(question)
{
	var self = this;
	self.currentlyOpenQuestion = question;
	// check for input
	if( question.down('input') != undefined)
	{
		// is it radio, button or something else
		elementInput = question.down('input')
		if(elementInput.type == 'text')
		{
			elementInput.value = this.questions[question.id].value;
			if( question.down('.slider') != undefined)
			{
				// call input change so as to update
				this.updateSlider(question, elementInput.value);
			}
		}
	}
	else if( question.down('select') != undefined)
	{	
		var elementSelect = question.down('select');
		for(var index = 0; index<elementSelect.options.length; index++)
		{
			if( elementSelect.options[index].value == this.questions[question.id].value )
			{
				elementSelect.selectedIndex = index;
				break;
			}
		}
	}
},
setQuestionEventListeners : function(question)
{
	// save off this
	var self = this;
	
	// expand effect
	Event.observe(question, 'mouseover', function(event) { 
		self.expandQuestion(this); 
	});
	
	// input box (if any)
	var inputElement = question.down('input');
	if( inputElement != undefined)
	{
		// only wire up text fields
		if( inputElement.type == 'text' )
		{
			// wire up the blur event on the input element (if there is one)
			Event.observe(inputElement, 'blur', function(event)
			{
				return self.inputChanged(this, event);
			});

			// also keypress
			//Event.observe(input, 'keyup', function(event) {RAT_ValidateRemoveNonNumeric(this);})
			//Event.observe(input, 'keypress', function(event) {return(RAT_ValidateForceNumbersOnly(this, event));})
		}
	}
	
	// select box
	var inputElement = question.down('select');
	if( inputElement != undefined)
	{
		// wire up the blur event on the input element (if there is one)
		Event.observe(inputElement, 'change', function(event)
		{
			// update the question
			self.questions[question.id].value = this.options[this.selectedIndex].text;
		});
	}
},
setOverallEventListeners : function()
{
	var self = this;
	// flights
	$$('.addFlightBtn').each(function(button)
	{
		Event.observe(button,'click',function(event)
		{
			if( $(this).up('.question').id == 'Field_Transport_InternationalAir' )
				self.flights.loadCountries(true)
			else
				self.flights.loadCountries(false);
			showPopup('flights-div');
		});
	});
	
	var emailText = 'Enter your email here';
	// email address
	Event.observe($('email-address').down('input'), 'focus', function(event){ this.value = ""; })
	Event.observe($('email-address').down('input'), 'blur', function(event)
	{ 
		if( this.value == "")
			this.value = emailText; 
	});
	
	// finish button
	Event.observe($('finish-button').down('a'), 'click', function(event){
		// check for email address
		var email = $('email-address').down('input').value;
		if( email != emailText)
		{
			if( self.checkEmailAddress(email))
			{
				self.setEmailSession(email);
				self.saveData();
			}
		}
		else
		{
			// remind the user that they haven't
			// saved there data
			self.showSaveReminder();
		}
	});
	
	var signInTag = 'popup-sign-in-div';
	// setup grouping change
	Event.observe($('results-grouping'),'change',function(event)
	{
		self.grapher.refresh();
	});
	
	
	// try signing in click
	Event.observe($('popup-sign-in-done'), 'click', function(event){ self.signIn(); })
	Event.observe($('popup-sign-in-close'), 'click', function(event)
	{ 
		hidePopup(signInTag);
	})
},
checkEmailAddress : function(email)
{
	// reg ex for email address
	var regEx = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	if( email.match(regEx) )
		return true;
	else
		return false;
},
signIn : function()
{
	var signInErrorTag = 'popup-sign-in-failed';
	$(signInErrorTag).setStyle('display:none');
	// get the value of the email address
	var emailAddress = $('popup-sign-in-email').value;
	if( emailAddress != '' && this.checkEmailAddress(emailAddress))
	{
		// try to
		var url = './server/stcrcServer.php?fx=LoadData&w=' + emailAddress;
		var self = this;
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) 
		  {
			
		  	// see what we got back
			var rawData = transport.responseText.evalJSON();
			if( rawData != false )
			{
				// all is well so call load
				self.setEmailSession(emailAddress);
				self.loadData(rawData);
				self.flights.loadData(emailAddress, function(dom,inter){ self.updateFlights(dom,inter); });
				// finally move the user to the first screen of the wizard
				$('email-address').down('input').value = emailAddress;
				$('popup-sign-in-div').hide();
				self.wizard.gotoStart();
			}
			else
			{
				$(signInErrorTag).setStyle('display:inline');
				$(signInErrorTag).update("Your email address was not found. Please try again.");
			}
		  }
		});
	}
	else
	{
		$(signInErrorTag).setStyle('display:inline');
		$(signInErrorTag).update('Please enter a valid email address and try again.');
	}
},
loadData : function(data)
{
	// load the questions with the data using
	// the column names as the index
	for(columnIndex in data)
	{
		// this shouldn't happen, just sanity check
		if( this.questions[columnIndex] != undefined )
		{
			// update the value
			this.questions[columnIndex].value = data[columnIndex];
			// now update the page
			this.updateQuestionValue($(columnIndex));
		}
		else
		{
			if( columnIndex == 'StayInTouch' )
			{
				// special case
				$('StayInTouch').checked = (data[columnIndex] == 'Yes')?true:false;
			}
			// check if its the email or user id
			else if (columnIndex != 'EmailAddress' && 
				columnIndex != 'UserId' )
			{
				alert('error loading questions!');
				break;
			}
		}
	}

},
saveData : function()
{
	var self = this;
	// use the questions array saving, but copy
	// into a new array as we're only interested
	// in the value
	var data = {};
	for(questionIndex in this.questions)
	{
		if(this.questions[questionIndex].value != undefined)
			data[questionIndex] = this.questions[questionIndex].value.toString();
	}
	
	// try to
	var url = './server/stcrcServer.php?fx=SaveData&q=' + this.emailAddress + '&b=' + $H(data).toJSON() + '&z=' + $('StayInTouch').checked.toString();
	new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) 
	  {
	  	// see what we got back
		var result = transport.responseText;
		if( result == 'True' )
		{
			// ask flights to save its data as well
			self.flights.saveData(self.emailAddress, function()
			{
				// flights saved successfully
				// thankyou
				showPopup('popup-thankyou-div');
			}, function()
			{
				// flights save failed TBD
				self.showError("Cannot save to database. Please try again soon");
			});
		}
		else
		{
			// save failed TBD
			self.showError("Cannot save to database. please try again soon");
		}
	  }
	});
},
showError : function(error)
{
	$('popup-error-text').update(error);
	$('popup-error-div').show();
},
showSaveReminder : function()
{
	var self = this;
	var continueDiv = 'popup-reminder-continue';
	var cancelDiv = 'popup-reminder-cancel';
	var reminderDiv = 'popup-reminder-div';
	var thankyouDiv = 'popup-thankyou-div'
/*	
	// register events for the popup
	Event.observe($(continueDiv), 'click', function(event)
	{
		// show thankyou pate
		$(reminderDiv).hide();
		$(thankyouDiv).show();
		Event.stopObserving($(continueDiv), 'click');
		Event.stopObserving($(cancelDiv), 'click');		
	});
	
	Event.observe($(cancelDiv), 'click', function(event)
	{
		$(reminderDiv).hide();		
		Event.stopObserving($(continueDiv), 'click');
		Event.stopObserving($(cancelDiv), 'click');
	});
*/	
	// show reminder div
	showPopup(reminderDiv);
	
},
setEmailSession : function(email)
{
	// for the moment we can just
	// save off the email address
	
	this.emailAddress = email;
	
	// TBD add changing of gui to signify
	// logged in user
},
expandQuestion : function(questionBlock)
{
	// dont bother opening msyelf again if already open
	if (questionBlock == this.currentlyOpenQuestion){
		return;
	}
	
	// setup default animation for expanding/contract
	var effectOptions = {
			duration: 0.5,
			transition: Effect.Transitions.sinoidal
	};
	
	// first all set to closed look and feel
	$$('.question').each(function(obj) {
	  	obj.removeClassName('open');
		obj.addClassName('closed');
		obj.morph('height: 17px', effectOptions );
	});

	// show selected one's <p> and highlight it
	$(questionBlock).addClassName('open');
	questionBlock.morph('height: 90px', effectOptions );
	
	this.currentlyOpenQuestion = questionBlock;
},
inputChanged : function(input, event)
{
		this.updatingQuestion = true;
		var question = $(input).up('.question');
		switch( this.questions[question.id].type )
		{
			case "slider":
				// must be numeric
				if( isNaN(input.value) )
				{
					input.value = this.questions[question.id].slider_range.min();
				}
			
				if(parseFloat(input.value) > this.questions[question.id].slider_range.max())
				{
					// in this situation allow the value but set the slider to be
					// at its maximum point
					this.updateSlider(question,this.questions[question.id].slider_range.max());
				}
				else if( parseFloat(input.value) < this.questions[question.id].slider_range.min())
				{
					// set to min range as well as the 
					this.updateSlider(question,this.questions[question.id].slider_range.min());
					input.value = this.questions[question.id].slider_range.min();
				}
				else
				{
					// is well update the slide
					this.updateSlider(question,input.value);
				}
				break;
			
			case "button":
				// numeric check
				if( isNaN(input.value) )
				{
					input.value = 0;
				}
				this.updateEmissions(question, input.value);
				break;
			
			
		}
		// update the question
		this.questions[question.id].value = input.value;
		
		this.updatingQuestion = false;
		
	return true;
},
generateSliders : function(question)
{
	// setup the sliders (if there are any for this field)
	
	var slider = question.down('.slider');
	if( slider != undefined )
	{
		// sanity check
		if( this.questions[question.id] != undefined)
		{
			// This doesn't seem to be working as the DOM isn't
			// populated and then the div is required
			//slider.innerHtml = "<div class='handle'></div>";
			var self = this;
			this.questions[question.id].slider = new Control.Slider(slider.down('.handle'), slider, {
			      range: this.questions[question.id].slider_range,
				  values: this.questions[question.id].slider_values,
			      sliderValue: this.questions[question.id].value,
			      onSlide: function(value)
					{ 
						//self.questions[self.currentlyOpenQuestion.id].onSliderChange(self.currentlyOpenQuestion,value);
						self.updateInput(self.currentlyOpenQuestion,value);
					},
				  onChange: function(value)
			    	{
						if(!self.updatingQuestion)
						{
							self.updateInput(self.currentlyOpenQuestion,value);
						}
				    }
			    });
		}
		else
		{
			assert("missing field definition!")
		}
	}
},
updateInput : function(question, value)
{
	// find the one and only input tag and update val
	setInput(question, Math.round(parseFloat(value)).toString());
	this.questions[question.id].value = value;
	this.updateEmissions(question, value);
},
updateSlider : function(question, value)
{
	// set the slider
	this.questions[question.id].slider.setValue(value);
	this.updateEmissions(question, value);
},
updateEmissions : function(question, value)
{
	if(this.questions[question.id].calcValuePerPerson != undefined )
	{
		// update the valuePerPerson and valuePerGroup for easy use later on
		doCalcEmission(this.questions,question.id,getInput(question.id));
		setResultFromQuestion(question, this.questions[question.id].emissionsPerPerson);
		// update the total emissions
		this.updateEmissionsSection(question.up('.sliding-content'));
	}
},
updateEmissionsSection : function(section)
{
	var total = 0;
	// loop through all results to get total value
	$(section).select('.result').each(function(result)
	{
		var resultInt = getResult(result);
		if( resultInt != NaN)
			total += resultInt;
	});
	
	// update the total
	setEmission($(section).down('.emissions'), roundNumber(total).toString());

}

});


/*
	class which will deal with all wizard
	navigation using only prototype and css classes
*/
var Wizard = Class.create({
	initialize : function(callback)
	{
		// lets try to do this without 
		// building any array data structs
		this.onChangePage = callback;
		var self = this;
		var first = true;
		this.pageClass = '.sliding-content';
		
		$$(this.pageClass).each(function(slider)
		{
			self.setEventListener($(slider).down('li.back'), self.movePrevious);
			self.setEventListener($(slider).down('li.next'), self.moveNext);
			// might not need this if JC can hide
			// everything except the home page to start with
			if(first)
			{
				$(slider).show();
				first = false;
			}
			else
			{
				$(slider).hide();
			}
		})
	},
	setEventListener : function(nav, onclick)
	{
		// now get the previous and next buttons
		var self = this;
		if( nav != undefined)
			Event.observe($(nav).down('a'), 'click', function(event){
				onclick(self, this ); });
	},
	movePrevious : function(me, control)
	{
		var current = $(control).up(me.pageClass);
		if( $(current).previous(me.pageClass) != undefined)
		{
			// do callback for any processing
			// before moving
			me.onChangePage(current,$(current).previous(me.pageClass));
			
			current.hide();
			// there is a previous
			var next = $(current).previous(me.pageClass);
			next.appear();
			$$('.progress-inner').first().className = 'progress-inner ' + next.id;
			updateTips();
			var nextQ = next.down(".question")
			if (nextQ){
				myUIRunner.expandQuestion(nextQ);
			}
			
		}
		// make sure we return false so href isn't followed
		return false;
	},
	moveNext : function(me, control)
	{
		var current = $(control).up(me.pageClass);
		if( $(current).next(me.pageClass) != undefined)
		{
			// do callback for any processing
			// before moving
			me.onChangePage(current,$(current).next(me.pageClass));
			current.hide();
			var next = $(current).next(me.pageClass);
			next.appear();
			$$('.progress-inner').first().className = 'progress-inner ' + next.id;
			updateTips();
			var nextQ = next.down(".question")
			if (nextQ){
				myUIRunner.expandQuestion(nextQ);
			}
			
	}
		
		// make sure we return false so href isn't followed
		return false;
	},
	gotoStart : function()
	{
		// this is dodgy just to get it going
		this.moveNext(this, $('Page_Home').down('li.next'));
	}
});


/*
	Deals with the flights popup
*/

var Flights = Class.create({
	initialize : function(callback)
	{
		this.flightsTag = 'flights-div';
		this.countryFromTag = 'flight-from-country-select';
		this.countryToTag = 'flight-to-country-select';
		this.airportFromTag = 'flight-from-airport-select';
		this.airportToTag = 'flight-to-airport-select';
		this.returnTag = 'flight-input-return';
		this.addTag = 'flight-add';
		this.doneTag = 'flight-done';
		this.resultsTag = 'flight-results'
		
		this.emailAddress = '';
		this.flightData = Array();

		var self = this;

		// wireup event handlers
		Event.observe($(this.countryFromTag), 'change', function(event)
		{ 
			self.onCountryChanged($(self.countryFromTag),$(self.airportFromTag),'AirportId', 'AirportNameNice');
		});
		Event.observe($(this.countryToTag), 'change', function(event)
		{ 
			self.onCountryChanged($(self.countryToTag), $(self.airportToTag), 'AirportId', 'AirportNameNice' );
		});
		
		// add href
		Event.observe($(this.addTag), 'click', function(event){ self.addFlight(self); });
		Event.observe($(this.doneTag), 'click', function(event)
		{ 
			self.calcTotals(callback); 
		});
		
	},
	loadCountries: function(international)
	{
		var self = this;
		if(international)
		{

			// load the countries
			var url = './server/stcrcServer.php?fx=GetAirportCountries';
			new Ajax.Request(url, {
			  method: 'get',
			  onSuccess: function(transport) 
			  {
			  	// see what we got back
				var rawData = transport.responseText.evalJSON();
				if(rawData.length > 0)
				{
					self.buildMenu(self.countryToTag, rawData, 'Country', 'Country');
					// make sure that first airport at selected country shows
					self.onCountryChanged($(self.countryToTag),$(self.airportToTag),'AirportId', 'AirportNameNice');
				
					self.buildMenu(self.countryFromTag, rawData, 'Country', 'Country');
					// make sure that first airport at selected country shows
					self.onCountryChanged($(self.countryFromTag),$(self.airportFromTag),'AirportId', 'AirportNameNice');				
				}
			  }
			});
			
		}
		else
		{
			self.buildMenu(self.countryToTag, $A([{'Country' : 'AUSTRALIA'}]), 'Country', 'Country');
			// make sure that first airport at selected country shows
			self.onCountryChanged($(self.countryToTag),$(self.airportToTag),'AirportId', 'AirportNameNice');
			
			self.buildMenu(self.countryFromTag, $A([{'Country' : 'AUSTRALIA'}]), 'Country', 'Country');
			// make sure that first airport at selected country shows
			self.onCountryChanged($(self.countryFromTag),$(self.airportFromTag),'AirportId', 'AirportNameNice');
		}
		
	},
	loadData : function(emailAddress, callback)
	{
		var self = this;

		if( emailAddress != "")
		{
			var url = './server/stcrcServer.php?fx=GetFlightsData&e=' + emailAddress

			new Ajax.Request(url, {
			  method: 'get',
			  onSuccess: function(transport) 
			  {
			  	// see what we got back
				var rawData = transport.responseText.evalJSON();;
				if(rawData.length > 0)
				{
					self.flightData = rawData;
					self.buildTable();
				}
				// update the totals in the main page
				self.calcTotals(callback);
			  }
			});
		}
		
	},
	saveData : function(emailAddress, successCallback, failCallback)
	{
		// take the flights data and send to the server
		var url = './server/stcrcServer.php?fx=SaveFlightsData&e=' + emailAddress + '&o=' + Object.toJSON(this.flightData);
		var self = this;
		
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) 
		  {
		  	// see what we got back
			var result = transport.responseText;
			if(result == 'True')
				successCallback();
			else
				failCallback();
		  },
		  onFailure: function(transport)
		  {
				failCallback();			
		  }
		});
	},
	calcTotals : function(callback)
	{
		// if there are any flights, then
		// get the data and update the total back in the wizard
		var totalEmissionsDom = 0.0;
		var totalEmissionsInt = 0.0;
		for(var index=0; index < this.flightData.length; index++)
		{
			if(this.flightData[index].IsDomestic == 'Yes')
				totalEmissionsDom += parseFloat(this.flightData[index].Emissions);
			else
				totalEmissionsInt += parseFloat(this.flightData[index].Emissions);
		}
		hidePopup('flights-div');
		// callback
		callback(totalEmissionsDom, totalEmissionsInt);
	},
	getFlightData : function(callback)
	{
		this.done(callback);
	},
	buildMenu : function(div, data, keyString, valueString)
	{
		// loop through the countries
		// and setup the select list

		var html = "";
		for(var counter = 0; counter < data.length; counter++)
		{
			html += "<option value='" + data[counter][keyString] + "'>" + data[counter][valueString] + "</option>";
		}
		// this might be the select itself and not a div
		$(div).update(html);
	},
	onCountryChanged : function(country, airport, arrayKey, arrayValue)
	{
		// get the selected item (key)
		var selectedItem = $(country).options[$(country).selectedIndex].value;
		
		// use ajax to call and get a list of airports for the selected country
		var url = './server/stcrcServer.php?fx=GetAirports&l=' + selectedItem;
		var self = this;
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) 
		  {
		  	// see what we got back
			var rawData = transport.responseText.evalJSON();;
			if(rawData.length > 0)
			{
				$(airport).show();
				self.buildMenu(airport, rawData, arrayKey, arrayValue);
			}
		  }
		});
	},
	buildTable : function()
	{
		var htmlInt = '<h4>International Flights</h4><table>';
		var htmlDom = '<h4>Domestic Flights</h4><table>'
		htmlInt += '<tr><th>From</th><th>To</th><th>Distance</th><th>Emissions</th><th>Action</th></tr>';
		htmlDom += '<tr><th>From</th><th>To</th><th>Distance</th><th>Emissions</th><th>Action</th></tr>';
		var wasInt = false;
		var wasDom = false;
		for(var index = 0; index< this.flightData.length; index++)
		{
			if( this.flightData[index].IsDomestic == 'Yes' )
			{
				wasDom = true;
				htmlDom += '<tr><td>' + this.flightData[index].FromAirport + '</td><td>' + this.flightData[index].ToAirport;
				htmlDom += '</td><td>' + roundNumber(this.flightData[index].Distance) + ' km</td><td>' + roundNumber(this.flightData[index].Emissions) + ' kg CO2-e</td><td><a id="flight_index_'+index+'" href="#">Delete Flight</a></td></tr>';
			}
			else
			{
				wasInt = true;
				htmlInt += '<tr><td>' + this.flightData[index].FromAirport + '</td><td>' + this.flightData[index].ToAirport;
				htmlInt += '</td><td>' + roundNumber(this.flightData[index].Distance) + ' km </td><td>' + roundNumber(this.flightData[index].Emissions) + ' kg CO2-e</td><td><a id="flight_index_'+index+'" href="#">Delete Flight</a></td></tr>';
			}
		}
		htmlInt += '</table>';
		htmlDom += '</table>';
		var html = '';
		if( wasInt )
			html += htmlInt;
		if( wasDom )
			html += htmlDom;
			
		$(this.resultsTag).innerHTML = html;
		
		var self = this;
		// wire up delete
		for(var index = 0; index< this.flightData.length; index++)
		{
			Event.observe($('flight_index_'+index.toString()), 'click', function(event){
				var i = parseInt(this.id.slice(this.id.lastIndexOf('_')+1));
				self.flightData.splice(i,1);
				self.buildTable();
			});
		}
	},
	addFlight : function(self)
	{
		// get the new values and call the webservice
		if($(self.airportToTag).selectedIndex != -1 && $(self.airportFromTag).selectedIndex != -1)
		{
			var aFromKey = $(self.airportFromTag).options[$(self.airportFromTag).selectedIndex].value;
			var aToKey = $(self.airportToTag).options[$(self.airportToTag).selectedIndex].value;
			var aFromValue = $(self.airportFromTag).options[$(self.airportFromTag).selectedIndex].text;
			var aToValue = $(self.airportToTag).options[$(self.airportToTag).selectedIndex].text;
			if( aFromKey != aToKey )
			{
				var isDomestic = false;

				if(($(self.countryFromTag).options[$(self.countryFromTag).selectedIndex].text.trim() == 'AUSTRALIA') &&
				($(self.countryToTag).options[$(self.countryToTag).selectedIndex].text.trim() == 'AUSTRALIA'))
				{
					isDomestic = true;
				}
				// make a call to the server to get the distance and emissions
				var url = './server/stcrcServer.php?fx=GetDistanceEmissions&g=' + aToKey + '&f=' + aFromKey;

				new Ajax.Request(url, {
				  method: 'get',
				  onSuccess: function(transport) 
				  {
				  	// see what we got back
					var rawData = transport.responseText.evalJSON();;
					if( rawData != undefined)
					{
						// add to array and rebuild
					
						self.flightData.push(
							{
								'FromAirport' : aFromValue, 'ToAirport' : aToValue, 'Distance': rawData.Distance,
								'Emissions' : rawData.Emissions, 'IsDomestic': (isDomestic==false)?'No':'Yes'
							});
						// if return then just add again reversing from and to
						if($(self.returnTag).checked )
						{
							self.flightData.push(
								{
									'FromAirport' : aToValue, 'ToAirport' : aFromValue, 'Distance': rawData.Distance,
									'Emissions' : rawData.Emissions, 'IsDomestic': (isDomestic==false)?'No':'Yes'
								});
						}
					
						// finally call the table build
						self.buildTable();
					}
				  }
				});
			}
			else
				alert('Origin and Destination must be different');
		}
	}
});

var GDirectionObject;
var DrivingMap = Class.create({
	initialize : function(mapDiv, directionsDiv, ddFrom, ddTo, distanceSpan, callback)
	{
		this.container = 'popup-drivingcalc';
		this.mapDiv = mapDiv;
		this.ddFrom = ddFrom;
		this.ddTo = ddTo;
		this.directionsDiv = directionsDiv;
		this.distanceSpan = distanceSpan;
		this.cities = new Array();
		
		this.map 			= new GMap2(this.mapDiv);
		this.geocoder		= new GClientGeocoder();
		this.directions;
		
		$(directionsDiv).hide();
		
		// Center on australia at widest zoom
		this.map.setCenter(new GLatLng(-29.5,134), 2);
		
		this.loadCities();
		this.fillDropDowns();
		
		this.question = undefined; // the current question that will  be filled onShow
		var self = this;

		// special transport event listeners
		/*
		THIS IS DONE IN index.html
		$$('.transport-calc').each(function(transport)
		{
			Event.observe(transport, 'click', function(control)
			{
				// show the popup
				self.onShow($(this).up('.question'));
			})
		});
		*/
		this.wireSelectEvent($(this.ddFrom));
		this.wireSelectEvent($(this.ddTo));
		Event.observe($('addKMBtn'), 'click', function(event)
		{
			// update the question information
			self.done(callback);
		});
	},
	wireSelectEvent : function(element)
	{
		var self = this;
		Event.observe(element, 'change', function(event)
		{
			self.showDirections();
			$('driving_distance_box').hide();
		});
	},
	loadCities : function()
	{
		this.cities = new Array('Adelaide', 'Alice Springs', 'Brisbane', 'Broome', 'Byron Bay', 'Cairns', 'Canberra', 'Darwin', 'Hobart',  'Melbourne', 'Perth', 'Surfers Paradise', 'Sydney');
	},
	fillDropDowns: function()
	{
		for (var i=1; i<=this.cities.length; i++)
		{
			var cityName = this.cities[i-1];
			this.ddFrom.options[i] = new Option(cityName, cityName);
			this.ddTo.options[i] = new Option(cityName, cityName);
		}
	},
	showDirections: function()
	{
		var fromCity = this.ddFrom.options[this.ddFrom.selectedIndex].value;
		var toCity = this.ddFrom.options[this.ddTo.selectedIndex].value;
		
		if ((this.ddFrom.selectedIndex != 0 && this.ddTo.selectedIndex != 0) && (fromCity != toCity))
		{
			$('driving_distance_wait').show();
			if (!GDirectionObject)
			{
				GDirectionObject = new GDirections(this.map, this.directionsDiv);
			}
			GDirectionObject.clear();
			GDirectionObject.load("from: "+fromCity+", Australia to: "+toCity+", Australia");
		
			GEvent.addListener(GDirectionObject, "load", this.onDirectionsLoad);
		}
	},
	onDirectionsLoad: function()
	{
		var distanceObj = GDirectionObject.getDistance();
		
		$('driving_distance').update(distanceObj.html);
		$('driving_distance_box').appear();
		$('driving_distance_wait').hide();
		
		// JC NOTE: use distanceObj.meters to get numberical value and divide by 1000
	},
	onShow : function(quest)
	{
		// save off the question
		this.question = quest;
		$('driving_distance_box').hide();
		
		$('driving_distance_wait').hide();
		this.ddTo.selectedIndex = 0;
		this.ddFrom.selectedIndex = 0;
		
		 $('popup-drivingcalc').down('h3').update ("Add "+$(quest).down('h3').innerHTML.toLowerCase() + " trips");
		
		showPopup(this.container);
	},
	done : function(callback)
	{
		if(GDirectionObject)
		{
			var distanceObj = GDirectionObject.getDistance();
			if( distanceObj != undefined)
			{
				callback(this.question, distanceObj.meters / 1000);
			}
		}
		
		hidePopup(this.container);
	}
});

var Grapher = Class.create({
	initialize : function(quests)
	{
		// setup variables
		this.questions = quests;
		this.graphs = {
			'Page_Transport' : {html:'', percentage:0,total:0},
			'Page_Accommodation' : {html:'', percentage:0,total:0},
			'Page_Recreation' : {html:'', percentage:0,total:0}
		}
		this.counters = {};
		this.grandTotal = 0;
		
		// do a refresh
		this.refresh();
	},
	refresh : function()
	{
		this.counters = {
			'Page_Transport' : 0,
			'Page_Accommodation' : 0,
			'Page_Recreation' : 0
		}
		
		// work out totals
		this.clearArray();
		this.calculateTotals();
		this.calculatePercentages();
		this.buildHtml();
		this.outputGraph();
		
		$('total-emissions').down('sub').update("("+roundNumber(this.grandTotal / 1000) + " tonnes)");
		
		// finally update the grandTotal
		setEmissionFromPage('Page_Results',this.grandTotal);
	},
	clearArray : function()
	{
		this.grandTotal = 0;
		//update the grand total
		for(graphId in this.graphs)
		{
			this.graphs[graphId].total = 0;
			this.graphs[graphId].percentage = 0;
			this.graphs[graphId].html = '';			
		}
	},
	calculateTotals: function()
	{
		var self = this;
		// going to have to loop through quesitons
		for(questionId in this.questions)
		{
			var question = this.questions[questionId];

			// only interested about questions that having grouping
			if( question.group != undefined )
			{
				if( this.isPerPerson() )
					this.graphs[question.group].total += roundNumber(question.emissionsPerPerson);
				else
					this.graphs[question.group].total += roundNumber(question.emissionsPerGroup);
			}
		}
		//update the grand total
		for(graphId in this.graphs)
		{
			this.grandTotal += this.graphs[graphId].total;
		}

	},
	calculatePercentages: function()
	{
		// work out the percentages
		for(graphId in this.graphs)
		{
			// check for zero
			if(this.graphs[graphId].total > 0 )
				this.graphs[graphId].percentage = roundNumber(parseFloat((this.graphs[graphId].total / this.grandTotal)*100));
			else
				this.graphs[graphId].percentage = 0;
		}
	},
	buildHtml : function()
	{
		// now add the filler onto each group
		for(graphIndex in this.graphs)
		{
			var filler = 100 - this.graphs[graphIndex].percentage;
			this.addToGraphHtml(graphIndex, filler, -1)
		}
		// work out questions
		for(questionId in this.questions)
		{
			// just to be helpful
			if( this.questions[questionId].group != undefined)
			{
				this.addToStack(this.questions[questionId], questionId);
			}
		}
	},
	addToStack : function(question, questionIndex)
	{

		// build the stack html
		var units = this.grandTotal / this.graphs[question.group].total;
		// check if in per person or per group
		var questionValWithGrouping = 0;
		
		if( this.isPerPerson())
			questionValWithGrouping = roundNumber(question.emissionsPerPerson);
		else
			questionValWithGrouping = roundNumber(question.emissionsPerGroup);
		var percentQuestionHeight = parseInt(((questionValWithGrouping / this.graphs[question.group].total) * 100) / units );
		// only write question if > 0
		if( percentQuestionHeight > 0){
			this.addToGraphHtml(question.group, percentQuestionHeight, questionIndex);
			this.counters[question.group] ++;
		}
	},
	addToGraphHtml : function(graphIndex, percentageHeight, questionIndex)
	{
		
		if( questionIndex == -1)
		{
			this.graphs[graphIndex].html += '<div class="cell padder';
		}
		else
		{
			this.graphs[graphIndex].html += '<div class="cell cell'+this.counters[graphIndex]+'" title="';
			this.graphs[graphIndex].html += ''+$(questionIndex).down('h3').innerHTML+'<br>';

			if(this.isPerPerson)
				this.graphs[graphIndex].html += ' ' + roundNumber(this.questions[questionIndex].emissionsPerPerson).toString() + ' kg* or ';
			else
				this.graphs[graphIndex].html += ' ' + roundNumber(this.questions[questionIndex].emissionsPerGroup).toString() + ' kg* or ';

			this.graphs[graphIndex].html += percentageHeight.toString() + '% of Holiday total';
			// TBD add other things to the title
		}
		
		this.graphs[graphIndex].html += '" style="height:' + percentageHeight.toString() + '%" ';
		this.graphs[graphIndex].html += '></div>';
	},
	outputGraph : function()
	{
		var self = this;
		
		if (this.grandTotal < 0){
			$('results').hide();
		}
		else
		{
			$('results').show();
			$$('.graph').each(function(graph)
			{
				var graphName = graph.id.slice(graph.id.indexOf('_')+1);
				$(graph).down('.cell-wrapper').update(self.graphs[graphName].html);
				$(graph).down('.percent').update(roundNumber(self.graphs[graphName].percentage).toString() + '%');
				$(graph).down('.kilos').update(roundNumber(self.graphs[graphName].total).toString() + ' kg*');			
			});
			
			$$('.cell').each(function(cell)
			{
				var my_tooltip = new Tooltip(cell, 'callout');			
			});
			
		}
	/*	
		$$('.graph .cell').each(function(cell)
		{
			Event.observe(cell, 'mouseover', function(event) { 
				popupTitle(event, cell); 
			});	
			Event.observe(cell, 'mouseout', function(event) { 
				popupTitleHide(); 
			});	
		});
	*/	
		
	},
	isPerPerson : function()
	{
		var grouping = $('results-grouping').options[$('results-grouping').selectedIndex].text;
		if( grouping == 'Per Person')
			return true;
		else
			return false;
	}
});

function showPopup(obj){
	//Effect.Grow(obj, { duration: 0.5 });
	$(obj).show();
	$('popup-hider').show();
}

function hidePopup(obj){
	//Effect.Shrink(obj, { duration: 0.5 });
	$(obj).hide();
	$('popup-hider').hide();
}

var Tips_Page_Transport = new Array(
	"You’re on holiday, so why not slow down and enjoy the drive? Driving at 90km/h instead of 120km/h saves up to 20% in fuel usage and carbon emissions.",
	"Meet more people and fly economy class. Economy class emits less than half the carbon compared to business class.",
	"Hire a car that runs on LPG gas or diesel and reduce carbon emissions by 15-20%.",
	"Get cosy and hire a small car. They produce around half the carbon emissions per km compared to large cars.",
	"Smell the fresh air. Wind the windows down in the car instead of using air-conditioning. Air-conditioning can increase carbon emissions by 5-25%",
	"Travel on public transport at peak periods. A fully loaded train/plane/bus reduces the carbon emissions per passenger/km.",
	"See the sights. Choose to travel on a bus or tram in cities. Taxis produce twice the amount of carbon emissions.",
	"Explore the local area. Hire a bike or buy a second-hand one and sell it on departure."
);

var Tips_Page_Holiday = new Array(
	"Chat to service station staff at the service station. Good maintenance and correct tyre pressure on vehicles will ensure maximum operational efficiency.",
	"Travel light and move faster. Think about hiring or buying equipment and clothing at your destination and selling or donating on departure.",
	"Take short showers. Australia is a dry continent and water is a scarce resource.",
	"Eat locally produced foods. Travel impacts are less and it will be fresh.",
	"Spend more time in fewer locations. Get to know the place/culture and reduce your transport carbon emissions.",
	"Turn off all appliances at the wall when not in use. Appliances left on standby still use energy."
);

var Tips_Page_Accomodation = new Array(
	"Consider staying in eco-accommodation. They have considered the environmental impacts of their operation.",
	"Camping is a great way to see untouched parts of Australia and will minimise your carbon footprint. Remember to take your rubbish with you!",
	"Minimise waste and enjoy fresh Australian water by bringing your own water bottle and refilling it from your accommodation taps.",
	"Hang towels for drying and reuse in your hotel. This will minimise water consumption and energy use.",
	"Make the switch! Switch lights and air conditioning off if you are not in the room or you don’t need them."
);

var Tips_Page_Recreation = new Array(
	"Think before you eat. By cutting down on red meat you will reduce your personal carbon emissions.",
	"Avoid plastic bags. Carry your own re-usable bag when shopping.",
	"Visit 'eco' fairs and festivals! They are a great way to learn more about the latest information about sustainability.",
	"Visit nature sites and parks. Australia is full of fabulous parks to explore! Enjoy the nature that your sustainable behaviour is aiming to protect.",
	"Volunteer for a day. You will meet locals and perhaps even contribute to making your trip carbon positive!",
	"Take part in clean-up campaigns, such as 'clean up Australia'. And for the remaining 364 days don't litter!"
);

function updateTips(){
	$$('#Page_Holiday .tip div').first().update(Tips_Page_Holiday[ (5*Math.random()).round()]);
	$$('#Page_Transport .tip div').first().update(Tips_Page_Transport[ (5*Math.random()).round()]);
	$$('#Page_Accomodation .tip div').first().update(Tips_Page_Accomodation[ (5*Math.random()).round()]);
	$$('#Page_Recreation .tip div').first().update(Tips_Page_Recreation[ (5*Math.random()).round()]);
}

function getTips(key){
	var all = {
		'Tips_Page_Recreation': Tips_Page_Recreation,
		'Tips_Page_Accomodation': Tips_Page_Accomodation,
		'Tips_Page_Holiday': Tips_Page_Holiday,
		'Tips_Page_Transport' : Tips_Page_Transport
	};
	return all[key];
}

function popupTips(){
	window.open("tips.html", "tipsWindow", "height=460,width=550,resizable=1,scrollbars=1");
}

function peopleCount(){
	return allQuestions.Field_Holiday_WhoIsGoing.value;
}

function roundNumber(num) {
	dec = 2;
	if (num > 9) {
		dec = 1;
	}
	if (num > 99) {
		dec = 0;
	}
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);

	return result;
}











/*
 * Copyright (c) 2006 Jonathan Weiss <jw@innerewut.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */


/* tooltip-0.1.js - Small tooltip library on top of Prototype 
 * by Jonathan Weiss <jw@innerewut.de> distributed under the BSD license. 
 *
 * Unlike other libraries it does not declare its own tooltip 
 * div or window. It relies on an already existing div or element defined by you to display as 
 * the tooltip. This element will be placed (and shown) near the mouse pointer when a trigger-element is moused-over.
 * 
 *
 * Usage: 
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *   <script type="text/javascript">
 *     var my_tooltip = new Tooltip('id_of_trigger_element', 'id_of_tooltip_to_show_element')
 *   </script>
 * 
 * Now whenever you trigger a mouseOver on the `trigger` element, the tooltip element will
 * be shown. On o mouseOut the tooltip disappears. 
 * 
 * Example:
 * 
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *
 *   <div id='tooltip' style="display:none; margin: 5px; background-color: red;">
 *     Detail infos on product 1....<br />
 *   </div>
 *
 *   <div id='product_1'>
 *     This is product 1
 *   </div>
 *
 *   <script type="text/javascript">
 *     var my_tooltip = new Tooltip('product_1', 'tooltip')
 *   </script>
 *
 * You can use my_tooltip.destroy() to remove the event observers and thereby the tooltip.
 */

var Tooltip = Class.create();
Tooltip.prototype = {
  initialize: function(element, tool_tip) {
    var options = Object.extend({
      default_css: false,
      margin: "0px",
	  padding: "5px",
	  backgroundColor: "#d6d6fc",
	  delta_x: -18,
	  delta_y: -83,
      zindex: 1000
    }, arguments[1] || {});

    this.element      = $(element);
    this.tool_tip     = $(tool_tip);

    this.options      = options;

    // hide the tool-tip by default
    this.tool_tip.hide();

    this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
    this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);

    this.registerEvents();
  },

  destroy: function() {
    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
    Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
  },

  registerEvents: function() {
    Event.observe(this.element, "mouseover", this.eventMouseOver);
    Event.observe(this.element, "mouseout", this.eventMouseOut);
  },

  showTooltip: function(event){
	
	Event.stop(event);
	
	var text = this.element.title;
	if (text == null || text.length < 1){
		return;
	}
	
	this.tool_tip.down('.inner').update(text);
	
	// get Mouse position
    var mouse_x = Event.pointerX(event);
	var mouse_y = Event.pointerY(event);

	// decide if wee need to switch sides for the tooltip
	var dimensions = Element.getDimensions( this.tool_tip );
	var element_width = dimensions.width;
	var element_height = dimensions.height;
	
	if ( (element_width + mouse_x) >= ( this.getWindowWidth() - this.options.delta_x) ){ // too big for X
		mouse_x = mouse_x - element_width;
		// apply delta to make sure that the mouse is not on the tool-tip
		mouse_x = mouse_x - this.options.delta_x;
	} else {
		mouse_x = mouse_x + this.options.delta_x;
	}
	
	if ( (element_height + mouse_y) >= ( this.getWindowHeight() - this.options.delta_y) ){ // too big for Y
		mouse_y = mouse_y - element_height;
	    // apply delta to make sure that the mouse is not on the tool-tip
		mouse_y = mouse_y - this.options.delta_y;
	} else {
		mouse_y = mouse_y + this.options.delta_y;
	} 
	
	// now set the right styles
	this.setStyles(mouse_x, mouse_y);
	
		
	// finally show the Tooltip
	//new Effect.Appear(this.tool_tip);
	new Element.show(this.tool_tip);

  },
  
  setStyles: function(x, y){
    // set the right styles to position the tool tip
	Element.setStyle(this.tool_tip, { position:'absolute',
	 								  top:y + "px",
	 								  left:x + "px",
									  zindex:this.options.zindex
	 								});
	
	// apply default theme if wanted
	if (this.options.default_css){
	  	Element.setStyle(this.tool_tip, { margin:this.options.margin,
		 								  padding:this.options.padding,
		                                  backgroundColor:this.options.backgroundColor,
										  zindex:this.options.zindex
		 								});	
	}	
  },

  hideTooltip: function(event){
	//new Effect.Fade(this.tool_tip);
	new Element.hide(this.tool_tip);
  },

  getWindowHeight: function(){
    var innerHeight;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerHeight = document.body.clientHeight;
    } else {
		innerHeight = window.innerHeight;
    }
    return innerHeight;	
  },
 
  getWindowWidth: function(){
    var innerWidth;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerWidth = document.body.clientWidth;
    } else {
		innerWidth = window.innerWidth;
    }
    return innerWidth;	
  }

}

/* END tooltip-0.1.js - Small tooltip library on top of Prototype  */
