0% found this document useful (0 votes)
22 views84 pages

changes_v2

Uploaded by

adarsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views84 pages

changes_v2

Uploaded by

adarsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 84

var baseUrl = $('#baseUrl').

val();
var final_status = 0;
var sms_status = 0;

init = function () {
$('#gotoLetterTemplate').hide();
$('#gotoLetterTemplate').attr('href', baseUrl + 'clients/letterTemplates')
}();

function toggle_status(checkAll) {
if (checkAll.checked) {
$(".select").each(function () {
$(this).prop("checked", true);
});
} else {
$(".select").each(function () {
$(this).prop("checked", false);
});
}
}

function validateForm() {
var chks = document.getElementsByName('id[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
hasChecked = true;
break;
}

}
if (!hasChecked) {
show_hide_toastr_message('errorMessage', 'Please select atleast one contact
row to continue !');
return false;
} else {
return true;
}
}

function validateImportForm() {
$('.clientImport').find('i').removeClass('fa-save').addClass('fa-spin fa-
spinner');
if ($('#client_visibility').val() == 1 && $('#assign_business').val() == 0) {
swal({
title: '',
text: "'Client Visibility' in your account is turned on however you
have not selected 'Assign Business' from the data fields. Are you sure you wish to
proceed without assigning clients to a business?",
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: "Proceed",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
$('#import-client-to-db-form').append('<input type="hidden"
name="import" value="1" />');
$('#import-client-to-db-form').submit();
} else {
$('.clientImport').find('i').removeClass('fa-spin fa-
spinner').addClass('fa-save');
return false;
}
});
} else {
$('#import-client-to-db-form').append('<input type="hidden" name="import"
value="1" />');
$('#import-client-to-db-form').submit();
}
}

function checkBoxChange() {
$(".select").each(function () {
if ($(this).prop("checked") == true) {
$(this).closest("tr").addClass('selected');
} else {
$('.importSelectAll').prop("checked", false);
if ($(this).closest("tr").hasClass('selected')) {
$(this).closest("tr").removeClass('selected');
}
}
});
}

function mergeClients() {
var client_id = $('#client_id').val();
var checked = false;
var clientsNo = $('.delete_checkbox_id:checked').length;
if (clientsNo >= 2) {
$('#deleteCheckedForm').append('<input type="hidden" name="merge_client"
value=1 />');
$('#deleteCheckedForm').submit();
} else {
swal({
title: '',
text: languageConversion('mergeClients'),
type: "warning",
showCancelButton: false,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('ok'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
return false;
});
}
}

function archiveClients(msg) {
var countChecked = $('.delete_checkbox_id:checked').length;
swal({
title: languageConversion('deleteConfirmTitle'),
text: msg,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('archive'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
if (parseInt(countChecked) > 0) {
$('#deleteCheckedForm').append('<input type="hidden"
name="archive_clients" value=1 />');
$('#deleteCheckedForm').submit();
} else {
show_hide_toastr_message('infoMessage',
languageConversion('checkRowMsg'));
}
}
});
}

function addTag2(val) {
var str = 'tags=' + $('#tags_2').val() + '&page=' + $('#page').val();
var msgtype = '';
$tagPage = $('#tagPage').val();
if ($tagPage == 'messaging/new_message/') {
var booking_remainder_type = $('#booking_remainder_type').val();
var msg_type = 'email';
if (booking_remainder_type)
msg_type = 'sms';

msgtype = '&msg_type=' + msg_type;

if ($('#type').val()) {
msgtype = '&type=' + $('#type').val();
}
}
if ($tagPage = "clients") {
setClientUrl('tags', $('#tags_2').val())
} else {
window.location.href = $('#baseUrl').val() + $('#tagPage').val() + '?tags='
+ $('#tags_2').val() + msgtype;
}
return;

}
function setClientUrl(param, setValue) {
var urlString = location.search.substring(1);
var urlParams = new URLSearchParams(urlString);
var hasParam = urlParams.has(param);
if (hasParam && setValue) {
urlParams.set(param, setValue);
} else if (hasParam && !setValue) {
urlParams.delete(param);
} else {
urlParams.append(param, setValue);
}
if (param == "type" && setValue == "deleted") {
window.location.href = baseUrl + 'clients?type=deleted';
} else {
var query_string = urlParams.toString();
if (query_string) {
window.location.href = baseUrl + 'clients?' + query_string;
} else {
window.location.href = baseUrl + 'clients';
}
}
}
function addTag() {
var client_id = $('#client_id').val();
var str = 'tags=' + $('#tags_3').val() + '&client_id=' + client_id;
$.ajax({
type: "POST",
url: $('#baseUrl').val() + 'clients/add_client_tags',
data: str,
success: function (data) {
$('#tags_3').importTags(data);
$('.tagsinput input').focus();
}
});
}

function addClientTag(element) {
var clientArray = element.split('_');

var client_id = clientArray[1];


var str = 'tags=' + $("#" + element).val() + '&client_id=' + client_id;
$.ajax({
type: "POST",
url: $('#baseUrl').val() + 'clients/add_client_tags',
data: str,
success: function (data) {
$("#" + element).importTags(data);
$('.tagsinput input').focus();
}
});
}

function addNewClientTag() {
var tag_val = $('#tags_newc').val();
$("#newclient_tags").val(tag_val);
}

function client_search() {
var searchText = $('.cliens-search-wrap input#autosuggest').val();
setClientUrl('search_client_text', searchText);
}

function categoryFieldSortable() {
$(".categoryFieldSortable").sortable({
stop: function (event, ui) {
var categoryId = $(ui.item).attr('data-id');
var order_count = 1;
$('#category_' + categoryId + ' .formElement').each(function () {
$(this).find("input[name='noteFieldOrder[]']").val(order_count)
order_count++;
});
}
});
}

$(document).ready(function () {

var clientsNo = $('.delete_checkbox_id:checked').length;


if (clientsNo >= 2) {
$("#btnMerge").removeClass("d-none");
}
var note_type = $('#note_type').val();
sortOptionFields();
$('.userCategoryBlocks').removeClass('row');
// Sorting of categories and category fields from client details page
$("body").on("change", "#client_edit_mode", function (e) {
if (!$(this).prop('checked')) {
$('.userCategoryBlocks').masonry({ itemSelector: ".grid-item-masonry",
horizontalOrder: true });
$('.client-edit-mode').hide();
$(".userCategoryBlocks, .categoryFieldNSortable").sortable("disable");
$(".grid-item-masonry").removeClass('do-sort');
$('.userCategoryBlocks').removeClass('row');
} else {
$('.grid').masonry('destroy');
$('.grid').removeData('masonry');
$(".grid-item-masonry").addClass('do-sort');
$('.userCategoryBlocks').addClass('row');

$('.client-edit-mode').show();
if ($('.userCategoryBlocks').hasClass('ui-sortable-disabled')) {
$(".userCategoryBlocks").sortable("enable");
}
$(".userCategoryBlocks").sortable({
items: ".portable",
scroll: true,
scrollSensitivity: 100,
connectWith: ".userCategoryBlocks",
placeholder: 'category_block_placeholder',
stop: function (event, ui) {
var order_count = 0;
$('.portable').each(function () {
var categoryId = $(this).attr('data-categoryID');
$.post($('#baseUrl').val() + 'clients/order_category/', {
'categoryId': categoryId,
'order_count': order_count,
'from': $('#from').val()
}, function (data) { });
order_count++;
});
},
cancel: ".disabled"
});
if ($('.categoryFieldNSortable').hasClass('ui-sortable-disabled')) {
$(".categoryFieldNSortable").sortable("enable");
}
$(".categoryFieldNSortable").sortable({
items: ".catFields",
connectWith: ".categoryFieldNSortable",
stop: function (event, ui) {
var categoryId = $(ui.item).attr('data-id');
console.log('categoryId' + categoryId);
var order = 1;
$('#category_' + categoryId).find('.catFields').each(function
() {
var field_tag = $(this).attr('data-catval')
console.log('fieldtag' + field_tag);
$.post($('#baseUrl').val() +
'clients/order_category_fields/', {
'categoryId': categoryId,
'order_count': order,
'field_tag': field_tag,
'from': $('#from').val()
});

order++;
});
}
});
}
});
//fix for control is jumping to top/bottom in safari when selecting an item
from dropdown
$('#clientAddForm select').on('select2:close', function (e) {
$(this).parent().find('select').focus();
});
$('.insert_field_val_tnmce').click(function (e) {
e.preventDefault();

var fieldVal = $(this).data('field_val');


var editor = tinymce.get('letter_message'); // Replace 'your-editor-id'
with the actual ID of your TinyMCE editor
if (editor) {
tinymce.get('letter_message').save();
}
editor.insertContent("{" + fieldVal + "}", { paste: true });
});

if ($('.clientFieldTextArea').length) {
$('.clientFieldTextArea').each(function () {
if (!$(this).val().trim()) {
$(this).parent().find('.note-placeholder').show();
}
});
}
//copy form url
$('body').on('click', '.copyFormUrl', function (e) {
var formId = $(this).attr('data-formid');
var $temp = $("<input>");
var $this = $(this);
$("body").append($temp);
$temp.val($('#formUrl_' + formId).html()).select();
document.execCommand("copy");
$temp.remove();
$this.attr('data-original-title', 'Copied!');
$this.find('i').removeClass('fa-copy').addClass('fa-check');
$this.removeClass('copyFormUrl');
setTimeout(function () {
$this.find('i').removeClass('fa-check').addClass('fa-copy');
$this.addClass('copyFormUrl');
$this.attr('data-original-title', 'Copy Form Url');
}, 3000
);
});
//assign client to form
$('#assignForm').on('click', function (e) {
var clientId = $('#client_id').val();
var clientFormId = $('#clientFormId').val();
var formOwnerId = $('#clientFormId option:selected').attr('data-
formownerid');
if (clientFormId) {
$('.loader').show();
$.ajax({
type: "POST",
url: baseUrl + 'client_intake_form/assignClientForm',
data: {
clientId: clientId,
clientFormId: clientFormId,
formOwnerId: formOwnerId
},
success: function (data) {
$('#clientIntakeForms').trigger('click');
}
});
} else {
swal("", 'Please select form to continue', "error");
}
});
//datepicker for client field if its type is datepicker
$('.datepickerField').each(function () {
$(".datepickerField").datepicker({
show: true,
format: 'dd/mm/yy',
language: 'en',
changeMonth: true,
changeYear: true,
autoclose: true,
orientation: "bottom auto",
yearRange: '1900:' + (new Date().getFullYear() + 25),
});
});
categoryFieldSortable();
$(".categoryFieldSortable").disableSelection();

setCookie('noteFilterOpened', 'yes', 1);

$('.tags_3').tagsInput({
autocomplete_url: $('#baseUrl').val() + 'clients/tagdata/' + $
('#noSystemTag').val(),
autocomplete: { selectFirst: true, width: '100px', autoFill: true },
'height': 'auto',
'onAddTag': function () {
addClientTag($(this).attr('id'));
},
'onRemoveTag': function () {
addClientTag($(this).attr('id'));
}
});
/* client details page updates */
$("#client_tabs").on('change', function () {
$("#client_sales_btn").addClass('d-none');
$('.subnav-container').hide();
$("#export_apnt_btn").addClass('d-none');
$('.client').hide();
$('.' + $(this).val() + 'Box').show();
$('.ae-select-content').html($(this).find('a').html());
if ($(this).val() == 'ClientDetails') {
}
if ($(this).val() == 'ClientNotes') {
}
if ($(this).val() == 'ClientSales') {
$('.loader').show();
$.post($('#baseUrl').val() + 'business/ajaxClientSales', {
client_id: client_id
}, function (data) {
if ($('#printInvoice').val() == 'yes') {
pdf_path = 'pdf/download_pdf/' + client_id + '/' + $
('#paymentID').val();
var path = baseUrl + pdf_path;
window.parent.location = path;
}
$('.ClientSalesBox').html(data);
$("#client_sales_btn").removeClass('d-none');
});
$('.loader').delay(100).fadeOut(1000);
}
if ($(this).val() == 'ClientAppointments') {
$(this).addClass('activePac');
$('.loader').show();
$.post($('#baseUrl').val() + 'booking/ajaxClientAppointment/1/' +
client_id, {
client_id: client_id
}, function (data) {
$('.ClientAppointmentsBox').removeClass('formBox').html(data);
$("#export_apnt_btn").removeClass('d-none');
});
$('.loader').delay(100).fadeOut(1000);
}
});

$('.removeCustomFieldCheckList').on('click', function (e) {


swal({
title: '',
text: languageConversion('removeCustomFieldText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() +
'clients/removeCustomFieldCheckList/', function (data) {
if (data) {
window.location.reload(true);
}
});
}
});
});

// Alert message when import is queued.


if ($('#import_queued').val()) {
infoMsg = languageConversion('importQueued');
swal("", infoMsg, "info");
}

$('.uploadedList select').change(function () {
if ($('#client_visibility').val() == 1) {
$('#assign_business').val(0);
$('.uploadedList select').each(function () {
thisVal = $(this).val();
if (thisVal == 'assign_business') {
$('#assign_business').val(1);
}
});
}
});

//validation before client import


$('.clientImport').on('click', function (e) {
if (!$('.select.check_b:checked').length) {
e.preventDefault();
swal({
title: '',
text: languageConversion('clientImportValidationMsg'),
type: "info",
showCancelButton: false,
confirmButtonColor: "#44d7c5",
confirmButtonText: languageConversion('ok'),
closeOnConfirm: true
});
}
});

$('select#note_type').select2({
width: 'auto'
});

// client list
$('.exportClient').click(function () {
totalClients = $('#totalClients').val();
if (totalClients > 500) {
$("#exportExcelPopup").trigger('click');
} else {
window.location.href = baseUrl + 'clients/export_client_new?type=' + $
('#clientType').val() + 'tags=' + $('#clientTags').val();
}
});
// end client list

$('#clientDetailsSave').click(function () {
if (!$("#clientAddForm").valid()) {
return;
}
$('#clientDetailsSave').find('i').removeClass('fa-save').addClass('fa-
spinner fa-spin');
$('body').css('pointer-events', 'none');
var allTextareas = null;
$('.clientFieldTextArea').each(function(){
var thisId = $(this).attr('id');
var thisName = $(this).attr('name');
var thisValue = tinymce.get(thisId) ?
tinymce.get(thisId).getContent() : '';
if (thisValue) {
tinymce.get(thisId).save();
}
allTextareas += '&' + thisName + '=' + thisValue;
});
$.post($('#clientAddForm').prop('action'), $('#clientAddForm').serialize()
+allTextareas, function (data) {
$('#clientDetailsSave').find('i').removeClass('fa-spinner fa-
spin').addClass('fa-save');
$('body').css('pointer-events', 'initial');
if (data && data.data) {
if (data.data.err_msg) {
toastr.error(data.data.err_msg,
languageConversion('been_problem'), window.overrides);
location.reload();
} else if (data.data.suc_msg) {
toastr.success(data.data.suc_msg,
languageConversion('success'), window.overrides);
location.reload();
}

if (data.data.redirect_url) {
window.location.href = data.data.redirect_url;
location.reload();
}
}
});
});
/* User Add */
$('.addClients').click(function () {
$.post(baseUrl + 'clients/checkPlanAdduser',
function (data) {
if (data == 1) {
$("#clientAdd").trigger('click');
} else {
parent.document.location.href = baseUrl + 'clients/add';
}
});
});

/*search Client*/

$('.cliens-search-wrap .btn').click(function () {
client_search();
});

$('.cliens-search-wrap input#autosuggest').keypress(function (e) {


if (e.which == 13) {
client_search();
}

});

$('#form_client_status').on('submit', function (e) {


var searchTxt = $('input#autosuggest').val();
$("input[name='search_client_text']").val(searchTxt);
});

// Country vs state
country_id = $('#country_id').val();
if (country_id) {
$id = country_id;
$.post(baseUrl + "my_profile/ajax_state/", {
country_id: $id,
state_id: $('#ajax_state_id').val(),
actualCountryId: $('#actualCountryId').val()
}, function (data) {
$("#ajax_state").html(data);
if ($('#state_id option').length > 0) {
$('#state_id').select2({ width: '95%' });
}
});
}
$("#country_id").change(function () {
if (!$('#mobile').val()) {
let mobile_code = $(this).find(':selected').data('mobile_code');
if (mobile_code) {
var mobile_no = $("#mobile").val();
window.iti.setNumber("+" + mobile_code);
$("#mobile").val(mobile_no);
} else {
var mobile_code_data = $("#mobile_code").data("mobile_code");
if (mobile_code_data) {
window.iti.setCountry(mobile_code_data);
} else {
$.get('https://ipinfo.io', function () {
}, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country :
"";
window.iti.setCountry(countryCode);
});
}
}
}
$id = parseInt($(this).val());
if ($id) {
$.post(baseUrl + "my_profile/ajax_state/", {
country_id: $id,
state_id: $('#ajax_state_id').val(),
actualCountryId: $('#actualCountryId').val()
}, function (data) {
$("#ajax_state").html(data);
if ($('#state_id option').length > 0) {
$('#state_id').select2({ width: '95%' });
}
});
}
});

var leadSourceNo = $('#leadSourcetable').find('tr').size();


if (leadSourceNo >= 8) {
$('.customLeadSource').slimscroll({
height: '177px',
wheelStep: 10,
useFixedHeight: true,
fixedHeight: 20,
alwaysVisible: true,
railVisible: true
}).show();
}
// Slim Scroll for future appointments
if (parseInt($('#countFutureAppointment').val()) > 2) {
$('#listFutureAppointment').slimscroll({
height: '115px',
wheelStep: 1,
useFixedHeight: true,
fixedHeight: 10,
alwaysVisible: true,
railVisible: true
}).show();
}
$('.active_inactive').click(function () {
status = ($(this).is(':checked')) ? 1 : 0;
if (status == 1) {
$('.client_status').html(languageConversion('active'));
$('.client_status_toggle').attr('data-original-title',
languageConversion('archive_client'));
} else {
$('.client_status').html(languageConversion('archived'));
$('.client_status_toggle').attr('data-original-title',
languageConversion('reactivate_client'));
}
$.post($('#baseUrl').val() + 'clients/change_status/', {
client_id: $('#client_id').val(),
status: status
}, function (data) {
$('.ClientSalesBox').html(data);
});

});

var client_id = $('#client_id').val();


/* Common tabs */
$('#tabs li').not('#ClientBack').click(function (e, clientInvNumber) {
$('.clientMessageSettings').hide();
$("#export_apnt_btn").addClass('d-none');
$("#client_sales_btn").addClass('d-none');
$("#client_sales_export").addClass('d-none');
$('.subnav-container').hide();
$('.clientMessageFilter').removeClass('d-block').addClass('d-none');
$('.clientInvoiceFilter').removeClass('d-block').addClass('d-none');
$('.clientPaymentFilter').removeClass('d-block').addClass('d-none');
$('.clientSalesFilter').removeClass('d-block').addClass('d-none');
$('.client').hide();
$('.' + $(this).attr('id') + 'Box').show();
$('#tabs li').removeClass('active');
$(this).addClass('active');
$('.ae-select-content').html($(this).find('a').html());
if ($('.clientAppointmentDateRange').hasClass('d-block')) {
$('.clientAppointmentDateRange').removeClass('d-block').addClass('d-
none');
}
if ($(this).attr('id') == 'ClientDetails') { }
if ($(this).attr('id') == 'ClientNotes') { }
if ($(this).attr('id') == 'ClientSales') {
$('.clientSalesFilter').removeClass('d-none').addClass('d-block');
getClientSalesFilter();
}
if ($(this).attr('id') == 'ClientAppointments') {
$('.clientAppointmentDateRange').removeClass('d-none').addClass('d-
block');
$(this).addClass('activePac');
getClientappointmentFilter();
}
if ($(this).attr('id') == 'clientSentMessages') {
$('.clientMessageFilter').removeClass('d-none').addClass('d-block');
$('.clientMessageSettings').show();
getClientSentMessages();
}
if ($(this).attr('id') == 'clientIntakeForms') {
$('.clientFormsWrap').removeClass('d-none').addClass('d-inline-block');
getClientIntakeForms();
} else {
$('.clientFormsWrap').removeClass('d-inline-block').addClass('d-none');
}
if ($(this).attr('id') == 'ClientInvoices') {
$('.clientInvoiceFilter').removeClass('d-none').addClass('d-block');
getClientInvoicesFilter(clientInvNumber);
}
if ($(this).attr('id') == 'ClientPayments') {
$('.clientPaymentFilter').removeClass('d-none').addClass('d-block');
getClientPaymentsFilter();
}
});
/* End Common tabs */

//function to get client intake forms

function getClientIntakeForms() {
var clientId = $('#client_id').val();
var bookingId = $('#formBookingId').val();
$('.loader').show();
$.ajax({
type: "POST",
url: baseUrl + 'client_intake_form/ajaxClientIntakeForms/1/',
data: {
clientId: clientId,
bookingId: bookingId
},
success: function (data) {
$('.loader').hide();
$('.ClientAppointmentsBox').addClass('formBox').html(data).show();
if ($("#sms_msg_status").length && ($("#sms_msg_status").val() ==
1)) {
setInterval(updateSmsStatus, 2000);
}
}
});

}
$('#addContactTab li').click(function () {
$('#addContactTab li').removeClass('active');
$(this).addClass('active');
if ($(this).attr('id') == 'billingInvoices') {
$('.clientInvoiceFilter').removeClass('d-none').addClass('d-block');
$('.invoiceExport').removeClass('d-none');
getBillingInvoicesFilter();
}
if ($(this).attr('id') == 'billingDetails') {
$('.invoiceExport').addClass('d-none');
$('.billingInvoiceBox').hide();
$('.ClientDetailsBox').show();
}
});
$('.billingInvoiceFilter').on('change', function () {
getBillingInvoicesFilter();
});
$('.billingInvoiceFilterWrap .btn').click(function (e) {
e.preventDefault();
billingInvoiceSearch();

});
function getBillingInvoicesFilter(value = null) {
if (value) {
$('#billingInvoiceFilterWrap
input.billingInvoiceautosuggest').val(value);
}
var query_string = '?type=' + $('#billingInvoiceType').val() +
'&search_product_text=' + $('.billingInvoiceautosuggest').val() +
'&invoiceFilterType=' + $('#invoiceFilterType').val() + '&sale_business_id=' + $
('#sale_business_id').val() + '&sale_venu_id=' + $('#sale_venu_id').val() +
'&date_range=' + $('#billing_invoice_date_range').val();
var billingContactId = $('.billingContactId').val();
var baseUrl = $('#baseUrl').val();
$('.loader').show();
$.post(baseUrl + 'clients/invoices' + query_string, {
billingContactId: billingContactId,
fromBillingContact: 'true',
paging_data: 1
}, function (data) {
$('.loader').hide();
$('.billingInvoiceBox').html(data).show();
$('.ClientDetailsBox').hide();
renderDateRangePicker('billingInvoiceRange');
})
var url = $("#billingInvoiceExport").attr("href");
url += '&type=' + $('#billingInvoiceType').val() + '&search_product_text='
+ $('.billingInvoiceautosuggest').val() + '&invoiceFilterType=' + $
('#invoiceFilterType').val() + '&sale_business_id=' + $('#sale_business_id').val()
+ '&sale_venu_id=' + $('#sale_venu_id').val() + '&date_range=' + $
('#billing_invoice_date_range').val();
$("#billingInvoiceExport").attr("href", url)
}
$('#billingInvoiceFilterWrap
input.billingInvoiceautosuggest').keypress(function (e) {
if (e.which == 13) {
getBillingInvoicesFilter();
}
});
$('#billingInvoiceFilterWrap .btn').click(function () {
getBillingInvoicesFilter();
});
$(".billingInvoiceautosuggest").autocomplete({
source: function (request, response) {
var searchText = $(".billingInvoiceautosuggest").val();
var ajaxUrl = $('#billingInvoiceAutosuggestUrl').val();
var clientId = $('#client_id').val();
var invoiceFilterType = $('#invoiceFilterType').val();
$.ajax({
url: ajaxUrl,
data: {
searchtext: searchText.replace(/^0+/, ''),
invoiceFilterType: invoiceFilterType,
clientId: clientId
},
dataType: "json",
type: "post",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.label,
value: obj.displayText,
};
}));
}
});
},
select: function (event, ui) {
event.preventDefault();
getBillingInvoicesFilter(ui.item.value);
},
});
//Function to get client messages
function getClientSentMessages() {
var clientId = $('#client_id').val();
var deliveryStatus = ($('#deliveryStatusDropdown').length && $
('#deliveryStatusDropdown').val()) ? $('#deliveryStatusDropdown').val() : '';
var messageType = ($('#messageTypeDropdown').length && $
('#messageTypeDropdown').val()) ? $('#messageTypeDropdown').val() : '';
var date_range = ($('#message_date_range').length && $
('#message_date_range').val()) ? $('#message_date_range').val() : '';
var messageStatus = ($('#messageStatusDropdown').length && $
('#messageStatusDropdown').val()) ? $('#messageStatusDropdown').val() : '';
$('.loader').show();
$.ajax({
type: "POST",
url: baseUrl + 'clients/ajaxClientSentMessages/1/',
data: {
clientId: clientId,
deliveryStatus: deliveryStatus,
messageType: messageType,
date_range: date_range,
messageStatus: messageStatus,
},
success: function (data) {
$('.loader').hide();
$
('.ClientAppointmentsBox').removeClass('formBox').html(data).show();
if ($("#sms_msg_status").length && ($("#sms_msg_status").val() ==
1)) {
sms_status = setInterval(updateSmsStatus, 2000);
}
renderDateRangePicker('messageRange');
}
});
}

/* Client Details */
$('#activeInactive').change(function () {
$.post($('#baseUrl').val() + "clients/activeInactive/?activate=" + $
(this).val(), function (data) {
if (data) {
var msg = client_name + data;
if (data == 'Archived')
msg = msg + "\n" + languageConversion('clientReinstate')
alert(msg);
}
});
});

$("body").on('click', '#tags_3_tag', function () {


//special tag ||-|| to handle the term
//just a fake search to trigger the search to fetch all item
$('#tags_3_tag').autocomplete("search", '||-||')
})

$('#tags_3').tagsInput({
autocomplete_url: $('#baseUrl').val() + 'clients/tagdata/' + $
('#noSystemTag').val() + '?client_id=' + $('#client_id').val(),
autocomplete: {
selectFirst: true,
width: '100px',
autoFill: true
},
'onAddTag': function () {
addTag();
},
'onRemoveTag': function () {
addTag();
}
});

$('#tags_newc').tagsInput({
autocomplete_url: $('#baseUrl').val() + 'clients/tagdata/' + $
('#noSystemTag').val(),
autocomplete: {
selectFirst: true,
width: '100px',
autoFill: true
},
'onAddTag': function () {
addNewClientTag();
},
'onRemoveTag': function () {
addNewClientTag();
}
});
/* End Client Details */
/* Note section */
if (!$("#date_range").val()) {
$("#getstartType").val("All");
}
$('#reportrange').daterangepicker({
startDate: getFromToDate(),
endDate: getFromToDate('to'),
showDropdowns: true,
showWeekNumbers: true,
timePicker: false,
timePickerIncrement: 1,
timePicker12Hour: true,
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days',
1)],
'Tomorrow': [moment().add('days', 1), moment().add('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'),
moment().subtract('month', 1).endOf('month')],
'All': [moment().subtract('days', $('#allDays').val()), moment()]
},
opens: 'right',
buttonClasses: ['btn btn-default'],
applyClass: 'btn-small btn-primary',
cancelClass: 'btn-small',
format: 'DD/MM/YYYY',
separator: ' to ',
locale: {
applyLabel: 'Submit',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom Range',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
}
},
function (start, end) {
var startDate = start.format('MMMM D, YYYY');
var endDate = end.format('MMMM D, YYYY');
var allStart = moment().subtract('days', $
('#allDays').val()).format('MMMM D, YYYY');
var allEnd = moment().format('MMMM D, YYYY');
var dateValue = '';
if (startDate == allStart && endDate == allEnd) {
dateValue = 'All';
} else {
dateValue = startDate + ' - ' + endDate;
}
$('#reportrange span').html(dateValue);
$("#date_range").val(dateValue);
if ($("#clientsPage").val("invoices")) {
$("#clientSearchForm").submit();
} else {
loadClientNotes();
}
if ($("#note_page").val()) {
loadClientNotes();
}
});
if ($("#date_range").val()) {
$('#reportrange span').html($("#date_range").val());
} else {
$('#reportrange span').html('All');
$("#date_range").val('All');
}
if ($("#appointment_date_range").val()) {
$('#appointmentRange span').html($("#date_range").val());
} else {
//Set the initial state of the picker label
$('#appointmentRange span').html('All');
$("#appointment_date_range").val('all');
}
if ($("#invoice_date_range").val()) {
$('#invoiceRange span').html($("#date_range").val());
} else {
//Set the initial state of the picker label
$('#invoiceRange span').html('All');
$("#invoice_date_range").val('all');
}
if ($("#payment_date_range").val()) {
$('#paymentRange span').html($("#date_range").val());
} else {
//Set the initial state of the picker label
$('#paymentRange span').html('All');
$("#payment_date_range").val('all');
}
if ($("#sales_date_range").val()) {
$('#salesRange span').html($("#date_range").val());
} else {
//Set the initial state of the picker label
$('#salesRange span').html('All');
$("#sales_date_range").val('all');
}
if ($("#message_date_range").val()) {
$('#messageRange span').html($("#date_range").val());
} else {
//Set the initial state of the picker label
$('#messageRange span').html('All');
$("#message_date_range").val('all');
}
if ($("#billing_invoice_date_range").val()) {
$('#billingInvoiceRange span').html($("#date_range").val());
} else {
//Set the initial state of the picker label
$('#billingInvoiceRange span').html('All');
$("#billing_invoice_date_range").val('all');
}
//client Appointmet download
$("#export_apnt_btn").on('click', function (e) {
e.preventDefault();
var url = $("#export_apnt_btn").attr("href");
window.location.href = url;
});

var clickedEventTriggered = false;


$('.notesNavLink').click(function () {
$('#gotoLetterTemplate').hide();
if ($(this).attr('id') == 'letter-note') {
$('#gotoLetterTemplate').show();
}
$('#text_note_changed').val(1);
clickedEventTriggered = true;
saveNoteDraft(clickedEventTriggered, false);
});

//dropzone
$(".note-uploader").dropzone({
paramName: 'file',
url: $('#baseUrl').val() + 'clients/upload_item/' + client_id + '/1',
clickable: true,
enqueueForUpload: false,
maxFilesize: 20,
addRemoveLinks: false,
dictDefaultMessage: '',
init: function () {
this.on("sending", function (file, xhr, formData) {
formData.append("note_type", $("#note_type").val());
});
},
accept: function (file, done) {
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(file.name)[1];
ext = ext.toUpperCase();
if (ext == "JPEG" || ext == "BMP" || ext == "GIF" || ext == "JPG" ||
ext == "PNG" || ext == "JPE" ||
ext == "DOC" || ext == "DOCX" || ext == "PPT" || ext == "PPS" ||
ext == "PPTX" || ext == "XLS" ||
ext == "XLSX" || ext == "TXT" || ext == "MSG" || ext == "CSV" ||
ext == "PDF" || ext == "XML") {
done();
} else {
$(".dz-preview").remove();
$(".dz-processing").remove();
done("Disallowed File Format.");
alert("Disallowed File Format.");
return false;
}
},
success: function (data, responseText) {
$('#note-attachment-error').hide();
if (responseText != undefined && responseText != '' && responseText !=
'failure' && responseText != 'upload failed') {
$("#img_error").html("").hide();
$(".dz-preview").remove();
$("#img_error").html("").hide();
var note_type = $("#note_type").val();
$('#' + note_type + '_listAttachment').append(responseText);
} else if (responseText == 'failure') {
$(".dz-preview").remove();
alert('Invalid File Format');
} else if (responseText == 'upload failed') {
$(".dz-preview").remove();
$(".dz-processing").remove();
alert('Unable to upload the file.');
}
}
});
$('#uploding').click(function () {
$('#uploader').trigger('click');
});
$('#listAttachment').on('click', '.deleteAttachment', function () {
clnt_id = client_id;
var att_id = $(this).attr('id').split('_')[1];
$this = $(this);
swal({
title: languageConversion('deleteAttachment'),
text: languageConversion('deleteConfirmation'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() + 'clients/ajax_removenotes/', {
id: att_id,
client_id: clnt_id
}, function (data) {
$this.parent().remove();
});
}
});
});

$('#AddNoteAttachment').click(function () {
var note_type = $('#note_type').val();
if (!note_type || (note_type == 'text' || note_type == 'payment')) {
var clientNote = $('#client_note').val();
var draft_id = $('#draft_id').val();
var attachmentId = $('input.attachmentId').serialize();
if (!clientNote) {
show_hide_toastr_message('errorMessage',
languageConversion('addNote'));
} else {
$('.buttonDisable').attr('disabled', true);
$.post($('#baseUrl').val() + "clients/add_noteSubmit/", {
note: clientNote,
client_id: client_id,
draft_id: draft_id,
'attachmentId': attachmentId
}, function (data) {
$('.notes-shadow:first').before(data);
$('.notes-shadow:first').slideDown(500);
$('#draft_id').val('');
$('#ClientNote').val('');
$('#client_note').val('');
$('#listAttachment').html('');
$('.note-editable').html('');
$('.categoryTextArea').val('');
$('.noNoteFound').hide();
$('.buttonDisable').attr('disabled', false);
});
}
} else {
//validation and custom note submission
$('.buttonDisable').attr('disabled', true);
$.ajax({
type: 'POST',
url: $('#baseUrl').val() + "clients/categoryNoteSubmit/",
data: $('#add-note').find('input,select,textarea').serialize(),
success: function (data) {
$('.notes-shadow:first').before(data);
$('.notes-shadow:first').slideDown(500);
$('#draft_id').val('');
$('#ClientNote').val('');
$('#note').val('');
$('.categoryTextArea').val('');
$('#listAttachment').html('');
$('.note-editable').html('');
$('.noNoteFound').hide();
$('.buttonDisable').attr('disabled', false);
}
});
}
});
$('.letterList tr').click(function () {
var tempId = $(this).find('h2').attr('data-temId');
linkUrl = $('#clickableUrl').val();
window.location.href = linkUrl + '?temp_id=' + tempId;
});

$('#letter_template').change(function () {
var temp_id = $('#letter_template').val();
$.ajax({
type: "POST",
url: baseUrl + 'clients/getLetterTemplate',
data: {
tempId: temp_id
},
success: function (data) {
try {
// Process the response data and update the relevant element
$('#letterTemp').html(data);
// Remove the existing TinyMCE instance
tinymce.remove('#letter_message');
// Reinitialize TinyMCE on the updated textarea element
tinymce.init({
selector: '#letter_message',
branding: false,
menubar: false,
paste_as_text: true,
plugins: 'advlist autolink lists link image charmap preview
anchor table searchreplace autolink directionality visualblocks visualchars media
codesample charmap pagebreak nonbreaking anchor insertdatetime advlist wordcount
charmap emoticons autosave',
toolbar: 'undo redo print spellcheckdialog formatpainter |
blocks fontfamily fontsize| formatselect | bold italic underline forecolor
backcolor| table | link | alignleft aligncenter alignright alignjustify | outdent
indent | removeformat',
height: '500px',
setup: function (editor) {
editor.on('keyup', function () {
$("#letter-message-error").hide();
});
}
});
$("#filetype").select2({
width: '95%'
});
} catch (error) {
console.error(error); // Log any errors that occur during
processing
}
},
error: function (xhr, status, error) {
console.log(error); // Log the error for debugging purposes
}
});
});

$('.cancelLetterTemplate ').click(function () {
linkUrl = $('#clickableUrl').val();
window.location.href = linkUrl;
});

$('.letterSubmit').click(function (e) {
var content = tinymce.get("letter_message") ?
tinymce.get("letter_message").getContent() : '';
if (!content.trim()) {
swal("", 'Please add letter content', "error");
e.preventDefault();
} else {
$("#addTemplate").validate();
}
});
$("body").on('click', '.letterMergeVariable', function () {
$(this).parent().find(".custom-popover").toggle('fast');
});
$(document).on("click", "table.variables_table a.insert_field_val", function
(e) {
let el = e.target;
if (el.tagName !== "A") {
el = $(el).closest('a')[0];
}
e.preventDefault();
// $("#letter_message").summernote('insertText', "{"+$
(el).data('field_val')+"} ");
});

$('#note_template').change(function () {
$("#note-template-error").hide();
$('.loader').show();
$('body').css('pointer-events', 'none');
$.post(baseUrl + "clients/getNoteCategory/", {
category_id: $(this).val(),
note_id: $('#note_id').val(),
client_id: $('#client_id').val()
}, function (data) {
if (data) {
$('#NoteFormCategory').show().html(data);
if ($('#NoteFormCategory').find('.noteSelectBox')) {
$('.noteSelectBox').select2();
}
$('.datepickerField').each(function () {
var format = $(this).next('.dateFormatHidden').val();
$(this).datepicker({
show: true,
dateFormat: 'dd/mm/yy',
language: 'en',
changeMonth: true,
changeYear: true,
autoclose: true,
orientation: "bottom auto",
yearRange: '1900:' + (new Date().getFullYear() + 25),
}).on('changeDate', function (e) {
$(this).datepicker('hide');
});
});
if ($(".signature").length) {
var $sigdiv = $(".signature").jSignature();
}
}
$('body').css('pointer-events', 'initial');
$('.loader').hide();
});
});

if ($(".signature").length && !($('#edit_note').length)) {


var $sigdiv = $(".signature").jSignature();
}

$("body").on("click", ".clear", function (e) {


$(this).parent().parent().parent().find('.signature').jSignature("reset");
});

/*
categoryTextArea
* */
$("body").on("change", ".noteSelectBox, .noteOnChangeInputs, .episode_type",
function (e) {
console.log('am out');
$('.noteSelectBox, .noteOnChangeInputs , .episode_type').each(function () {
if ($(this).val()) {
console.log('am here');
$('#template_note_changed').val(1);
}
});
});
$("body").on("keyup", "#NoteFormCategory .note-editable,
#NoteFormCategory .noteInputs", function (e) {
$('#template_note_changed').val(1);
});
editNote = $('#editNote').val();
editLetter = $('#editLetter').val();
if (editNote == 1 || editLetter == 1) {
window.addEventListener('load',
function () {
$('#ClientNotesNew').trigger('click');
$('#read_notes').trigger('click');
}, false);
}
clientAppts = $('#clientAppts').val();
if (clientAppts) {
window.addEventListener('load',
function () {
$('#ClientAppointments').trigger('click');
}, false);
}

