function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}
function calc(e){
		var row_no = $(e).attr('name') ;
		var numb = row_no.match(/\d+/);
			numb = numb.join("");
		
		var total = 0;
		var quantity = document.getElementById("purchaseorderitems["+numb+"][quantity]");
		var unit_price = document.getElementById("purchaseorderitems["+numb+"][unit_price]");
		var subtotal = document.getElementById("subtotal["+numb+"]");
		
		var total = quantity.value * unit_price.value;
		
		subtotal.innerHTML = roundNumber(total, 2);
		
		var sum = 0;
		$('.subtotal').each(function(){
			if($(this).text() !== ""){
				sum += parseFloat($(this).text());
			}
		});
		$("#total").html(sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
		
	}
var FormWizard = function () {


    return {
		init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }
		var form = $('#stepy_form');
		var error = $('.alert-danger', form);
		var success = $('.alert-success', form);
		form.validate({
			doNotHideMessage: true,
			ignore: [],
			errorElement: 'span',
			errorClass: 'help-block help-block-error',
			focusInvalid: false,
			rules: {
                forwarder_id: {
                    required: true,
                }
            },
            messages: {
                forwarder_id: {
                    required: "You must choose forwarder to proceed",
                }            
            },
			
			errorPlacement: function(error, element) { // render error placement for each input type
				error.insertAfter(element); // for other inputs, just perform default behavior
			},

			invalidHandler: function(event, validator) { //display error alert on form submit   
				success.hide();
				error.show();
				App.scrollTo(error, -200);
			},

			highlight: function(element) { // hightlight error inputs
				$(element)
					.closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
			},

			unhighlight: function(element) { // revert the change done by hightlight
				$(element)
					.closest('.form-group').removeClass('has-error'); // set error class to the control group
			},
			success: function (label) {
				if (label.attr("for") == "gender" || label.attr("for") == "payment[]") {
					label
						.closest('.form-group').removeClass('has-error').addClass('has-success');
					label.remove();
				} else {
					label
						.addClass('valid')
					.closest('.form-group').removeClass('has-error').addClass('has-success');
				}
			},
			submitHandler: function (form) {
				
				var dataString = $('#stepy_form').serialize();
				$.ajax({
					type: "POST",
					url: "/purchase-order/add-purchase-order",
					data: dataString,
					cache: false,
					beforeSend: function(){ 
						$("#finish").hide();
						$("#wait").show();
						$("#suksesupdate").hide();
						$("#gagalupdate").hide();
					},
					complete: function(e, xhr, settings){
						if(e.status === 200){
							var po_id = $.trim(e.responseText);
							var dataStringg = 'po_id='+ po_id;
							$.ajax({
								type: "POST",
								url: "/purchase-order/getModalSuccess",
								data: dataStringg,
								cache: false,
								success: function(data) {
									$("#success-content").html(data);
									$('#modal_success').modal('show');
								}	
							});
						}else{
							$("#finish").show();
							$("#wait").hide();
							$("#gagalupdate").show();
						}
					}
					
				});
			
			return false;
			}
		 });
		 
            var handleTitle = function(tab, navigation, index) {
                var total = navigation.find('li').length;
                var current = index + 1;
                // set wizard title
                $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                // set done steps
                jQuery('li', $('#form_wizard_1')).removeClass("done");
                var li_list = navigation.find('li');
                for (var i = 0; i < index; i++) {
                    jQuery(li_list[i]).addClass("done");
                }

                if (current == 1) {
                    $('#form_wizard_1').find('.button-previous').hide();
                } else {
                    $('#form_wizard_1').find('.button-previous').show();
                }

                if (current >= total) {
                    $('#form_wizard_1').find('.button-next').hide();
                    $('#form_wizard_1').find('.button-submit').show();
                } else {
                    $('#form_wizard_1').find('.button-next').show();
                    $('#form_wizard_1').find('.button-submit').hide();
                }
                App.scrollTo($('.page-title'));
            }

            // default form wizard
            $('#form_wizard_1').bootstrapWizard({
                'nextSelector': '.button-next',
                'previousSelector': '.button-previous',
                onTabClick: function(tab, navigation, index, clickedIndex) {
                    return false;

                    success.hide();
                    error.hide();
                    if (form.valid() == false) {
                        return false;
                    }

                    handleTitle(tab, navigation, clickedIndex);
                },
                onNext: function(tab, navigation, index) {
                    success.hide();
                    error.hide();

                    if (form.valid() == false) {
                        return false;
                    }

                    handleTitle(tab, navigation, index);
                },
                onPrevious: function(tab, navigation, index) {
                    success.hide();
                    error.hide();

                    handleTitle(tab, navigation, index);
                },
                onTabShow: function(tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    var $percent = (current / total) * 100;
                    $('#form_wizard_1').find('.progress-bar').css({
                        width: $percent + '%'
                    });
                    3
                }
            });

            $('#form_wizard_1').find('.button-previous').hide();
            $('#form_wizard_1 .button-submit').click(function () {
                
            }).hide();

        }

    };

}();

