/**
 * Loan Customer Object
 */
 var loanCustomer = {
	/**
	 * Init function
	 * @return void
	 */
    init: function () {
      var lc = this;
      lc.loadActiveTab();
      lc.changeTab();
      lc.updateCustomer();
      lc.updateCompany();
      lc.updateGarantor();
      lc.showInstallmentForm();
      lc.newInstallment();
      lc.deleteInstallment();
  },

  deleteInstallment: function () {
    var lc = this;
    $(document).on('click', '.btn-delete-installment', function (e) {
        e.preventDefault();
        var me = $(this);
        var url = me.attr('href');
            swal({
              title: me.data('msg'),
              type: "warning",
              showCancelButton: true,
              confirmButtonText: me.data('yes'),
              cancelButtonText: me.data('no'),
              closeOnConfirm: false
            },
            function(){
              $.ajax({
                url: url,
                type: "DELETE",
                success: function (data) {
                    if (data.error) {
                        swal("", data.message, "error")
                        console.log(data);
                    } else {
                        console.log(data);
                        swal("", data.message, "success")
                        lc.loadActiveTab()
                    }
                }
              });
            });             
    });
  },

  loadActiveTab: function () {
      var lc = this;
		// load first tab content
        var a = $(".active a");
        var url = a.attr('data-url');
        var content = a.attr('href');
        console.log(url);
        $.ajax({
          type: "GET",
          url: url,
          success: function (data) {
            $(content).html(data);
            $(".preview_snapshot").hide();
            $(".cancel_preview").hide();
            $('#dob, #date_of_stay, #hired_date').datepicker({
               format: "dd/mm/yyyy",
               todayHighlight: true
           });
            lc.addSelect2();
            $(".spinner").hide();
        },
        beforeSend: function () {
            $(".spinner").show();
        }
    });
    },
    updateCustomer: function () {
      var lc = this;
      $(document).on('submit', '#form-update-customer', function (e) {
        e.preventDefault();
        var form = $(this);
        form.find('.text-danger').remove();
        form.find('.form-group').removeClass('has-error');
        var formData = new FormData(this);
        $.ajax({
          type:'POST',
          url: $(this).attr('action'),
          data:formData,
          cache:false,
          contentType: false,
          processData: false,
          success:function(data){
              if (data.error == true) {
                 sweetAlert("ជូនដំណឹង", "ការបន្ទាន់សម័យទទួលបានជោគជ័យ", "error");

             } else {
                 sweetAlert("ជូនដំណឹង", "ការបន្ទាន់សម័យទទួលបានជោគជ័យ", "success");
                 lc.loadActiveTab();
                 console.log(data);
             }

         },
         error: function(data){
          var json = data.responseJSON;
          var errors = json.errors;
          if ($.isEmptyObject(errors) == false) {
             $.each(errors, function (key, val) {
                 $("#" + key)
                 .closest('.form-group')
                 .addClass('has-error')
                 .append('<small class="text-danger">' + val +'</samll>');
             });
         }
         sweetAlert("ជូនដំណឹង", "Someting Wrong!", "error");
     }
 });
    });
  },
  changeTab: function () {
   var lc = this;
   $('#customerTab a').click(function (e) {
     e.preventDefault();
     var url = $(this).attr("data-url");
     var href = this.hash;
     var pane = $(this);
     var content = pane.attr('href');
     $.ajax({
       type: "GET",
       url: url,
       success: function (data) {
         $(content).html(data);
         $(".preview_snapshot").hide();
         $(".cancel_preview").hide();
         $('#dob, #date_of_stay, #hired_date', '#in_date').datepicker({
             format: "dd/mm/yyyy",
             todayHighlight: true
         });
         lc.addSelect2();
         $(".spinner").hide();
         $(".spinner").hide();
     },
     beforeSend: function () {
         $(".spinner").show();
     }
 });
 });
},
addSelect2: function () {
   $("#gender, #marital_status, #nationality, #property, #live_with , #day_of_salary, #company_type, #position, #job_condition").select2();
},

updateCompany: function () {
  var lc = this;
  $(document).on('submit','#form-update-company', function (e) {
    e.preventDefault();
    var form = $(this);
    form.find('.text-danger').remove();
    form.find('.form-group').removeClass('has-error');
    $.ajax({
      type:'PUT',
      url: $(this).attr('action'),
      data: form.serialize(),
      success:function(data){
          if (data.error == true) {
             sweetAlert("ជូនដំណឹង", data.message, "error");

         } else {
             sweetAlert("ជូនដំណឹង", data.message, "success");
             console.log(data);
         }

     },
     error: function(data){
      var json = data.responseJSON;
      var errors = json.errors;
      if ($.isEmptyObject(errors) == false) {
        $.each(errors, function (key, val) {
            $("#" + key)
            .closest('.form-group')
            .addClass('has-error')
            .append('<small class="text-danger">' + val +'</samll>');
        });
    }
    sweetAlert("ជូនដំណឹង", "Someting Wrong!", "error");
}
});
});
},
updateGarantor: function () {
  var lc = this;
  $(document).on('submit','#form-update-garantor', function (e) {
    e.preventDefault();
    var form = $(this);
    form.find('.text-danger').remove();
    form.find('.form-group').removeClass('has-error');
    $.ajax({
      type:'PUT',
      url: $(this).attr('action'),
      data: form.serialize(),
      success:function(data){
          if (data.error == true) {
             sweetAlert("ជូនដំណឹង", data.message, "error");

         } else {
             sweetAlert("ជូនដំណឹង", data.message, "success");
             console.log(data);
         }
     },
     error: function(data){
      var json = data.responseJSON;
      var errors = json.errors;
      if ($.isEmptyObject(errors) == false) {
        $.each(errors, function (key, val) {
            $("#" + key)
            .closest('.form-group')
            .addClass('has-error')
            .append('<small class="text-danger">' + val +'</samll>');
        });
    }
    sweetAlert("ជូនដំណឹង", "Someting Wrong!", "error");
}
});
});
},
showInstallmentForm: function () {
   $("body").on("click", ".btn-show-installment-modal", function (e) {
      e.preventDefault();
      var btn = $(this).data("type");
      var url = $(this).attr('href');
      var title = $(this).data("title");
      $(".spinner").show();
      $.ajax({
          url: url,
          dataType: "html",
          success: function (data) {
              $("#form-installment-body").html(data);
              if (btn == "add") {
                $('#in_date').datepicker({
                    format: "dd/mm/yyyy",
                    todayHighlight: true,
                    autoclose: true
                }).datepicker("setDate", "0");
            } else {
                $('#in_date').datepicker({
                    format: "dd/mm/yyyy",
                    todayHighlight: true,
                    autoclose: true
                });
            }
            if (title) {
              var icon = '<i class="fa fa-calculator"></i>';
              $("#installment-modal-title").html(icon + " " +title);
            }
            $(".spinner").hide();
            $('#installmentModal').modal({backdrop: 'static', keyboard: false}).show();
            $("#installmentModal").on('shown.bs.modal', function () {
            $("#type_of_product").focus();
          });
        }
    });
  });
},
newInstallment: function () {
   var lc = this;
   $(".btn-installment-save").on('click' , function (e) {
      e.preventDefault();
      var form = $("#form-installment-body form"),
      url  = form.attr('action');
      method = $('#form-installment-body input[name=_method]').val() == undefined ? "POST" : "PUT";
      form.find('.text-danger').remove();
      form.find('.form-group').removeClass('has-error');
      var customerId = $("#customerTab").data('id');
      var data = form.serialize();
      data = data.concat("&customer_id=" + customerId);
      console.log(data);
      $.ajax({
          url: url,
          type: "POST",
          data: data,
          success: function (data) {
            console.log(data);
            if (data.error) {
             toastr.error(data.message);
         } else {  
             lc.loadActiveTab();  
             $("#installmentModal").modal('hide');
             sweetAlert("ជូនដំណឹង", data.message, "success");
         }
     }, 
     error: function (data) {
        var json = data.responseJSON;
        var errors = json.errors;
        if ($.isEmptyObject(errors) == false) {
          $.each(errors, function (key, val) {
              $("#" + key)
              .closest('.form-group')
              .addClass('has-error')
              .append('<small class="text-danger">' + val +'</samll>');
          });
      }
  }
});
  });
}
};