clientSales = $('#clientSales').val();
if (clientSales) {
window.addEventListener('load',
function () {
$('.clientSales').trigger('click');
}, false);
}

ClientInvoices = $('#clientInvoice').val();
if (ClientInvoices) {
window.addEventListener('load',
function () {
$('#ClientInvoices').trigger('click');
}, false);
}
clientMsg = $('#fromClientDetailsMsg').val();
if (clientMsg) {
window.addEventListener('load',
function () {
$('#clientSentMessages').trigger('click');
}, false);
}
// Delete Notes
$('.DeleteNotes').on('click', function () {
var noteId = $(this).attr('id').split('_')[1];
swal({
title: languageConversion('swalDeleteNoteTitle'),
text: languageConversion('swalDeleteNoteText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() + "clients/delete_note/" + $
('#client_id').val() + '/' + noteId, {
note: noteId
}, function (data) {
readNoteRedirect();
});
} else {
return 0;
}
});
});
/* End Note Section */
/* Client tag page */
$('#tags_1').tagsInput({
width: 'auto',
height: '200px'
});
/* Client List */
$(function () {

$('#tags_2').tagsInput({
autocomplete_url: $('#baseUrl').val() + 'clients/tagdata/' + $
('#noSystemTag').val(),
autocomplete: {
selectFirst: true,
width: '100px',
autoFill: true
},
'defaultText': 'Filter by tag',
'onAddTag': function () {
addTag2();
},
'onRemoveTag': function () {
addTag2();
}
});
});