var TableDatatablesEditable = function () {

    var handleTable = function () {

        $(document).ready(function() {
			var t = $('#sample_editable_1').DataTable({
			"bPaginate": false,
			"bLengthChange": false,
			"bFilter": false,
			"ordering": false,
			"bInfo": false,
			});
			var counter = 1;
		 
			$('#sample_editable_1_new').on( 'click', function () {
				t.row.add( [
					counter,
					"<input name='purchaseorderitems[" + counter + "][product_name]' id='purchaseorderitems[" + counter + "][product_name]' class='form-control' />",
					"<input name='purchaseorderitems[" + counter + "][item_code]' id='purchaseorderitems[" + counter + "][item_code]' class='form-control' />",
					"<input name='purchaseorderitems[" + counter + "][model_no]' id='purchaseorderitems[" + counter + "][model_no]' class='form-control' />",
					"<textarea name='purchaseorderitems[" + counter + "][description]' id='purchaseorderitems[" + counter + "][description]' class='form-control' ></textarea>",
					"<input onfocusout='calc(this)' onkeydown='calc(this)' onkeyup='calc(this)' onchange='calc(this)' type='number' min='1' name='purchaseorderitems[" + counter + "][quantity]' id='purchaseorderitems[" + counter + "][quantity]' class='form-control' />",
					"<input name='purchaseorderitems[" + counter + "][uom]' id='purchaseorderitems[" + counter + "][uom]' class='form-control' />",
					"<input onfocusout='calc(this)' onkeydown='calc(this)' onkeyup='calc(this)' onchange='calc(this)' step='0.01' min='0.01' name='purchaseorderitems[" + counter + "][unit_price]' id='purchaseorderitems[" + counter + "][unit_price]' class='form-control' type='number' />",
					"<p class='subtotal' id='subtotal["+ counter +"]'></p>",
					"<a class='delete' data-id='" + counter + "'>Delete</a>"
					
				] ).draw( false );
		 
				counter++;
				$('#sample_editable_1 tbody tr').each(function () {
					var this_row = $(this);
					var rowIndex = this_row.index()+1;
					$.each(this_row.find(':input'), function (i, val) {
						var oldName = $(this).attr('name');
						var newName = oldName.replace(/\d+/, rowIndex);
						$(this).attr('name', newName);
						$(this).attr('id', newName);
					});
					$.each(this_row.find('td:eq(0)'), function (i, val) {
						var oldName = $(this).html();
						var newName = oldName.replace(/\d+/, rowIndex);
						$(this).html(newName);
					});				
					$.each(this_row.find('p'), function (i, val) {
						var oldName = $(this).attr('id');
						var newName = oldName.replace(/\d+/, rowIndex);
						
						$(this).attr('id', newName);
					});
				});
			} );
			
			t.on('click', '.delete', function (e) {
				var nRow = $(this).parents("tr");
				t.row(nRow).remove().draw( false );
				$('#sample_editable_1 tbody tr').each(function () {
					var this_row = $(this);
					var rowIndex = this_row.index()+1;
					$.each(this_row.find(':input'), function (i, val) {
						var oldName = $(this).attr('name');
						var newName = oldName.replace(/\d+/, rowIndex);
						$(this).attr('name', newName);
						$(this).attr('id', newName);
					});			
					$.each(this_row.find('td:eq(0)'), function (i, val) {
						var oldName = $(this).html();
						var newName = oldName.replace(/\d+/, rowIndex);
						$(this).html(newName);
					});				
					$.each(this_row.find('p'), function (i, val) {
						var oldName = $(this).attr('id');
						var newName = oldName.replace(/\d+/, rowIndex);
						
						$(this).attr('id', newName);
					});		
				});
			});
			
			$('#sample_editable_1_new').click();
		} );
    }

    return {

        init: function () {
            handleTable();
        }

    };

}();

