$(document).ready(function () {
  var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
      sURLVariables = sPageURL.split("&"),
      sParameterName,
      i;

    for (i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split("=");

      if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined
          ? ""
          : decodeURIComponent(sParameterName[1]);
      }
    }
  };
  $('[data-toggle="switch"]').bootstrapSwitch();
  bsCustomFileInput.init();
  var sticky = new Sticky("#addimport");

  $(".widgeteditor").summernote({
    height: 500,
  });

  $(".select2").select2({
    theme: "bootstrap4",
  });

  $("#sidebar-card").html(
    '<div class="sidebar-card"><p class="text-center mb-2">Designed & Developed By <strong>Pratik Dev</strong></p><a class="btn btn-success btn-sm" href="http://facebook.com/pratikbarman.mtb" target="_blank">Follow Me!</a></div>'
  );

  $("#notiform").ready(function () {
    $("#artist").select2({
      theme: "bootstrap4",
      ajax: {
        url: "process.php",
        data: function (params) {
          var query = {
            search: params.term,
            submit: "artistlist",
          };
          // Query parameters will be ?search=[term]&type=public
          return query;
        },
      },
    });

    $("#category").select2({
      theme: "bootstrap4",
      ajax: {
        url: "process.php",
        data: function (params) {
          var query = {
            search: params.term,
            submit: "catlist",
          };
          // Query parameters will be ?search=[term]&type=public
          return query;
        },
      },
    });

    $("#files").select2({
      theme: "bootstrap4",
      ajax: {
        url: "process.php",
        data: function (params) {
          var query = {
            search: params.term,
            submit: "files",
          };
          // Query parameters will be ?search=[term]&type=public
          return query;
        },
      },
    });
  });

  $(".htmleditor").summernote({
    placeholder: "Description",
    tabsize: 2,
    height: 200,
    toolbar: [
      ["color", ["color"]],
      ["para", ["ul", "ol", "paragraph"]],
      ["insert", ["link"]],
      ["view", ["codeview", "help"]],
    ],
  });

  $(document).on("submit", "#profileform", function (event) {
    event.preventDefault();
    var formData = $(this).serialize();
    $("#submitbutton").attr("disabled", "disabled");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: formData,
      success: function (data) {
        $("#submitbutton").removeAttr("disabled");
        if (data.status == 1) {
          swal("Success!", data.message, "success");
          window.location.reload();
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $(document).on("click", "#sitemapgen", function (event) {
    event.preventDefault();
    $("#sitemapgen").attr("disabled", "disabled");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: {
        submit: "genarateSitemap",
      },
      success: function (data) {
        $("#sitemapgen").removeAttr("disabled");
        if (data.status == 1) {
          swal("Success!", data.message, "success");
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $(document).on("submit", "#settingform", function (event) {
    event.preventDefault();
    var settingform = new FormData($("#settingform")[0]);
    $("#submit").attr("disabled", "disabled");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: settingform,
      contentType: false,
      processData: false,
      success: function (data) {
        $("#submit").removeAttr("disabled");
        if (data.status == 1) {
          swal("Success!", data.message, "success");
          swal(
            {
              title: "Success",
              text: "Successfuly Updated",
              type: "success",
            },
            function () {
              window.location.replace("../index.php");
            }
          );
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $(".tagsinput").tagsInput({
    autocomplete_url: "process.php?submit=tagsartist",
    defaultText: "",
    height: "calc(1.5em + .75rem + 2px)",
    // width: "350px",
  });

  $("#file").change(function () {
    var filename = $(this)[0].files[0].name;
    var newfilename = filename.replace(/\.php|\.js/i, "");
    $("#filename").val(newfilename);
    SlugCheck();
  });

  $("#url").blur(function () {
    var rename = $(this)
      .val()
      .replace(/\.php|\.js/i, "");
    var rename1 = rename.split("/");
    var finalname = decodeURIComponent(rename1.pop()).replace(/[+]/g, " ");
    $("#filename").val(finalname);
    SlugCheck();
  });

  var SlugCheck = function () {
    var slug = $("#category_name,#filename").val().trim();
    if (slug.length > 3) {
      if ($("#catform").attr("name") == "catform") {
        var id = $("#id").val();
      } else {
        var id = getUrlParameter("id");
      }
      $.ajax({
        url: "process.php",
        type: "POST",
        dataType: "json",
        data: {
          submit: "slugcheck",
          id: id,
          slug: slug,
        },
        success: function (res) {
          if (res.status == "1") {
            $("#slug").removeClass("is-invalid");
            $("#slug").val(res.slug);
            $("#slug").addClass("is-valid");
          } else {
            $("#slug").removeClass("is-valid");
            $("#slug").val(res.slug);
            $("#slug").addClass("is-invalid");
          }
        },
      });
    } else {
      $("#slug").removeClass("is-valid");
      $("#slug").addClass("is-invalid");
    }
  };

  $("#category_name,#filename").keyup(SlugCheck).blur(SlugCheck);

  $("#slug").blur(function (e) {
    e.preventDefault();
    if ($("#catform").attr("name") == "catform") {
      var id = $("#id").val();
    } else {
      var id = getUrlParameter("id");
    }
    var slug = $(this).val().trim();
    if (slug == "") {
      $("#slug").removeClass("is-valid");
      $("#slug").addClass("is-invalid");
      return false;
    }
    $.ajax({
      url: "process.php",
      type: "POST",
      dataType: "json",
      data: {
        submit: "slugcheck",
        slug: slug,
        id: id,
      },

      success: function (response) {
        if (response.status == "1") {
          $("#slug").removeClass("is-invalid");
          $("#slug").val(response.slug);
          $("#slug").addClass("is-valid");
        } else {
          $("#slug").removeClass("is-valid");
          $("#slug").val(response.slug);
          $("#slug").addClass("is-invalid");
        }
      },
      error: function () {
        $("#slug").removeClass("is-valid");
        $("#slug").val("");
        $("#slug").addClass("is-invalid");
      },
    });
  });

  $(document).on("submit", "#uploadform", function (e) {
    e.preventDefault();
    if ($("#slug").hasClass("is-invalid")) {
      swal("Error", "Slug exists", "warning");
      return false;
    }
    $(".alertDialog").hide();
    $(".progress-bar").css("width", "0");
    $(".progress-bar").text("0%");
    var __Action = $("#uploadform").attr("action");
    var form = $("#uploadform")[0];
    var formData = new FormData(form);
    formData.append("cid", getUrlParameter("cid"));
    $.ajax({
      url: __Action,
      data: formData,
      processData: false,
      contentType: false,
      type: "POST",
      // this part is progress bar
      beforeSend: function () {
        $("#submit").attr("disabled", "disabled");
        $("#progressbar").show();
      },
      xhr: function () {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener(
          "progress",
          function (evt) {
            if (evt.lengthComputable) {
              var percentComplete = evt.loaded / evt.total;
              percentComplete = parseInt(percentComplete * 100);
              $(".progress-bar").text(percentComplete + "%");
              $(".progress-bar").css("width", percentComplete + "%");
            }
          },
          false
        );
        return xhr;
      },
      success: function (data) {
        $("#progressbar").hide();
        $("#submit").removeAttr("disabled");
        if (data.status == 1) {
          $("#url_display").hide();
          $("#file_display").show();
          $("#thumb_url_display").hide();
          $("#thumb_file_display").show();
          $("#slug").removeClass("is-valid");
          form.reset();
          $("#description").summernote("reset");
          $(".tagsinput").importTags("");
          $(".alertDialog").text("Last File: " + data.message);
          $(".alertDialog").show();
          if (__Action == "editAction.php") {
            swal(
              {
                title: "Success",
                text: "Upload Sucessfuly",
                type: "success",
              },
              function () {
                window.location.reload();
              }
            );
          } else {
            $("li[class=breadcrumb-item] a")
              .last()
              .attr("href", "../files/index.php?cid=" + getUrlParameter("cid"));
            swal("Success", "Upload Sucessfuly", "success");
          }
        } else {
          $("#submit").removeAttr("disabled");
          swal("Error", data.message, "warning");
        }
      },
      error: function () {
        $("#submit").removeAttr("disabled");
        $("#progressbar").hide();
        swal("Error", "Internal Error", "warning");
      },
    });
  });

  $("#filefrom").change(function (e) {
    e.preventDefault();
    var type = $("#filefrom").val();
    if (type == "EXTERNAL_LINK") {
      $("#file_display").hide();
      $("#url_display").show();
    } else {
      $("#url_display").hide();
      $("#file_display").show();
    }
  });

  $("#thumbfrom").change(function (e) {
    e.preventDefault();
    var type = $("#thumbfrom").val();
    if (type == "EXTERNAL_LINK") {
      $("#thumb_file_display").hide();
      $("#thumb_url_display").show();
    } else {
      $("#thumb_url_display").hide();
      $("#thumb_file_display").show();
    }
  });

  $("#notifyfrom").change(function (e) {
    e.preventDefault();
    var type = $("#notifyfrom").val();
    if (type == "FILE") {
      $("#ex_notify").hide();
      $("#artistnotify").hide();
      $("#catnotify").hide();
      $("#filenotify").show();
    } else if (type == "CAT") {
      $("#ex_notify").hide();
      $("#artistnotify").hide();
      $("#filenotify").hide();
      $("#catnotify").show();
    } else if (type == "ARTIST") {
      $("#ex_notify").hide();
      $("#catnotify").hide();
      $("#filenotify").hide();
      $("#artistnotify").show();
    } else {
      $("#catnotify").hide();
      $("#filenotify").hide();
      $("#artistnotify").hide();
      $("#ex_notify").show();
    }
  });


  var files = $(".files").DataTable({
    responsive: true,
    dom: "Bflrtip",
    stateSave: true,
    select: {
      style: "os",
      selector: "td:nth-child(2)",
    },
    buttons: [
      {
        text: "Visiblity",
        extend: "colvis",
        className: "btn btn-success",
      },
      {
        text: "Delete",
        className: "btn btn-danger",
        action: function () {
          var ids = files.rows({ selected: true }).ids().toArray();
          var count = files.rows({ selected: true }).count();
          if (count > 0) {
            DeleteMultiple(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Deleted", "warning");
          }
        },
      },
      {
        text: "Move",
        className: "btn btn-warning",
        action: function () {
          var ids = files.rows({ selected: true }).ids().toArray();
          var count = files.rows({ selected: true }).count();
          if (count > 0) {
            MoveFiles(ids, count);
          } else {
            swal("Error", "You Have no Item Selected for Moving", "warning");
          }
        },
      },
      {
        extend: "selectAll",
        className: "btn btn-dark",
      },
      {
        extend: "selectNone",
        className: "btn btn-light",
      },
    ],
    lengthChange: true,
    lengthMenu: [
      [10, 25, 50, -1],
      [10, 25, 50, "All"],
    ],
    processing: true,
    serverSide: true,
    order: [],
    ajax: {
      url: "process.php",
      type: "POST",
      data: function (d) {
        d.parentid = getUrlParameter("cid");
        d.filterdata = $("#fileTable").attr('data-filter');
        d.userid = getUrlParameter("userid");
        d.submit = "list";
      },
      dataType: "json",
    },
    columnDefs: [
      {
        targets: [1, 3, 4, 5, 6, 7, 12, 13],
        orderable: false,
      },
      { width: 60, targets: 1 },
      { responsivePriority: 1, targets: 0 },
      { responsivePriority: 2, targets: 2 },
      { responsivePriority: 3, targets: 1 },
      { responsivePriority: 4, targets: 3 },
    ],
    rowId: function (a) {
      return a[0];
    },
    pageLength: 10,
  });

  var categories = $(".catlist").DataTable({
    responsive: true,
    dom: "Bflrtip",
    stateSave: true,
    select: {
      style: "os",
      selector: "td:nth-child(2)",
    },
    buttons: [
      {
        text: "Visiblity",
        extend: "colvis",
        className: "btn btn-success",
      },
      {
        text: "Delete",
        className: "btn btn-danger",
        action: function () {
          var ids = categories.rows({ selected: true }).ids().toArray();
          var count = categories.rows({ selected: true }).count();
          if (count > 0) {
            DeleteMultiple(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Deleted", "warning");
          }
        },
      },
      {
        text: "Move",
        className: "btn btn-warning",
        action: function () {
          var ids = categories.rows({ selected: true }).ids().toArray();
          var count = categories.rows({ selected: true }).count();
          if (count > 0) {
            MoveFiles(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Moving", "warning");
          }
        },
      },
      {
        extend: "selectAll",
        className: "btn btn-light",
      },
      {
        extend: "selectNone",
        className: "btn btn-light",
      },
    ],
    lengthChange: true,
    lengthMenu: [
      [10, 25, 50, -1],
      [10, 25, 50, "All"],
    ],
    processing: true,
    serverSide: true,
    order: [],
    ajax: {
      url: "process.php",
      type: "POST",
      data: {
        parentid: getUrlParameter("parentid"),
        submit: "list",
      },
      dataType: "json",
    },
    columnDefs: [
      {
        targets: [1, 3, 4, 5, 6],
        orderable: false,
      },
      { width: 60, targets: 1 },
    ],

    rowId: function (a) {
      return a[0];
    },
    pageLength: 10,
  });

  var artist = $(".artist").DataTable({
    responsive: true,
    dom: "Bflrtip",
    select: {
      style: "os",
      selector: "td:nth-child(2)",
    },
    buttons: [
      "selectAll",
      "selectNone",
      {
        text: "Delete",
        className: "btn btn-danger",
        action: function () {
          var ids = artist.rows({ selected: true }).ids().toArray();
          var count = artist.rows({ selected: true }).count();
          if (count > 0) {
            DeleteMultiple(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Deleted", "warning");
          }
        },
      },
    ],
    lengthChange: true,
    lengthMenu: [
      [10, 25, 50, -1],
      [10, 25, 50, "All"],
    ],
    processing: true,
    serverSide: true,
    order: [],
    ajax: {
      url: "process.php",
      type: "POST",
      data: {
        submit: "list",
      },
      dataType: "json",
    },
    columnDefs: [
      {
        targets: [1, 3, 4],
        orderable: false,
      },
      { width: 60, targets: 1 },
    ],
    rowId: function (a) {
      return a[0];
    },
    pageLength: 10,
  });

  $("#add_artist").click(function (e) {
    e.preventDefault();
    $("#artistform")[0].reset();
    $("#id").val("");
    $("#action").val("create");
    $("#mlabel").html("<i class='fas fa-user-plus'></i> Add Artist");
    $("#thumbnail").hide();
    $("#modalform").modal("show");
  });

  $(".artist").on("click", ".edit", function (e) {
    e.preventDefault();
    var id = $(this).attr("id");
    var action = "getOne";
    $("#mlabel").html("<i class='fa fa-user-edit'></i> Edit Artist");
    $("#thumbnail").hide();
    $("#artistform")[0].reset();
    $("#action").val("edit");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: {
        id: id,
        submit: action,
      },
      dataType: "json",
      success: function (data) {
        $("#name").val(data.name);
        $("#id").val(data.id);
        $("#meta_title").val(data.meta_title);
        $("#meta_keyw").val(data.meta_keyw);
        $("#meta_des").val(data.meta_des);
        if (data.added_home == "1") {
          if ($("#added_home").prop("checked") == false) {
            $("#added_home").trigger("click");
          }
        }
        if (data.status == "1") {
          if ($("#status").prop("checked") == false) {
            $("#status").trigger("click");
          }
        }
        if (data.thumb != "") {
          $("#thumbnail").show();
          $("#thumb").attr("src", data.thumb);
        }
        $("#modalform").modal("show");
      },
    });
  });




  $(document).on("submit", "#artistform", function (event) {
    event.preventDefault();
    if ($("#name").val() == "") {
      swal("Error", "Please Fill Artist Name", "warning");
      return false;
    }
    $("#submit").attr("disabled", "disabled");
    var formcat = $("#artistform")[0];
    var formData = new FormData(formcat);
    $.ajax({
      url: "process.php",
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {
        $("#submit").attr("disabled", false);
        if (data.status == 1) {
          $("#thumb_url_display").hide();
          $("#thumb_file_display").show();
          $("#artistform")[0].reset();
          $("#modalform").modal("hide");
          $("#submit").attr("disabled", false);
          artist.draw(false);
          swal("Success!", data.message, "success");
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  var users = $(".users").DataTable({
    dom: "Bflrtip",
    select: {
      style: "os",
      selector: "td:nth-child(2)",
    },
    buttons: [
      "selectAll",
      "selectNone",
      {
        text: "Delete",
        className: "btn btn-danger",
        action: function () {
          var ids = users.rows({ selected: true }).ids().toArray();
          var count = users.rows({ selected: true }).count();
          if (count > 0) {
            DeleteMultiple(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Deleted", "warning");
          }
        },
      },
    ],
    lengthChange: true,
    processing: true,
    serverSide: true,
    order: [],
    ajax: {
      url: "process.php",
      type: "POST",
      data: {
        submit: "list",
      },
      dataType: "json",
    },
    columnDefs: [
      {
        targets: [3, 4, 7, 8],
        orderable: false,
      },
    ],
    rowId: function (a) {
      return a[0];
    },
    pageLength: 10,
  });

  var reports = $(".reports").DataTable({
    dom: "Bflrtip",
    select: {
      style: "os",
      selector: "td:nth-child(2)",
    },
    lengthChange: true,
    processing: true,
    serverSide: true,
    buttons: [
      "selectAll",
      "selectNone",
      {
        text: "Delete",
        className: "btn btn-danger",
        action: function () {
          var ids = reports.rows({ selected: true }).ids().toArray();
          var count = reports.rows({ selected: true }).count();
          if (count > 0) {
            DeleteMultiple(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Deleted", "warning");
          }
        },
      },
    ],
    order: [],
    ajax: {
      url: "process.php",
      type: "POST",
      data: {
        submit: "list",
      },
      dataType: "json",
    },
    columnDefs: [
      {
        targets: [2, 3, -1],
        orderable: false,
      },
    ],
    rowId: function (a) {
      return a[0];
    },
    pageLength: 10,
  });

  $(document).on("submit", "#userform", function (event) {
    event.preventDefault();
    $("#submit").attr("disabled", "disabled");
    var formData = new FormData($("#userform")[0]);
    $.ajax({
      url: "process.php",
      method: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {
        $("#submit").attr("disabled", false);
        if (data.status == 1) {
          $("#userform")[0].reset();
          $("#modalform").modal("hide");
          users.ajax.reload();
          swal("Success!", data.message, "success");
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $(".users").on("click", ".edit", function (e) {
    e.preventDefault();
    var id = $(this).attr("id");
    var action = "getOne";
    $("#modal-title").html("<i class='fa fa-plus'></i> Edit User");
    $.ajax({
      url: "process.php",
      method: "POST",
      data: {
        id: id,
        submit: action,
      },
      dataType: "json",
      success: function (data) {
        $("#userform")[0].reset();
        $("#id").val(data.id);
        $("#username").val(data.user_name);
        $("#name").val(data.name);
        $("#email").val(data.email);
        $("#phone").val(data.mobile);
        $("#status").val(data.status);
        $("#action").val("edit");
        $("#modalform").modal("show");
      },
    });
  });


  $(document).on("submit", "#notiform", function (event) {
    event.preventDefault();
    $("#submit").attr("disabled", "disabled");
    var formcat = $("#notiform")[0];
    var formData = new FormData(formcat);
    $.ajax({
      url: "process.php",
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {
        $("#submit").attr("disabled", false);
        if (data.status == 1) {
          $("#thumb_url_display").hide();
          $("#thumb_file_display").show();
          swal(
            {
              title: "Successfuly",
              text: data.message,
              type: "success",
            },
            function () {
              window.location.reload();
            }
          );
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $("#create_type").change(function (e) {
    e.preventDefault();
    var type = $("#create_type").val();
    var ctype = $("#action").val();
    if (type == 1) {
      $("#description_display").hide();
      $("#release_display").hide();
      if (ctype == "create") {
        $("#ModalLabel").html("<i class='fa fa-plus'></i> Add Category");
        $("#catLabel").text("Category Name");
      } else {
        $("#ModalLabel").html("<i class='fas fa-edit'></i> Edit Category");
        $("#catLabel").text("Category Name");
      }
    } else {
      if (ctype == "create") {
        $("#ModalLabel").html("<i class='fa fa-plus'></i> Add Album/Movie");
        $("#catLabel").text("Category Name");
      } else {
        $("#ModalLabel").html("<i class='fas fa-edit'></i> Edit Album/Movie");
        $("#catLabel").text("Category Name");
      }
      $("#description_display").show();
      $("#release_display").show();
    }
  });

  $(document).on("click", ".addcatTo", function (e) {
    e.preventDefault();
    var id = $(this).attr("id");
    var cname = $(this).data("name");
    $("#catform")[0].reset();
    $("#parentid").val(id);
    $("#id").val("");
    $("#ModalLabel").html(
      "<i class='fas fa-folder-plus'></i> Add Category to " + cname
    );
    $("#thumbnail").hide();
    $("#category_des").summernote("reset");
    $("#description_display").hide();
    $("#release_display").hide();
    $("#action").val("create");
    $("#ModalCategory").modal("show");
  });

  $(document).on("click", ".addAlbumTo", function (e) {
    e.preventDefault();
    var id = $(this).attr("id");
    var cname = $(this).data("name");
    $("#catform")[0].reset();
    $("#parentid").val(id);
    $("#id").val("");
    $("#ModalLabel").html(
      "<i class='fas fa-film'></i> Add Album/Movie to " + cname
    );
    $("#thumbnail").hide();
    $("#category_des").summernote("reset");
    $("#description_display").show();
    $("#release_display").show();
    $("#action").val("create");
    $("#ModalCategory").modal("show");
  });

  $(document).on("click", "#addCat", function (e) {
    e.preventDefault();
    let id = getUrlParameter("parentid");
    $("#catform")[0].reset();
    $("#parentid").val(id);
    $("#id").val("");
    $("#create_type").val("1");
    $("#ModalLabel").html("<i class='fas fa-folder-plus'></i> Add Category");
    $("#catLabel").text("Category Name");
    $("#thumbnail").hide();
    $("#category_des").summernote("reset");
    $("#action").val("create");
    $("#description_display").hide();
    $("#release_display").hide();
    $("#ModalCategory").modal("show");
  });

  $(document).on("click", "#addAlbum", function (e) {
    let id = getUrlParameter("parentid");
    $("#catform")[0].reset();
    $("#parentid").val(id);
    $("#id").val("");
    $("#create_type").val("");
    $("#ModalLabel").html("<i class='fas fa-film'></i> Add Album/Movie");
    $("#catLabel").text("Album/Movie Name");
    $("#thumbnail").hide();
    $("#category_des").summernote("reset");
    $("#description_display").show();
    $("#release_display").show();
    $("#action").val("create");
    $("#ModalCategory").modal("show");
  });

  $(document).on("submit", "#catform", function (event) {
    event.preventDefault();
    if ($("#category_name").val() == "") {
      swal("Error", "Please Fill Category Name", "warning");
      return false;
    }

    if ($("#slug").hasClass("is-invalid")) {
      swal("Error", "Slug exists", "warning");
      return false;
    }
    $("#submit").attr("disabled", "disabled");
    var formcat = $("#catform")[0];
    var formData = new FormData(formcat);
    $.ajax({
      url: "process.php",
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {
        $("#submit").attr("disabled", false);
        if (data.status == 1) {
          $("#thumb_url_display").hide();
          $("#thumb_file_display").show();
          $("#slug").removeClass("is-valid");
          $("#catform")[0].reset();
          $("#category_des").summernote("reset");
          $("#ModalCategory").modal("hide");
          $("#submit").attr("disabled", false);
          categories.draw(false);
          swal("Success!", data.message, "success");
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $("body").on("click", ".removethumb", function (e) {
    e.preventDefault();
    var id = $("#id").val();
    $.ajax({
      url: "process.php",
      type: "POST",
      data: {
        id: id,
        submit: "removethumb",
      },
      dataType: "json",
      success: function (data) {
        $("#thumbnail").hide();
      },
    });
  });

  $(".catlist").on("click", ".edit", function (e) {
    e.preventDefault();
    var id = $(this).attr("id");
    var action = "getOne";
    $("#thumbnail").hide();
    $("#catform")[0].reset();
    $("#category_des").summernote("reset");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: {
        id: id,
        submit: action,
      },
      dataType: "json",
      success: function (data) {
        if (data.is_cat == "1") {
          $("#create_type").val("1");
          $("#ModalLabel").html("<i class='fas fa-edit'></i> Edit Category");
          $("#catLabel").text("Category Name");
          $("#description_display").hide();
          $("#release_display").hide();
        } else {
          $("#create_type").val("");
          $("#ModalLabel").html("<i class='fas fa-edit'></i> Edit Album/Movie");
          $("#catLabel").text("Album/Movie Name");
          $("#description_display").show();
          $("#release_display").show();
        }
        $("#category_name").val(data.name);
        $("#release_year").val(data.release_year);
        $("#id").val(data.id);
        $("#slug").val(data.slug);
        $("#meta_title").val(data.meta_title);
        $("#meta_keyw").val(data.meta_keyw);
        $("#meta_des").val(data.meta_des);
        $("#category_order").val(data.pos);

        if (data.description) {
          $("#category_des").summernote("pasteHTML", data.description);
        }
        if (data.added_home == "1") {
          if ($("#added_home").prop("checked") == false) {
            $("#added_home").trigger("click");
          }
        }
        if (data.newtag == "1") {
          if ($("#newtag").prop("checked") == false) {
            $("#newtag").trigger("click");
          }
        }
        // if (data.updatetag == "1") {
        //   if ($("#updatetag").prop("checked") == false) {
        //     $("#updatetag").trigger("click");
        //   }
        // }
        if (data.status == "1") {
          if ($("#status").prop("checked") == false) {
            $("#status").trigger("click");
          }
        }
        if (data.thumb != "") {
          $("#thumbnail").show();
          $("#thumb").attr("src", data.thumb);
        }

        $("#action").val("edit");
        $("#ModalCategory").modal("show");
      },
    });
  });

  function youtube_parser(url) {
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
    var match = url.match(regExp);
    return (match && match[7].length == 11) ? match[7] : "";
  }

  $(document).on("click", "#movieSearch", function (ev) {
    ev.preventDefault();
    let query = $("#youtube_query").val();
    if (query.length < 3) {
      swal("Error!", 'Please Enter Valid Youtube URL', "warning");
      return false;
    }
    query = youtube_parser(query);
    $.ajax({
      url: "process.php",
      type: "POST",
      data: {
        submit: 'importfromyoutube',
        query: query
      },
      dataType: "json",
      success: function (resp) {
        if (resp.status == "1") {
          $("#filename").val(resp.data.title);
          $("#url").val(resp.data.url);
          $("#thumb_url").val(resp.data.thumb);
          $("#thumbfrom").val("EXTERNAL_LINK");
          $("#thumb_file_display").hide();
          $("#thumb_url_display").show();
          $("#importmodal").modal("hide");
        } else {
          swal("Error!", resp.message, "warning");
        }

      },
      error: function () {
        swal("Error!", "Internal Error", "warning");
      }
    });

  });

  var adschanger = $(".adschanger").DataTable({
    responsive: true,
    dom: "Bflrtip",
    select: {
      style: "os",
      selector: "td:nth-child(2)",
    },
    buttons: [
      "selectAll",
      "selectNone",
      {
        text: "Delete",
        className: "btn btn-danger",
        action: function () {
          var ids = adschanger.rows({ selected: true }).ids().toArray();
          var count = adschanger.rows({ selected: true }).count();
          if (count > 0) {
            DeleteMultiple(ids, count);
          } else {
            swal("Error", "You Have no Item Seleted for Deleted", "warning");
          }
        },
      },
    ],
    lengthChange: true,
    lengthMenu: [
      [10, 25, 50, -1],
      [10, 25, 50, "All"],
    ],
    processing: true,
    serverSide: true,
    order: [],
    ajax: {
      url: "process.php",
      type: "POST",
      data: {
        submit: "list",
      },
      dataType: "json",
    },
    columnDefs: [
      {
        targets: [2, 3],
        orderable: false,
      },
    ],
    rowId: function (a) {
      return a[0];
    },
    pageLength: 10,
  });

  $(document).on("submit", "#adchangerform", function (event) {
    event.preventDefault();
    var formData = $(this).serialize();
    $("#submitbutton").attr("disabled", "disabled");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: formData,
      success: function (data) {
        $("#adchangerform")[0].reset();
        $("#adchangermodal").modal("hide");
        $("#submitbutton").removeAttr("disabled");
        if (data.status == 1) {
          adschanger.draw(false);
          swal("Success!", data.message, "success");
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });

  $(document).on("click", "#adchanger_add", function (e) {
    e.preventDefault();
    $("#modallabel").html("<i class='fa fa-plus'></i> Add Ads Changer");
    $("#adchangermodal").modal("show");
    $("#adchangerform")[0].reset();
  });

  $(document).on("click", ".status", function (e) {
    e.preventDefault();
    var _id = $(this).attr("id");
    var _type = $("#datalist").attr("name");
    if (_type == "files" || _type == "categories" || _type == "artist" || _type == "users") {
      $.ajax({
        type: "post",
        url: "process.php",
        dataType: "json",
        data: {
          id: _id,
          action: "status",
          submit: "statusUpdater",
        },
        success: function (data) {
          if (data.status == "1") {
            if (_type == "files") {
              files.draw(false);
            }
            if (_type == "categories") {
              categories.draw(false);
            }
            if (_type == "artist") {
              artist.draw(false);
            }
            if (_type == "users") {
              users.draw(false);
            }
          }
        },
      });
    }
  });

  function MoveFiles(ids, totalitem) {
    var _type = $("#datalist").attr("name");
    swal(
      {
        title: "Move Files",
        text: "Are you sure Total: " + totalitem + " Item Move",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "Please enter Category Id very carefully",
      },
      function (inputValue) {
        if (inputValue == "") {
          return false;
        }
        $.ajax({
          type: "post",
          url: "process.php",
          dataType: "json",
          data: {
            ids: ids,
            targetId: inputValue,
            submit: "MoveFiles",
          },
          success: function (res) {
            if (res.status == "1") {
              if (_type == "files") {
                files.draw(false);
              } else if (_type == "categories") {
                categories.draw(false);
              }
              swal("Successfully", res.message, "success");
            } else {
              swal("Error", res.message, "warning");
            }
          },
          error: function () {
            swal("Error", "Something are wrong", "warning");
          },
        });
      }
    );
  }

  function DeleteMultiple(ids, totalitem) {
    var _type = $("#datalist").attr("name");
    var _submit = "multipledelete";
    swal(
      {
        title: "Are you sure to delete Total: " + totalitem + " Items?",
        type: "warning",
        showCancelButton: true,
        cancelButtonClass: "btn-warning",
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: false,
        closeOnCancel: false,
        showLoaderOnConfirm: true,
      },
      function (isConfirm) {
        if (isConfirm) {
          $.ajax({
            type: "post",
            url: "process.php",
            dataType: "json",
            data: {
              ids: ids,
              submit: _submit,
            },
            success: function (res) {
              if (res.status == "1") {
                if (_type == "categories") {
                  categories.draw(false);
                } else if (_type == "adschanger") {
                  adschanger.draw(false);
                } else if (_type == "files") {
                  files.draw(false);
                } else if (_type == "artist") {
                  artist.draw(false);
                }
                else if (_type == "users") {
                  users.draw(false);
                }
                else if (_type == "reports") {
                  reports.draw(false);
                }
                swal("Successfully", res.message, "success");
              } else {
                swal("Error", res.message, "warning");
              }
            },
          });
        } else {
          swal.close();
        }
      }
    );
  }

  $(document).on("click", ".delete", function (e) {
    e.preventDefault();
    var _id = $(this).attr("id");
    var _type = $("#datalist").attr("name");
    var _submit = "delete";

    swal(
      {
        title: "Are you sure to delete this?",
        type: "warning",
        showCancelButton: true,
        cancelButtonClass: "btn-warning",
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: false,
        closeOnCancel: false,
        showLoaderOnConfirm: true,
      },
      function (isConfirm) {
        if (isConfirm) {
          $.ajax({
            type: "post",
            url: "process.php",
            dataType: "json",
            data: {
              id: _id,
              submit: _submit,
            },
            success: function (res) {
              if (res.status == "1") {
                if (_type == "categories") {
                  categories.draw(false);
                } else if (_type == "adschanger") {
                  adschanger.draw(false);
                } else if (_type == "files") {
                  files.draw(false);
                } else if (_type == "artist") {
                  artist.draw(false);
                }
                else if (_type == "users") {
                  users.draw(false);
                }
                else if (_type == "reports") {
                  reports.draw(false);
                }
                swal("Successfully", res.message, "success");
              } else {
                swal("Error", res.message, "warning");
              }
            },
          });
        } else {
          swal.close();
        }
      }
    );
  });

  $(document).on("click", ".changetag", function (e) {
    e.preventDefault();
    var id = $(this).attr("id");
    $("#modal-title").html("<i class='fa fa-edit'></i> Change Tag");
    $("#changetag")[0].reset();
    $("#action").val("changeTag");
    $.ajax({
      url: "process.php",
      type: "POST",
      data: {
        id: id,
        submit: "getId3",
      },
      dataType: "json",
      success: function (res) {
        var resp = res.data;
        if (res.status == "1") {
          $("#id").val(id);
          $("#title").val(resp.title);
          $("#singer").val(resp.artist);
          $("#album").val(resp.album);
          $("#year").val(resp.year);
          $("#comment").val(resp.comment);
          $("#modalform").modal("show");
        } else {
          swal("Error", data.message, 'warning');
        }
      },
    });
  });

  $(document).on("submit", "#changetag", function (event) {
    event.preventDefault();
    $("#submit").attr("disabled", "disabled");
    var frm = $("#changetag")[0];
    var formData = new FormData(frm);
    $.ajax({
      url: "process.php",
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {
        $("#submit").attr("disabled", false);
        if (data.status == 1) {
          $("#thumb_url_display").hide();
          $("#thumb_file_display").show();
          $("#changetag")[0].reset();
          $("#modalform").modal("hide");
          swal("Success!", data.message, "success");
        } else {
          swal("Error!", data.message, "warning");
        }
      },
    });
  });


  $(document).on("click", ".restore", function (e) {
    e.preventDefault();
    let id = $(this).attr("id");
    let ids = [id];
    singleStatus("restoreAll", ids);
  });


  $(document).on("click", ".trash", function (e) {
    e.preventDefault();
    let id = $(this).attr("id");
    let ids = [id];
    singleStatus("trashedAll", ids);
  });


  $(document).on("click", ".showpending", function (e) {
    e.preventDefault();
    $(".showingby").text("Pending Files");
    $("#fileTable").attr('data-filter', 'PENDING');
    files.ajax.reload();
  });

  $(document).on("click", ".showall", function (e) {
    e.preventDefault();
    $(".showingby").text("All Files");
    $("#fileTable").attr('data-filter', 'ALL');
    files.ajax.reload();
  });


  $(document).on("click", ".showtrashed", function (e) {
    e.preventDefault();
    $(".showingby").text("Trashed Files");
    $("#fileTable").attr('data-filter', 'TRASHED');
    files.ajax.reload();

  });

  $(document).on("click", ".approveAll", function (e) {
    e.preventDefault();
    ActiontoStatus("approveAll");
  });

  $(document).on("click", ".restoreAll", function (e) {
    e.preventDefault();
    ActiontoStatus("restoreAll");
  });

  $(document).on("click", ".trashedAll", function (e) {
    e.preventDefault();
    ActiontoStatus("trashedAll");
  });


  function singleStatus(type, ids) {
    swal(
      {
        title: "Are you sure ?",
        type: "warning",
        showCancelButton: true,
        cancelButtonClass: "btn-warning",
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: false,
        closeOnCancel: false,
        showLoaderOnConfirm: true,
      },
      function (isConfirm) {
        if (isConfirm) {
          $.ajax({
            type: "post",
            url: "process.php",
            dataType: "json",
            data: {
              ids: ids,
              type: type,
              submit: 'userfilestatus',
            },
            success: function (res) {
              if (res.status == "1") {
                files.draw(false);
                swal("Successfully", res.message, "success");
              } else {
                swal("Error", res.message, "warning");
              }
            },
          });
        } else {
          swal.close();
        }
      }
    );
  }


  function ActiontoStatus(type) {
    let title;

    if (type == "approveAll") {
      title = "Approve";
    } else if (type == "restoreAll") {
      title = "Restore";
    } else {
      title = "Trash";
    }
    var ids = files.rows({ selected: true }).ids().toArray();
    var count = files.rows({ selected: true }).count();
    if (count == 0) {
      swal("Error", "You Have no Item Seleted for " + title, "warning");
      return false;
    }

    swal(
      {
        title: "Are you sure to " + title + " Total: " + count + " Items?",
        type: "warning",
        showCancelButton: true,
        cancelButtonClass: "btn-warning",
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: false,
        closeOnCancel: false,
        showLoaderOnConfirm: true,
      },
      function (isConfirm) {
        if (isConfirm) {
          $.ajax({
            type: "post",
            url: "process.php",
            dataType: "json",
            data: {
              ids: ids,
              type: type,
              submit: 'userfilestatus',
            },
            success: function (res) {
              if (res.status == "1") {
                files.draw(false);
                swal("Successfully", res.message, "success");
              } else {
                swal("Error", res.message, "warning");
              }
            },
          });
        } else {
          swal.close();
        }
      }
    );

  }

  $(document).ready(function () {
    var max_fields_limit = 10; //set limit for maximum input fields
    var x = 1; //initialize counter for text box
    $('#addmoreurl').click(function (e) { //click event on add more fields button having class add_more_button
      e.preventDefault();
      if (x < max_fields_limit) { //check conditions
        x++; //counter increment
        $('#input_url_more').append('<div><p class="m-1"></p><input type="text" name="copy_url[]" class="form-control" id="copy_url" value="" placeholder="Copy File Via URL" required="1"/><a href="#" class="remove_url_field">Remove</a></div>'); //add input field
      }
    });

    $('#addmorefile').click(function (e) { //click event on add more fields button having class add_more_button
      e.preventDefault();
      if (x < max_fields_limit) { //check conditions
        x++; //counter increment
        $('#input_file_more').append('<div><p class="m-1"></p><input type="file" name="uploadfile[]" class="form-control" id="uploadfile" value="" required="1"/><a href="#" class="remove_file_field">Remove</a></div>'); //add input field
      }
    });


    $('#input_url_more').on("click", ".remove_url_field", function (e) { //user click on remove text links
      e.preventDefault(); $(this).parent('div').remove(); x--;
    });

    $('#input_file_more').on("click", ".remove_file_field", function (e) { //user click on remove text links
      e.preventDefault(); $(this).parent('div').remove(); x--;
    });
  });


});
