<script>
<?php if($page_name=='documents_view'){?>

  $("#table_filter_user,#table_filter_user_2").select2({
    placeholder: "Select  User"
  })
  $("#table_filter_work,#table_filter_work_2").select2({
    placeholder: "Select  Work",
    templateResult: format_project_dropdown
  })

  function GetSearchUser(){
    return $('#table_filter_user').val();
  }
  function GetSearchwork(){
    return $('#table_filter_work').val();
  }
  function GetSearchUser2(){
    return $('#table_filter_user_2').val();
  }
  function GetSearchwork2(){
    return $('#table_filter_work_2').val();
  }
  function GetSearchDate(){
    return $('#table_filter_date_range').val();
  }

  <?php } ?>
  var documents_view_table = $('#documents_view_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'documents/select_documents' ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        <?php if($page_name=='documents_view'){?>
          // d.date = GetSearchDate();
          d.user = GetSearchUser2();
          d.work = GetSearchwork2();

          <?php }elseif($page_name=='work_profile' || $page_name=='projects_profile'){ ?>
            d.work =   "<?php echo $work_data->work_id?>";
            <?php }elseif($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
                d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
                <?php } ?>

          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        "scrollX" : true,
        buttons: [
          { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'List of Project Documents' },
          { extend: 'csv', className: 'btn purple btn-outline ' },
          { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
        ],
        dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
        "lengthMenu": [
          [25, 50, 100, -1],
          [25, 50, 100, "All"] // change per page values here
        ],
        "columnDefs": [
          {
            "targets": [ 9,10,11,12<?php if($this->session->userdata('user_role')=='auditor'){ echo ",8"; }?>],
            className: "hidden"
          }
        ],
        'order': false
      });
      var document_revisions_view_table = $('#document_revisions_view_table').DataTable({
        "ajax":{
          url :"<?php echo base_url().'documents/select_document_revisions' ?>", // json datasource
          type: "post", // type of method  , by default would be get
          data: function(d){
            <?php if($page_name=='documents_view'){?>
              // d.date = GetSearchDate();
              d.user = GetSearchUser();
              d.work = GetSearchwork();

              <?php }elseif($page_name=='work_profile' || $page_name=='projects_profile'){ ?>
                d.work =   "<?php echo $work_data->work_id?>";
                <?php }elseif($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
                    d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
                    <?php } ?>

              }
            },
            "bProcessing": true,
            "deferRender": true,
            "bDeferRender": true,
            "scrollX" : true,
            buttons: [
              { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Document Revisions' },
              { extend: 'csv', className: 'btn purple btn-outline ' },
              { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
            ],
            dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
            "lengthMenu": [
              [25, 50, 100, -1],
              [25, 50, 100, "All"] // change per page values here
            ],
            "columnDefs": [
              {
                "targets": [ 12,13<?php if($this->session->userdata('user_role')=='auditor'){ echo ",11"; }?>],
                className: "hidden"
              }
            ],
            'order': false
          });
          $(".table_filter").on("change", function() {
            documents_view_table.ajax.reload();
            document_revisions_view_table.ajax.reload();
          });
          $(".hide_column").hide();
          <?php if($page_name=='documents_view'){?>
            // Date Range Picker
            var start = moment();
            var end = moment();

            function cb(start, end) {
              $('#table_filter_date_range').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
              documents_view_table.ajax.reload();
            }

            $('#table_filter_date_range').daterangepicker({
              buttonClasses: "m-btn btn",
              applyClass: "btn-primary",
              cancelClass: "btn-secondary",
              startDate: start,
              endDate: end,
              locale: {
                format: 'MMMM D, YYYY'
              },
              ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                'All time': [moment('1970-01-01'), moment().add(9999, 'days')],
              }
            }, cb);

            cb(start, end);

            $(".form_submit_btn").click(function (e) {
              e.preventDefault();
              var a = $(this),
              l = $(this).closest("form"),
              action = l.attr('action');
              var form_id = l.attr('id');
              l.validate({
                rules: {

                }, invalidHandler: function (e, r) {
                  var i = $("#" + form_id + "_msg");
                  i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
                }, submitHandler: function (e) {
                }
              }), l.valid() && (a.addClass("m-loader m-loader--right m-loader--light").attr("disabled", !0),
              l.ajaxSubmit({
                url: action,
                success: function (e, t, r, s) {
                  var modal_id = l.attr('data-modal-id');
                  var form_type = l.attr('data-form-type');
                  $("#" + form_id + "_msg").addClass("m--hide");
                  // Block UI
                  mApp.blockPage({
                    overlayColor: "#000000",
                    type: "loader",
                    state: "success",
                    message: "Please wait..."
                  }), setTimeout(function () {
                    mApp.unblockPage()
                  }, 2e3);
                  var obj = $.parseJSON(e);
                  if (obj.status == 1) {
                    a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                    toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                    $("#"+modal_id).modal('toggle');
                    $("."+form_id+"_fields").val('');
                    $("."+form_id+"_select").val('').trigger("change");
                    documents_view_table.ajax.reload();
                    document_revisions_view_table.ajax.reload();
                    select_documents();
                  } else {
                    a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                    toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                  }
                  if (obj == null) {
                    setTimeout(function () {
                      a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                      toastr["warning"]("Your Attempt is Timed Out. Please Try Again.", "Timed Out");
                    }, 2e4)
                  }
                },error: function() {
                  a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                  toastr["error"]("Sorry. There Has Been Some Error Occurred. Please Try Again.", "Error");
                }
              })
            )
          });
          <?php } ?>
          $("[data-switch=true]").bootstrapSwitch()

          $("#revision_send_date_add,#revision_send_date_edit").datepicker( {
            todayHighlight:!0, orientation:"bottom left", templates: {
              leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
            }
          })
          $('body').on('click', '#document_edit_btn', function() {
            var no = $(this).closest('tr').children('td');
            $('#title_edit').val(no.eq(3).text());
            $('#description_edit').val(no.eq(4).text());
            $('#document_id_edit').val(no.eq(9).text());
            $('#work_id_edit').val(no.eq(10).text()).trigger('change');
            if(no.eq(11).text()==1){
              $('#drive_link_edit_div').show();
              $('#drive_link_edit').val(no.eq(12).text());
              $('#drive_link_edit').attr('required','required');
            }
          });
          $('body').on('click', '#document_delete_btn', function() {
            var no = $(this).closest('tr').children('td');
            $('#document_id_delete').val(no.eq(9).text());
          })
          $('body').on('click', '#document_revision_edit_btn', function() {
            var no = $(this).closest('tr').children('td');
            $('#revision_id_edit').val(no.eq(0).text());
            $('#document_id_revision_edit').val(no.eq(12).text());
            $('#document_name_revision_edit').val(no.eq(1).text());
            $('#revision_no_edit').val(no.eq(5).text());
            $('#revision_send_date_edit').datepicker("setDate", no.eq(6).text());
            $('#revision_remarks_edit').val(no.eq(8).text());
            var status = no.eq(13).text();
            $("input[name=revision_status_edit][value=" + status + "]").prop('checked', true);
            $('#revision_feedback_edit').val(no.eq(7).text());
          });
          $('#document_add_modal').on('hidden.bs.modal', function () {
            $(this).find('form').trigger('reset');
          })
          function select_documents(){
            $('#document_revision_add').html('');
            $("#document_revision_add").append("<option disabled selected >Select Document</option>");
            var work_id='';
            <?php if($page_name=='work_profile' || $page_name=='projects_profile'){ ?>
              work_id = "<?php echo $work_data->work_id?>";
              <?php } ?>
            $.post("<?php echo base_url() ?>documents/select",{work:work_id},function(data) {
              var obj = $.parseJSON(data);
              var i=0;
              if(obj.count>0) {
                while (i < obj.data.length) {
                  $("#document_revision_add").append("<option value=" + obj.data[i]['id'] + ">#" + obj.data[i]['id'] + " - "+obj.data[i]['title']+" [" + obj.data[i]['work_name'] + "][" + obj.data[i]['description'] + "]</option>");
                  i++;
                }
              }
            })
          }
          select_documents();
          $("#work_id").select2({
            placeholder: "Select Work",
            dropdownParent: $("#form_document_add"),
            templateResult: format_project_dropdown
          })
          $("#work_id_edit").select2({
            placeholder: "Select Work",
            dropdownParent: $("#form_document_edit"),
            templateResult: format_project_dropdown
          })
          $("#document_revision_add").select2({
            placeholder: "Select Document",
            dropdownParent: $("#form_document_revision_add")
          })
          </script>