// Client excel uploads


$('#upload-excel-file').on('change', function () {
$('.loader').show();
$('#excel-upload-form').submit();
});

/* Field Management */
$(".sortableBlock").sortable({
stop: function (event, ui) {
var order_count = 0;
$('.catBlock').each(function () {
var id = $(this).attr('id');
var categoryId = id.split('_')[1];
$.post($('#baseUrl').val() + 'clients/order_category/', {
'categoryId': categoryId,
'order_count': order_count,
'from': $('#from').val()
}, function (data) { });
order_count++;
});
},
cancel: ".disabled"
});
$("#sortable").disableSelection();
$('a.disable').click(function (event) {
event.stopPropagation();
});

$('.catContent').hide();

function addFields(main_div, value_div) {


var htmls = $('#ClientFieldsValue').html();
var str = htmls;
$('#' + main_div).append(str);
tax_fields += 1;
$("#" + main_div + " li:last-
child").find('label.numbering_tax').html(tax_fields + '.');
$("#" + main_div + " li:last-child").find('input').removeAttr('disabled');
}

function removeFields(node) {
$(node).remove();
}

$('#sortable').on('click', '.AddFields', function () {


var htmls = $('#ClientFieldsValue').html();
var id = $(this).attr('id');
var categoryId = id.split('_')[1];
$(this).parent().parent().find('.ClientFieldList').append(htmls);
$("[data-toggle=tooltip]").tooltip();
$
(this).parent().parent().find('.ClientFieldList').find('input').removeAttr('disable
d');
$
(this).parent().parent().find('.ClientFieldList .field_tag').attr('readonly',
'readonly');
$(this).parent().parent().find('.ClientFieldList .field_type').select2();
var fieldLength = $(this).parent().parent().find('.formElement').length;
$(this).parent().parent().find('.formElement').attr('data-id', categoryId);
$
(this).parent().parent().find('.formElement').last().find('input[name="noteFieldOrd
er[]"]').val(fieldLength);
$
(this).parent().parent().find('.ClientFieldList .field_type').last().val('text').se
lect2().trigger('change');
$('.box').find("input, select, textarea").
bind('mousedown.ui-disableSelection selectstart.ui-disableSelection',
function (e) {
e.stopImmediatePropagation();
});
$("[data-toggle=tooltip]").tooltip();
});
$('#sortable').on('click', '.AddFieldsOption', function () {
var htmls = $('#ClientFieldsOptionValue').html();
var field_tag = $(this).parent().parent().find('.field_tag').val() + '[]';
$(this).parent().parent().find('.fieldBlock ul.childField').append(htmls);
$("[data-toggle=tooltip]").tooltip();
$(this).parent().parent().find('.fieldBlock
ul.childField').find('input').removeAttr('disabled');
$(this).parent().parent().find('.fieldBlock
ul.childField').find('input').attr('name', field_tag);
$('.box').find("input, select, textarea").
bind('mousedown.ui-disableSelection selectstart.ui-disableSelection',
function (e) {
e.stopImmediatePropagation();
});
});

$('#sortable').on('click', '.field_name', function () {


var htmls = $('#ClientFieldsOptionValue').html();
var field_tag = $(this).val() + '[]';
$(this).parent().find('ul.childField').find('input').attr('name',
field_tag);
});

$('#sortable').on('click', '.RemoveFieldOption', function () {


$(this).parent().remove();
});

$('#sortable').on('click', '.RemoveField', function () {


$this = $(this);
swal({
title: languageConversion('swalDeleteFieldTitle'),
text: languageConversion('swalDeleteFieldText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$this.parent().parent().remove();
}
});
});

$('#sortable').on('click', '.hide', function () {


$("#sortable").bind('mousedown.ui-disableSelection selectstart.ui-
disableSelection', function (event) {
event.stopPropagation();
});
$(this).parent().parent().parent().find('.catContent').slideUp(1000);
$(this).parent().prev('div.shiftLeft').find('strong.catTitle').show();
$(this).parent().prev('div.shiftLeft').find('input.catTitle').hide();
$(this).removeClass('hide');
$(this).addClass('show');
$(this).html('<i class="fal fa-arrow-down"></i> Edit');
});

$('#sortable').on('click', '.show', function () {


$("#sortable").bind('mousedown.ui-disableSelection selectstart.ui-
disableSelection', function (event) {
event.stopImmediatePropagation();
});
$(this).parent().parent().parent().find('.catContent').slideDown(1000);
$(this).parent().parent().parent().find('input').attr('disabled');
$(this).parent().prev('div.shiftLeft').find('strong.catTitle').hide();
$(this).parent().prev('div.shiftLeft').find('input.catTitle').show();
$(this).removeClass('show');
$(this).addClass('hide');
$(this).html('<i class="fal fa-arrow-up"></i> Hide');
});

$('#sortable').on('click', '.default-value', function () {


var default_value = $(this).val();
var title = $(this).attr('default');
if (default_value == title) {
$(this).val('');
}
});

$('#sortable').on('blur', '.default-value', function () {


var default_value = $(this).value;
var title = $(this).attr('default')
if (this.value == '') {
$(this).val(title);
}
});

$('#sortable').on('click', '.deleteBtn', function () {


var id = $(this).attr('id');
var categoryId = id.split('_')[1];
var $this = $(this);
swal({
title: languageConversion('swalDeleteCategoryTitle'),
text: languageConversion('swalDeleteCategoryText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() + 'clients/delete_field_category/',
{
'categoryId': categoryId,
'from': $('#from').val()
}, function (data) {

$this.parent().parent().parent().parent().slideUp('slow').hide();
});
}
});
});

$('.addCatBtn').click(function () {
var $_this = $(this);
$.post($('#baseUrl').val() + 'clients/add_field_category/', {
category_title: $('#categoryTitle').val(),
'from': $('#from').val()
}, function (data) {
if (data != 'error') {
$('.sortableBlock').prepend(data);
var curCatId = $('#sortable').find('.catBlock').first().attr('id');
$('#' + curCatId).find('.AddFields').trigger('click');
categoryFieldSortable();
$('#categoryTitle').val('');
show_hide_toastr_message('successMessage',
languageConversion('categoryCreateSuccessMsg'));
} else {
swal({
title: languageConversion('error'),
text: languageConversion('categoryTitleValidationMsg'),
type: "warning",
showCancelButton: false,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('ok'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
return false;
}
});
}
});
});

$('#sortable').find('.activeCat').on('click', '.stat', function () {


$(this).parent('.catBlock').removeClass('activeCat');
$(this).parent('.catBlock').addClass('deactiveCat');
});
//field type change
$('body').on('change', '#sortable .field_type', function () {
var fieldType = $(this).val();
var parent = $(this).parent().parent().parent();
parent.find('.nameBlock').prop("type", "text");
if (fieldType == 'checkbox' || fieldType == 'select' || fieldType ==
'radio' || fieldType == 'toggle') {
sortOptionFields();
parent.find('.actionBtns .AddFieldsOption').show().trigger('click');
parent.find('.placeholderBlock .field_placeholder').val('');
parent.find('.placeholderBlock').css("visibility", "hidden");
} else if (fieldType == 'divider') {
parent.find('.nameBlock').prop("type", "number");
parent.find('.placeholderBlock .field_placeholder').val('');
parent.find('.placeholderBlock').css("visibility", "hidden");
} else if (fieldType == 'signature') {
parent.find('.placeholderBlock .field_placeholder').val('');
parent.find('.placeholderBlock').css("visibility", "hidden");
} else {
parent.find('.actionBtns .AddFieldsOption').hide();
parent.find('.placeholderBlock .field_placeholder').val('');
parent.find('.placeholderBlock').css("visibility", "visible").show();
parent.find('.childField').html('');
}
});
$('#sortable').on('click', '.saveFields', function () {
var id = $(this).attr('id');
var categoryId = id.split('_')[1];
var values = $('#cat_' + categoryId).find('input,select').serialize();
var fieldName = $('#cat_' + categoryId + "
input[name='field_name[]']").val();
var fieldType = $('#cat_' + categoryId + "
input[name='field_type[]']").val();
var categoryTitle = $('#cat_' + categoryId + "
input[name='category_title']").val();
var error = false;
var errorTitle = '';
$('#cat_' + categoryId + ' a').addClass('disable');
$('#cat_' + categoryId + ' button').attr('disabled', 'disabled');
//validate category title
if (!categoryTitle) {
error = true;
errorTitle = languageConversion('categoryTitleValidationMsg');
}
//validate field types
var fieldTypeArray = $('#cat_' + categoryId + "
select[name='field_type[]']").map(function () {
if (!this.value) {
error = true;
errorTitle = languageConversion('categoryFieldTypeValidationMsg');
}
if (this.value == 'select' || this.value == 'checkbox' || this.value ==
'radio') {
if (!$(this).parent().find('.field_options').length) {
error = true;
errorTitle =
languageConversion('categoryFieldOptionsValidationMsg');
}
}
return this.value;
}).get();
//validate field names
var inputArray = $('#cat_' + categoryId + "
input[name='field_name[]']").map(function () {
if (!this.value) {
error = true;
errorTitle = languageConversion('categoryFieldNameValidationMsg');
}
return this.value;
}).get();

var fieldTags = $('#cat_' + categoryId + "


input[name='field_tag[]']").map(function () {
return this.value;
}).get();
if (hasDuplicates(fieldTags)) {
error = true;
errorTitle = languageConversion('categoryFieldTagValidationMsg');
}
// validate field options
fieldTags.forEach(function (item, index) {
var optionArray = $(" input[name='" + item + "[]']").map(function () {
if (!this.value) {
error = true;
errorTitle =
languageConversion('categoryFieldOptionValidationMsg');
}
return this.value;
}).get();
});

if (!fieldName) {
error = true;
errorTitle = languageConversion('categoryFieldValidationMsg');
}

if (error || !fieldName) {
$('#cat_' + categoryId).addClass('error');
swal({
title: '',
text: errorTitle,
type: "warning",
showCancelButton: false,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('ok'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
return false;
}
});
$('#cat_' + categoryId + ' a').removeClass('disable');
$('#cat_' + categoryId + ' button').removeAttr('disabled');
return false;
}
$('#cat_' + categoryId).removeClass('error');
_this = $(this);
$.ajax({
url: $('#baseUrl').val() + 'clients/addFields',
type: "post",
data: values + "&from=" + $('#from').val(),
success: function () {
show_hide_toastr_message('successMessage',
languageConversion('customFieldCreateSuccessMsg'));
setTimeout(function () {
window.location.reload();
}, 2000);
},
error: function () { }
});
});

$('#sortable').on('keyup', '.field_name', function () {


var fieldVal = $(this).val();
if (/^[a-zA-Z0-9-_ ]*$/.test(fieldVal) == false) {
// alert('Field Name contains illegal characters.');
// return false;
}
var fieldVal = $(this).val().replace(/\s/g, "_").replace('.',
'_').replace('-', '_').replace(/[^a-zA-Z0-9-_ \s]/gi, '').toLowerCase();
var id = $(this).parent().parent().parent().parent().parent().attr('id');
if (!id) {
// For new category not sure but it works with 7 parent() only.
var id = $
(this).parent().parent().parent().parent().parent().parent().parent().attr('id');
}
var categoryId = id.split('_')[1];
fieldVal = getRandomFieldTag(fieldVal, categoryId);
$(this).parent().parent().find('.field_tag').val(fieldVal);
field_tag = fieldVal + '[]';
$(this).parent().parent().find('ul.childField').find('input').attr('name',
field_tag);
});

$('#sortable').on('click', '.deactivate', function () {


var id = $(this).attr('id');
var categoryId = id.split('_')[1];
$this = $(this);
$.post($('#baseUrl').val() + 'clients/deactivate_category/', {
'categoryId': categoryId,
'from': $('#from').val()
}, function (data) {
$('#cat_' + categoryId).removeClass('activeCat');
$('#cat_' + categoryId).removeClass('deactiveCat');
$this.removeClass('deactivate');
$this.addClass('activate');
$this.html('<i class="fal fa-check" aria-hidden="true"></i> Activate');
show_hide_toastr_message('successMessage',
languageConversion('categoryDeactivateSuccessMsg'));
});

});

$('#sortable').on('click', '.activate', function () {


var id = $(this).attr('id');
var categoryId = id.split('_')[1];
$this = $(this);
$.post($('#baseUrl').val() + 'clients/deactivate_category/', {
'categoryId': categoryId,
'activate': 1,
'from': $('#from').val()
}, function (data) {
$('#cat_' + categoryId).removeClass('activeCat');
$('#cat_' + categoryId).removeClass('deactiveCat');
$this.removeClass('activate');
$this.addClass('deactivate');
$this.html('<i class="fal fa-times" aria-hidden="true"></i>
Deactivate');
show_hide_toastr_message('successMessage',
languageConversion('categoryActivateSuccessMsg'));
});
});

$('.box').find("input, select, textarea").bind('mousedown.ui-disableSelection


selectstart.ui-disableSelection', function (e) {
e.stopImmediatePropagation();
});
/* End Field Management */
// Merge Client
if ($('#mergeClient').val() == 1) {
$('.blue-bg').show();
}
$('#mergeSave').click(function () {
var myRadio = $('input[name=merge_client_id]');
var checkedValue = myRadio.filter(':checked').val();
if (checkedValue) {
swal({
title: languageConversion('swalMergeClientTitle'),
text: languageConversion('swalMergeClientText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText:
languageConversion('swalMergeClientConfirmText'),
cancelButtonText: languageConversion('swalMergeClientCancelText'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
$('#formDeleteClient').submit();
} else {
return 0;
}
});
} else {
alert(languageConversion('mergeClientValidationMsg'));
}
});

$('#deleteClient').click(function () {
swal({
html: true,
title: $('#deleteTittle').val(),
text: $('#deletemsg').val(),
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('deleteConfirmButtonText'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
if (isConfirm) {
window.location.href = $('#deleteurl').val();
} else {
return 0;
}
}
});
});

//Function to validate clients have any appointments on removing business from


client details
$('.businessOptions').click(function () {
var clientId = $('#client_id').val();
var $this = $(this);
if ($this.prop("checked") === false) {
$.ajax({
type: "POST",
url: baseUrl + 'clients/validate-remove-business-from-clients/',
data: {
clientId: clientId,
businessId: $(this).val(),
},
success: function (data) {
if (data) {
swal({
title: '',
text: languageConversion('validateRemoveBusinessMsg'),
type: "warning",
confirmButtonColor: "#3ada25",
confirmButtonText: 'ok',
closeOnConfirm: true,
});
$this.trigger('click', true);
}
}
});
}
});

/* js for new Notes section*/

$(".note_user").on('change', function () {
var user_id = $(this).val();
loadUserAvatar(user_id);
});

if ($("#note_edit").val() == 1) {
loadUserAvatar($("#user_id").val());
}

$('.notedatepicker').datetimepicker({
show: true,
format: 'dd/MM/yyyy',
language: 'en',
pickTime: true,
showButtonPanel: true,
autoclose: true

}).on('changeDate', function (e) {


$(this).datetimepicker('hide');
var day = e.date.getDate();
var month = e.date.getMonth() + 1;
var year = e.date.getFullYear();
var displayDate = day + '/' + month + '/' + year;
$('.displayDate').html(displayDate);

});
$(".notedatepicker").on('click', function () {
var id = $(this).attr('id');
$('#' + id).datetimepicker('show');
});
$(".new-notes-tab-content .nav-link").on("click", function () {
// Check if the clicked tab is the "Letter" tab
if ($(this).attr("id") === "letter-note") {
$('#savesend').removeClass('d-none');
} else {
$('#savesend').addClass('d-none');
}
});

$('.client_tabs').on('click', function () {
$("#editNote").val(0);
var id = $(this).attr('id');
var isReadNotesTabClicked = $('#read_notes_li').hasClass('active');
if (isReadNotesTabClicked) {
$('.blue-bg').hide();
}
if (id == 'ClientNotesNew') {
$('.edit_single_episode').hide();
$(".notes-client-name").show();
$("#sub-chlidnav").hide();
$("#template_tags").val('');
$('#tags_5').val('');
$(".delete_note").hide();
$(".save_note").show();
$(".right-side-tabs").hide();
if ($("#client_id").val()) {
loadEpisodes($("#client_id").val());
loadUserAvatar($("#user_id").val());
}
} else {

if (id == 'ClientDetails') {
$('.blue-bg').show();
}

$(".notes-client-name").hide();
$("#sub-chlidnav").show();
}
});

$('.notes-container .nav-item').on('click', function () {


var ids = $(this).children('a').attr('id').split('-');
$("#note_type").val(ids[0]);
});

$('.notes-add-new').on('click', function () {
$.post($('#baseUrl').val() + 'clients/addEpisode', {
}, function (data) {
$("#addEpisode").modal('show');
$("#addEpisode").html(data);
});

});

$('.discharge-btn').on('click', function () {
$.post($('#baseUrl').val() + 'clients/addDischarge?discharge_id=' + $
("#discharge_id").val(), {
}, function (data) {
$("#addDischarge").modal('show');
$("#addDischarge").html(data);
});
});

$("body").on("click", "#add_episode", function (e) {


$("#new_episode").validate();
e.preventDefault();
if ($("#new_episode").valid()) {
$('.buttonDisable').attr('disabled', true);
$.ajax({
type: "POST",
url: $('#baseUrl').val() + 'clients/addEpisode',
data: $('#new_episode').serialize() + '&client_id=' + $
("#client_id").val(),
dataType: 'json',
success: function (data) {
if (data.success) {
if ($("#episode_edit").length && $("#episode_edit").val() >
0) {
show_hide_toastr_message('successMessage',
languageConversion('episodeUpdated'));
} else {
show_hide_toastr_message('successMessage',
languageConversion('newEpisodeAdded'));
}
loadEpisodes($("#client_id").val(), 0, data.new_episode);
$("#addEpisode").modal('hide');
$('.buttonDisable').attr('disabled', false);
$("#addEpisode").on('hidden.bs.modal', function () {
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
});
loadEpisodeFilter();
if ($("#episode_edit").val()) {
$('.blue-bg').hide();
loadClientNotes();
}
} else {
$('.buttonDisable').attr('disabled', false);
show_hide_toastr_message('errorMessage',
languageConversion('unableToAddEpisode'));
}
}
}, 'json')
}
});

$('#editLetterDraft').on('click', function (e) {


$('#editDraft').val(1);
});

$(".edit_letter").on('click', function (e) {


if ($('#locId').val() == 0) {
$('#letter-location-error').show();
return false;
}
if ($('#letterSub').val() == 0) {
$('#letter-subject-error').show();
return false;
}
if (tinymce.get('letter_message').getContent() === '') {
$('#letter-message-error').show();
return false;
}
var finalStatus = 1;
if ($('#editDraft').val() == 1) {
finalStatus = 0;
}
saveLetter(0, finalStatus);
});
function saveLetter(saveSend, finalStatus) {
var client_id = $('#clientId').val();
var email = $('#emailLetter').val();
var finalStatus = finalStatus;
var saveSend = saveSend;
var locId = $('#locId').val();
var letterDate = $('#letter_date').val();
var letterTemplate = $('#letter_template').val();
var filetype = $('#filetype').val();
var letterSub = $('#letterSub').val();
var editLetter = $('#edit_letter').val();
var letterMessage = tinymce.get('letter_message') ?
tinymce.get('letter_message').getContent() : '';
if (letterMessage) {
tinymce.get('letter_message').save();
}
var letterId = $('#letterId').val();
$('.btn-wrap button').prop('disabled', true);
$('.loader').show();
$.ajax({
type: "POST",
url: baseUrl + 'clients/saveEditLetters',
data: {
email: email,
clientId: client_id,
locId: locId,
letterDate: letterDate,
letterTemplate: letterTemplate,
filetype: filetype,
letterSub: letterSub,
letterMessage: letterMessage,
finalStatus: finalStatus,
saveSend: saveSend,
editLetter: editLetter,
letterId: letterId
},
success: function (data) {
$('.btn-wrap button').prop('disabled', false);
$('.loader').hide();
$('#emailCheck').addClass('d-none');
show_hide_toastr_message('successMessage',
languageConversion('letterSavedSuccessfully'));
readNoteRedirect(1);
$('#locId').val(0).trigger("change");
$('#letter_template').val(0).trigger("change");
$("#letterSub").val('');
tinymce.get('letter_message').setContent('');
}
})
}
$('.deleteLetter').on('click', function () {
var letterId = $('#letter_id').val();
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'clients/deleteLetters',
data: {
letterId: letterId
},
success: function (data) {
readNoteRedirect(1);
show_hide_toastr_message('successMessage',
languageConversion('swalDeleteLetterNotification'));
}
})
});
$('#saveEmailSned').on('click', function (e) {
$('#emailConfirmation').validate();
e.preventDefault();
if ($("#emailConfirmation").valid()) {
$('#emailConfirm').val(1);
saveLetter(1, 1);
}
});
$('.emailCancel').on('click', function (e) {
$('#emailCheck').modal('hide');
});
$('.emailCancel').on('click', function (e) {
$('#emailCheck').modal('hide');
});
$('#locId').on('change', function () {
$('#letter-location-error').hide();
});
$('#letterSub').on('keyup', function () {
$("#letter-subject-error").hide();
});

$('#savesend').on('click', function (e) {


if ($('#locId').val() == 0) {
$('#letter-location-error').show();
return false;
}
if ($('#letterSub').val() == 0) {
$('#letter-subject-error').show();
return false;
}
if (tinymce.get('letter_message').getContent() === '') {
$('#letter-message-error').show();
return false;
}
if ($('#emailAvailable').val() == 0) {
return;
}
saveLetter(1, 1);
});

$('#read_notes_li').click(function () {
$(".notesNavLink").first().trigger('click');
});
$('#add_new_note').click(function () {
clickedEventTriggered = false;
$('#text_note_changed').val(0);
});

$('.save_note').on('click', function (e, data) {


//don't show any error for draft if switching on a tab;
var notesNavLinkClick = data != null &&
data.hasOwnProperty('notesNavLinkClick');
var note_type = $('#note_type').val();
var save_type = $(this).attr('id');
var client_id = $("#client_id").val();
var discharge_id = $("#discharge_id").val();
if (note_type == 'letter') {
if ($('#locId').val() == 0) {
if (!notesNavLinkClick) {
$('#letter-location-error').show();
}
return false;
}
if ($('#letterSub').val() == 0) {
if (!notesNavLinkClick) {
$('#letter-subject-error').show();
}
return false;
}
if (tinymce.get('letter_message').getContent() === '') {
if (!notesNavLinkClick) {
$('#letter-message-error').show();
}
return false;
}
var finalStatus = 0;
if (save_type == 'final') {
finalStatus = 1;
}
saveLetter(0, finalStatus);
}
if (note_type == 'text' || note_type == 'payment' || note_type == 'credits'
|| note_type == 'appointment') {
document.getElementById("text_note_changed").value = "0";
if ($("#edit_note").length && $("#edit_note").val() == 1) {
var clientNote = tinymce.get('edit_client_note') ?
tinymce.get('edit_client_note').getContent() : '';
if (clientNote) {
tinymce.get('edit_client_note').save();
}
} else {
var clientNote = tinymce.get('note') ?
tinymce.get('note').getContent() : '';
if (clientNote) {
tinymce.get('note').save();
}
}
var draft_id = $('#draft_id').val();
var consent_check = 0;
if ($('#treatment_consent').is(":checked")) {
consent_check = 1;
}
//this will not get the global attachment id we need to be specific
on this
var attachmentId = $('#text-
notes').find('input.attachmentId').serialize();
if (!clientNote || $("<div/>").html(clientNote).text() == '') {
if (!notesNavLinkClick) {
$("#note-text-error").show();
$('.buttonDisable').attr('disabled', false);
}
return false;
} else {
$('.buttonDisable').attr('disabled', true);
$.post($('#baseUrl').val() + "clients/add_noteSubmit/", {
note: clientNote.replace('Consent to Treatment', ""),
client_id: client_id,
save_type: save_type,
note_date: $("input[name=text_note_date]").val(),
note_added_by: $("select[name=text_note_user]").val(),
episode: $("select[name=note_episode]").val(),
draft_id: draft_id,
attachmentId: attachmentId,
discharge: discharge_id,
consent: consent_check,
note_tags: $("#note_tags").val()
}, function (data) {
$('.buttonDisable').attr('disabled', false);
if (data > 0) {
$('#draft_id').val(data);
if ($("#edit_note").val() != 1) {
tinymce.get('note').setContent('');
}
$("div.episode-select-box
select").val("").trigger('change');
$("#note-text-error").hide();
if (!notesNavLinkClick) {
show_hide_toastr_message('successMessage',
languageConversion('notesSavedSuccessfully'));
readNoteRedirect();
}
} else {
$("#note-size-error").show();
}
});
}
} else if (note_type == 'template' || note_type == 'category') {
if (typeof tinymce !== 'undefined') {
var textAreas = document.querySelectorAll('.categoryTextArea');
textAreas.forEach(function(textArea) {
if (tinymce.get(textArea.id)) {
textArea.value = tinymce.get(textArea.id).getContent();
if (textArea.value) {
tinymce.get(textArea.id).save();
}
}
});
}
$('.buttonDisable').attr('disabled', true);
var draft_id = '';
if ($("#note_template").val() == 0) {
if (!notesNavLinkClick) {
$("#note-template-error").show();
}
$('.buttonDisable').attr('disabled', false);
return false;
}
if ($("#template_draft_id").val() > 0) {
draft_id = $("#template_draft_id").val();
}
var consent_check = 0;
if ($('#template_treatment_consent').is(":checked")) {
consent_check = 1;
}
$('.signature').each(function (e) {
if ($(this).is(':visible')) {
var sigData = $(this).jSignature('getData');
var baseValue = sigData.split(",");
var length = parseInt(sigData.length);
if (length >= 1950) {
$
(this).parent().parent().parent().find('.signatureData').val(baseValue[1]);
}
}
});

var formData = $('#save_template').serializeArray();


textAreas.forEach(function(textArea) {
formData.push({name: textArea.name, value: textArea.value});
});

$.ajax({
type: 'POST',
url: $('#baseUrl').val() + "clients/categoryNoteSubmit/",
data: $('#save_template').serialize() + '&client_id=' + client_id +
'&save_type=' + save_type + '&discharge=' + discharge_id + '&draft_id=' + draft_id
+ '&consent=' + consent_check,
success: function (data) {
$('.buttonDisable').attr('disabled', false);
if (notesNavLinkClick) {
if ($("#template_draft_id").val() <= 0 || $
("#template_draft_id").val() === '') {
var noteObj = JSON.parse(data);
$("#template_draft_id").val(noteObj.note_id)
}
}
if (!notesNavLinkClick) {
show_hide_toastr_message('successMessage',
languageConversion('notesSavedSuccessfully'));
readNoteRedirect();
}
}
});

} else if (note_type == 'attachment') {


var hasTags = false;
var serializeArray = $('#save_attachment').serializeArray();
serializeArray.forEach(r => {
if (r.name === "attachment_tags") {
hasTags = r.value !== "";
return;
}
});
var shouldSave = hasTags || $(".noteAttachmentIds").val() > 0;
if (!shouldSave) return;
var draft_id = $("#note_attachment_draft_id").val();
$('.buttonDisable').attr('disabled', true);
$.ajax({
type: 'POST',
url: $('#baseUrl').val() + "clients/saveAttachmentNote/",
data: $('#save_attachment').serialize() + '&client_id=' + client_id
+ '&save_type=' + save_type + '&discharge=' + discharge_id + '&draft_id=' +
draft_id,
success: function (data) {
$('.buttonDisable').attr('disabled', false);
$("#note_attachment_draft_id").val(data);
if (!notesNavLinkClick) {
show_hide_toastr_message('successMessage',
languageConversion('notesSavedSuccessfully'));
readNoteRedirect();
}
}
});
} else if (note_type == 'bodychart' || note_type == 'body_chart') {
var draft_id = '';
if ($('#body_chart_note_draft_id').val()) {
draft_id = $('#body_chart_note_draft_id').val();
}

$('.buttonDisable').attr('disabled', true);
var bodyChartLength = $('#bodychart_listBodyChart .attach-file').length
if (!bodyChartLength) {
$('#body-chart-error').show();
$('.buttonDisable').attr('disabled', false);
return false;
}
$.ajax({
type: 'POST',
url: $('#baseUrl').val() + "clients/saveBodyChartNote/",
data: $('#save_bodychart').serialize() + '&client_id=' + client_id
+ '&save_type=' + save_type + '&discharge=' + discharge_id + '&draft_id=' +
draft_id,
success: function (data) {
$('#body_chart_note_draft_id').val(data);
if (!notesNavLinkClick) {
show_hide_toastr_message('successMessage',
languageConversion('notesSavedSuccessfully'));
readNoteRedirect();
}
$('.buttonDisable').attr('disabled', false);
}
});
}
});
$('.allNoteTags').tagsInput({
'onAddTag': function () {
addNoteTag($(this).attr('id'));
},
'onRemoveTag': function () {
addNoteTag($(this).attr('id'));
}
})

$('.note-attachment').on('click', '.deleteAttachment', function () {


clnt_id = client_id;
var att_id = $(this).attr('id').split('_')[1];
$this = $(this);
swal({
title: languageConversion('deleteAttachment'),
text: languageConversion('deleteConfirmation'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() + 'clients/ajax_removenotes/', {
id: att_id,
client_id: clnt_id
}, function (data) {
$("#attachmentDiv_" + att_id).remove();
$this.parent().parent().remove();
});
}
});
});

$("body").on("click", "#add_discharge", function (e) {


$("#new_discharge").validate();
e.preventDefault();
if ($("#new_discharge").valid()) {
$.ajax({
type: "POST",
url: $('#baseUrl').val() + 'clients/addDischarge',
data: $('#new_discharge').serialize() + '&client_id=' + $
("#client_id").val(),
dataType: 'json',
success: function (data) {
if (data.success) {
show_hide_toastr_message('successMessage',
languageConversion('clientDischarged'));
$("#discharge_id").val(data.dischargeId);
$("#addDischarge").modal('hide');
$("#addDischarge").on('hidden.bs.modal', function () {
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
});
} else {
show_hide_toastr_message('errorMessage',
languageConversion('unableToDischarge'));
}
}
}, 'json')
}
});

$(".main-notes-tab").on('click', function () {
if ($(this).children('a').attr('href') == '#read-notes') {
$('#current_note_view').val('read_notes_view');
$('.blue-bg').hide();
$(".right-side-tabs").show();
$(".read-subs").addClass('fade');
$(".read-nav-tabs").removeClass('active');
$("#all-nav-tab").addClass('active');
$("#read_note_type").val('all');
$(".export_note").hide();
$('.notesAllSelect').hide();
$('.selectAllNotes').prop("checked", false);
$(".noteAlert").addClass('readNoteAlert');
loadClientNotes();
} else {
$('#current_note_view').val('new_notes_view');
var displayDate = $("#today_date").val();
$('.displayDate').html(displayDate);
$('.default-datepicker-input').val(displayDate);
$('.notedatepicker').datetimepicker('setDate', displayDate);
$('.blue-bg').show();
$('.edit_single_episode').hide();
$(".delete_note").hide();
$(".export_note").hide();
$(".save_note").show();
$(".right-side-tabs").hide();
$('.notesAllSelect').hide();
$('.selectAllNotes').prop("checked", false);
$(".noteAlert").removeClass('readNoteAlert');
}
});

$('.selectAllNotes').on('click', function (e) {


var prop = true;
if (!$(this).prop("checked")) {
prop = false;
}
$('.delete_notes_id , .episode_edit_delete, .deleteLetterId').each(function
() {
if (prop) {
$(this).closest('li').addClass('checked');
} else {
$(this).closest('li').removeClass('checked');
}
$(this).prop("checked", prop);
});
showHideDelet();
});

// Filter click
$(".open-filter").on('click', function () {
var effect = 'slide';
var options = {
direction: 'left'
};
var duration = 1;
$('.filter-widget').toggle(effect, options, duration, function () {
$('.new-filter-wrap').toggleClass('slider-open');
$(this).toggleClass('opened');
$('.filter-widget').css('visibility', 'visible');
if ($('.new-filter-wrap').hasClass('slider-open')) {
$('.open-filter').find('i').removeClass('fa-angle-right');
$('.open-filter').find('i').addClass('fa-angle-left');
setCookie('noteFilterOpened', 'yes', 1);
} else {
setCookie('noteFilterOpened', 'no', 1);
$('.open-filter').find('i').removeClass('fa-angle-left');
$('.open-filter').find('i').addClass('fa-angle-right');
}
});
});

$(".read-nav-tabs").on('click', function () {
$(".read-subs").addClass('fade');
var selection = $(this).children('a').attr('href').replace('#', '');
$("#read_note_type").val(selection);
$('.blue-bg').hide();
loadClientNotes();
$("#navtab-ul").removeClass('in');
$("#navtab-ul").addClass('collapse');
});

function showHideDelet() {
let lockedFalg = false;
$("#read_notes_div input.delete_notes_id:checkbox:checked").each(function
(e) {
if ($(this).data('note_final_status') === 1) {
lockedFalg = true;
return false;
}
});
if (lockedFalg) {
$('.delete_note').hide();
} else {
$('.delete_note').show();
}
}

$("body").on("change", '#read_notes_div .filter-right-checkbox .checkbox


input[type=checkbox]', function (e) {
checkedLen = $('.filter-right-tab .filter-right-checkbox .checkbox
input[type=checkbox]:checked').length;
let letters = $("#read_notes_div
input.deleteLetterId:checkbox:checked").length;
if ($(this).prop("checked") == true) {
$(this).parents('li').addClass('checked');
} else {
$(this).parents('li').removeClass('checked');
}
if (checkedLen > 0) {
$('.blue-bg').show();
$('.save_note').hide();
$('.save_send').hide();
$(".export_note").show();
$('.notesAllSelect').show();
$('.selectAllNotes').prop("checked", false);
if ($("#read_note_type").val() == 'episodes') {
$(".edit_single_episode").show();
} else {
$(".edit_single_episode").hide();
}
} else {
$('.blue-bg').hide();
$(".edit_single_episode").hide();
$(".export_note").hide();
$('.notesAllSelect').hide();
$('.selectAllNotes').prop("checked", false);
$(this).parents('li').removeClass('checked');
}
if (letters > 0) {
$(".export_note").hide();
}
showHideDelet();
});

$('.user-checkbox').on('click', function () {
totalCheckbox = $('.user-checkbox').length;
checkedLength = $('.user-checkbox:checked').length;
if (totalCheckbox > checkedLength) {
$('input#user-checkobx-chekall').removeAttr('checked');
} else if (totalCheckbox == checkedLength) {
$('input#user-checkobx-chekall').prop('checked', 'checked');
}
if (checkedLength == 0) {
$('input.first-checkbox').prop('checked', 'checked');
}
loadClientNotes();
});

$("body").on("click", '.episode-checkbox', function (e) {


totalCheckbox = $('.episode-checkbox').length;
checkedLength = $('.episode-checkbox:checked').length;
if (totalCheckbox > checkedLength) {
$('input#episode-checkbox-checkall').removeAttr('checked');
} else if (totalCheckbox == checkedLength) {
$('input#episode-checkbox-checkall').prop('checked', 'checked');
}
loadClientNotes();
});

$('#user-checkobx-chekall').click(function () {
if ($(this).is(':checked')) {
$('input.user-checkbox').prop('checked', 'checked');
} else {
$('#user-checkobx-chekall').removeAttr('checked');
$('input.first-checkbox').prop('checked', 'checked');
}
loadClientNotes();
});

$("body").on("click", '#episode-checkbox-checkall', function (e) {


if ($(this).is(':checked')) {
$('input.episode-checkbox').prop('checked', 'checked');
}
loadClientNotes();
});

$("body").on("click", '.notes-paging', function (e) {


var page_id = $(this).attr('page');
loadClientNotes(page_id);
});

$("body").on("click", '.notes-view-text', function (e) {

var episode_id = $(this).attr('id').split('_')[2];


$('input#episode-checkbox-checkall').removeAttr('checked');
$("#read_note_type").val('all');
$(".episode-checkbox").removeAttr('checked');
$("input#episode-" + episode_id).prop('checked', 'checked');
$(".read-nav-tabs").removeClass('active');
$("#all-nav-tab").addClass('active');
loadClientNotes();
});

$("body").on("change", '#final_notes_filter', function (e) {


if ($(this).prop('checked')) {
$("#final_status").val(1);
final_status = 1;
} else {
$("#final_status").val(0);
final_status = 0;
}
loadClientNotes();
});
$("body").on("click", 'input.episode_edit_delete', function (e) {
$('.episode_edit_delete').parents('li').removeClass('checked');
$('input.episode_edit_delete').not(this).prop('checked', false);
if ($(this).prop("checked") == true) {
$(this).parents('li').addClass('checked');
} else {
$(this).parents('li').removeClass('checked');
}
});

$(".edit_single_episode").on('click', function (e) {


var n = $("input.episode_edit_delete:checked").length;
if (parseInt(n) > 0) {
var episode = $("input.episode_edit_delete:checked").val();
$.post($('#baseUrl').val() + 'clients/addEpisode', {
episode_id: episode,
}, function (data) {
$("#addEpisode").modal('show');
$("#addEpisode").html(data);
});
} else {
show_hide_message('infoMessage', languageConversion('selectItemEdit'));
return false;
}
});

function deleteNotesAndEpisodes() {
$("#deleteNotesForm > input.note-id").remove();
$("#deleteNotesForm > input.episode-id").remove();
$("#read_notes_div input.delete_notes_id:checkbox:checked").each(function
(e) {
if ($(this).prop('checked')) {
$("<input type='hidden' class='note-id' name='note_id[]' value='" +
$(this).data("note_id") + "'/>").appendTo("#deleteNotesForm");
}
});
$("#read_notes_div
input.episode_edit_delete:checkbox:checked").each(function (e) {
if ($(this).prop('checked')) {
$("<input type='hidden' class='episode-id' name='episode_id[]'
value='" + $(this).data("episode_id") + "'/>").appendTo("#deleteNotesForm");
}
});
$.ajax({
type: "POST",
data: $("#deleteNotesForm").serialize(),
cache: false,
url: $("#deleteNotesForm").attr("action"),
success: function (data) {
loadClientNotes();
}
});
}
$(".delete_note").on('click', function (e) {
let notes = $("#read_notes_div
input.delete_notes_id:checkbox:checked").length;
let episodes = $("#read_notes_div
input.episode_edit_delete:checkbox:checked").length;
let letters = $("#read_notes_div
input.deleteLetterId:checkbox:checked").length;
var letterId = $("#read_notes_div
input.deleteLetterId:checkbox:checked").map(function () {
return this.value;
}).get();
if (letters > 0) {
swal({
title: languageConversion('swalDeleteLetterTitle'),
text: languageConversion('swalDeleteLetterText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'clients/deleteLetters',
data: {
letterId: letterId
},
success: function (data) {
show_hide_toastr_message('successMessage',
languageConversion('swalDeleteLetterNotification'));
readNoteRedirect(1);
}
})
} else {
return 0;
}
});
}
if (notes > 0 && episodes > 0) {
swal({
title: languageConversion('swalDeleteNoteEpisodeTitle'),
text: languageConversion('swalDeleteNoteEpisodeText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
deleteNotesAndEpisodes();
} else {
return 0;
}
});
} else if (episodes > 0) {
swal({
title: languageConversion('swalDeleteEpisode'),
text: languageConversion(episodes > 1 ? 'swalDeleteEpisodesText' :
'swalDeleteEpisodeText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
deleteNotesAndEpisodes();
} else {
return 0;
}
});
} else if (notes > 0) {
swal({
title: languageConversion('swalDeleteNoteTitle'),
text: languageConversion(notes > 1 ? 'swalDeleteNotesText' :
'swalDeleteNoteText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
deleteNotesAndEpisodes();
} else {
return 0;
}
});
}

});

$("body").on("click", '.export_note', function (e) {


var notes_ids = $("input.delete_notes_id:checked").length;
var episode_ids = $("input.episode_edit_delete:checked").length;
if (notes_ids || episode_ids) {
var note_ids = getNotesToExport();
$("#export_note_ids").val(note_ids);
var episode_ids = getEpisodesToExport();
$("#export_episode_ids").val(episode_ids);
$('#exportNotesForm').submit();
} else {
swal("", 'Please select a note to continue', "error");
return false;
}
});

$("body").on("click", '.auth_note_edit', function (e) {


var note_id = $(this).attr('id').split('_')[1];
$("#authNoteEdit").modal('show');
$("#auth_note_id").val(note_id);
$('.modal-blue-bg').show();
$("#auth_password").val('');
});

$('body').on('keyup keypress', '#auth_password', function (e) {


$('.note-password-error').hide();
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
e.preventDefault();
$("#auth_validate").trigger('click');
return false;
}
});

$("body").on("click", '.edit-redirect', function (e) {


e.preventDefault();
var url = $(this).data('url');
window.location.href = url;
});

$("body").on("click", '#auth_validate', function (e) {


$('.note-password-error').hide();
$("#note_validate").validate();
e.preventDefault();
if ($("#note_validate").valid()) {
$('.buttonDisable').attr('disabled', true);
$.ajax({
type: 'POST',
url: $('#baseUrl').val() + "clients/validateNoteEdit/",
data: $('#note_validate').serialize() + '&client_id=' + $
("#client_id").val(),
dataType: "json",
success: function (data) {
if (data.success) {
$("#authNoteEdit").modal('hide');
window.location.href = $('#baseUrl').val() +
'clients/edit_note/' + data.client_id + '/' + $("#auth_note_id").val();
} else {
$('.note-password-error').show();
$('.buttonDisable').attr('disabled', false);
}
}
});
$("#auth_note_id").val();
}
});

$("body").on("click", '.note-search', function (e) {


if ($("#search_notes").val() != '') {
loadClientNotes();
}
});

$("#search_notes").on('keyup', function () {
if (($("#search_notes").val() != '' && $("#search_notes").val().length > 3)
|| !$("#search_notes").val()) {
loadClientNotes();
}
});

$(".cancel_edit").on('click', function () {
readNoteRedirect();
});

setInterval(function() {
saveNoteDraft(clickedEventTriggered, true);
}, 5000);
setInterval(saveTemplateDraft, 5000);

$.validator.addMethod(
"australianDate",
function (value, element) {
// put your own logic here, this is just a (crappy) example
if (value) {
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
} else {
return true;
}
},
languageConversion('dateFormatError')
);
$('#clientAddForm,#form1').validate({
rules: {
myDate: {
australianDate: true
},
'businessId[]': {
required: true,
minlength: 1
}
},
messages: {
'businessId[]': {
required: "You must assign at least 1 business"
}
},
ignore: "checkbox:hidden",
errorPlacement: function (error, element) {
if (element.attr("name") == "teamMemberId[]") {
error.appendTo('.teamMembersCheck');
} else if (element.attr("name") == "businessId[]") {
error.appendTo('.businessCheck');
} else {
error.insertAfter(element);
}
}
});
$(".australianDate").datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1900:' + new Date().getFullYear().toString(),
maxDate: '-1d',
defaultDate: '01/01/2000'
});

