var table;
$(document).ready(function(){
  table = $("#businessTable").DataTable({
    "paging":   true,
    "scrollX": true,
    "scrollY": false,
    "processing": true, 
    "serverSide": true, 
    "pageLength": 20,
    "order": [],
    "ajax": {
      "url": CI_ROOT+'business/getBusiness',
      "type": "POST",
      "data": function(data){
        data.sortby = $('#sortby').val();
        data.sortorder = $('#sortorder').val();
      }
    },
    "columnDefs": [
      { 
        "targets": [0,1,2,3,4,5,6,7],
        "orderable": false
      },
      {"targets":[0,1],"width":80},
      {"targets":[2],"width":250},
      {"targets":[3],"width":250},
      {"targets":[4],"width":150},
      {"targets":[5],"width":150},
      {"targets":[6],"width":60},
      {"targets":[7,8],"width":120}
    ],
    dom: 'Bfrtip',
    buttons: []
  });
  
  $("#add_business").on("submit", function(e){
    e.preventDefault();
    $(".error").html("");
    $(".error").css("display", "none");

    var t = new FormData(this);
    $.ajax({
      type: "POST",
      data: t,
      url: CI_ROOT + "business/addBusinessAction",
      mimeType: "multipart/form-data",
      contentType: !1,
      processData: !1,
      dataType: "json",
      beforeSend: function(){
        $(".preloader").fadeIn();
      },
      success: function(result) {
      	$(".preloader").fadeOut();
      	
        if(result.status == "success"){
          window.location.href = CI_ROOT + "business/list";
        }else{
          $.each(result, function(e, t) {
            $("label[for='" + e + "']").html(t)
          });
          var t = Object.keys(result);
          $(".error").css("display", "block");
          $('input[name="' + t[0] + '"]').focus();
        }
      }
    })
  });
  
  $("#update_business").on("submit", function(e){
    e.preventDefault();
    $(".error").html("");
    $(".error").css("display", "none");

    var t = new FormData(this);
    $.ajax({
      type: "POST",
      data: t,
      url: CI_ROOT + "business/updateBusinessAction",
      mimeType: "multipart/form-data",
      contentType: !1,
      processData: !1,
      dataType: "json",
      beforeSend: function(){
        $(".preloader").fadeIn();
      },
      success: function(result) {
      	$(".preloader").fadeOut();
        if(result.status == "success"){
          window.location.href = CI_ROOT + "business/list";
        }else{
          $.each(result, function(e, t) {
            $("label[for='" + e + "']").html(t)
          });
          var t = Object.keys(result);
          $(".error").css("display", "block");
          $('input[name="' + t[0] + '"]').focus();
        }
      }
    })
  });

  $('#btn-filter').click(function(e){ 
    e.preventDefault();
    table.ajax.reload(); 
  });

  $('#btn-reset').click(function(e){ 
    e.preventDefault();
    $('#form-filter')[0].reset();
    table.ajax.reload(); 
  });
});