$('#decision_request').find('.submit').show();
function toggleCheckbox(element)
{
	if(element.checked == true){
		$('#decision_request_title').text("Unmatched Quantity & Damaged");
	}else{
		$('#decision_request_title').text("Unmatched Quantity");
	}
}
var FormWizard = function () {


    return {
        //main function to initiate the module
        init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }

            
            var form = $('#submit_form');
            var error = $('.alert-danger', form);
            var success = $('.alert-success', form);

            form.validate({
                doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                rules: {
                    //account
                    so_id: {
                        required: true
                    },
                    consignment_note_no: {
                        remote:{
							url: "/warehouse-arrangements/checkConsignmentNote",
							type: "post",
							data: {
								consignment_note_no: function() {
									return $( "#consignment_note_no" ).val();
								}
							}
						}
                    },
                    warehouse_receive_note_no: {
                        remote:{
							url: "/warehouse-arrangements/checkReceiveNote",
							type: "post",
							data: {
								warehouse_receive_note_no: function() {
									return $( "#warehouse_receive_note_no" ).val();
								}
							}
						}
                    },
                   
                },

                messages: { // custom messages for radio buttons and checkboxes
                    'so_id': {
                        required: "Please select at least one option",                        
                    }, 
					'consignment_note_no': {
                        remote: "Consigment Note No. must be unique! Try another."
						
                    }, 
					'warehouse_receive_note_no': {
                        remote: "Warehouse Receive Note No. must be unique! Try another."
                    }, 
                },

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

            });

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

                    $('#form_wizard_1').find('.button-decision-request').show();
                    $('#form_wizard_1').find('.button-decision-reject').show();					
                } else {
                    $('#form_wizard_1').find('.button-next').show();
                    $('#form_wizard_1').find('.button-submit').hide();
					$('#form_wizard_1').find('.button-decision-request').hide();
                    $('#form_wizard_1').find('.button-decision-reject').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 + '%'
                    });
                }
            });

            $('#form_wizard_1').find('.button-previous').hide();
            
            $('#form_wizard_1 .button-submit').click(function () {
					var dataString = $('#submit_form').serialize() + '&submit_type=no_decision_request';
					$.ajax({
						type: "POST",
						url: "/warehouse-arrangements/add-warehouse-arrangements",
						data: dataString,
						cache: false,
						beforeSend: function(){ 
							$("#finish").hide();
							$("#wait").show();
							$("#suksesupdate").hide();
							$("#gagalupdate").hide();
						},
						complete: function(e, xhr, settings){
							if(e.status === 200){
								$("#finish").show();
								$("#wait").hide();
								$("#suksesupdate").show();
								//$("#gagalupdate").hide();
								location.reload();
							}else{
								$("#finish").show();
								$("#wait").hide();
								//$("#suksesupdate").show();
								$("#gagalupdate").show();
								location.reload();
							}
						}
						
					});
            }).hide();
			$('#decision_request .submit').click(function () {
					var dataString = $('#submit_form').serialize() + '&' + $('#decision_request').serialize() + '&type=decision_request';
					$.ajax({
						type: "POST",
						url: "/warehouse-arrangements/add-warehouse-arrangements",
						data: dataString,
						cache: false,
						beforeSend: function(){ 
							$("#finish").hide();
							$("#wait").show();
							$("#suksesupdate").hide();
							$("#gagalupdate").hide();
						},
						complete: function(e, xhr, settings){
							if(e.status === 200){
								$("#finish").show();
								$("#wait").hide();
								$("#suksesupdate").show();
								//$("#gagalupdate").hide();
								location.reload();
							}else{
								$("#finish").show();
								$("#wait").hide();
								//$("#suksesupdate").show();
								$("#gagalupdate").show();
								location.reload();
							}
						}
						
					});
            }).hide();
			$('#form_wizard_1 .button-decision-request').click(function () {
				jQuery("#form_add").modal('hide');
				jQuery("#form_decision_request").modal('show');					 
            });
			$('#form_wizard_1 .button-decision-reject').click(function () {
				jQuery("#form_add").modal('hide');
				jQuery("#form_decision_reject").modal('show');					 
            });
			$('#decision_reject .submit').click(function () {
					var dataString = $('#submit_form').serialize() + '&' + $('#decision_reject').serialize() + '&type=decision_reject';
					$.ajax({
						type: "POST",
						url: "/warehouse-arrangements/add-warehouse-arrangements",
						data: dataString,
						cache: false,
						beforeSend: function(){ 
							$("#finish").hide();
							$("#wait").show();
							$("#suksesupdate").hide();
							$("#gagalupdate").hide();
						},
						complete: function(e, xhr, settings){
							if(e.status === 200){
								$("#finish").show();
								$("#wait").hide();
								$("#suksesupdate").show();
								//$("#gagalupdate").hide();
								location.reload();
							}else{
								$("#finish").show();
								$("#wait").hide();
								//$("#suksesupdate").show();
								$("#gagalupdate").show();
								location.reload();
							}
						}
						
					});
            }).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) {

		            }

        		});
        	});
        }

    };

}();