//client and business association


if ($('#clientsPage').val() == 'clients') {
$('.delete_checkbox_id').on('change', function (e) {
var clientsNo = $('.delete_checkbox_id:checked').length;
if (clientsNo >= 2) {
$("#btnMerge").removeClass("d-none");
} else {
$("#btnMerge").addClass("d-none");
}
if ($(this).prop("checked") == true) {
manageClientIdsStorage($(this).val(), 'add');
} else {
$(this).prop("checked", false);
manageClientIdsStorage($(this).val(), 'remove')
localStorage.setItem('businessAssociateClientIds', '');
localStorage.setItem('selectAll', '');
}
checkedLen = $('.client-list-nav .clientlistTable .checkbox
input[type=checkbox]:checked').length;
var optionWrapMargin = 84;
var clientTablePadding = 84;
if (checkedLen > 0) {
$('.blue-bg').addClass('selected-action-nav');
$('.client-list-nav').addClass('selected');
var optionWrapHeight = $('.blue-bg').innerHeight();
clientTablePadding = clientTablePadding + optionWrapHeight;
} else {
$('.blue-bg').removeClass('selected-action-nav');
$('.client-list-nav').removeClass('selected');
}
if ($('body').hasClass('filter-opened')) {
var filterHeight = $('#filter-container').innerHeight();
clientTablePadding = clientTablePadding + filterHeight;
}
$('.fixed-header-bar .client-table.table-list.client-list-
nav').css('padding-top', clientTablePadding + 'px');
});

$('.clientSelectAll').on('click', function (e) {


var dataAction = $(this).attr('data-action');
var prop = true;
var action = 'deselect';
var text = 'Deselect All'

if (dataAction == 'deselect') {
prop = false;
action = 'select';
text = 'Select All';
}
$('.clientSelectAll').attr('data-action', action);
$('.clientSelectAll span').html(text);
$('#client-list .delete_checkbox_id:visible').each(function () {
$(this).prop("checked", prop);
if (prop) {
$(this).parents('tr').addClass('checked');
$('.client-list').addClass('selected');
manageClientIdsStorage($(this).val(), 'add');
localStorage.setItem('selectAll', 1);
} else {
$(this).parents('tr').removeClass('checked');
manageClientIdsStorage($(this).val(), 'remove');
localStorage.setItem('selectAll', '');
}
});
var clientsNo = $('.delete_checkbox_id:checked').length;
if (clientsNo >= 2 && dataAction != 'deselect') {
$("#btnMerge").removeClass("d-none");
} else {
$("#btnMerge").addClass("d-none");
}
});

if (localStorage.getItem('selectAll')) {
$('.client-list .option-wrap.blue-bg').show();
$('.clientSelectAll').trigger('click');
} else {
localStorage.setItem('businessAssociateClientIds', '');
}

$('.associateBusiness').on('click', function (e) {


if (localStorage.getItem('businessAssociateClientIds')) {
$("#associateClientsModal").modal("show");
} else {
swal({
title: '',
text: languageConversion('selectAtLeastOneClient'),
type: "warning",
showCancelButton: false,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('ok'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
return false;
});
}
});
$.validator.setDefaults({
errorPlacement: function (error, element) {
if (element.attr("name") == "businessId[]") {
error.appendTo('.businessCheck');
} else if (element.attr("name") == "teamMemberId[]") {
error.appendTo('.teamMembersCheck');
}
}
});
$('#associateClientForm').validate({
rules: {
'businessId[]': {
required: true,
minlength: 1
}
},
messages: {
'businessId[]': {
required: "You must check at least 1 business"
}
},
ignore: "checkbox:hidden",
});

$('body').on('submit', '#associateClientForm', function (e) {


e.preventDefault();
if ($('#associateClientForm').valid()) {
$('.saveAssociateClients').css('pointer-events', 'none');
var businessIds = '';
var clientIds = localStorage.getItem('businessAssociateClientIds');
$("input[name='businessId[]']:checked").each(function () {
businessIds = businessIds + this.value + ',';
});
businessIds = businessIds.replace(/,\s*$/, "");
$.ajax({
type: "POST",
url: baseUrl + 'clients/associateClientsWithBusiness',
data: {
businessIds: businessIds,
clientIds: clientIds,
},
success: function (data) {
$('.saveAssociateClients').css('pointer-events',
'inherit');
$("#associateClientsModal").modal("hide");
localStorage.setItem('businessAssociateClientIds', '');
localStorage.setItem('selectAll', '');
window.location.href = baseUrl + 'clients?type=active';
}
});
}
});
}

//Show Keep pill in merge client screen


$('.merge_client_radio').on('change', function () {
var clientId = $(this).val();
$(".keepPillSpan").addClass("hidden");
if ($(this).is(':checked')) {
$("#keepPillDiv_" + clientId).removeClass("hidden");
}
else {
$("#keepPillDiv_" + clientId).addClass("hidden");
}
});

$('#treatment_consent').on('change', function () {
if ($(this).is(":checked")) {
$("#NoteForm .note-editable").prepend('Consent to Treatment');
} else {
var k = $("#NoteForm .note-editable").html();
var h = k.replace('Consent to Treatment', "");
$("#NoteForm .note-editable").html(h);
}
});

$('body').on('click', '#clientRelationSave', function (e) {


var clientRelation = $('#clientRelationTypes').val();
var relatedClientId = $('#relatedClientId').val();
if ($('#clientRelation').val()) {
clientRelation = $('#clientRelation').val();
}
var clientRelationId = $('#clientRelationId').val();
$("#clientRelationViewModel").modal("hide");
$('#SelectedClientList').append('<input type="hidden"
name="clientRelation[]" value="' + clientRelation + '">' +
'<input type="hidden" name="clientRelationId[]" value="' +
clientRelationId + '">' + '</span>');
$("#clientRelationText_" + relatedClientId).text(' : ' + clientRelation);
});

$('#clientLinkSaves').click(function () {
$(".clientSearchRelation").css('visibility', 'visible');
});

$("body").on("click", '.clientRelationship', function () {


var client_id = $("#client_id").val();
var relation_id = $(this).data('client_code');
$.ajax({
type: "POST",
url: baseUrl + 'clients/getClientRelationPopup',
data: {
client_id: client_id,
relation_id: relation_id,
},
success: function (data) {
$('#clientRelationViewModel').html(data);
$("#clientRelationViewModel").modal("show");
$("#relatedClientId").val(relation_id);
}
})
});

$('body').on('click', '.addNewRelationship', function (e) {


$('.newClientRelation').removeClass('d-none');
});

$('body').on('change', '#clientRelationTypes', function (e) {


var clientRelationValue = $('#clientRelationValue').val();
if ($(this).val()) {
$('#clientRelation').val('');
} else {
$('#clientRelation').val(clientRelationValue);
}
});

$("#autosuggestClientRelation").autocomplete({
source: function (request, response) {
var searchText = $("#autosuggestClientRelation").val();
var ajaxUrl = $('#autosuggestUrl').val();
var client_id = $('#client_id').val();
$.ajax({
url: ajaxUrl,
data: {
searchtext: searchText.replace(/^0+/, ''),
relation: 1,
client_id: client_id,
},
dataType: "json",
type: "post",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.label,
value: obj.id,
dob: obj.dob,
};
}));
}
});
},
select: function (event, ui) {
var searchId = ui.item.value;
event.preventDefault();
ClientSearchRelation(searchId);
},
});

