/*
* Author: Clarence A Andaya
* Date: June 08 2022
*/
//Only const Variable Here
(function () {
"use strict";
//Logic,Variables, Functions Here
var myList = null;
var search_type_filter = [];
var user_id = "";
var event_id = "";
const $UserForm = $("#UserForm");
const $TeamForm = $("#TeamForm");
const $EventForm = $("#EventForm");
const $tableList = $("#tableList");
var create_from_mate = false;
function delay(callback, ms) {
var timer = 0;
return function () {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
function initActionRemove() {
myList.on("click", "[data-action-remove]", function () {
var data = myList.row(this).data();
if (typeof data === "undefined" || data == null) {
var row = $(this).closest("tr");
data = myList.row(row).data();
}
// $("[data-action-remove]").each(function () {
// $(this).on("click", function () {
// var row = $(this).closest("tr");
// var data = myList.row(row).data().id;
// console.log(data);
// return false;
const id = data.id; //$(this).attr('data-action-remove');
Swal.fire({
title: "Are you sure, you want to remove this user?",
text: "This action cannot be undone.",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, remove it!",
showClass: {
backdrop: "swal2-noanimation", // disable backdrop animation
popup: "", // disable popup animation
icon: "", // disable icon animation
},
hideClass: {
popup: "", // disable popup fade-out animation
},
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: update_user_status_uri,
data: {
id: id,
status: 0,
active: 0,
csrf_token: $("meta[name='csrf-token']").attr("content"),
},
type: "POST",
dataType: "json",
beforeSend: function () {
toast("info", "Updating...");
},
success: function (result) {
toast("success", result.message);
// myList.fnStandingRedraw();
myList.draw(false);
},
error: function () {
toast("error", "Error has occurred. Try again.");
},
});
}
});
});
// });
}
function eventFormStatus(status) {
if (status) {
$("#EventForm :input:not(#event):not(.modal-cancel):not(.close)").prop(
"disabled",
status
);
} else {
$("#EventForm :input").prop("disabled", status);
}
}
function resetPlayerForm() {
$('select[name="mate"]').empty().trigger("change");
$('select[name="team"]').empty().trigger("change");
$("select[name='course'] option:first")
.prop("selected", true)
.trigger("change");
$("select[name='division'] option:first")
.prop("selected", true)
.trigger("change");
$("select[name='course_n'] option:first")
.prop("selected", true)
.trigger("change");
$("select[name='flight_n'] option:first")
.prop("selected", true)
.trigger("change");
$("select[name='registration_type'] option:first")
.prop("selected", true)
.trigger("change");
$("select[name='registration_status'] option:first")
.prop("selected", true)
.trigger("change");
}
function initActionEvent() {
myList.on("click", "[data-action-event]", function () {
var data = myList.row(this).data();
if (typeof data === "undefined" || data == null) {
var row = $(this).closest("tr");
data = myList.row(row).data();
}
// $("[data-action-event]").each(function () {
// $(this).on("click", function () {
// var row = $(this).closest("tr");
user_id = data.id;
$("#selected_user").text(data.name);
eventFormStatus(true);
$('select[name="event"]').empty().trigger("change");
resetPlayerForm();
$("#modal_event").modal("show");
});
// });
}
function initActionUpdate() {
myList.on("click", "[data-action-update]", function () {
var data = myList.row(this).data();
if (typeof data === "undefined" || data == null) {
var row = $(this).closest("tr");
data = myList.row(row).data();
}
// $("[data-action-update]").each(function () {
// $(this).on("click", function () {
// var row = $(this).closest("tr");
// var data = myList.row(row).data().id;
// console.log(data);
// return false;
user_id = data.id; //$(this).attr('data-action-remove');
$.ajax({
url: fetch_user_uri,
data: {
id: user_id,
csrf_token: $("meta[name='csrf-token']").attr("content"),
},
type: "POST",
dataType: "json",
beforeSend: function () {
toast("info", "Fetching...");
},
success: function (result) {
// console.log(result);
toastr.remove();
$UserForm.trigger("reset");
$.each(result, function (index, value) {
// console.log(value);
$("[name=" + index + "]").val(value);
});
// $("#txt_name").val(result.name);
// $("#txt_event_date").val(result.date);
// $("#txt_description").val(result.description);
create_from_mate = false;
$("#modal_user").modal("show");
$("input[name=firstname]").trigger("focus");
},
error: function () {
toast("error", "Error has occurred. Try again.");
},
});
});
// });
}
function initList() {
//search
$("#txt_search").on(
"keyup",
delay(function (e) {
myList.search($("#txt_search").val()).draw();
}, 500)
);
const search_type_default = "Name";
const search_types = ["ID", "Name", "Email", "Mobile"];
$.each(search_types, function (i, n) {
$(".product-search-type").append(
`
` +
n +
``
);
});
$(".product-search-type li").each(function () {
if ($(this).text() == search_type_default) {
$(this).removeClass("active").addClass("active");
var active_items_arr = [];
active_items_arr.push(search_type_default);
search_type_filter = JSON.stringify(active_items_arr);
}
$(this).on("click", function () {
//remove all selected menu
$(".product-search-type")
.find("li.active")
.map(function () {
$(this).removeClass("active");
});
$(this).toggleClass("active");
var active_items = $(".product-search-type")
.find("li.active")
.map(function () {
var item = {};
// item.id = this.value;
item.status = $(this).text();
return item;
});
var active_items_arr = [];
$.each(active_items, function (i, n) {
active_items_arr.push(n.status);
});
search_type_filter = JSON.stringify(active_items_arr);
// refreshOrcrPlateTable();
// if ($('#txt_search').val() != '') {
myList.draw(false);
// }
});
});
// Delete a record
$tableList.on("click", "td.table-action > a action-delete", function (e) {
e.preventDefault();
});
var cols = [
{
title: "ID",
data: "id",
className: "align-middle p-1 dt-center",
orderable: true,
width: "5%",
},
{
title: "Name",
data: "name",
className: "align-middle p-1 dt-left",
orderable: true,
width: "20%",
},
{
title: "Mobile",
data: "mobile",
className: "align-middle p-1 dt-center",
orderable: true,
width: "10%",
render: function (data, type, row, meta) {
return (
`` +
row.mobile +
``
);
},
},
{
title: "Email",
data: "email",
className: "align-middle p-1 dt-center",
orderable: true,
width: "15%",
render: function (data, type, row, meta) {
return (
`` +
row.email +
``
);
},
},
{
title: "Date Added",
data: "created_at",
className: "align-middle p-1 dt-center",
orderable: true,
width: "10%",
},
{
title: "Action",
data: null,
orderable: false,
width: "10%",
className: "align-middle p-1 dt-center",
render: function (data, type, row, meta) {
return `
`;
},
},
];
myList = $tableList.DataTable({
// fnInitComplete: function() {
// initActionRemove();
// },
// stateSave: true,
fnDrawCallback: function () {},
// columnDefs: [{
// width: 200,
// targets: 0
// }],
/* Disable initial sort */
order: [[1, "asc"]],
retrieve: true,
columns: cols,
// data: data,
paging: true,
lengthChange: false,
searching: true,
// ordering: true,
pageLength: 10,
info: true,
autoWidth: false,
responsive: true,
processing: true,
fixedColumns: true,
serverSide: true,
// ajax: "/admin/products/list",
ajax: {
url: list_uri,
data: function (d) {
return $.extend({}, d, {
search_type: search_type_filter,
});
},
},
sDom: "lrtip",
});
}
function tableEvents() {
initActionRemove();
initActionUpdate();
initActionEvent();
}
$(function () {
initList();
tableEvents();
$('select[name="event"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Search event name.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: event_options_uri,
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
limit: 15,
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="mate"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Search name.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: user_mate_options_uri,
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
exclude_id: user_id,
event_id: event_id,
limit: 15,
course: $('select[name="course_n"]').val(),
flight: $('select[name="flight_n"]').val(),
course_cat: $('select[name="course"]').val(),
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="team"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Search team.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: team_options_uri,
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
event_id: event_id,
limit: 15,
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="event"]').on("change", function (event) {
resetPlayerForm();
if (!isEmpty($(this).val()) && parseInt($(this).val())) {
event_id = $(this).val();
eventFormStatus(false);
// fetch any existing player
$.ajax({
url: fetch_player_uri,
data: {
user_id: user_id,
event_id: event_id,
csrf_token: $("meta[name='csrf-token']").attr("content"),
},
type: "POST",
dataType: "json",
beforeSend: function () {},
success: function (result) {
if (result.length === 0) {
return false;
}
if (result.team_id) {
$("select[name='team']")
.empty()
.append(
new Option(result.team_name, result.team_id, false, false)
)
.trigger("change");
}
if (result.partner_id) {
$("select[name='mate']")
.empty()
.append(
new Option(
result.partner_name,
result.partner_id,
false,
false
)
)
.trigger("change");
}
$("select[name='course']").val(result.course_id).trigger("change");
$("select[name='division']")
.val(result.division_id)
.trigger("change");
$("select[name='course_n']").val(result.course).trigger("change");
$("select[name='flight_n']").val(result.flight).trigger("change");
$("select[name='registration_type']")
.val(result.registration_type)
.trigger("change");
$("select[name='registration_status']")
.val(result.registration_status)
.trigger("change");
},
error: function () {},
});
} else {
eventFormStatus(true);
event_id = "";
}
});
$("#btn_add_team").on("click", function () {
$("input[name=team_name]").val("");
$("#modal_team").modal("show");
$("input[name=team_name]").trigger("focus");
});
$(document).on("click", ".dropdown-filter,.daterangepicker", function (e) {
e.stopPropagation();
});
const createEvt = function (status) {
create_from_mate = status;
if (!create_from_mate) {
user_id = "";
}
$UserForm.trigger("reset");
$("#modal_user").modal("show");
$("input[name=firstname]").trigger("focus");
};
const $btn_create = $("#btn_create");
const $btn_add_mate = $("#btn_add_mate");
$btn_create.on("click", function () {
createEvt(false);
});
$btn_add_mate.on("click", function () {
createEvt(true);
});
$("#div_event_date").datetimepicker({
format: "L",
});
$("[data-mask]").inputmask();
$("#reload-list").on("click", function () {
// myList.draw(false);
myList.draw(false);
});
$("#filter-list").on("click", function () {
$("#filter-list-section").toggleClass("hidden");
});
$UserForm.validate({
rules: {
firstname: {
required: true,
},
lastname: {
required: true,
},
email: {
email: true,
},
mobile: {
digits: true,
minlength: 5,
},
},
messages: {},
errorElement: "span",
errorPlacement: function (error, element) {
error.addClass("invalid-feedback");
element.closest(".form-group").append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass("is-invalid");
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass("is-invalid");
},
submitHandler: function () {
// check has selected type
var $form = $UserForm[0];
var formData = new FormData($form);
// formData.append("add_anyway", orcr_plate_add_anyway);
if (!create_from_mate) {
formData.append("user_id", user_id);
}
formData.append(
"csrf_token",
$("meta[name='csrf-token']").attr("content")
);
$.ajax({
url: create_users_uri,
data: formData,
type: "POST",
dataType: "json",
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
beforeSend: function () {
toastr.remove();
toastr.info("Saving data.");
$("#btn_save").prop("disabled", true);
},
success: function (result) {
if (parseInt(result.status) === 1) {
toastr.remove();
toastr.success("Data successfully saved.");
$("#modal_user").modal("hide");
myList.draw(false);
if (create_from_mate) {
var newOption = new Option(
result.name,
result.id,
false,
false
);
$("select[name='mate']")
.empty()
.append(newOption)
.trigger("change");
}
} else {
toastr.remove();
toastr.error(result.message);
}
$("#btn_save").prop("disabled", false);
},
error: function () {
toastr.remove();
toastr.error("Error has occurred. Try again.");
$("#btn_save").prop("disabled", false);
},
});
},
});
$TeamForm.validate({
rules: {
team_name: {
required: true,
},
},
messages: {},
errorElement: "span",
errorPlacement: function (error, element) {
error.addClass("invalid-feedback");
element.closest(".form-group").append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass("is-invalid");
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass("is-invalid");
},
submitHandler: function () {
// check has selected type
var $form = $TeamForm[0];
var formData = new FormData($form);
// formData.append("add_anyway", orcr_plate_add_anyway);
formData.append("event_id", event_id);
formData.append(
"csrf_token",
$("meta[name='csrf-token']").attr("content")
);
$.ajax({
url: create_team_uri,
data: formData,
type: "POST",
dataType: "json",
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
beforeSend: function () {
toastr.remove();
toastr.info("Saving data.");
$("#btn_save_team").prop("disabled", true);
},
success: function (result) {
if (parseInt(result.status) === 1) {
toastr.remove();
toastr.success("Data successfully saved.");
var newOption = new Option(
result.name,
result.team_id,
false,
false
);
$("select[name='team']")
.empty()
.append(newOption)
.trigger("change");
$("#modal_team").modal("hide");
} else if (parseInt(result.status) === 2) {
toastr.remove();
toastr.error(result.message);
} else {
toastr.remove();
toastr.error(result.message);
}
$("#btn_save_team").prop("disabled", false);
},
error: function () {
toastr.remove();
toastr.error("Error has occurred. Try again.");
$("#btn_save_team").prop("disabled", false);
},
});
},
});
$EventForm.validate({
rules: {
event: {
required: true,
min: 1,
},
},
messages: {
team: "This field is required.",
},
errorElement: "span",
errorPlacement: function (error, element) {
error.addClass("invalid-feedback");
element.closest(".form-group").append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass("is-invalid");
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass("is-invalid");
},
submitHandler: function () {
// check has selected type
var $form = $EventForm[0];
var formData = new FormData($form);
// formData.append("add_anyway", orcr_plate_add_anyway);
formData.append("user_id", user_id);
formData.append(
"csrf_token",
$("meta[name='csrf-token']").attr("content")
);
$.ajax({
url: create_add_to_evt_uri,
data: formData,
type: "POST",
dataType: "json",
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
beforeSend: function () {
toastr.remove();
toastr.info("Saving data.");
$("#btn_save_team").prop("disabled", true);
},
success: function (result) {
if (parseInt(result.status) === 1) {
toastr.remove();
toastr.success("Data successfully saved.");
$("#modal_event").modal("hide");
} else {
toastr.remove();
toastr.error(result.message);
}
$("#btn_save_team").prop("disabled", false);
},
error: function () {
toastr.remove();
toastr.error("Error has occurred. Try again.");
$("#btn_save_team").prop("disabled", false);
},
});
},
});
//comfig
$(document).on("show.bs.modal", ".modal", function () {
const zIndex = 1040 + 10 * $(".modal:visible").length;
$(this).css("z-index", zIndex);
setTimeout(() =>
$(".modal-backdrop")
.not(".modal-stack")
.css("z-index", zIndex - 1)
.addClass("modal-stack")
);
});
$(document).on("select2:open", () => {
document.querySelector(".select2-search__field").focus();
});
});
})();