$("#pack_type_uom").hide();
$("#pack_type_photo").hide();
$("#sack").hide();
$("#pallet").hide();
$("#carton").hide();
$("#wooden_box").hide();

$(".warehouse").show();
$(".warehouse_address").show();
$(".warehouse_name").show();
$(".supplier").show();
$(".order_no").hide();
$(".forwarder_id").show();

$('#stepy_form').find('select,input:not(#forwarder_id),button,a:not(#button-select-last-selected),textarea,.button-next').prop( "disabled", true );

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,
            });

            $(document).on("click", ".button-edit2", function() {
                var counter = $('#rowNumber').val();
                counter++;

                //tarik data dari popup letak dalam table
                document.getElementById("shippingorderitems[" + counter + "][description]").innerHTML = $('#description').val();
                document.getElementById("shippingorderitems[" + counter + "][model_no]").innerHTML = $('#model_no').val();
                document.getElementById("shippingorderitems[" + counter + "][uom]").innerHTML = $('#uom').val();
                document.getElementById("shippingorderitems[" + counter + "][quantity]").innerHTML = $('#quantity').val();
                document.getElementById("shippingorderitems[" + counter + "][packaging_cbm]").innerHTML = ($('#packaging_height').val() * $('#packaging_depth').val() * $('#packaging_width').val()) + "m³";
                document.getElementById("shippingorderitems[" + counter + "][packaging_height]").innerHTML = "Height = " + $('#packaging_height').val() + "m";
                document.getElementById("shippingorderitems[" + counter + "][packaging_width]").innerHTML = "Width = " + $('#packaging_width').val() + "m";
                document.getElementById("shippingorderitems[" + counter + "][packaging_depth]").innerHTML = "Depth = " + $('#packaging_depth').val() + "m";
                document.getElementById("shippingorderitems[" + counter + "][weight]").innerHTML = $('#packaging_gross').val() + "kg";
                document.getElementById("shippingorderitems[" + counter + "][packaging_gross]").innerHTML = "Gross = " + $('#packaging_gross').val() + "kg";
                document.getElementById("shippingorderitems[" + counter + "][packaging_nett]").innerHTML = "Nett = " + $('#packaging_nett').val() + "kg";
                document.getElementById("shippingorderitems[" + counter + "][image]").src = $("#uploadPreview").attr('src');

                $("input[name='shippingorderitems[" + counter + "][description]']").val($('#description').val());
                $("input[name='shippingorderitems[" + counter + "][model_no]']").val($('#model_no').val());
                $("input[name='shippingorderitems[" + counter + "][item_code]']").val($('#item_code').val());
                $("input[name='shippingorderitems[" + counter + "][brand_no]']").val($('#brand_no').val());
                $("input[name='shippingorderitems[" + counter + "][uom]']").val($('#uom').val());
                $("input[name='shippingorderitems[" + counter + "][quantity]']").val($('#quantity').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_quantity]']").val($('#packaging_quantity').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_type1]']").val($('#packaging_type1').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_type2]']").val($('#packaging_type2').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_cbm]']").val($('#packaging_height').val() * $('#packaging_width').val() * $('#packaging_depth').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_height]']").val($('#packaging_height').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_width]']").val($('#packaging_width').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_depth]']").val($('#packaging_depth').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_gross]']").val($('#packaging_gross').val());
                $("input[name='shippingorderitems[" + counter + "][packaging_nett]']").val($('#packaging_nett').val());
                $("input[name='shippingorderitems[" + counter + "][image]']").val($('#image').val());
                $("input[name='shippingorderitems[" + counter + "][image2]']").val($('#image2').val());
                $("input[name='shippingorderitems[" + counter + "][image3]']").val($('#image3').val());
                $("input[name='shippingorderitems[" + counter + "][image4]']").val($('#image4').val());

                //Kosongkan form
                $('#description').val('');
                $('#brand_no').val('');
                $('#model_no').val('');
                $('#item_code').val('');
                $('#uom').val('');
                $('#quantity').val('');
                $('#packaging_quantity').val('');
                $('#packaging_type1').val('');
                $('#packaging_type2').val('');
                $('#packaging_width').val('');
                $('#packaging_depth').val('');
                $('#packaging_height').val('');
                $('#packaging_gross').val('');
                $('#packaging_nett').val('');
                $("#image").val('');
                $("#image2").val('');
                $("#image3").val('');
                $("#image4").val('');
                $("#pack_type_uom").hide();
                $("#pack_type_photo").hide();
                $("#sack").hide();
                $("#pallet").hide();
                $("#carton").hide();
                $("#wooden_box").hide();
                document.getElementById("uploadPreview").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
                document.getElementById("uploadPreview2").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
                document.getElementById("uploadPreview3").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
                document.getElementById("uploadPreview4").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";

                $('.button-previous2').trigger('click');
                
				$('#finish2').remove();
                $('.button-next2').after('&nbsp;<a class="btn green button-submit2" id="finish2" style="display: inline-block;"> Finish!</a>'); //add input box
                $('#finish2').hide();
                $('#rowNo').remove();
                $('#form_add').modal('hide');

            }).hide();
            var counter = 1;
            $(document).on("click", ".submitpin", function() {
                var name = $("#name").val();
                var address = $("#address").val();
                var city = $("#city").val();
                var zip = $("#zip").val();
                var state = $("#state").val();
                var contact_person = $("#contact_person").val();
                var contact_person_no = $("#contact_person_no").val();
                var country = $("#country").val();
                var branch = $("#branch").val();
                var dataString = 'name=' + name +
                    '&address=' + address +
                    '&city=' + city +
                    '&zip=' + zip +
                    '&state=' + state +
                    '&contact_person=' + contact_person +
                    '&contact_person_no=' + contact_person_no +
                    '&branch=' + branch +
                    '&country=' + country;

                $.ajax({
                    type: "POST",
                    url: "/company/warehouse/add",
                    data: dataString,
                    cache: false,
                    complete: function(e, xhr, settings) {
                        if (e.status === 200) {
                            $.ajax({
                                type: "POST",
                                url: "/shipping-order/getDeliveryAddress",
                                success: function(data) {
                                    $("#name").val("");
                                    $("#address").val("");
                                    $("#city").val("");
                                    $("#zip").val("");
                                    $("#state").val("");
                                    $("#contact_person").val("");
                                    $("#contact_person_no").val("");
                                    $("#country").val("");
                                    $("#branch").val("");
                                    $("#delivery_id").html(data);
                                    $('#form_add_delivery').modal('hide');
                                }
                            });
                        }
                    }

                });
            }).hide();

            $(document).on("click", ".button-submit2", function() {
                var form = $('#stepy_form2');
				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: {
                        description: {
                            required: true,
                        },
                        packaging_quantity: {
                            required: true,
                  
                    },
                    messages: {
                        description: {
                            required: "You must choose description to proceed",
                        },
                        packaging_quantity: {
                            required: "You must choose package quantity 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[]") { // for checkboxes and radio buttons, no need to show OK icon
							label
								.closest('.form-group').removeClass('has-error').addClass('has-success');
							label.remove(); // remove error label here
						} else { // display success icon for other inputs
							label
								.addClass('valid') // mark the current input as valid and display OK icon
								.closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
						}
					}
				});
				success.hide();
				error.hide();
				
				if (form.valid() == false) {
					return false;
				}
				
				//add new row
                t.row.add([
                    counter,
                    "<p id='shippingorderitems[" + counter + "][description]' class='form-control-static'></p>",
                    "<p id='shippingorderitems[" + counter + "][model_no]' class='form-control-static'></p>",
                    "<p id='shippingorderitems[" + counter + "][uom]' class='form-control-static'></p>",
                    "<p id='shippingorderitems[" + counter + "][quantity]' class='form-control-static'></p>",
                    "<div class='btn-group'><button class='btn green btn-xs btn-circle btn-outline dropdown-toggle btiv' data-toggle='dropdown'><p id='shippingorderitems[" + counter + "][packaging_cbm]' class='form-control-static'></p><i class='fa fa-angle-down'></i></button><ul class='dropdown-menu'><li id='shippingorderitems[" + counter + "][packaging_height]'></li><li id='shippingorderitems[" + counter + "][packaging_width]'></li><li id='shippingorderitems[" + counter + "][packaging_depth]'></li></ul></div>",
                    "<div class='btn-group'><button class='btn green btn-xs btn-circle btn-outline dropdown-toggle btiv' data-toggle='dropdown'><p id='shippingorderitems[" + counter + "][weight]' class='form-control-static'></p><i class='fa fa-angle-down'></i></button><ul class='dropdown-menu'><li id='shippingorderitems[" + counter + "][packaging_gross]'></li><li id='shippingorderitems[" + counter + "][packaging_nett]'>packaging_nett = 15kg</li></ul></div>",
                    "<center><img id='shippingorderitems[" + counter + "][image]' style='max-width: 100px; max-height: 100px;' src='http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image'/></center>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][description]'  style='display:none;' value='" + $('#description').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][model_no]'  style='display:none;' value='" + $('#model_no').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][item_code]'  style='display:none;' value='" + $('#item_code').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][brand_no]'  style='display:none;' value='" + $('#brand_no').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][uom]'  style='display:none;' value='" + $('#uom').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][quantity]'  style='display:none;' value='" + $('#quantity').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_quantity]'  style='display:none;' value='" + $('#packaging_quantity').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_type1]'  style='display:none;' value='" + $('#packaging_type1').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_type2]'  style='display:none;' value='" + $('#packaging_type2').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_cbm]'  style='display:none;' value='" + ($('#packaging_height').val() * $('#packaging_depth').val() * $('#packaging_width').val()) + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_height]'  style='display:none;' value='" + $('#packaging_height').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_width]'  style='display:none;' value='" + $('#packaging_width').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_depth]'  style='display:none;' value='" + $('#packaging_depth').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_gross]'  style='display:none;' value='" + $('#packaging_gross').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][packaging_nett]'  style='display:none;' value='" + $('#packaging_nett').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][image]'  style='display:none;'   value='" + $('#imagebase64').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][image2]'  style='display:none;' value='" + $('#image2base64').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][image3]'  style='display:none;' value='" + $('#image3base64').val() + "'>" +
                    "<input class='hiden-input' name='shippingorderitems[" + counter + "][image4]'  style='display:none;' value='" + $('#image4base64').val() + "'>",
                    "<a class='delete'>Delete</a> <a class='edit'>Edit</a>",
                ]).draw(false);

                //tarik data dari popup letak dalam table
                document.getElementById("shippingorderitems[" + counter + "][description]").innerHTML = $('#description').val();
                document.getElementById("shippingorderitems[" + counter + "][model_no]").innerHTML = $('#model_no').val();
                document.getElementById("shippingorderitems[" + counter + "][uom]").innerHTML = $('#uom').val();
                document.getElementById("shippingorderitems[" + counter + "][quantity]").innerHTML = $('#quantity').val();
                document.getElementById("shippingorderitems[" + counter + "][packaging_cbm]").innerHTML = ($('#packaging_height').val() * $('#packaging_depth').val() * $('#packaging_width').val()) + "m³";
                document.getElementById("shippingorderitems[" + counter + "][packaging_height]").innerHTML = "Height = " + $('#packaging_height').val() + "m";
                document.getElementById("shippingorderitems[" + counter + "][packaging_width]").innerHTML = "Width = " + $('#packaging_width').val() + "m";
                document.getElementById("shippingorderitems[" + counter + "][packaging_depth]").innerHTML = "Depth = " + $('#packaging_depth').val() + "m";
                document.getElementById("shippingorderitems[" + counter + "][weight]").innerHTML = $('#packaging_gross').val() + "kg";
                document.getElementById("shippingorderitems[" + counter + "][packaging_gross]").innerHTML = "Gross = " + $('#packaging_gross').val() + "kg";
                document.getElementById("shippingorderitems[" + counter + "][packaging_nett]").innerHTML = "Nett = " + $('#packaging_nett').val() + "kg";
                document.getElementById("shippingorderitems[" + counter + "][image]").src = $("#uploadPreview").attr('src');


                //Kosongkan form
                $('#description').val('');
                $('#brand_no').val('');
                $('#model_no').val('');
                $('#item_code').val('');
                $('#uom').val('');
                $('#quantity').val('');
                $('#packaging_quantity').val('');
                $('#packaging_type1').val('');
                $('#packaging_type2').val('');
                $('#packaging_width').val('');
                $('#packaging_depth').val('');
                $('#packaging_height').val('');
                $('#packaging_gross').val('');
                $('#packaging_nett').val('');
                $("#image").val('');
                $("#image2").val('');
                $("#image3").val('');
                $("#image4").val('');
                $("#pack_type_uom").hide();
                $("#pack_type_photo").hide();
                $("#sack").hide();
                $("#pallet").hide();
                $("#carton").hide();
                $("#wooden_box").hide();
                document.getElementById("uploadPreview").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
                document.getElementById("uploadPreview2").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
                document.getElementById("uploadPreview3").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
                document.getElementById("uploadPreview4").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";

                $('.button-previous2').trigger('click');
                $('#form_add').modal('hide');
                $('#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');
                        if (typeof oldName === 'undefined') {

                        } else {
                            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);
                    });
                });
                counter++;

            }).hide();

            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');
                        if (typeof oldName === 'undefined') {

                        } else {
                            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', '.edit', function(e) {
                var nRow = $(this).parents("tr");


                $.each(nRow.find(':input'), function(i, val) {
                    var oldName = $(this).attr('name');
                    if (typeof oldName === 'undefined') {

                    } else {
                        var value = $("input[name='" + oldName + "']").val();
                        if (oldName.indexOf('packaging_type1') != -1) {
                            $("#packaging_type1").val(value).change();
                        } else if (oldName.indexOf('packaging_quantity') != -1) {
                            $('#packaging_quantity').val(value);
                        } else if (oldName.indexOf('description') != -1) {
                            $('#description').val(value);
                        } else if (oldName.indexOf('model_no') != -1) {
                            $('#model_no').val(value);
                        } else if (oldName.indexOf('brand_no') != -1) {
                            $('#brand_no').val(value);
                        } else if (oldName.indexOf('item_code') != -1) {
                            $('#item_code').val(value);
                        } else if (oldName.indexOf('uom') != -1) {
                            $('#uom').val(value);
                        } else if (oldName.indexOf('quantity') != -1) {
                            $('#quantity').val(value);
                        } else if (oldName.indexOf('packaging_type2') != -1) {
                            $('#packaging_type2').val(value);
                        } else if (oldName.indexOf('packaging_width') != -1) {
                            $('#packaging_width').val(value);
                        } else if (oldName.indexOf('packaging_depth') != -1) {
                            $('#packaging_depth').val(value);
                        } else if (oldName.indexOf('packaging_height') != -1) {
                            $('#packaging_height').val(value);
                        } else if (oldName.indexOf('packaging_gross') != -1) {
                            $('#packaging_gross').val(value);
                        } else if (oldName.indexOf('packaging_nett') != -1) {
                            $('#packaging_nett').val(value);
                        }

                    }
                });
                $('#form_wizard_2').append('<div id="rowNo"><input type="text" style="display:none;" name="rowNumber" id="rowNumber" value="' + nRow.index() + '"/></div>'); //add input box

                $('#finish2').remove();
                $('.button-next2').after('&nbsp;<a class="btn green button-edit2" id="finish2" style="display: inline-block;"> Finish!</a>'); //add input box
                $('#finish2').hide();

                $('#form_add').modal('show');
            });

        });
    }

    return {

        //main function to initiate the module
        init: function() {
            handleTable();
        }

    };

}();
// }