$("#SelectedClientList").on("click", ".removeRelatedClient", function () {


$(this).closest(".relatedClient").remove();
});

$(".removeRelatedClient").on("click", function () {
var relationClientId = $(this).attr("data-client_code");
var clientId = $('#client_id').val();
$(this).closest(".relatedClient").remove();
$.ajax({
type: "POST",
url: $('#baseUrl').val() + 'clients/deleteLinkedClients',
dataType: "JSON",
data: {
relationClientId: relationClientId,
clientId: clientId,
},
success: function (data) {
return true;
}
});
});

$("#discard_draft").on('click', function () {
var draftId = '';
if ($("#note_type").val() == 'template' || $("#note_type").val() ==
'category') {
draftId = $("#template_draft_id").val();
} else if ($("#note_type").val() == 'text') {
draftId = $("#draft_id").val();
}
if (draftId != '') {
$.post($('#baseUrl').val() + "clients/delete_note/" + $
('#client_id').val() + '/' + draftId, {}, function (data) {
if (data) {
$("#discard_draft").hide();
$('#treatment_consent').prop('checked', false);
$(".autosave_text").html('');
$(".autosave_text").hide();
$('#draft_id').val('');
$('#template_draft_id').val('');
$("#template_note_changed").val(0);
$("#text_note_changed").val(0);
$('.episode_type').val(null).trigger("change");
$('#note_template').val(null).trigger("change");
loadUserAvatar($("#user_id").val());
tinymce.get("note").setContent('');
$('.note-attachment').html('');
$('.note-editable').html('');
$('#NoteFormCategory').html('');
$("#note_template").val(0).trigger("change");
$("#template_tags").val('');
$('#tags_5').val('');
$('.tag').remove();
$('.buttonDisable').attr('disabled', false);
}
});
}
});

