jQuery( document ).ready(
	function ( $ ) {

		function updateButtonState() {
			var $type             = $( '#_oxygen_payment_note_type' ).val();
			var $createInvoiceBtn = $( '.create_invoice' );

			console.log( $type );

			if ($type === '0' || $type === '') {
				$createInvoiceBtn.addClass( 'disabled' );
			} else {
				$createInvoiceBtn.removeClass( 'disabled' );
				var buttonText = ($type === 'alp' || $type === 'apy')
					? MyLocalizedText.createReceiptText
					: MyLocalizedText.createInvoiceText;

				$createInvoiceBtn.text( buttonText );
			}
		}

		if ($( '#_oxygen_payment_note_type' ).length > 0) {
			updateButtonState();

			$( '#_oxygen_payment_note_type' ).on( 'change', updateButtonState );

			// Handle create invoice click event
			$( '.create_invoice' ).on(
				'click',
				function (e) {
					e.preventDefault();

					if ($( this ).hasClass( 'disabled' )) {
						return false;
					}

					$( '.create_invoice, .create_notice' ).addClass( 'disabled' );
					var selectedType = $( '#_oxygen_payment_note_type' ).val();

					console.log( "selected " + $( this ).attr( 'href' ) + '&_oxygen_payment_note_type=' + selectedType );

					window.location.href = $( this ).attr( 'href' ) + '&_oxygen_payment_note_type=' + selectedType;
				}
			);
		}

		// Handle create notice click event
		$( '.create_notice' ).on(
			'click',
			function (e) {
				e.preventDefault();

				if ($( this ).hasClass( 'disabled' )) {
					return false;
				}

				$( '.create_notice' ).addClass( 'disabled' );
				window.location.href = $( this ).attr( 'href' ) + '&_oxygen_payment_note_type=notice';
			}
		);

	}
);
