$(document).ready(function() {

	mf = {};
	mf.calculator = {};
	
	mf.calculator.oldFieldValues = new Array();
	mf.calculator.oldFieldValues['energy_cost'] = $('#energy_cost').val();
	mf.calculator.oldFieldValues['number_of_fittings'] = $('#number_of_fittings').val();
	
	mf.calculator.firstRun = true;
	
	
	
	// attach click event to the call to action badge - will cause the carousel to fade out and the calcluator to fade in.
	
	$('#calculator-trigger').click( function(e)
	{
	 	var animationDuration = 800;
		var transitionOffset = 635;
		
		// hide the carousel and intro text, then reveal the calculator and cacluator text
		//$('header[role="banner"]').animate( { height: 665 }, animationDuration );
		$('header[role="banner"]').css( 'height', '665px' );
		//$('header[role="banner"]').addClass('calculator_bg');
		
		$('#page-intro').animate( { top: 0 - transitionOffset }, animationDuration );
		$('#carousel').animate( { top: 0 - transitionOffset }, animationDuration);
		$('#calculator-intro').animate( { top: 0 - transitionOffset }, animationDuration );
		$('#calculator').animate( { top: 0 - transitionOffset }, animationDuration, function(){ mf.calculator.initialise(); } );
		
		// if the browser doesn't support css transitions, put a transition on the background, otherwide, add a class and the transitions will take care of the background movement
	});
	
	
	
	// initialise the calculator
	
	mf.calculator.initialise = function()
	{
		// attach change events to the various form fields
		$('#number_of_fittings, #energy_cost').keyup( function(){ mf.calculator.onInputFieldChange( $(this) ); } );
		$('#wattage').change( function(){ mf.calculator.onWattageChange( $(this) ); } );
		$('#type_of_fitting').change( function(){ mf.calculator.onLightingTypeChange( $(this) ); } );
		$('#hours, #days, #weeks').change( function(){ mf.calculator.onOperatingTimesChange( $(this) ); } );
		
		// attach rollover events to the help icons
		$('.help_icon').click( function(){ mf.calculator.rollOverHelp( $(this) ) } );
	}

	// functions
	
	mf.calculator.recalculateResult = function()
	{
		// if it's the first time, don't caclulate a result until both text fields have values greater than zero
		if( mf.calculator.firstRun && !($('#number_of_fittings').val() > 0 && $('#energy_cost').val() > 0 ) )
		{
			return;
		}
		
		mf.calculator.firstRun = false;
		
		// Get the total annual operating hours
		var operatingHours = $('#hours').val() * $('#days').val() * $('#weeks').val();
		
		// get the other values (some will have to be changed from blank to zero
		var numberOfFittings = validateNumber( $('#number_of_fittings').val() ) ? $('#number_of_fittings').val() : 0 ;
		var oldWattage = $('#wattage').val()
		var newWattage = $('#new_wattage').html();
		var energyCost = validateNumber( $('#energy_cost').val() ) ? $('#energy_cost').val() : 0 ;
		
		// Calculate the current total energy cost, new energy cost, cost savings and energy reduction
		var currentKilowattHours = operatingHours * ((oldWattage * 1.1) * numberOfFittings) / 1000;
		var newKilowattHours = operatingHours * (newWattage * numberOfFittings) / 1000;
		
		var totalCurrentCost = currentKilowattHours * energyCost;
		var totalNewCost = newKilowattHours * energyCost;
		
		var costSavings = totalCurrentCost - totalNewCost;
		var energyReduction = 100 - Math.round( (newKilowattHours / currentKilowattHours) * 100 );
		
		var carbonReduction = ((oldWattage * 1.1 * numberOfFittings * operatingHours) - (newWattage * numberOfFittings * operatingHours)) / 1000 * 0.54 / 1000;
		// carbon saving  = ((( currentWattage * 1.1 ) * noOfFittings * annualHours ) - ( newWattage * noOfFittings * annualHours )) / 1000 * 0.54 / 1000
		
		/*
		console.log('-------------------------------------------------------------');
		console.log( 'currentKilowattHours: ' + currentKilowattHours);
		console.log( 'newKilowattHours: ' + newKilowattHours);
		console.log( 'totalCurrentCost: ' + totalCurrentCost);
		console.log( 'totalNewCost: ' + totalNewCost);
		console.log( 'costSavings: ' + costSavings);
		console.log( 'energyReduction: ' + energyReduction);
		console.log('-------------------------------------------------------------');
		*/
		
		// Render the results - first the figures
		$('#output_current_cost').html( formatCurrency( Math.round(totalCurrentCost) ) );
		$('#output_new_cost').html(  formatCurrency( Math.round(totalNewCost) ) );
		$('#output_total_savings').html(  formatCurrency( Math.round(costSavings) ) );
		$('#output_total_energy_reduction').html( Math.round(energyReduction) );
		$('#output_total_carbon_saving').html( carbonReduction < 10 ? Math.round( carbonReduction * 10 ) / 10 : Math.round( carbonReduction ));
		//$('#output_total_carbon_saving').html( Math.round(carbonReduction) );
		
		// Now animate the bar charts
		/*
			For the bars themselves, minimum 50px (zero point) / maximum 225px
			For the figures (<p> tags), minimum 0px (zero point) / maximum 90px
		*/
		
		var currentBarHeight = totalCurrentCost > 0 ? 205 : 50;
		var currentFigurePos = totalCurrentCost > 0 ? 90 : 0;
		
		$('#calculator #current-cost .cost').clearQueue();
		$('#calculator #current-cost p').clearQueue();
		$('#calculator #current-cost .cost').animate( { height: currentBarHeight }, 800 );
		$('#calculator #current-cost p').animate( { bottom: currentFigurePos }, 800 );
		
		var newBarHeight = ( totalNewCost > 0 ) ? 50 + ( totalNewCost / totalCurrentCost * 135 ) : 50;
		var newFigureHeight = ( totalNewCost > 0 ) ? totalNewCost / totalCurrentCost * 90 : 0; 
		
		$('#calculator #potential-cost .cost').clearQueue();
		$('#calculator #potential-cost p').clearQueue();
		$('#calculator #potential-cost .cost').animate( { height: newBarHeight }, 800 );		
		$('#calculator #potential-cost p').animate( { bottom: newFigureHeight }, 800 );
	}
	
	// Called when the user changes rhe value of an input field in the calculator
	mf.calculator.onInputFieldChange = function( inputField )
	{
		var value = inputField.val();
		
		// if it's not a number
		if( !validateNumber( inputField.val() ) )
		{
			if( value == '' || value == ' ' || value == '  ' || value == '   ' || value == '    ' )
			{
				inputField.prop('value', '');		
				$('#new_' + inputField.attr('id')).prop('value', '');
				mf.calculator.oldFieldValues[inputField.attr('id')] = '';	
			}
			inputField.prop('value',  mf.calculator.oldFieldValues[inputField.attr('id')] );
		}
		else
		{
			mf.calculator.oldFieldValues[inputField.attr('id')] = value;	
		}
		
		// display the equivalent value in the 'new / potential' column
		$('#new_number_of_fittings').html( $('#number_of_fittings').val() );
		$('#new_energy_cost').html( $('#energy_cost').val() );
		
		// recalculate
		mf.calculator.recalculateResult();
	}
	
	// Called the user changes the operating times drop down
	mf.calculator.onOperatingTimesChange = function( inputField )
	{
		// no need for any validation etc. - just recalculate the result
		mf.calculator.recalculateResult();
	}
	
	mf.calculator.onLightingTypeChange = function( inputField )
	{		
		// update the wattage field accordingly
		if( inputField.val() == 'Flood' )
		{
			$('#wattage').html('<option value="250">250</option><option value="80">80</option>');
			$('#new_wattage').html('120');
		}
		else
		{
			$('#wattage').html('<option value="400">400</option><option value="250">250</option>');
			$('#new_wattage').html('200');
		}

		// display the equivalent value in the 'new / potential' column, then recalculate
		$('#new_type_of_fitting').html( inputField.val() );
		mf.calculator.recalculateResult();
	}
	
	// called when user changes the current wattage drop down
	mf.calculator.onWattageChange = function( inputField )
	{
		// before recalculating the result we'll have to change the new / potential wattage value depending on the value entered into the current wattage field
		switch( inputField.val() )
		{
			case '400':
				$('#new_wattage').html('200');
				break;
				
			case '250':
				$('#new_wattage').html('120');
				break;
				
			case '80':
				$('#new_wattage').html('40');
				break;
		}
		
		mf.calculator.recalculateResult();
	}
	
	function validateNumber( testString )
	{
		return parseFloat(testString) == testString;
	}
	
	function formatCurrency( amount )
	{
		// all this does is insert a single "," at the appropriate place if the number is more than 1000
		
		amount = amount.toString();
		strLen = amount.length;
		if( strLen > 3 )
		{
			amount = amount.substr( 0, strLen-3 ) + ',' + amount.substr( strLen-3, 3 );
		}
		return amount;
	}
	
	mf.calculator.rollOverHelp = function( helpIcon )
	{				
		$('#help_text').css('left', (helpIcon.offset().left + 35)+ 'px');
		$('#help_text').css('top', (helpIcon.offset().top) + 'px');
		$('#help_text p').html( helpIcon.attr('alt') );
		$('#help_text').fadeIn(400);
		
		// attach a mouseout event to hide the button when we're done
		helpIcon.bind( 'mouseout', function(helpIcon)
		{
			$('#help_text').fadeOut(400, function(helpIcon)
			{
				$(helpIcon).unbind('mouseout');
			});
		});
	}
	
});