function PreviewImage() {
    var oFReader = new FileReader();
	var mime = document.getElementById("image").files[0].type;
    oFReader.readAsDataURL(document.getElementById("image").files[0]);
	if(mime == "image/jpeg" || mime == "image/gif" || mime == "image/png" || mime == "image/tiff" || mime == "image/x-windows-bmp" || mime == "image/bmp" || mime == "image/pjpeg" || mime == "image/x-jps"){
		oFReader.onload = function(oFREvent) {
			document.getElementById("uploadPreview").src = oFREvent.target.result;
			$("#imagebase64").val(oFREvent.target.result);
		};
	}else{
		alert("Only image files are allowed!");
		return false;
	}
};

function PreviewImage2() {
    var oFReader = new FileReader();
    var mime = document.getElementById("image2").files[0].type;
	oFReader.readAsDataURL(document.getElementById("image2").files[0]);
	
	if(mime == "image/jpeg" || mime == "image/gif" || mime == "image/png" || mime == "image/tiff" || mime == "image/x-windows-bmp" || mime == "image/bmp" || mime == "image/pjpeg" || mime == "image/x-jps"){
		oFReader.onload = function(oFREvent) {
			document.getElementById("uploadPreview2").src = oFREvent.target.result;
			$("#image2base64").val(oFREvent.target.result);
		};
	}else{
		alert("Only image files are allowed!");
		return false;
	}
    
};