$('body').on('click', '.toggleBtn', function (e) {


$(this).parent().find('button').removeClass('active');
$(this).addClass('active');
var tag = $(this).attr('data-tag');
var value = $(this).attr('data-value');
$('input[name="' + tag + '"').val(value);
});

$('.edit-signature-button').on('click', function (e) {


if (!($(this).parent().find('.display-signature-box').is(':visible'))) {
$(this).parent().find('.display-signature-box').show();
var $sigdiv = $(this).parent().find(".signature").jSignature();
}
});

$(document).on('click', '.client-merge-row', function () {


$(this).find('td input[type=radio]').click();
});

//delete form check box click


$('body').on('click', '.delete_form_checkbox', function (e) {
var count = $('.delete_form_checkbox:checked').length;
if (count) {
$('.option-wrap.action-client-form').show();
$('.form-table.action-nav-setup-forms').addClass('blueBgOpen');
} else {
$('.option-wrap.action-client-form').hide();
$('.form-table.action-nav-setup-forms').removeClass('blueBgOpen')
}
});
//delete form
$('body').on('click', '.deleteClientForm', function (e) {
var clientId = [];
var formId = [];
var attemptId = [];
var setupForm = $(this).hasClass('setUpForm') ? 1 : 0;
$('.delete_form_checkbox:checked').each(function () {
clientId.push($(this).val());
formId.push($(this).attr('data-form-id'));
attemptId.push($(this).attr('data-attempt-id'));
})
swal({
title: languageConversion('deleteConfirmTitle'),
text: languageConversion('deleteFormMsg'),
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('deleteConfirmButtonText'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
if (isConfirm) {
if (!setupForm) {
$('.loader').show();
}
$.ajax({
type: "POST",
url: baseUrl +
'client_intake_form/deleteCompletedForm',
data: {
clientIds: clientId,
formIds: formId,
attemptIds: attemptId
},
success: function (data) {
show_hide_toastr_message('successMessage',
languageConversion('formDeleteSuccessMsg'));
if (setupForm) {
location.reload();
} else {
$('#clientIntakeForms').trigger('click');
}
}
})
} else {
return false;
}
}
});
});
// us mobile number formatting issue fix
if (($('#mobile').length && $('#mobile').val() && $('#mobile_code').val() ==
'us')) {
window.iti.setNumber($('#mobile').val());
}
$('body').on('click', '.viewInvoice', function () {
var clientInvNumber = $(this).attr('fromClientInvNumber');
$('.invoice-search-wrap input#invoiceautosuggest').val(clientInvNumber);
searchInvoiceById(clientInvNumber);
$('#ClientInvoices').trigger('click', clientInvNumber);
});

$('.invoiceFilter').on('change', function () {
getClientInvoicesFilter();
});

// Function to get Client Invoices with Filters


function getClientInvoicesFilter() {
var query_string = '?type=' + $('#invoiceType').val() +
'&search_product_text=' + $('#invoiceautosuggest').val() +
'&invoiceFilterType=invoice' + '&sale_business_id=' + $('#sale_business_id').val()
+ '&sale_venu_id=' + $('#sale_venu_id').val() + '&date_range=' + $
('#invoice_date_range').val();
var clientId = $('#client_id').val();
var baseUrl = $('#baseUrl').val();
$('.loader').show();
$.post(baseUrl + 'invoices' + query_string, {
clientId: clientId,
// clientDetailsInvoice: 'true',
paging_data: 1
}, function (data) {
$('.loader').hide();
$('.ClientInvoiceBox').html(data).show();
if ($('#printInvoice').val() == 'yes' && $('#downloadedPdf').val() !=
1) {
pdf_path = 'pdf/download_pdf/' + client_id + '/' + $
('#paymentID').val();
$('#printInvoice').val('');
$('#paymentID').val('');
var path = baseUrl + pdf_path;
window.parent.location = path;
}
renderDateRangePicker('invoiceRange');
});
}

$('.paymentFilter').on('change', function () {
getClientPaymentsFilter();
});

// Function to get Client Payments with Filters


function getClientPaymentsFilter() {
var query_string = '?business_id=' + $('#payment_business_id').val() +
'&venu_id=' + $('#payment_venu_id').val() + '&user_id=' + $('#team_member').val() +
'&filter_category=' + $('#filter_product_category').val() + '&date_range=' + $
('#payment_date_range').val();
var clientId = $('#client_id').val();
var baseUrl = $('#baseUrl').val();
$('.loader').show();
$.post(baseUrl + 'payments' + query_string, {
clientId: clientId,
paging_data: 1
}, function (data) {
$('.loader').hide();
$('.ClientPaymentBox').html(data).show();
renderDateRangePicker('paymentRange');
});
}
$('.salesFilter').on('change', function () {
getClientSalesFilter();
});

$('.appointmentFilter').on('change', function () {
getClientappointmentFilter();
});

// Function to get Client Invoices with Filters


function getClientappointmentFilter() {
var clientId = $('#client_id').val();
var baseUrl = $('#baseUrl').val();
var appointment_business_id = $('#appointment_business_id').val();
var appointment_venu_id = $('#appointment_venu_id').val();
var appointment_product_category = $
('#appointment_product_category').val();
var appointment_date_range = $('#appointment_date_range').val();
var query_string = '?business_id=' + appointment_business_id + '&venu_id='
+ appointment_venu_id + '&product_category=' + appointment_product_category;
$('.loader').show();
$.post(baseUrl + 'booking/ajaxClientAppointment/1/' + client_id +
query_string, {
client_id: clientId,
date_range: appointment_date_range
}, function (data) {
$('.loader').hide();
$('.ClientAppointmentsBox').html(data).show();
renderDateRangePicker('appointmentRange');
});
var url = $("#client_apnt_export").attr("href");
url += query_string + '&date_range=' + appointment_date_range;
$("#export_apnt_btn").attr("href", url)
$("#export_apnt_btn").removeClass('d-none');
}

// Function to get Client Sales with Filters


