$(document).ready(function() {
	initial_update();
	maintain_quantity_fields();
	watch_delivery_cost();
	validate_submit();
	same_as_billing();
	maintain_form_fields();
});

// Goes through all quantity fields and validates and updates them if they have values
function initial_update() {
	var quantity_fields = $('.purchase input.quantity');

	quantity_fields.each(function() {
		if($(this).val() != "") {
			var line = $(this).parent().parent("tr");
			var quantity = $(this).val();
			var wine_number = $(this).attr("name").replace("wine_quantity_","");

			var valid = validate_quantity_field(this);
			if(valid) {
				var value = calc_quantity_field_value(line, quantity);
				update_safepay_field(wine_number, quantity, value);
				update_line_total(line, value);
				update_form_total();
				valid_field(true, this);
			} else {
				valid_field(false, this);
			}

			// reset fields
			line = null;
			value = null;
		}
	});

	update_form_total();
}

function maintain_quantity_fields() {
	var quantity_fields = $('.purchase input.quantity');

	// when quantity is set then update total on line
	quantity_fields.each(function() {
		$(this).keyup(function(){
			var line = $(this).parent().parent("tr");
			var quantity = $(this).val();

			var wine_number = $(this).attr("name").replace("wine_quantity_","");

			var valid = validate_quantity_field(this);
			if(valid) {
				var value = calc_quantity_field_value(line, quantity);
				update_safepay_field(wine_number, quantity, value);
				update_line_total(line, value);
				update_form_total();
				valid_field(true, this);
			} else {
				valid_field(false, this);
			}

			// reset fields
			line = null;
			value = null;
		})
	});
}

function valid_field(valid, field) {
	if(valid) {
		$(field).removeClass('invalid');
	} else {
		$(field).addClass('invalid');
	}
}


function calc_quantity_field_value(line, quantity) {
	var bottle_price = currencyToFloat($(line).children('.bottle-price').text());
	return quantity * bottle_price;
}

function update_line_total(line, value) {
	// when quantity is set then update total on line
	var total_cell = $(line).children('.total');
	total_cell.text(formatAsMoney(value));
}

function update_safepay_field(wine_number, quantity, value) {
	// when quantity is set then update safepay total
	$('#wine_num_'+wine_number+'_output').val(quantity + ',' + value/quantity);
}

function update_form_total() {
	update_delivery_cost();
	var total_fields = $('.purchase tr.cost td.cost');
 	var item_total_cell = total_fields[0];
 	var all_total_cell = total_fields[1];

	// update item total
	var line_total_cells = $('.purchase tr td.total');
	var item_total = 0;
	line_total_cells.each(function() {
		item_total += currencyToFloat($(this).text());
	});
	$(item_total_cell).text(formatAsMoney(item_total));

	// update all total
	var delivery_total = currencyToFloat($('.purchase tr.delivery td.cost').text());
	$(all_total_cell).text(formatAsMoney(delivery_total + item_total));

	$('#disclaimer-total-price').html(formatAsMoney(delivery_total + item_total));
}

function validate_quantity_field(field) {
	// stop text boxes accepting non digits
	if(isNumeric($(field).val()) || $(field).val() == "") {
		return true;
	} else {
		return false;
	}
}

function watch_delivery_cost() {
	// copy from macforbes prices when delivery is set
	$('.purchase tr.delivery select#delivery_region').change(function() {
		update_form_total();
	});
}

function update_delivery_cost(value) {
	var total_quantity = get_quantity();
	var delivery_value = 0.00;

	if(total_quantity < 12) {
		delivery_value = currencyToFloat($('.purchase tr.delivery select#delivery_region').val());
	}
	$('.purchase tr.delivery td.cost').text(formatAsMoney(delivery_value));
	$('#freight_value').val(delivery_value);
	$('#Freight_Charge').val('1,'+delivery_value);
}

function same_as_billing() {
	// wire up "same as billing"
	var same_as_billing_checkbox = $('#delivery-details-section #delivery-check')[0];
	var fields = new Array();
	$.merge(fields, $('#delivery-details-section [name=Delivery_Name]'));
	$.merge(fields, $('#delivery-details-section [name=Delivery_Address]'));
	$.merge(fields, $('#delivery-details-section [name=Delivery_City]'));
	$.merge(fields, $('#delivery-details-section [name=Delivery_Post_Code]'));
	$.merge(fields, $('#delivery-details-section [name=Delivery_State]'));

	$(fields).each(function(){
		$(this).change(function(){
			if($(same_as_billing_checkbox).is(':checked')) {
				$(same_as_billing_checkbox).attr('checked', false);
			}
		});
	});

	$(same_as_billing_checkbox).click(function(){
		if($(same_as_billing_checkbox).is(':checked')) {
			// copy over data
			$('#delivery-details-section [name=Delivery_Name]').val($('#billing-details-section [name=Billing_Name]').val());
			$('#delivery-details-section [name=Delivery_Address]').val($('#billing-details-section [name=Billing_Address]').val());
			$('#delivery-details-section [name=Delivery_City]').val($('#billing-details-section [name=Billing_City]').val());
			$('#delivery-details-section [name=Delivery_Post_Code]').val($('#billing-details-section [name=Billing_Post_Code]').val());
			$('#delivery-details-section [name=Delivery_State]').val($('#billing-details-section [name=Billing_State]').val());
		}
	});
}