function PreviewImage3() {
    var oFReader = new FileReader();
    var mime = document.getElementById("image3").files[0].type;
	oFReader.readAsDataURL(document.getElementById("image3").files[0]);

	if(mime == "image/jpeg" || mime == "image/gif" || mime == "image/png" || mime == "image/tiff" || mime == "image/x-windows-bmp" || mime == "image/bmp" || mime == "image/pjpeg" || mime == "image/x-jps"){
		oFReader.onload = function(oFREvent) {
			document.getElementById("uploadPreview3").src = oFREvent.target.result;
			$("#image3base64").val(oFREvent.target.result);
		};
	}else{
		alert("Only image files are allowed!");
		return false;
	}
};

function PreviewImage4() {
    var oFReader = new FileReader();
	var mime = document.getElementById("image4").files[0].type;
	oFReader.readAsDataURL(document.getElementById("image4").files[0]);

	if(mime == "image/jpeg" || mime == "image/gif" || mime == "image/png" || mime == "image/tiff" || mime == "image/x-windows-bmp" || mime == "image/bmp" || mime == "image/pjpeg" || mime == "image/x-jps"){
		oFReader.onload = function(oFREvent) {
			document.getElementById("uploadPreview4").src = oFREvent.target.result;
			$("#image4base64").val(oFREvent.target.result);
		};
	}else{
		alert("Only image files are allowed!");
		return false;
	}
};

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);
    }
}