function getClientSalesFilter() {
var page = 1;
var sale_business_id = $('#sales_business_id').val();
var select_type = $('#select_type').val();
var baseUrl = $('#baseUrl').val();
var clientId = $('#client_id').val();
var sale_venu_id = $('#sales_venu_id').val();
var product_category = $('#product_category').val();
var query_string = '?type=' + select_type + '&sale_business_id=' +
sale_business_id + '&sale_venu_id=' + sale_venu_id + '&product_category=' +
product_category + '&date_range=' + $('#sales_date_range').val();
$('.loader').show();
$.post(baseUrl + 'business/ajaxClientSales/' + page + query_string, {
client_id: clientId
}, function (data) {
if ($('#printInvoice').val() == 'yes' && $('#downloadedPdf').val() !=
1) {
pdf_path = 'pdf/download_pdf/' + client_id + '/' + $
('#paymentID').val();
$('#printInvoice').val('');
$('#paymentID').val('');
var path = baseUrl + pdf_path;
window.parent.location = path;
}
$('.ClientSalesBox').html(data);
$('.loader').hide();
renderDateRangePicker('salesRange');
});
var url = $("#client_sales_export").attr("href");
url += '&type=' + select_type + '&sale_business_id=' + sale_business_id +
'&sale_venu_id=' + sale_venu_id + '&product_category=' + product_category +
'&date_range=' + $('#sales_date_range').val();
$("#client_sales_btn").removeClass('d-none');
$("#client_sales_export").attr("href", url)
$("#client_sales_export").removeClass('d-none');
}
//share form popup
$('body').on('click', '.formShareBtn', function (e) {
var formId = $(this).attr('data-formid');
var attemptId = $(this).attr('data-formattemptid');
var clientId = $(this).attr('data-clientid');
var $this = $(this);
$this.find('.fal').removeClass('fa-share').addClass('fa-spinner fa-spin');
$('body').css('pointer-events', 'none');
$.ajax({
type: "POST",
url: baseUrl + 'client_intake_form/getSharePopup',
data: {
clientId: clientId,
formId: formId,
attemptId: attemptId
},
success: function (data) {
$('#shareFormPopup').html(data);
$('.shareFormPopup .select').select2();
$("#shareFormPopup").modal("show");
$this.find('.fal').removeClass('fa-spinner fa-spin').addClass('fa-
share');
$('body').css('pointer-events', 'initial');
$('.shareFormPopup #sendMessageType').trigger('change');
}
});
});
//send Form
$('body').on('click', '#proceedSendForm', function (e) {
$this = $(this);
$this.find('.fal').removeClass('fa-share').addClass('fa-spinner fa-spin');
$('body').css('pointer-events', 'none');
var formId = $('#sendShareFormId').val();
var attemptId = $('#shareFormAttemptId').val();
var clientId = $('#shareFormClientId').val();
var messageType = $('#sendMessageType').val();
var message = $('.shareFormPopup #message').val();
var smsContent = $('.shareFormPopup #smsEditor').val();
var subject = $('.shareFormPopup #shareFormEmailSubject').val();
$.ajax({
type: "POST",
url: baseUrl + 'client_intake_form/processShareForm',
data: {
formId: formId,
attemptId: attemptId,
clientId: clientId,
messageType: messageType,
message: message,
smsContent: smsContent,
subject: subject,
},
dataType: "json",
success: function (data) {
$this.find('.fal').removeClass('fa-spinner fa-spin').addClass('fa-
share');
$('body').css('pointer-events', 'initial');
$("#shareFormPopup").modal("hide");
$('#shareFormPopup').html('');
if (data.data.status == 'success') {
show_hide_toastr_message('successMessage', data.data.msg);
} else {
show_hide_toastr_message('errorMessage', data.data.msg);
}
}
});
});

//message type change for share form


$('body').on('change', '.shareFormPopup #sendMessageType', function (e) {
var messageType = $(this).val();
if (messageType == 'sms') {
$('.shareFormPopup .shareFormSubject').hide();
$('.shareFormPopup .emailContent').hide();
$('.shareFormPopup .smsContent').show();
} else if (messageType == 'email') {
$('.shareFormPopup .shareFormSubject').show();
$('.shareFormPopup .emailContent').show();
$('.shareFormPopup .smsContent').hide();
} else {
$('.shareFormPopup .shareFormSubject').show();
$('.shareFormPopup .emailContent').show();
$('.shareFormPopup .smsContent').show();
}
});

//filter sent messages of client


$('body').on('change', '#deliveryStatusDropdown, #messageTypeDropdown,
#messageStatusDropdown', function (e) {
getClientSentMessages();
});

$("#client_export_csv").on('click', function (e) {


e.preventDefault();
let url = $('#baseUrl').val();
url += "clients/export_client?";
url += location.search.substring(1);
window.open(url, '_blank').focus();
});
$("#client_export_iif").on('click', function (e) {
e.preventDefault();
$("#form_export_client_iif .filters").empty();
$("#more_filter .client_status
input.chk_client_status:checkbox:checked").each(function (e) {
$("#form_export_client_iif .filters").append("<input type='hidden'
name='client_status[]' value='" + $(this).val() + "' />");
});
$("#more_filter .lead_sources
input.chk_lead_source:checkbox:checked").each(function (e) {
$("#form_export_client_iif .filters").append("<input type='hidden'
name='lead_source_status[]' value='" + $(this).val() + "' />");
});
$("#more_filter .custom_sources
input.chk_custom_source:checkbox:checked").each(function (e) {
$("#form_export_client_iif .filters").append("<input type='hidden'
name='custom_source_status[]' value='" + $(this).val() + "' />");
});
$("#form_export_client_iif").submit();
});
$("#teamMemberAll").on('click', function (e) {

if ($("#teamMemberAll").prop('checked')) {

$("#team_members_row input.teamMemberIds").prop('checked', true);

});
let flag = true;
$("#team_members_row input.teamMemberIds").each(function (e) {
let checked = $(this).prop('checked');
flag = flag && checked;
});
$("#teamMemberAll").prop('checked', flag);
function renderDateRangePicker(id) {
var dateRangeOpen = datePickerRangeOpens();
$('#' + id).daterangepicker({
startDate: moment().subtract('days', $('#allDays').val()),
endDate: moment(),
showDropdowns: true,
showWeekNumbers: true,
timePicker: false,
timePickerIncrement: 1,
timePicker12Hour: true,
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1),
moment().subtract('days', 1)],
'Tomorrow': [moment().add('days', 1), moment().add('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'),
moment().subtract('month', 1).endOf('month')],
'All': [moment().subtract('days', $('#allDays').val()), moment()]
},
opens: dateRangeOpen,
buttonClasses: ['btn btn-default'],
applyClass: 'btn-small btn-primary',
cancelClass: 'btn-small',
format: 'MM/DD/YYYY',
separator: ' to ',
locale: {
applyLabel: 'Submit',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom Range',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
}
},
function (start, end) {
var startDate = start.format('MMMM D, YYYY');
var endDate = end.format('MMMM D, YYYY');
var allStart = moment().subtract('days', $
('#allDays').val()).format('MMMM D, YYYY');
var allEnd = moment().format('MMMM D, YYYY');
var dateValue = '';
if (startDate == allStart && endDate == allEnd) {
dateValue = 'All';
} else {
dateValue = startDate + ' - ' + endDate;
}
$('#' + id + ' span').html(dateValue);
if (id == 'invoiceRange') {
$("#invoice_date_range").val(dateValue);
getClientInvoicesFilter();
} else if (id == 'paymentRange') {
$("#payment_date_range").val(dateValue);
getClientPaymentsFilter();
} else if (id == 'salesRange') {
$("#sales_date_range").val(dateValue);
getClientSalesFilter();
} else if (id == 'appointmentRange') {
$("#appointment_date_range").val(dateValue);
getClientappointmentFilter();
} else if (id == 'messageRange') {
$("#message_date_range").val(dateValue);
getClientSentMessages();
} else if (id == 'billingInvoiceRange') {
$("#billing_invoice_date_range").val(dateValue);
getBillingInvoicesFilter();
}
});
}
$("#teamMemberAll").on('click', function (e) {
if ($("#teamMemberAll").prop('checked')) {
$("#team_members_row input.teamMemberIds").prop('checked', true);
}
});
$("#team_members_row input.teamMemberIds").on('click', function (e) {
$flag = true;
$("#team_members_row input.teamMemberIds").each(function (e) {
$flag = $flag && $(this).prop('checked');
});
$("#teamMemberAll").prop('checked', $flag);
});
$("#invoice_type").on('change', function (e) {
e.preventDefault();
$("#type").val($(e.target).val());
$("#clientSearchForm").submit();
});
$("#invoiceFilterType").on('change', function (e) {
e.preventDefault();
$("#autosuggest").val('');
});
$("#contact_submenu").on('change', function (e) {
window.location = $(this).find(':selected').data('url');
});
// delete invoice
$('body').on('click', '.delete-invoice', function () {
var thisElement = $(this);
var thisIdArray = $(this).attr('id').split('-');
var client_id = thisIdArray[1];
var payment_id = thisIdArray[2];

swal({
title: languageConversion('deleteConfirmTitle'),
text: languageConversion('invoiceDeleteConfirmMsg'),
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('deleteConfirmButtonText'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post(baseUrl + 'delete-invoice', {
payment_id: payment_id,
client_id: client_id,
my_token_name: $("input[name*='my_token_name']").val()
}, function (data) {
if (data == 'success') {
if ($('#type').val() == 'sales') {
location.reload();
}
thisElement.closest('tr').slideUp('slow');
} else {
swal("", languageConversion('cannotDeleteInvoice'),
"error");
}
});
}
});
});

//billing contact -> invoice page, set search placeholder text based on filter
type when changing filter type
$('#invoiceFilterType').on('change', function (e) {
setSearchPlaceholder();
});
setSearchPlaceholder();

//show popup to scan QR code


$('body').on('click', '.qr-form', function (e) {
var formUrl = $(this).attr('data-form-url');
$('.loader').show();
$('body').css('pointer-events', 'none');
$.ajax({
type: "POST",
url: baseUrl + 'client_intake_form/getQRPopup',
data: {
formUrl: formUrl
},
success: function (data) {
$('#qrFormPopup').html(data);
$("#qrFormPopup").modal("show");
$('.loader').hide();
$('body').css('pointer-events', 'initial');
}
});
});
$(".bootstrap-datetimepicker-widget .timepicker").hide();
//restore clients
$('body').on('click', '#restoreBtn', function (e) {
var countChecked = $('.delete_checkbox_id:checked').length;
swal({
title: languageConversion('deleteConfirmTitle'),
text: languageConversion('restoreClient'),
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('restoreAlert'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
if (parseInt(countChecked) > 0) {
$('#deleteCheckedForm').append('<input type="hidden"
name="restoreClient" value=1 />');
$('#deleteCheckedForm').submit();
} else {
show_hide_toastr_message('infoMessage',
languageConversion('checkRowMsg'));
}
}
});
})

$("#clientAddForm input#email").on('focusout', function () {


if ($(this).valid()) {
$("#clientAddForm button[name='submit']").prop('disabled', true);
$("#clientDetailsSave").prop('disabled', true);
validateClientEmail($(this)).then(function (result) {
if (result) {
$("#clientAddForm button[name='submit']").prop('disabled',
false);
$("#clientDetailsSave").prop('disabled', false);
$("#clientAddForm
label.remove_client_email_validation").remove();
} else if ($("#clientAddForm
label.remove_client_email_validation").length == 0) {
$("#clientAddForm input#email").after("<label
class='remove_client_email_validation'>Invalid Email. Continue? <span data-
submit_btn=\"" + "#clientAddForm button[name='submit']" + ", #clientDetailsSave\"
>Yes</span></label>");
}
});
}
});
});

$("#clientAddForm input#email").on('focusin', function () {


$("#clientAddForm label.remove_client_email_validation").remove();
});

function setSearchPlaceholder() {
let filterType = $('#invoiceFilterType').val();
let placeholderText = null;
if (filterType == 'client') {
placeholderText = 'Client First or Last Name';
} else if (filterType == 'mobile') {
placeholderText = 'Client Mobile Number';
} else if (filterType == 'invoice') {
placeholderText = 'Invoice Number';
} else if (filterType == 'contact') {
placeholderText = 'Billing Contact Name';
}
if (placeholderText) {
$('#autosuggest').attr('placeholder', placeholderText);
}
}
function manageClientIdsStorage(clientId, action) {
var businessAssociateClientIds =
localStorage.getItem('businessAssociateClientIds');
if (businessAssociateClientIds) {
var arrayClientIds = businessAssociateClientIds.split(',');
var inAarry = $.inArray(clientId, arrayClientIds);
if (inAarry > -1) {
if (action == 'remove') {
arrayClientIds.splice(inAarry, 1);
localStorage.setItem('selectAll', '');
}
} else {
if (action == 'add') {
arrayClientIds.push(clientId)
}
}
businessAssociateClientIds = arrayClientIds.join(',');
localStorage.setItem('businessAssociateClientIds',
businessAssociateClientIds);
} else if (action == 'add') {
localStorage.setItem('businessAssociateClientIds', clientId);
}
}

//Select a tab to view on load


if ($('#clientTabActive').val()) {
document.addEventListener("DOMContentLoaded", function () {
var clientTab = $('#clientTabActive').val();

if (clientTab == 'notes') {
$('#ClientNotesNew').click()
}
});
}

function removeNotes() {
var note_id = $("input.delete_notes_id:checked").val();
swal({
title: languageConversion('swalDeleteNoteTitle'),
text: languageConversion('swalDeleteNoteText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() + "clients/delete_note/" + $
('#client_id').val() + '/' + note_id, {
note: note_id
}, function (data) {
if (data) {
$(".blue-bg").hide();
loadClientNotes();
}
});
} else {
return 0;
}
});
}
function removeEpisode() {
var episode = $("input.episode_edit_delete:checked").val();
var note_count = $("#view_episode_" + episode).parent().find('span').html();
if (note_count == 0) {
swal({
title: languageConversion('swalDeleteEpisode'),
text: languageConversion('swalDeleteEpisodeText'),
type: "info",
showCancelButton: true,
confirmButtonColor: "#3ada25",
confirmButtonText: languageConversion('yes'),
cancelButtonText: languageConversion('cancel'),
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm == true) {
$.post($('#baseUrl').val() + "clients/delete_episode/", {
episode_id: episode
}, function (data) {
if (data) {
$(".blue-bg").hide();
loadClientNotes();

}
});
} else {
return 0;
}
});
} else {
swal("", languageConversion('swalEpisodeDeleteError'), "error");
return false;
}
}
var intervalId;
$("#open_non_modal_dialog").on("click", function () {
$("#client_modal").show();
var iframeDoc = $('#contentIframe')[0].contentWindow.document;
if ($(iframeDoc).find('#read_notes_li').length > 0) {
openReadNotes();
}
intervalId = setInterval(checkButtonInsideIframe, 100);
});

$("#close_non_modal_dialog").on("click", function () {
$("#client_modal").hide();
clearInterval(intervalId);
});

$("#expand_non_modal_dialog").on("click", function () {
if ($("#client_modal").outerWidth() == $(window).innerWidth() && $
("#client_modal").outerHeight() == $(window).innerHeight()-90) {
// If already maximized, restore to initial size
$('#expand_non_modal_dialog').find('i.fa-compress-alt').removeClass('fa-
compress-alt').addClass('fa-expand-alt');
var left = $("#client_modal").outerWidth()-($
("#client_modal").outerWidth()*70/100 + 80);
var top = $("#client_modal").outerHeight()-($
("#client_modal").outerHeight()*70/100 + 20);
$("#client_modal").animate({
left: left,
top: top,
width: '70%',
height: '70%',
});
} else {
// Otherwise, maximize
var height = $(window).innerHeight()-90;
$('#expand_non_modal_dialog').find('i.fa-expand-alt').removeClass('fa-
expand-alt').addClass('fa-compress-alt');
$("#client_modal").animate({
left: '0',
top: '90',
width: '100%',
height: height,
});
}
});

$('#contentIframe').on('load', function() {
var iframeDoc = $('#contentIframe')[0].contentWindow.document;
$(iframeDoc).find('#ClientNotesNew').click();
$(iframeDoc).find('#open_non_modal_dialog').hide();
});

function checkButtonInsideIframe() {
var iframeContent = $('#contentIframe')[0].contentWindow.document;
var buttonInsideIframe = $(iframeContent).find("#open_non_modal_dialog");
if (buttonInsideIframe.length) {
$(iframeContent).find('#open_non_modal_dialog').hide();
}
}

function openReadNotes(){
var iframeDoc = $('#contentIframe')[0].contentWindow.document;
$(iframeDoc).find('#read_notes_li').click();
$(iframeDoc).find('.main-notes-tab').click();
$(iframeDoc).find('#read_notes').addClass('active');
$(iframeDoc).find('.main-notes-tab').addClass('active');

$(iframeDoc).find('.main-notes-tab').removeClass('active');
$(iframeDoc).find('.read-notes-tab').addClass('active');
$(iframeDoc).find('.blue-bg').hide();
$(iframeDoc).find("#new-notes-tab").removeClass('active');
$(iframeDoc).find("#new-notes-tab").addClass('fade');
$(iframeDoc).find("#read-notes").removeClass('fade');
$(iframeDoc).find("#read-notes").addClass('active');
$(iframeDoc).find(".right-side-tabs").show();
$(iframeDoc).find(".read-subs").addClass('fade');
$(iframeDoc).find(".read-nav-tabs").removeClass('active');
$(iframeDoc).find("#all-nav-tab").addClass('active');
$(iframeDoc).find("#read_note_type").val('all');
$(iframeDoc).find("#discard_draft").hide();
}

dragElement(document.getElementById("client_modal"));

function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if ($('#' + elmnt.id + "header").length) {
//if present, the header is where you move the DIV from:
$('#' + elmnt.id + "header").on('mousedown', dragMouseDown);
} else {
//otherwise, move the DIV from anywhere inside the DIV
$(elmnt).on('mousedown', dragMouseDown);
}

function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
$(document).on('mouseup', closeDragElement);
// call a function whenever the cursor moves:
$(document).on('mousemove', elementDrag);
}

function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
$(elmnt).css('top', (elmnt.offsetTop - pos2) + "px");
$(elmnt).css('left', (elmnt.offsetLeft - pos1) + "px");
}

function closeDragElement() {
/* stop moving when mouse button is released:*/
$(document).off('mouseup', closeDragElement);
$(document).off('mousemove', elementDrag);
}
}
function readNoteRedirect(letter = null) {
if (($("#edit_note").length && $("#edit_note").val() == 1) || $
("#emailConfirm").val() || $('#edit_letter').val()) {
window.location.href = $("#notesEdit").val();
} else {
$('#treatment_consent').prop('checked', false);
$(".autosave_text").html('');
$(".autosave_text").hide();
$('#draft_id').val('');
$('#template_draft_id').val('');
$("#template_note_changed").val(0);
$("#text_note_changed").val(0);
$('.episode_type').val(null).trigger("change");
$('#note_template').val(null).trigger("change");
loadUserAvatar($("#user_id").val());
$('#note').val('');
$('.note-attachment').html('');
$('.note-editable').html('');
$('#NoteFormCategory').html('');
$("#note_template").val(0).trigger("change");
$("#template_tags").val('');
$('#tags_5').val('');
$('.tag').remove();
$('.buttonDisable').attr('disabled', false);

$('.main-notes-tab').removeClass('active');
$('.read-notes-tab').addClass('active');
$('.blue-bg').hide();
$("#new-notes-tab").removeClass('active');
$("#new-notes-tab").addClass('fade');
$("#read-notes").removeClass('fade');
$("#read-notes").addClass('active');
$(".right-side-tabs").show();
$(".read-subs").addClass('fade');
$(".read-nav-tabs").removeClass('active');
$("#all-nav-tab").addClass('active');
$("#read_note_type").val('all');
$("#discard_draft").hide();
loadClientNotes(0, letter);
}

}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}