function reset_form_submit_error() {
	var messagebox = $('#form-error-message-box');
	$(messagebox).html('');
	$(messagebox).hide();
}

function alert_form_submit_error(message) {
	var messagebox = $('#form-error-message-box');
	$(messagebox).html('<p>'+message+'</p>');
	$(messagebox).show();
}

function validate_submit() {
	reset_form_submit_error();

	// quantity must be multiple of six
	$('#final-submit-button').click(function() {
		// check at least one quantity field has value
		if(at_least_one_quantity() == false && is_map_quantity_set() == false){
			alert_form_submit_error('Invalid Quantity. You must specify at least one wine or map to purchase.');
			return false;
			exit();
		}

		// check that total quantity is divisible by 6
		if(is_quantity_multiple_of_six() == false) {
			alert_form_submit_error('Invalid Quantity. Must be divisible by 6.');
			return false;
			exit();
		}

		// check delivery is set
		if($('.purchase tr.delivery select#delivery_region').val() == '$0.00') {
			alert_form_submit_error('Delivery not set.');
			return false;
			exit();
		}

		// check all required form fields are filled
		var fields = get_required_form_fields();
		var invalid_field_count = 0;
		$(fields).each(function() {
			if(validate_form_field(this) == false) {
				invalid_field_count += 1;
			}
		});
		if(invalid_field_count != 0) {
			alert_form_submit_error('All required fields must be filled.');
			return false;
			exit();
		}

		return true;
	})
}

function at_least_one_quantity() {
	var quantity_fields = $('.purchase input.quantity');
	var total_quantity = 0;

	quantity_fields.each(function() {
		var value = $(this).val();
		if(isNumeric(value)){
			total_quantity += parseInt(value);
		}
	});

	if(total_quantity == 0) {
		return false;
	} else {
		return true;
	}
}

function get_quantity() {
	var quantity_fields = $('.purchase input.quantity:not(.map-field)');
	var total_quantity = 0;

	quantity_fields.each(function() {
		var value = $(this).val();
		if(isNumeric(value)){
			total_quantity += parseInt(value);
		}
	});

	return total_quantity;
}

function is_quantity_multiple_of_six() {
	var total_quantity = get_quantity();
	if(total_quantity % 6 == 0) {
		return true;
	} else {
		return false;
	}
}

function is_map_quantity_set() {
	var quantity_fields = $('.purchase input.map-quantity');
	var total_quantity = 0;

	quantity_fields.each(function() {
		var value = $(this).val();
		if(isNumeric(value)){
			total_quantity += parseInt(value);
		}
	});

	if(total_quantity == 0) {
		return false;
	} else {
		return true;
	}
}

function maintain_form_fields() {
	var fields = get_required_form_fields();

	$(fields).blur(function() {
		validate_form_field(this);
	});
}

function get_required_form_fields() {
	var fields = new Array();
	$.merge(fields, $('#delivery-details-section input[type=text]'));
	$.merge(fields,$('#billing-details-section input[type=text]'));
	$.merge(fields, $('#delivery-details-section select'));
	$.merge(fields,$('#billing-details-section select'));
	$.merge(fields, $('#delivery-details-section textarea'));
	$.merge(fields,$('#billing-details-section textarea'));

	return fields;
}

function validate_form_field(field) {
	if(isNotEmpty($(field).val())) {
		valid_field(true, field);
		return true;
	}	else {
		valid_field(false, field);
		return false;
	}
}

function currencyToFloat(currency) {
	if(currency != undefined) {
		return parseFloat(currency.replace('$',''));
	} else {
		return 0.00;
	}
}

function formatAsMoney(mnt) {
  mnt -= 0;
  mnt = (Math.round(mnt*100))/100;
	output = (mnt == Math.floor(mnt)) ? mnt + '.00'
    : ( (mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);
  return '$' + output;
}

function isNumeric(form_value)
{
    if (form_value.match(/^\d+$/) == null)
        return false;
    else
        return true;
}

function isNotEmpty(form_value)
{
    if (form_value == '')
        return false;
    else
        return true;
}