$(document).ready(function() {
	var deliveryBillingDiffer = $('#delivery_billing_differ');
	var notMandatory = ['billing_phone', 'billing_email', 'billing_net_address', 'billing_net_operator', 'billing_net_ovt', 'billing_net_business_id'];
	var mutuallyMandatory = ['billing_net_address', 'billing_net_operator'];
	if (deliveryBillingDiffer) {
		var addMandatoryAsterisks = function() {
			$('input[id^="billing_"]').each(function() {
				if (jQuery.inArray($(this).prop('id'), notMandatory) === -1) {
					$(this).parent().prev('td').text('*');
				}
				if (jQuery.inArray($(this).prop('id'), mutuallyMandatory) !== -1) {
					$(this).parent().prev('td').text('**');
				}
			});
		};
		if (deliveryBillingDiffer.prop('checked')) {
			addMandatoryAsterisks();
		}
		deliveryBillingDiffer.click(addMandatoryAsterisks);
	}

	$('.forward.continue').click(function() {
		if ( $('#delivery_billing_differ').prop('checked') == true) {
			var missing = [];
			var mutual = [];
			$("input[id^='billing_']").each(function () {
				if (jQuery.inArray($(this).prop('id'), notMandatory) === -1) {
					if ($(this).val() == '') {
						missing.push('- ' + $(this).parent().prev('td').prev('td').text().replace(':',''));
					}
				}
				if (jQuery.inArray($(this).prop('id'), mutuallyMandatory) !== -1 && $(this).val() === '') {
					mutual.push($(this).prop('id'));
				}
			});
			if (mutual.length === 1) {
				for (var i = 0; i < mutuallyMandatory.length; i++) {
					if (jQuery.inArray(mutuallyMandatory[i], mutual) !== -1) {
						missing.push('- ' + $('input[id="' + mutuallyMandatory[i] + '"]').parent().prev('td').prev('td').text().replace(':', ''));
					}
				}
			}
			if (missing.length > 0) {
				alert("Lomakkeen tietoja ei lähetetty. Maksutiedot-osion seuraavat kentät ovat pakollisia:\n" + missing.join("\n"));
				return false;
			}
		}
	});
	
});