var FormRepeater = function () {

    return {
        init: function () {
        	$('.mt-repeater').each(function(){
                $(this).repeater({
        			show: function () {
	                	$(this).slideDown();                        
		            },

		            hide: function (deleteElement) {
		                if(confirm('Are you sure you want to delete this element?')) {
		                    $(this).slideUp(deleteElement);
		                }
		            },

		            ready: function (setIndexes) {

		            }

        		});
        	});
        }

    };

}();
jQuery(document).ready(function() {
    TableDatatablesEditable.init();
    FormWizard.init();
    FormRepeater.init();
	
	
	$('#modal_success').on('hidden.bs.modal', function () {
		window.location.href = '/purchase-order';
	});
	
	$('.nav-item .nav-link').on('click', function () {
		return confirm('Are you sure? You will not be able to recover this Purchase Order.');
	});
	$("#sample_editable_1_new").trigger('click');
	$("#order_currency").change(function() {
	  var data = $("#order_currency option:selected").val();
	  
	  $("#currency").html(data);
		  
		
	});
	
	
	function loadData() {
        var oTable = $('#contact').DataTable({
            "serverSide": true,
            "ajax": {
                "url": "/shipping-order/contact",
                "type": "POST",
            },
            "ordering": false,
            "bInfo": false,
            "bAutoWidth ": false,
            buttons: [{
                    extend: 'print',
                    className: 'btn dark btn-outline'
                },
                {
                    extend: 'excel',
                    className: 'btn yellow btn-outline '
                },
                {
                    extend: 'colvis',
                    className: 'btn dark btn-outline',
                    text: 'Columns'
                }
            ],
            "lengthMenu": [
                [10, 25, 50, 100, 99999999],
                [10, 25, 50, 100, "All"]
            ],

            "bLengthChange": false,
        });
        $('.search-input-text').on('keyup click change', function() { // for text boxes
            var i = $(this).attr('data-column'); // getting column index
            var v = $(this).val(); // getting search input value
            oTable.columns(i).search(v).draw();
        });
        $('.search-input-select').on('change', function() { // for select box
            var i = $(this).attr('data-column');
            var v = $(this).val();
            oTable.columns(i).search(v).draw();
        });
        $('#fid').on('change', function() {
            var forwarder_id = $("#fid").val();
            var company_name = $(this).data("company_name");
            $("#forwarder").html("<a>" + company_name + "</a>");
            $("#forwarder_id").val(forwarder_id);
            $("#select_forwarder").hide();
            $("#forwarder").show();
        });
        $(document).on("change", "#fid", function() {
            var forwarder_id = $("#fid").val();
            var company_name = $(this).data("company_name");
            $("#forwarder").html("<a>" + company_name + "</a>");
            $("#forwarder_id").val(forwarder_id);
            $("#select_forwarder").hide();
            $("#forwarder").show();
        });
        $('.filter-cancel').on('click', function() { // for select box
            $('.search-input-text').val('');
            $('.search-input-select').val('');
            $('.search-input-text').trigger('change');
            $('.search-input-select').trigger('change');

            oTable.draw();
        });
        $("#contact_filter").css("display", "none");

    }
	
	 // Example #3
    var custom = new Bloodhound({
        datumTokenizer: function(d) {
            return d.tokens;
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: '/companies/company-list?query=%QUERY',
            wildcard: '%QUERY'
        }
    });

    custom.initialize();

    if (App.isRTL()) {
        $('#typeahead_example_modal_3').attr("dir", "rtl");
    }
    $('#typeahead_example_modal_3').typeahead(null, {
        name: 'datypeahead_example_modal_3',
        displayKey: 'value',
        hint: (App.isRTL() ? false : true),
        source: custom.ttAdapter(),
        templates: {
            suggestion: Handlebars.compile([
                '<a class="view-detail-add" data-id ="{{desc}}">',
                '<div class="media">',
                '<div class="pull-left">',
                '<div class="media-object">',
                '<img src="{{img}}" width="50" height="50"/>',
                '</div>',
                '</div>',
                '<div class="media-body">',
                '<h4 class="media-heading">{{value}}</h4>',
                '</div>',
                '</div>',
                '</a>',
            ].join(''))
        }
    });

    $('#user-detail').on('hidden.bs.modal', function(e) {
        $("#getCode").html("");
    });

    $('#add-user').on('hidden.bs.modal', function(e) {
        $("#getCode2").html("");
    });
	
    $(document).on("click", ".contact-list", function() {
        loadData();
        $('#form_contact_list').modal('show');
    });
	
	$(document).on("change", "#fid", function() {
        var forwarder_id = $("#fid").val();
        var company_name = $(this).data("company_name");
        $("#forwarder").html("<a>" + company_name + "</a>");
        $("#forwarder_id").val(forwarder_id);
        $("#select_forwarder").hide();
        $("#forwarder").show();
    });

    $(document).on("click", ".view-detail", function() {
        var id = $(this).data('id');
        var dataStringg = 'id=' + id;
        $.ajax({
            type: "POST",
            url: "/companies/get-detail",
            cache: false,
            data: dataStringg,
            success: function(data) {
                $("#getCode").html(data);
                jQuery("#user-detail").modal('show');
            }
        });
    });
    $(document).on("click", ".view-detail-add", function() {
        var id = $(this).data('id');
        var dataStringg = 'id=' + id;
        $.ajax({
            type: "POST",
            url: "/companies/get-detail",
            cache: false,
            data: dataStringg,
            success: function(data) {
                $("#getCode2").html(data);
            }
        });
    });
    $(document).on("click", ".exit", function() {
        $('#form_contact_list').modal('hide');
    });

    $(document).on("click", ".add", function() {
        var id = $(this).data('id');
        var dataStringg = 'id=' + id;
        $.ajax({
            type: "POST",
            url: "/companies/add-company",
            cache: false,
            data: dataStringg,
            beforeSend: function() {
                jQuery("#add-user").modal('hide');
                $("#submitprofile").hide();
                $("#waiting").show();
                $("#suksesupdate").hide();
                $("#gagalupdate").hide();
            },
            complete: function(e, xhr, settings) {
                if (e.status === 200) {
                    jQuery("#add-user").modal('hide');
                } else {
                    jQuery("#add-user").modal('hide');
                }
            }
        });

    });
	
    $('#form_contact_list').on('hidden.bs.modal', function() {
        var table = $('#contact').DataTable();
        table.destroy();
    });
});