var FormWizard = function() {


    return {
        //main function to initiate the module
        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,
                    },
                    warehouse_id: {
                        required: true,
                    },
                    delivery_address: {
                        required: true,
                    },
                    delivery_city: {
                        required: true,
                    },
                    delivery_state: {
                        required: true,
                    },
                    delivery_zip: {
                        required: true,
                    },
                    delivery_country: {
                        required: true,
                    },
                },
                messages: {
                    forwarder_id: {
                        required: "You must choose forwarder to proceed",
                    },
                    warehouse_id: {
                        required: "You must choose warehouse to proceed",
                    },
                    delivery_address: {
                        required: "Please enter your delivery address",
                    },
                    delivery_city: {
                        required: "Please enter your delivery city",
                    },
                    delivery_state: {
                        required: "Please enter your delivery state",
                    },
                    delivery_zip: {
                        required: "Please enter your delivery postcode",
                    },
                    delivery_country: {
                        required: "Please enter your delivery country",
                    },
                },
                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[]") { // for checkboxes and radio buttons, no need to show OK icon
                        label
                            .closest('.form-group').removeClass('has-error').addClass('has-success');
                        label.remove(); // remove error label here
                    } else { // display success icon for other inputs
                        label
                            .addClass('valid') // mark the current input as valid and display OK icon
                            .closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    }
                },
                submitHandler: function(form) {

					if ($(".dataTables_empty")[0]){
						alert("You need to enter atleast one item to proceed!");
						return false;
					} else {
						var dataString = $('#stepy_form').serialize();
						$.ajax({
							type: "POST",
							url: "/shipping-order/add-shipping-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 so_id = $.trim(e.responseText);
									var dataStringg = 'so_id=' + so_id;
									$.ajax({
										type: "POST",
										url: "/shipping-order/getModalSuccess",
										data: dataStringg,
										cache: false,
										success: function(data) {
											$("#success-content").html(data);
											setTimeout(function() {
											html2canvas(document.querySelector("#SOmarking"), {
											allowTaint: true,
											useCORS: true
											}).then(function(canvas) {
											$("#img-out").append(canvas);
											$("#SOmarking").hide();
											});


											}, 500);
											$('#modal_success').modal('show');

										}
									});
                                } 
                                else if (e.status === 403){
                                    $("#finish").show();
                                    $("#wait").hide();
                                    //$("#suksesupdate").show();
                                    alert(e.responseText);
                                }
                                else {
                                $("#finish").show();
                                $("#wait").hide();
                                //$("#suksesupdate").show();
                                $("#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() {
                // alert('Finished! Hope you like it :)');
            }).hide();

        }

    };

}();


