function reverse( e )
{
	var a, z
	
	a = e.toString().split( '' )
		
	z = ''
	
	for( i=a.length-1; i>=0; i-- )
		z += a[i]
	
	return z
} // reverse

function moneyRound( a )
{
	return Math.round( a * 100 ) / 100
} // moneyRound

function calc()
{

	var tab, percent, tip, subtotal, s, start, middle, end, newTotal, newTip, actualPercent, difference, moar
	
	tab = $( '#tab' ).val() * 1
	percent = $( 'input[name=generous]:checked' ).val() * 1
	tip = tab * percent
	subtotal = tab + tip
	
	s = Math.floor( moneyRound( subtotal ) * 100 )
		
	middle = ''
	
	// odd length
	if( s.toString().length % 2 )
		middle = s.toString().charAt( Math.floor( s.toString().length / 2 ) )

	start =  s.toString().substr( 0, Math.floor( s.toString().length / 2 ) )
	
	end = reverse( start )
	
	newTotal = parseInt( start + middle + end )/100
	newTip = newTotal - tab
	actualPercent = newTip / tab
	difference = newTip - tip
	
	if( difference < 0 )
		moar = ' less '
		
	else
		moar = ' more '
	
	$( '#tip' ).text( '$' + moneyRound( newTip ) ).fadeIn()
	$( '#actual_percent' ).text( moneyRound( actualPercent * 100 ) + '%, which is $' + moneyRound( Math.abs( difference ) ) + moar + 'than ' + percent*100 + '%' ).fadeIn()
	$( '#total' ).text( '$' + newTotal ).fadeIn()

} // calc

$( document ).ready(

	function()
	{
		$( '#tab' ).blur( 
			function()
			{
				if( isNaN( $( this ).val() ) || $( this ).val() < 0 )
					$( this ).val( '' )
				
				else
					$( '#tip, #actual_percent, #total' ).fadeOut( 'normal', calc )
					
			} // function
		) // blur
		
		$( 'input[name=generous]' ).change( 
			function()
			{
				if( isNaN( $( '#tab' ).val() ) || $( '#tab' ).val() < 0 )
					$( '#tab' ).val( '' )
				
				else
					$( '#tip, #actual_percent, #total' ).fadeOut( 'normal', calc )
					
			} // function
		) // change
		
		$( '#tab' ).val( '10.00' ).blur()

	} // function
) // ready