var ComponentsDateTimePickers = function() {
    var t = function() {
        jQuery().datepicker && $(".date-picker").datepicker({
            rtl: App.isRTL(),
			format: 'yyyy-mm-dd',
            orientation: "left",
            autoclose: !0
        }),
        $(document).scroll(function() {
            $("#submit_form .date-picker").datepicker("place")
        })
    }
    
    return {
        init: function() {
            t()
        }
    }
}();

	function loadData() {
	var oTable = $('#warehouse-arrangements').DataTable( {
	"serverSide": true,
	  "ajax": {
		"url": "/warehouse-arrangements/list",
		"type": "POST",
	  },
	"columnDefs": [
    { className: "dt-body-center", "targets": [ 0,1,2,3,4,5,6,7,8,9 ] },
    
  ],
	"language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "No data available in table",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                "infoEmpty": "No entries found",
                "infoFiltered": "(filtered1 from _MAX_ total entries)",
                "lengthMenu": "_MENU_ entries",
                "search": "Search:",
                "zeroRecords": "No matching records found"
            },
	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"] ],
	"order": [
		[ 0, 'asc' ]
	],
	
	});
	
	var tableWrapper = jQuery('#warehouse-arrangements_wrapper');
	$('.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();
	} );
	$('.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();
	} );
	$("#warehouse-arrangements_filter").css("display","none"); 
	$('#sample_3_tools > li > a.tool-action').on('click', function() {
		var action = $(this).attr('data-action');
		oTable.DataTable().button(action).trigger();
	});
	

}
jQuery(document).ready(function() {
    
    loadData(1);
    FormWizard.init();
    FormRepeater.init();
	ComponentsDateTimePickers.init()
	
	
	$(document).on("click", ".details", function() {
		var so_id = $(this).data('id');
		var dataStringg = 'so_id=' + so_id;
		 $.ajax({
			type: "POST",
			url: "/warehouse-arrangements/get-details",
			cache: false,
			data: dataStringg,
			success: function(data) {
				$("#getCode").html(data);
				jQuery("#detailss").modal('show');
			}
		});
	});
	
	$("#so_id").change(function() {
		var so_id = $("#so_id").val();
		var dataStringg = 'so_id='+so_id;
		
		$.ajax({
			type: "POST",
			url: "/warehouse-arrangements/getSOWarehouse",
			data: dataStringg,	
			success: function(data) {
				$("#warehouse").html(data);
			}
		});
		$.ajax({
			type: "POST",
			url: "/warehouse-arrangements/getSOItems",
			data: dataStringg,	
			success: function(data) {
				$("#tbody").html(data);
			}
		});
	});
});
jQuery('body').on('change','input.warehouse_arrangement_items',function(e){
	if($(this).closest('tr').find("input[name*='actual_height_ctn']").val()){
		$(this).closest('tr').find("input[name*='actual_height_ctn']").val(parseFloat($(this).closest('tr').find("input[name*='actual_height_ctn']").val()).toFixed(2));
	}
	
	if($(this).closest('tr').find("input[name*='actual_width_ctn']").val()){
		$(this).closest('tr').find("input[name*='actual_width_ctn']").val(parseFloat($(this).closest('tr').find("input[name*='actual_width_ctn']").val()).toFixed(2));
	}
	
	if($(this).closest('tr').find("input[name*='actual_depth_ctn']").val()){
		$(this).closest('tr').find("input[name*='actual_depth_ctn']").val(parseFloat($(this).closest('tr').find("input[name*='actual_depth_ctn']").val()).toFixed(2));
	}
	
	if($(this).closest('tr').find("input[name*='actual_weight_ctn']").val()){
		$(this).closest('tr').find("input[name*='actual_weight_ctn']").val(parseFloat($(this).closest('tr').find("input[name*='actual_weight_ctn']").val()).toFixed(2));
	}
	
	
	var actual_ctn =  $(this).closest('tr').find("td:eq(2)").text();
	var current_ctn =  $(this).closest('tr').find("input[name*='actual_ctn']").val();
	var current_balance =  $(this).closest('tr').find("input[name*='balance']").val();
	var balance = current_balance - current_ctn;
	
	if( balance ==  0 ){		
		var changetdtext = $(this).closest('tr').find("td:eq(8)").html(balance);
		var changetdtext = $(this).closest('tr').find("td:eq(9)").html("<span class='font-green-meadow'>Matched</span>");
		$(this).closest('tr').find("input[name*='status']").val("0");
	}else{
		var changetdtext = $(this).closest('tr').find("td:eq(8)").html(balance);
		var changetdtext = $(this).closest('tr').find("td:eq(9)").html("<span class='font-red'>Unmatched</span>");
		$(this).closest('tr').find("input[name*='status']").val("1");
	}
});
function PreviewImage(cc) {
	var oFReader = new FileReader();
	oFReader.readAsDataURL(document.getElementById("image["+cc+"]").files[0]);

	oFReader.onload = function (oFREvent) {
		document.getElementById("uploadPreview["+cc+"]").src = oFREvent.target.result;
		document.getElementById("warehouse_arrangement_items["+cc+"][image]").value = oFREvent.target.result;
		
	};
};