var FormRepeater = function() {

    return {
        //main function to initiate the module
        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) {

                    }

                });
            });
        }

    };

}();



function removePhoto(photo) {
    //var photo = $(this).data("id") ;
    if (photo == "image") {
        $("#imagebase64").val("");
        document.getElementById("uploadPreview").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
    } else if (photo == "image2") {
        $("#image2base64").val("");
        document.getElementById("uploadPreview2").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
    } else if (photo == "image3") {
        $("#image3base64").val("");
        document.getElementById("uploadPreview3").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
    } else if (photo == "image4") {
        $("#image4base64").val("");
        document.getElementById("uploadPreview4").src = "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image";
    }
};

var SweetAlert = function() {

    return {
        //main function to initiate the module
        init: function() {
            $('.mt-sweetalert').each(function() {
                var sa_title = $(this).data('title');
                var sa_message = $(this).data('message');
                var sa_type = $(this).data('type');
                var sa_allowOutsideClick = $(this).data('allow-outside-click');
                var sa_showConfirmButton = $(this).data('show-confirm-button');
                var sa_showCancelButton = $(this).data('show-cancel-button');
                var sa_closeOnConfirm = $(this).data('close-on-confirm');
                var sa_closeOnCancel = $(this).data('close-on-cancel');
                var sa_confirmButtonText = $(this).data('confirm-button-text');
                var sa_cancelButtonText = $(this).data('cancel-button-text');
                var sa_popupTitleSuccess = $(this).data('popup-title-success');
                var sa_popupMessageSuccess = $(this).data('popup-message-success');
                var sa_popupTitleCancel = $(this).data('popup-title-cancel');
                var sa_popupMessageCancel = $(this).data('popup-message-cancel');
                var sa_confirmButtonClass = $(this).data('confirm-button-class');
                var sa_cancelButtonClass = $(this).data('cancel-button-class');

                $(this).click(function() {
                    //console.log(sa_btnClass);
                    swal({
                            title: sa_title,
                            text: sa_message,
                            type: sa_type,
                            allowOutsideClick: sa_allowOutsideClick,
                            showConfirmButton: sa_showConfirmButton,
                            showCancelButton: sa_showCancelButton,
                            confirmButtonClass: sa_confirmButtonClass,
                            cancelButtonClass: sa_cancelButtonClass,
                            closeOnConfirm: sa_closeOnConfirm,
                            closeOnCancel: sa_closeOnCancel,
                            confirmButtonText: sa_confirmButtonText,
                            cancelButtonText: sa_cancelButtonText,
                        },
                        function(isConfirm) {
                            if (isConfirm) {
                                swal(sa_popupTitleSuccess, sa_popupMessageSuccess, "success");
                            } else {
                                swal(sa_popupTitleCancel, sa_popupMessageCancel, "error");
                            }
                        });
                });
            });

        }
    }

}();

