<script>
	jQuery('body').on('click', '.btn-payment', function() {
		var id = jQuery(this).attr('data-id');
		show_loading();

		jQuery.ajax({
			url: app_url + 'credit/get_payment',
			type: 'POST',
			dataType: 'JSON',
			data: {
				id: id
			},
			success: function(response) {
				hide_loading();
				show_modal('payment');
				jQuery('.box-payment').html(response.data);
				calculate_pay();
			},
			errors: function(response) {

			}
		});
	});


	jQuery('body').on('click', '#btn_add_payment', function() {
		add_payment();
	});

	function add_payment() {
		var content = jQuery('#tmp_credit').html();
		jQuery('#table_credit tbody').append(content);

		jQuery('.installment-payment-date').datetimepicker({
	    	format: 'DD-MM-YYYY HH:mm:ss'
		});		
	}

	jQuery('body').on('click', '.btn-action-save-payment', function() {
		show_loading();
		jQuery.ajax({
			url: app_url + 'credit/pay',
			type: 'POST',
			dataType: 'JSON',
			data: jQuery('#form_credit').serialize(),
			success: function(response) {
				hide_loading();
				if (response.err_code == 0) {
					hide_modal('payment');
					location.reload();
				}
				else {
					bootbox.alert(response.err_message);
				}
			},
			errors: function(response) {}
		});
	});

	jQuery('body').on('click', '.btn-delete', function() {
		jQuery(this).parents('tr').remove();
		calculate_pay();
	});

	jQuery('body').on('keyup', '.installment-payment', function() {
		calculate_pay();
	});

	function calculate_pay() {
		var total = 0;
		jQuery('.installment-payment').each(function(adata, bdata) {
			var the = remove_separator(jQuery(bdata).val());
			the = parseInt(the);
			total += the;
		});

		var the_total = jQuery('.txt-total').text();
		the_total = remove_separator(the_total);

		lack = the_total - total;
		jQuery('.txt-pay').text(thousand_separator_decimal(total));		
		jQuery('.txt-lack').text(thousand_separator_decimal(lack));
	}