function setCookie(name, value, days) {


var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function loadClientNotes(page_id, letter) {


$('.blue-bg').hide();
$(".loader").show();
var userIds = getCheckedUserIds();
var episodeIds = getCheckedEpisodeIds();
var page_no = 1;
if (page_id) {
page_no = page_id;
}
$.post($("#baseUrl").val() + 'clients/getNotes', {
userIds: userIds,
note_type: $("#read_note_type").val(),
client_id: $("#client_id").val(),
episodeIds: episodeIds,
date_range: $("#date_range").val(),
final_status: final_status,
page: page_no,
search_key: $("#search_notes").val(),
}, function (data) {
if (data) {
$(".loader").hide();
$('#read_notes_div').html(data);
if ($("#read_note_type").val() == 'notes' || $("#read_note_type").val()
== 'all')
$('.read-note-area').find('.note-editable').attr('contenteditable',
false);
$('.read-note-area').find('.note-statusbar').hide();
var window_height = $(window).height() - 230;
$('.note-scroll').css('height', window_height);
if ($("#date_range").val() == 'All') {
$('.ranges').find('li').removeClass('active');
// $('.ranges').find('li:contains("All")').addClass('active');
}
if ($('#current_note_view').val() == 'read_notes_view') {
$('.blue-bg').hide();
$('.delete_note').hide();
}
$(".edit_single_episode").hide();
$(".export_note").hide();
$('.notesAllSelect').hide();
$('.selectAllNotes').prop("checked", false);
// $(".read-nav-tabs").removeClass('active');
$("[data-toggle=tooltip]").tooltip();
if (letter) {
setTimeout(function () {
$('.letterTab').trigger('click');
$('#letter-tab').addClass('active');
$('#all-nav-tab').removeClass('active');
}, 100); // Adjust the delay (in milliseconds) as needed
}
if ($("#editLetter").val() == 1) {
$("#read_notes_li").addClass('active');
$("#add_new_note").removeClass('active');
$("#all-nav-tab").removeClass('active');
$('.letterTab').trigger('click');
$('.loader').hide();
$("#editLetter").val(0);
$('#text-notes').addClass('active');
}
}
});
}

function getCheckedUserIds() {
var userIds = [];
$.each($("input.user-checkbox:checked"), function () {
userIds.push($(this).attr('id').split('-')[1]);
});
return userIds.join(',');
}

function getCheckedEpisodeIds() {
var episodeIds = [];
$.each($("input.episode-checkbox:checked"), function () {
episodeIds.push($(this).attr('id').split('-')[1]);
});
return episodeIds.join(',');
}

function getEpisodesToExport() {
var episodeIds = [];
$.each($("input.episode_edit_delete:checked"), function () {
episodeIds.push($(this).val());
});
return episodeIds.join(',');
}

function getNotesToExport() {
var noteIds = [];
$.each($("input.delete_notes_id:checked"), function () {
noteIds.push($(this).val());
});
return noteIds.join(',');
}

function loadUserAvatar(user_id) {
$.post($('#baseUrl').val() + 'booking/getUserApppointmentColor/', {
user_id: user_id,
dataType: "json",
}, function (data) {
data = $.parseJSON(data);
if (data.picture) {
$('.note-avatar').removeClass('no-border');
$('.note-avatar').css('background-image', "url(" + data.picture + ")");
$('.note-avatar').show();
$('.no-avatar').hide();
} else if (data.initials) {
$('.note-avatar').hide();
$('.no-avatar').show();
$('.no-avatar').html(data.initials);
} else {
$('.no-avatar').hide();
$('.note-avatar').addClass('no-border');
$('.note-avatar').css('background-image', 'none');
}
});

if (user_id) {
$(".note_user").val(user_id);
}
setTimeout(function () {
$(".note_user").select2({ width: 150 });
});
}
function saveNoteDraft(clickedEvent, showTostr) {
if ($('#text_note_changed').val() == 1) {
if ($('#note_type').val() == 'text' || $('#note_type').val() == 'payment'
|| $('#note_type').val() == 'credits' || $('#note_type').val() == 'appointment') {
$('.buttonDisable').attr('disabled', true);
if ($("#note").length > 0) {
var note = tinymce.get("note") ? tinymce.get("note").getContent() :
'';
if (note) {
tinymce.get('note').save();
}
}
if ($("#note_edit").length > 0 && $("#note_edit").val() == 1) {
var note = tinymce.get('edit_client_note') ?
tinymce.get('edit_client_note').getContent() : '';
if (note) {
tinymce.get('edit_client_note').save();
}
}
if ($("<div/>").html(note).text() == '') {
if (!clickedEvent ) {
$("#note-text-error").show();
}
$('.buttonDisable').attr('disabled', false);
return false;
}
var consent_check = 0;
if ($('#treatment_consent').is(":checked")) {
consent_check = 1;
}
var attachmentId = $('#text-
notes').find('input.attachmentId').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: $('#baseUrl').val() + "clients/save_draft_note/",
data: {
client_id: $("#client_id").val(),
note: note.replace('Consent to Treatment', ""),
note_date: $("input[name=text_note_date]").val(),
note_added: $("select[name=text_note_user]").val(),
episode: $("select[name=note_episode]").val(),
draft_id: $('#draft_id').val(),
attachmentId: attachmentId,
consent: consent_check,
note_tags: $("#note_tags").val()
},
success: function (response) {
if (response.data.error) {
$("#note-size-error").show();
} else {
$("#note-size-error").hide();
$('#draft_id').val(response.data.note_id);
$('#text_note_changed').val(0);
$('.buttonDisable').attr('disabled', false);
if (showTostr) {
showToster('Your draft was saved at ' +
response.data.note_time, 'Draft Saved');
}
$("#discard_draft").show();
}
}
}, 'json');
}
}
}

function showToster(msg, title)


{
var overrides = {
timeOut: 2500,
"positionClass":"toast-bottom-right",
"showDuration": "300",
"hideDuration": "1000",
"extendedTimeOut": "500",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"

};

toastr.success(msg, title, overrides);

function saveTemplateDraft() {
if ($('#template_note_changed').val() == 1) {
if ($("#note_type").val() == 'template' || $("#note_type").val() ==
'category') {
$('.buttonDisable').attr('disabled', true);
var discharge_id = $("#discharge_id").val();
var consent_check = 0;
if ($('#template_treatment_consent').is(":checked")) {
consent_check = 1;
}
$('.signature').each(function (e) {
if ($(this).is(':visible')) {
var sigData = $(this).jSignature('getData');
var baseValue = sigData.split(",");
$
(this).parent().parent().parent().find('.signatureData').val(baseValue[1]);
}
});
$.ajax({
type: 'POST',
dataType: 'json',
url: $('#baseUrl').val() + "clients/categoryNoteSubmit/",
data: $('#save_template').serialize() + '&client_id=' + $
("#client_id").val() + '&save_type=draft&discharge=' + discharge_id + '&draft_id='
+ $("#template_draft_id").val() + '&consent=' + consent_check,
success: function (data) {
$('#template_draft_id').val(data.note_id);
$('#template_note_changed').val(0);
$('.buttonDisable').attr('disabled', false);
showToster('Your draft was saved at ' + data.note_time, 'Draft
Saved');
$("#discard_draft").show();
}
});
}
}
}
function autoSize(ele) {
ele.style.height = 'auto';
var newHeight = (ele.scrollHeight > 32 ? ele.scrollHeight : 32);
ele.style.height = newHeight.toString() + 'px';
}

function addTemplateTag() {
var tag_val = $('#tags_5').val();
$("#template_tags").val(tag_val);
}
function addNoteTag(element) {
var note_type = element.split('_')[1];
var tag_val = $('#' + element).val();
$("#" + note_type + "_tags").val(tag_val);
}

function updateNoteSection() {
var date_range = $('#date_range').val();
var client_id = $('#client_id').val();
$('.loader').show();
$.post($('#baseUrl').val() + "clients/ajaxNoteListing/" + client_id + "?
date_range=" + date_range, function (data) {
if (data) {
$('#noteListing').html(data);
}
$('.loader').delay(100).fadeOut(1000);
});
}

//Function to check duplicates in an array


function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}

function loadEpisodes(client_id, from, new_episode) {


var episode_param = 'Episode';
if ($("#site_param").val() == '0') {
episode_param = 'Project';
}
if (client_id) {
$.ajax({
type: "POST",
url: $('#baseUrl').val() + 'clients/getEpisodes',
data: { client_id: client_id },
dataType: 'json',
success: function (data) {
var k = '<option value="" title="">' +
languageConversion('selectEpisode', episode_param) + '</option>';
if (data) {

$.each(data, function (key, value) {


var check_variable = "";
if (new_episode == value.episode_id) {
check_variable = "selected = selected";
}
k = k + '<option value="' + value.episode_id + '" ' +
check_variable + ' title=" ">' + value.episode_name + '</option>';
});
}
if (from == 1) {
$(".discharge_episode_type").html(k);
$(".discharge_episode_type").select2({ width: 'auto' });

} else {
$(".episode_type").html(k);
$(".episode_type").select2({ width: 'auto' });
}
}
}, 'json')
}
}

function loadEpisodeFilter() {
$.post($('#baseUrl').val() + 'clients/getEpisodeFilter', {
client_id: $('#client_id').val()
}, function (data) {
$('#episode_filter').html(data);

});
}

function ClientSearchRelation(searchId) {
var clientSearch = $('#autosuggestClientRelation').val();
var client_id = $("#client_id").val();
var user_id = $("#user_id").val();
var parent_user_id = $("#parent_user_id").val();
var relation_id = searchId;
var added_by = $("#user_id").val();
var baseUrl = $('#baseUrl').val();
$('.selectedClient').each(function () {
var $this = $(this).val();
if ($this == relation_id) {
swal({
title: "error",
text: 'Client is already selected',
type: "error",
showCancelButton: false,
confirmButtonColor: "#3ada25",
confirmButtonText: "Ok",
closeOnConfirm: true,
closeOnCancel: true
});
$(this).closest(".relatedClient").remove();
}
});
$.ajax({
type: "POST",
dataType: 'json',
url: baseUrl + 'clients/addClientLink',
data: {
client_id: client_id,
user_id: user_id,
parent_user_id: parent_user_id,
relation_id: relation_id,
added_by: added_by,
clientSearch: clientSearch,
},
success: function (data) {
if (data == false) {
swal({
title: "error",
text: 'Already linked client.',
type: "error",
showCancelButton: false,
confirmButtonColor: "#3ada25",
confirmButtonText: "Ok",
closeOnConfirm: true,
closeOnCancel: true
});
} else {
var relationId = data.clientId;
var clientName = data.clientName;
var dob = data.dob;
if (!dob || dob == '00/00/0000') {
dob = '';
} else {
dob = '(' + dob + ')';
}
$('#SelectedClientList').append('<div class="relatedClient d-flex
justify-content-between mb-3"><input type="hidden" class="selectedClient"
name="relationId[]" value="' + relationId + '">' +
'<div class="d-flex"><a href="' + data.clientLink + '"
id="link" style="cursor: pointer;" target="_blank" data-client_code="' + relationId
+ '">' + clientName +
'<span>' + '&nbsp;&nbsp;' + dob + '</span> <span
id="clientRelationText_' + relationId + '"></span></a></div>' +
'<div><a data-toggle="tooltip" data-placement="top" title="Add
Client Relationship" href="javascript:void(0);" class="mr-4 clientRelationship"
id="ClientRelation" data-client_code="' + relationId + '"><i class="fal fa-
link"></i></a>' + '</span>' +
'<span>' + '<a data-toggle="tooltip" data-placement="top"
title="Remove" href="javascript:void(0);" class="removeRelatedClient"
id="removeRelatedClient" data-client_code="' + relationId + '"><i class="fal fa-
times"></i></a>' + '</span></div></div>');
$("[data-toggle=tooltip]").tooltip();
}
}
});
$("#autosuggestClientRelation").val('');
}

//Function to check field tag exists or not


function isFieldTagExist(categoryId, fieldTag) {
var exists = false;
$('#cat_' + categoryId + " input[name='field_tag[]']").each(function () {
if ($(this).val() == fieldTag) {
exists = true;
return;
}
})
return exists;
}
//get field tag with unique code
function getRandomFieldTag(fieldTag, categoryId) {
var newFieldTag = fieldTag + '_' + Math.random().toString(36).substr(2,
9).toLowerCase();
if (!isFieldTagExist(categoryId, newFieldTag)) {
return newFieldTag;
} else {
getRandomFieldTag(fieldTag, categoryId);
}
}

$("#invoiceautosuggest").autocomplete({
source: function (request, response) {
var searchText = $("#invoiceautosuggest").val();
var ajaxUrl = $('#invoiceAutosuggestUrl').val();
var clientId = $('#client_id').val();
$.ajax({
url: ajaxUrl,
data: {
searchtext: searchText.replace(/^0+/, ''),
searchType: 'invoice',
invoiceFilterType: 'invoice',
clientId: clientId
},
dataType: "json",
type: "post",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.label,
value: obj.id,
};
}));
}
});
},
select: function (event, ui) {
event.preventDefault();
searchInvoiceById(ui.item.value);
},
});
function searchInvoiceById(value) {
if (value) {
$('.invoice-search-wrap input#invoiceautosuggest').val(value);
var query_string = '?type=' + $('#invoiceType').val() +
'&search_product_text=' + value + '&invoiceFilterType=invoice' +
'&sale_business_id=' + $('#sale_business_id').val() + '&sale_venu_id=' + $
('#sale_venu_id').val() + '&date_range=' + $('#invoice_date_range').val();
var clientId = $('#client_id').val();
var baseUrl = $('#baseUrl').val();
$('.loader').show();
$.post(baseUrl + 'invoices' + query_string, {
clientId: clientId,
// clientDetailsInvoice: 'true',
paging_data: 1
}, function (data) {
$('.loader').hide();
$('.ClientInvoiceBox').html(data).show();
});
}
}

$("#paymentautosuggest").autocomplete({
source: function (request, response) {
var searchText = $("#paymentautosuggest").val();
var ajaxUrl = $('#paymentAutosuggestUrl').val();
var clientId = $('#client_id').val();
$.ajax({
url: ajaxUrl,
data: {
searchtext: searchText.replace(/^0+/, ''),
searchType: 'invoice',
invoiceFilterType: 'invoice',
clientId: clientId
},
dataType: "json",
type: "post",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.label,
value: obj.id,
};
}));
}
});
},
select: function (event, ui) {
event.preventDefault();
searchPaymentByInvoiceId(ui.item.value);
},
});
function searchPaymentByInvoiceId(value) {
if (value) {
$('.payment-search-wrap input#paymentautosuggest').val(value);
var query_string = '?business_id=' + $('#payment_business_id').val() +
'&venu_id=' + $('#payment_venu_id').val() + '&search_product_text=' + value +
'&paymentFilterType=invoice' + '&user_id=' + $('#team_member').val() +
'&filter_category=' + $('#filter_product_category').val() + '&date_range=' + $
('#payment_date_range').val();
var clientId = $('#client_id').val();
var baseUrl = $('#baseUrl').val();
$('.loader').show();
$.post(baseUrl + 'payments' + query_string, {
clientId: clientId,
paging_data: 1
}, function (data) {
$('.loader').hide();
$('.ClientPaymentBox').html(data).show();
});
}
}

function datePickerRangeOpens() {
var tabCount = $("#sub-chlidnav ul").find("li:visible").length;
var datePickerOpens = 'right';
if (tabCount > 4) {
var datePickerOpens = 'left';
}
return datePickerOpens;
}

//function for sorting option fields


function sortOptionFields() {
$('.childField').sortable();
}
$('.invDatepicker').each(function () {
id = $(this).attr('id');
$('#' + id).datetimepicker({
format: 'dd/MM/yyyy',
language: 'en',
pickTime: false,
showButtonPanel: false,
autoclose: true
}).on('changeDate', function (e) {
$(this).datetimepicker('hide');
var date_val = $(this).find('input.edit_date').val();
var invoiceId = $(this).parent().find('input.invoice_id').val();
var payment_id = $(this).parent().find('input.payment_id').val();
$.post(baseUrl + 'business/updateInvoiceDate/' + payment_id, {
date_val: date_val,
invoiceId: invoiceId,
updatePaymentId: payment_id,
my_token_name: $("input[name*='my_token_name']").val()
}, function (data) {
$('#displayInvoiceDate' + payment_id).html('Invoice Date: ' +
date_val);
$('#displayInvoiceDateMobile' + payment_id).html(date_val);
});
});
$(this).find('.fal').removeClass('icon-calendar');
});

$(function () {
var userId = $("#userId").val();
if (localStorage.getItem("filterStatus-" + userId) === 'open') {
$('.filter-nav').addClass('active');
$("#filter-container").show();
} else {
$('.filter-nav').removeClass('active');
$("#filter-container").hide();
}
filterShow = $('#filter-container').data('filter');
if ((getParam().char || getParam().tags || filterShow) &&
localStorage.getItem("filterStatus-" + userId) === 'close' && $
('#clientsPage').val() == 'clients') {
$('.filter-nav').addClass('clientFilterAppiled');
$('.filter-nav').attr('data-original-title',
languageConversion('clientFilterAppiled'));
}
});

//copy note description


$('body').on('click', '.copyNote', function (e) {
var noteId = $(this).attr('data-noteid');
var $temp = $("<input>");
var $this = $(this);
$("body").append($temp);
$temp.val($('#noteMessage_' + noteId).html()).select();
document.execCommand("copy");
$temp.remove();
$this.attr('data-original-title', 'Copied!');
$this.find('i').removeClass('fa-copy').addClass('fa-check');
$this.removeClass('copyNote');
setTimeout(function () {
$this.find('i').removeClass('fa-check').addClass('fa-copy');
$this.addClass('copyNote');
$this.attr('data-original-title', 'Copy Note Message');
}, 3000
);
});
$('body').on('click', '.duplicate-note', function (e) {
var noteId = $(this).attr('data-noteid');
var clientId = $('#client_id').val();
var draftId = $('#draft_id').val();
$.ajax({
url: baseUrl + 'clients/duplicateNote',
data: {
noteId: noteId,
clientId: clientId
},
dataType: "json",
type: "post",
success: function (data) {
if (data && data.url) {
window.location.href = data.url;
} else {
return 0;
}
}
});
});

// active select2 for client import fields


$(".uploadedList select").select2({ matcher: modelMatcher, width: 'auto' });

function modelMatcher(params, data) {


data.parentText = data.parentText || "";
// Always return the object if there is nothing to compare
if ($.trim(params.term) === '') {
return data;
}
// Do a recursive check for options with children
if (data.children && data.children.length > 0) {
var match = $.extend(true, {}, data);
for (var c = data.children.length - 1; c >= 0; c--) {
var child = data.children[c];
child.parentText += data.parentText + " " + data.text;
var matches = modelMatcher(params, child);
if (matches == null) {
match.children.splice(c, 1);
}
}
if (match.children.length > 0) {
return match;
}
return modelMatcher(params, match);
}
var original = (data.parentText + ' ' + data.text).toUpperCase();
var term = params.term.toUpperCase();
if (original.indexOf(term) > -1) {
return data;
}
// If it doesn't contain the term, don't return anything
return null;
}

You might also like