jQuery(document).ready(function() {
    TableDatatablesEditable.init();
    FormWizard.init();
    FormRepeater.init();
    SweetAlert.init();

	
    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();
        });
		
        $('#forwarder_id').on('change', function() {
			$('#stepy_form').find('select,input:not(#forwarder_id),button,a,textarea,.button-next').prop( "disabled", false );
        });
        
        $('.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("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');
                }
            }
        });

    });

    $(document).on('keydown', '.int', function(event) {
        if (event.shiftKey == true)
            event.preventDefault();

        if ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 190 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39) {} else
            event.preventDefault();

        if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
            event.preventDefault();
    });

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

    $('#modal_success').on('hidden.bs.modal', function() {
        window.location.href = '/shipping-order';
    });

    $('.nav-item .nav-link').on('click', function() {
        return confirm('Are you sure? You will not be able to recover this Shipping Order.');
    });

    $.ajax({
        type: "POST",
        url: "/shipping-order/getDeliveryAddress",
        success: function(data) {
            $("#delivery_id").html(data);
        }
    });
    $("#po_id").change(function() {
        var po_id = $("#po_id").val();
        if (po_id != "") {
            window.location.href = '/shipping-order/create?id=' + po_id;
        } else {
            $("#supplier").val("");
            $("#supplier_contact_person").val("");
            $("#supplier_contact_person_no").val("");
            $(".delete").trigger("click");
        }

        var dataStringg = 'po_id=' + po_id;
        $.ajax({
            type: "POST",
            url: "/shipping-order/getWarehouseFromPO",
            data: dataStringg,
            success: function(data) {
                $("#warehouse_id").html(data);
            }
        });
    });
    $(document).on("click", "#button-select-last-selected", function() {
		var forwarder_id = $(this).data("id");
		var company_name = $(this).data("company_name");
		$("#forwarder").html("<a>" + company_name + "</a>");
		$("#forwarder_id").val(forwarder_id);
		$("#select_forwarder").hide();
		$("#forwarder").show();
		$(".last-selected").hide();
		$('#stepy_form').find('select,input:not(#forwarder_id),button,a,textarea,.button-next').prop( "disabled", false );
		var dataStringg = 'forwarder_id=' + forwarder_id;
		$.ajax({
			type: "POST",
			url: "/shipping-order/getWarehouse",
			data: dataStringg,
			success: function(data) {
				$("#warehouse_id").html(data);
			}
		});
	});
    $(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();
		$('#stepy_form').find('select,input:not(#forwarder_id),button,a,textarea,.button-next').prop( "disabled", false );
        var dataStringg = 'forwarder_id=' + forwarder_id;
        $.ajax({
            type: "POST",
            url: "/shipping-order/getWarehouse",
            data: dataStringg,
            success: function(data) {
                $("#warehouse_id").html(data);
            }
        });

    });

    $("#warehouse_id").change(function() {
        var warehouse_id = $("#warehouse_id").val();
        var dataStringg = 'warehouse_id=' + warehouse_id;
        $.ajax({
            type: "POST",
            url: "/shipping-order/getwarehousedata",
            data: dataStringg,
            success: function(data) {
                var obj = JSON.parse(data);
                $("#warehouse_name").val(obj[0].name);
                $("#warehouse_address").val(obj[0].address);
                $("#warehouse_city").val(obj[0].city);
                $("#warehouse_zip").val(obj[0].zip);
                $("#warehouse_state").val(obj[0].state);
                $("#warehouse_country").val(obj[0].country);
                $("#warehouse_contact_person").val(obj[0].contact_person);
                $("#warehouse_contact_person_no").val(obj[0].contact_person_no);
            }
        });
    });
    $("#delivery_id").change(function() {
        var delivery_id = $("#delivery_id").val();
        var dataStringg = 'delivery_id=' + delivery_id;
        $.ajax({
            type: "POST",
            url: "/shipping-order/getdeliverydata",
            data: dataStringg,
            success: function(data) {
                var obj = JSON.parse(data);
                $("#delivery_name").val(obj[0].name);
                $("#delivery_address").val(obj[0].address);
                $("#delivery_city").val(obj[0].city);
                $("#delivery_zip").val(obj[0].zip);
                $("#delivery_state").val(obj[0].state);
                $("#delivery_country").val(obj[0].country);
                $("#delivery_contact_person").val(obj[0].contact_person);
                $("#delivery_contact_person_no").val(obj[0].contact_person_no);
            }
        });
    });
    $("#packaging_type1").change(function() {
        var data = $("#packaging_type1 option:selected").val();
        if (data == "Sacks") {
            $("#pack_type_uom").hide();
            $("#pack_type_photo").hide();
            $("#sack").show();
            $("#pallet").hide();
            $("#carton").hide();
            $("#wooden_box").hide();
        } else if (data == "Carton") {
            $("#pack_type_uom").hide();
            $("#pack_type_photo").hide();
            $("#sack").hide();
            $("#pallet").hide();
            $("#carton").show();
            $("#wooden_box").hide();
        } else if (data == "Pallet") {
            $("#pack_type_uom").hide();
            $("#pack_type_photo").hide();
            $("#sack").hide();
            $("#pallet").show();
            $("#carton").hide();
            $("#wooden_box").hide();
        } else if (data == "new") {
            $("#pack_type_uom").show();
            $("#pack_type_photo").show();
            $("#sack").hide();
            $("#pallet").hide();
            $("#carton").hide();
            $("#wooden_box").hide();
        } else if (data == "Wooden Box") {
            $("#pack_type_uom").hide();
            $("#pack_type_photo").hide();
            $("#sack").hide();
            $("#pallet").hide();
            $("#carton").hide();
            $("#wooden_box").show();
        } else {
            $("#pack_type_uom").hide();
            $("#pack_type_photo").hide();
            $("#sack").hide();
            $("#pallet").hide();
            $("#carton").hide();
            $("#wooden_box").hide();
        }
    });
    $("#order_type").change(function() {
        var data = $("#order_type option:selected").val();
        if (data == 1) {
            $(".warehouse").show();
            $(".warehouse_address").show();
            $(".warehouse_name").show();
            $(".supplier").show();
            $(".order_no").hide();
            $(".forwarder_id").show();
        } else if (data == 2) {
            $(".warehouse").show();
            $(".warehouse_address").show();
            $(".warehouse_name").show();
            $(".supplier").show();
            $(".order_no").show();
            $(".forwarder_id").hide();
        } else {
            $(".warehouse").hide();
            $(".warehouse_address").hide();
            $(".warehouse_name").hide();
            $(".supplier").hide();
            $(".order_no").hide();
            $(".forwarder_id").hide();
        }
    });

});