function roundNumber( number ) {
	number = Math.round(number * 100);
	if( number % 100 == 0 ) {
		return (number / 100) + '.00';
	} else if ( number % 10 == 0 ) {
		return (number / 100) + '0';
	} else {
		return (number / 100);
	}
}

function calculatePrice() {
	// page count or zero
	var pages = parseInt( $('#pages').val() ) || 0;

	var scanCost = roundNumber(pages * 0.17);
	var pdfCost = ( $('#output_pdf:checked').length ) ? roundNumber(pages * 0.05) : '0.00';
	var totalCost = roundNumber( parseFloat(scanCost) + parseFloat(pdfCost) );

	$('#scanningCost').html( '$' + scanCost );
	$('#pdfCost').html( '$' + pdfCost );
	$('#totalCost').html( '$' + totalCost );
}

function countPages() {
	var count = 0;
	$('.pagesField').each(function() {
		count += parseInt( $(this).val() ) | 0;
	});
	$('#pages').val( count );
	$('#visible_pages').val( count );

	calculatePrice();
}

$(function() {
	$('#visible_pages').live( 'keyup', countPages );
	$('.pagesField').live( 'keyup', countPages );

	// add book row
	$('#addbookrow').click( function(e) {
		var rowNum = parseInt( $('#books').val() );

		if( rowNum <= 19 ) {
			// row code
			var html = '<tr><td><input type="text" id="title_'+rowNum+'" name="title_'+rowNum+'" value="" size="28" maxlength="255" /></td>';
			html += '<td><input type="text" id="author_'+rowNum+'" name="author_'+rowNum+'" value="" size="28" maxlength="255" /></td>';
			html += '<td><input type="text" class="pagesField" id="pages_'+rowNum+'" name="pages_'+rowNum+'" value="" size="6" maxlength="4" /></td></tr>';

			$('.book-table tr:last-child').prev('tr').after(html);

			$('#books').val(rowNum + 1);
		} else {
			alert('This system is designed for small orders. For larger orders please contact us.');
		}

		e.preventDefault();
	});

	// delete book row
	$('#removebookrow').click( function(e) {
		var lastRow = $('#books').val() - 1;
		isSure = true;

		if( lastRow >= 1 ) {
			if( $('#title_'+lastRow).val() != '' || $('#author_'+lastRow).val() != '' || parseInt( $('#pages_'+lastRow).val() ) ) {
				isSure = confirm('This will remove the last book row.\n\nAre you sure?');
			}

			if( isSure ) {
				$('.book-table tr:last-child').prev('tr').remove();
				$('#books').val( parseInt( $('#books').val() ) - 1 );
			}
		} else {
			alert('Can not remove anymore rows.');
		}

		countPages();

		e.preventDefault();
	});

	// validate physical book order
	$('#bookOptionsForm').submit( function(e) {
		// clear errors
		if( $('.error').length ) {
			$('.error').remove();
		}

		if( $('.highlight-error').length ) {
			$('.highlight-error').removeClass('highlight-error');
		}

		$('.book-table tr').each( function( row ) {
			if( $('#title_'+row).val() != '' || $('#author_'+row).val() != '' || parseInt( $('#pages_'+row).val() ) ) {
				if( $('#title_'+row).val() == '' ) {
					$('#title_'+row).addClass('highlight-error');
				}

				if( $('#author_'+row).val() == '' ) {
					$('#author_'+row).addClass('highlight-error');
				}

				if( !parseInt( $('#pages_'+row).val() ) ) {
					$('#pages_'+row).addClass('highlight-error');
				}
			}

		});

		if( $('.highlight-error').length ) {
			var message = '<p class="error">Please fill out all fields.</p>';
			$('#bookOptionsForm').children(':nth-child(2)').prepend( message );
		}

		// need page count
		if( !parseInt( $('#pages').val() ) ) {
			var message = '<p class="error">Please fill out the page count</p>';
			$(this).children(':nth-child(2)').prepend( message );
		}

		// return false on error
		if( $('.error').length ) {
			return false;
		}
	});

	// validate customer information
	$('#customerOptionsForm').submit( function(e) {
		// clear errors
		if( $('.error').length ) {
			$('.error').remove();
		}

		// all fields are required
		if( !$('#company_name').val() || !$('#contact_name').val() ||
			!$('#email').val() || !$('#phone').val() ) {

			var message = '<p class="error">Please fill out all fields.</p>';
			$(this).children(':first-child').prepend( message );
		}

		// terms and conditions
		if( !$('#terms').attr('checked') ) {
			var message = '<p class="error">You must accept the Terms and Conditions</p>';
			$('#termsContainer').next().prepend( message );
		}

		// return false on error
		if( $('.error').length ) {
			return false;
		}
	});

	$('#checkoutForm').submit( function(e) {
		var order_id = $('#order_id').val();
		var comment = $('#comment').val();

		if( $('#comment').val() != '' ) {
			$.ajax({
				async: false,
				type: "POST",
				url: 'http://scanyourbooks.com/actions.php?p=comment',
				data: ({ id: order_id, comment: comment })
			});
		}
	});

	$('#output_pdf').click( calculatePrice );

	// update price if page count is already filled in
	if( parseInt( $('#pages').val() ) ) {
		calculatePrice();
	}
});
