// Start functioning when DOM is ready
$( function()
{
	// Set a var for the total
	var total = 2.80;
	
	// Set scope for current state (Default: toezenden_ja)
	var stateConst = 'toezenden_ja';
	
	// Start with zero's
	$('.ticketfield').val( 0 );
	$(':radio').removeAttr('checked');
	$('#toezenden_ja').attr( 'checked', 'checked' );
	$('#totaal').val( '2,80' );
	
	// Select whole field on focus
	$('.ticketfield').focus( function()
	{
		$(this).select();
	});
	
	
	// All the textfields with a rel are price fields
	$('.ticketfield').change( function()
	{
		// Set this field to zero if the value is not valid
		if ( $(this).val() == '' || parseInt($(this).val()).toString() == 'NaN' )
			$(this).val( 0 );
		
		// Start with a total of zero again
		total = 2.8;
		
		// Get all prices
		$('.ticketfield').each( function()
		{
			// Get the price per item
			var price = parseFloat( $(this).attr('rel') );
			
			// Get the amount
			var amount = parseInt( $(this).val() );
			
			// Math the total price for the current item
			var current = amount*price;
			
			// Add the price times amount in the total
			total += current;
		});
		
		// Add the 2.80 for 'toezenden'?
		// Check the state
		var state = $(':radio[name="Toezenden"]:checked').attr('id');
		
		// Add or remove 2.80 from total
		if ( state == 'toezenden_ja' )
			total += 2.8;
		
		// Check if the comma was found
		if ( total.toString().indexOf('.') != -1 ) {
			totaal = total.toString().replace('.', ',') + '0';
		} else {
			totaal = total.toString() + ',00';
		}
		
		// Update the price
		$('#totaal').val( totaal );
	});
	
	
	// Add 2.50 if 'toezenden' is preffered.
	$(':radio[name="Toezenden"], label[for^="toezenden"]').click( function()
	{
		// Check the state
		var state = $(':radio[name="Toezenden"]:checked').attr('id');
		
		// Add or remove 2.80 from total
		if ( state == 'toezenden_ja' && stateConst != 'toezenden_ja' )
			total += 2.8;
		else if ( state == 'toezenden_nee' && stateConst != 'toezenden_nee' )
			total -= 2.8;
			
		// Set the state constant to the current state
		stateConst = state;
		
		// Check if the comma was found
		if ( total.toString().indexOf('.') != -1 ) {
			totaal = total.toString().replace('.', ',') + '0';
		} else {
			totaal = total.toString() + ',00';
		}
		
		// Update the price
		$('#totaal').val( totaal );
	});
});

