var FormWizard = function () {


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

            function format(state) {
                if (!state.id) return state.text; // optgroup
                return "<img class='flag' src='../../assets/global/img/flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
            }

            $("#country_list").select2({
                placeholder: "Select",
                allowClear: true,
                formatResult: format,
                width: 'auto', 
                formatSelection: format,
                escapeMarkup: function (m) {
                    return m;
                }
            });

            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
                    username: {
                        minlength: 5,
                        required: true
                    },
                    password: {
                        minlength: 5,
                        required: true
                    },
                    rpassword: {
                        minlength: 5,
                        required: true,
                        equalTo: "#submit_form_password"
                    },
                    //profile
                    fullname: {
                        required: true
                    },
                    email: {
                        required: true,
                        email: true
                    },
                    phone: {
                        required: true
                    },
                    gender: {
                        required: true
                    },
                    address: {
                        required: true
                    },
                    city: {
                        required: true
                    },
                    country: {
                        required: true
                    },
                    //payment
                    card_name: {
                        required: true
                    },
                    card_number: {
                        minlength: 16,
                        maxlength: 16,
                        required: true
                    },
                    card_cvc: {
                        digits: true,
                        required: true,
                        minlength: 3,
                        maxlength: 4
                    },
                    card_expiry_date: {
                        required: true
                    },
                    'payment[]': {
                        required: true,
                        minlength: 1
                    }
                },

                messages: { // custom messages for radio buttons and checkboxes
                    'payment[]': {
                        required: "Please select at least one option",
                        minlength: jQuery.validator.format("Please select at least one option")
                    }
                },

                errorPlacement: function (error, element) { // render error placement for each input type
                    if (element.attr("name") == "gender") { // for uniform radio buttons, insert the after the given container
                        error.insertAfter("#form_gender_error");
                    } else if (element.attr("name") == "payment[]") { // for uniform checkboxes, insert the after the given container
                        error.insertAfter("#form_payment_error");
                    } else {
                        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) {
                }

            });

            var displayConfirm = function() {
                $('#tab4 .form-control-static', form).each(function(){
                    var input = $('[name="'+$(this).attr("data-display")+'"]', form);
                    if (input.is(":radio")) {
                        input = $('[name="'+$(this).attr("data-display")+'"]:checked', form);
                    }
                    if (input.is(":text") || input.is("textarea")) {
                        $(this).html(input.val());
                    } else if (input.is("select")) {
                        $(this).html(input.find('option:selected').text());
                    } else if (input.is(":radio") && input.is(":checked")) {
                        $(this).html(input.attr("data-title"));
                    } else if ($(this).attr("data-display") == 'payment[]') {
                        var payment = [];
                        $('[name="payment[]"]:checked', form).each(function(){ 
                            payment.push($(this).attr('data-title'));
                        });
                        $(this).html(payment.join("<br>"));
                    }
                });
            }

            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();
                    displayConfirm();
                } 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 + '%'
                    });
                }
            });

            $('#form_wizard_1').find('.button-previous').hide();
            $('#form_wizard_1 .button-submit').click(function () {
					 var dataString = $('#submit_form').serialize();
					$.ajax({
						type: "POST",
						url: "/delivery-arrangements/add-delivery-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();
							}
						}
						
					});
            }).hide();

            //apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
            $('#country_list', form).change(function () {
                form.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
            });
        }

    };

}();

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 = $('#delivery-arrangements').DataTable( {
	"serverSide": true,
	  "ajax": { 
		"url": "/delivery-arrangements/list",
		"type": "POST",
	  },
	"columnDefs": [
    { className: "dt-body-center", "targets": [ 0,1,2,3,4,5, 6 ] },
    
  ],
	"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('#delivery-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();
	} );
	$("#delivery-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();
	});
	

}
function loadData2() {
	var oTable = $('#orderSelection').DataTable( {
	
	"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"
            },
	
	"lengthMenu": [ [10, 25, 50,100,99999999], [10, 25, 50,100, "All"] ],
	"order": [
		[ 0, 'asc' ]
	],
	
	});
	
	var tableWrapper = jQuery('#orderSelection_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();
	} );
	$("#orderSelection_filter").addClass("pull-right"); 
	$('.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();
	} );
	
	$('#orderSelection_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();
	ComponentsDateTimePickers.init();
	
	$("#delivery_type").change(function() {
		var delivery_type = $("#delivery_type").val();
		if(delivery_type == ""){
			$('#own_transport').css('display', 'none');
			$('#courier').css('display', 'none');
			$('#self_collect').css('display', 'none');  
		}else if(delivery_type == "1"){
			$('#own_transport').css('display', '');
			$('#courier').css('display', 'none');
			$('#self_collect').css('display', 'none');
		}else if(delivery_type == "2"){
			$('#own_transport').css('display', 'none');
			$('#courier').css('display', '');
			$('#self_collect').css('display', 'none');
		}else if(delivery_type == "3"){
			$('#own_transport').css('display', '');
			$('#courier').css('display', 'none');
			$('#self_collect').css('display', 'none');			
		}else if(delivery_type == "4"){			
			$('#own_transport').css('display', 'none');
			$('#courier').css('display', 'none');
			$('#self_collect').css('display', '');
		}
	});
	$("#warehouse_id").change(function() {
		var warehouse_id = $("#warehouse_id").val();
		if (warehouse_id == ""){
			$("#warehouse_name").val("");
			$("#warehouse_address").val("");
			$("#warehouse_city").val("");
			$("#warehouse_zip").val("");
			$("#warehouse_state").val("");
			$("#warehouse_country").val("");
			$("#warehouse_contact_person").val("");
			$("#warehouse_contact_person_no").val("");
		}else{
			var dataStringg = 'warehouse_id='+warehouse_id;
			$.ajax({
				type: "POST",
				url: "/delivery-arrangements/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);					
				}
			});
		}
	});
	
		$.ajax({
			type: "POST",
			url: "/delivery-arrangements/getOrderSelection",
			success: function(data) {
				$("#tbody").html(data);
				loadData2();
			}
		});
});