Performed major javascript refactoring for more consistncy and efficiency in the code base (work in progress)

This commit is contained in:
Alex Tselegidis 2020-05-06 19:15:11 +02:00
parent 466a3a3c20
commit c670c023a7
24 changed files with 1168 additions and 1057 deletions

View file

@ -29,39 +29,37 @@ window.BackendCalendar = window.BackendCalendar || {};
var $calendarPage = $('#calendar-page'); var $calendarPage = $('#calendar-page');
$calendarPage.on('click', '#toggle-fullscreen', function () { $calendarPage.on('click', '#toggle-fullscreen', function () {
var $target = $(this); var $toggleFullscreen = $(this);
var element = document.documentElement; var element = document.documentElement;
var isFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) var isFullScreen = document.fullScreenElement || document.mozFullScreen || document.webkitIsFullScreen;
|| document.mozFullScreen
|| document.webkitIsFullScreen;
if (isFullScreen) { if (isFullScreen) {
// Exit fullscreen mode. // Exit fullscreen mode.
if (document.exitFullscreen) if (document.exitFullscreen) {
document.exitFullscreen(); document.exitFullscreen();
else if (document.msExitFullscreen) } else if (document.msExitFullscreen) {
document.msExitFullscreen(); document.msExitFullscreen();
else if (document.mozCancelFullScreen) } else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen(); document.mozCancelFullScreen();
else if (document.webkitExitFullscreen) } else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen(); document.webkitExitFullscreen();
}
$target $toggleFullscreen
.removeClass('btn-success') .removeClass('btn-success')
.addClass('btn-default'); .addClass('btn-default');
} else { } else {
// Switch to fullscreen mode. // Switch to fullscreen mode.
if (element.requestFullscreen) if (element.requestFullscreen) {
element.requestFullscreen(); element.requestFullscreen();
else if (element.msRequestFullscreen) } else if (element.msRequestFullscreen) {
element.msRequestFullscreen(); element.msRequestFullscreen();
else if (element.mozRequestFullScreen) } else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen(); element.mozRequestFullScreen();
else if (element.webkitRequestFullscreen) } else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(); element.webkitRequestFullscreen();
}
$target $toggleFullscreen
.removeClass('btn-default') .removeClass('btn-default')
.addClass('btn-success'); .addClass('btn-success');
} }

View file

@ -29,34 +29,30 @@ window.BackendCalendarApi = window.BackendCalendarApi || {};
* *
* @param {Object} appointment Contain the new appointment data. The ID of the appointment MUST be * @param {Object} appointment Contain the new appointment data. The ID of the appointment MUST be
* already included. The rest values must follow the database structure. * already included. The rest values must follow the database structure.
* @param {Object} customer Optional, contains the customer data. * @param {Object} [customer] Optional, contains the customer data.
* @param {Function} successCallback Optional, if defined, this function is going to be executed on post success. * @param {Function} [successCallback] Optional, if defined, this function is going to be executed on post success.
* @param {Function} errorCallback Optional, if defined, this function is going to be executed on post failure. * @param {Function} [errorCallback] Optional, if defined, this function is going to be executed on post failure.
*/ */
exports.saveAppointment = function (appointment, customer, successCallback, errorCallback) { exports.saveAppointment = function (appointment, customer, successCallback, errorCallback) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_appointment'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_appointment';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
appointment_data: JSON.stringify(appointment) appointment_data: JSON.stringify(appointment)
}; };
if (customer !== undefined) { if (customer) {
data.customer_data = JSON.stringify(customer); data.customer_data = JSON.stringify(customer);
} }
$.ajax({ $.post(url, data)
url: url,
type: 'POST',
data: data,
dataType: 'json'
})
.done(function (response) { .done(function (response) {
if (successCallback !== undefined) { if (successCallback) {
successCallback(response); successCallback(response);
} }
}) })
.fail(function (jqXHR, textStatus, errorThrown) { .fail(function (jqXHR, textStatus, errorThrown) {
if (errorCallback !== undefined) { if (errorCallback) {
errorCallback(); errorCallback();
} }
}); });
@ -70,19 +66,16 @@ window.BackendCalendarApi = window.BackendCalendarApi || {};
* @param {Function} errorCallback The ajax failure callback function. * @param {Function} errorCallback The ajax failure callback function.
*/ */
exports.saveUnavailable = function (unavailable, successCallback, errorCallback) { exports.saveUnavailable = function (unavailable, successCallback, errorCallback) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
unavailable: JSON.stringify(unavailable) unavailable: JSON.stringify(unavailable)
}; };
$.ajax({ $.post(url, data)
type: 'POST', .done(successCallback)
url: postUrl, .fail(errorCallback);
data: postData,
success: successCallback,
error: errorCallback
});
}; };
/** /**
@ -92,19 +85,16 @@ window.BackendCalendarApi = window.BackendCalendarApi || {};
* @param {Function} errorCallback The ajax failure callback function. * @param {Function} errorCallback The ajax failure callback function.
*/ */
exports.saveExtraPeriod = function (extra_periods, successCallback, errorCallback) { exports.saveExtraPeriod = function (extra_periods, successCallback, errorCallback) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_extra_period'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_extra_period';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
extra_period: JSON.stringify(extra_periods) extra_period: JSON.stringify(extra_periods)
}; };
$.ajax({ $.post(url, data)
type: 'POST', .done(successCallback)
url: postUrl, .fail(errorCallback);
data: postData,
success: successCallback,
error: errorCallback
});
} }
})(window.BackendCalendarApi); })(window.BackendCalendarApi);

View file

@ -26,7 +26,7 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
var providerId = $('#select-provider').val(); var providerId = $('#select-provider').val();
var provider = GlobalVariables.availableProviders.filter(function(availableProvider) { var provider = GlobalVariables.availableProviders.filter(function(availableProvider) {
return availableProvider.id == providerId; return Number(availableProvider.id) === Number(providerId);
}).shift(); }).shift();
if (provider && provider.timezone) { if (provider && provider.timezone) {
@ -129,11 +129,11 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
var $dialog = $('#manage-appointment'); var $dialog = $('#manage-appointment');
// Set the selected filter item and find the next appointment time as the default modal values. // Set the selected filter item and find the next appointment time as the default modal values.
if ($('#select-filter-item option:selected').attr('type') == 'provider') { if ($('#select-filter-item option:selected').attr('type') === 'provider') {
var providerId = $('#select-filter-item').val(); var providerId = $('#select-filter-item').val();
var providers = GlobalVariables.availableProviders.filter(function (provider) { var providers = GlobalVariables.availableProviders.filter(function (provider) {
return provider.id == providerId; return Number(provider.id) === Number(providerId);
}); });
if (providers.length) { if (providers.length) {
@ -147,7 +147,7 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
var serviceDuration = 0; var serviceDuration = 0;
$.each(GlobalVariables.availableServices, function (index, service) { $.each(GlobalVariables.availableServices, function (index, service) {
if (service.id == $dialog.find('#select-service').val()) { if (Number(service.id) === Number($dialog.find('#select-service').val())) {
serviceDuration = service.duration; serviceDuration = service.duration;
return false; // exit loop return false; // exit loop
} }
@ -204,17 +204,17 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
$('#manage-appointment').on('click', '#existing-customers-list div', function () { $('#manage-appointment').on('click', '#existing-customers-list div', function () {
var id = $(this).attr('data-id'); var id = $(this).attr('data-id');
$.each(GlobalVariables.customers, function (index, c) { $.each(GlobalVariables.customers, function (index, customer) {
if (c.id == id) { if (Number(customer.id) === Number(id)) {
$('#customer-id').val(c.id); $('#customer-id').val(customer.id);
$('#first-name').val(c.first_name); $('#first-name').val(customer.first_name);
$('#last-name').val(c.last_name); $('#last-name').val(customer.last_name);
$('#email').val(c.email); $('#email').val(customer.email);
$('#phone-number').val(c.phone_number); $('#phone-number').val(customer.phone_number);
$('#address').val(c.address); $('#address').val(customer.address);
$('#city').val(c.city); $('#city').val(customer.city);
$('#zip-code').val(c.zip_code); $('#zip-code').val(customer.zip_code);
$('#customer-notes').val(c.notes); $('#customer-notes').val(customer.notes);
return false; return false;
} }
}); });
@ -228,56 +228,52 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
$('#filter-existing-customers').keyup(function () { $('#filter-existing-customers').keyup(function () {
var key = $(this).val().toLowerCase(); var key = $(this).val().toLowerCase();
var $list = $('#existing-customers-list'); var $list = $('#existing-customers-list');
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_customers';
var postData = { var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_customers';
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key key: key
}; };
// Try to get the updated customer list. // Try to get the updated customer list.
$.ajax({ $.post(url, data)
type: 'POST', .done(function (response) {
url: postUrl,
data: postData,
dataType: 'json',
timeout: 1000,
global: false,
success: function (response) {
$list.empty(); $list.empty();
$.each(response, function (index, c) {
$list.append('<div data-id="' + c.id + '">' response.forEach(function (customer, index) {
+ c.first_name + ' ' + c.last_name + '</div>'); $list.append('<div data-id="' + customer.id + '">'
+ customer.first_name + ' ' + customer.last_name + '</div>');
// Verify if this customer is on the old customer list. // Verify if this customer is on the old customer list.
var result = $.grep(GlobalVariables.customers, var result = GlobalVariables.customers.filter(function(globalVariablesCustomer) {
function (e) { return Number(globalVariablesCustomer.id) === Number(customer.id);
return e.id == c.id; });
});
// Add it to the customer list. // Add it to the customer list.
if (result.length == 0) { if (!result.length) {
GlobalVariables.customers.push(c); GlobalVariables.customers.push(customer);
} }
}); })
}, })
error: function (jqXHR, textStatus, errorThrown) { .fail(function (jqXHR, textStatus, errorThrown) {
// If there is any error on the request, search by the local client database. // If there is any error on the request, search by the local client database.
$list.empty(); $list.empty();
$.each(GlobalVariables.customers, function (index, c) {
if (c.first_name.toLowerCase().indexOf(key) != -1 GlobalVariables.customers.forEach(function(customer, index) {
|| c.last_name.toLowerCase().indexOf(key) != -1 if (customer.first_name.toLowerCase().indexOf(key) !== -1
|| c.email.toLowerCase().indexOf(key) != -1 || customer.last_name.toLowerCase().indexOf(key) !== -1
|| c.phone_number.toLowerCase().indexOf(key) != -1 || customer.email.toLowerCase().indexOf(key) !== -1
|| c.address.toLowerCase().indexOf(key) != -1 || customer.phone_number.toLowerCase().indexOf(key) !== -1
|| c.city.toLowerCase().indexOf(key) != -1 || customer.address.toLowerCase().indexOf(key) !== -1
|| c.zip_code.toLowerCase().indexOf(key) != -1 || customer.city.toLowerCase().indexOf(key) !== -1
|| c.notes.toLowerCase().indexOf(key) != -1) { || customer.zip_code.toLowerCase().indexOf(key) !== -1
$list.append('<div data-id="' + c.id + '">' || customer.notes.toLowerCase().indexOf(key) !== -1) {
+ c.first_name + ' ' + c.last_name + '</div>'); $list.append('<div data-id="' + customer.id + '">'
+ customer.first_name + ' ' + customer.last_name + '</div>');
} }
}); });
} });
});
}); });
/** /**
@ -287,22 +283,22 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
* update the start and end time of the appointment. * update the start and end time of the appointment.
*/ */
$('#select-service').change(function () { $('#select-service').change(function () {
var sid = $('#select-service').val(); var serviceId = $('#select-service').val();
$('#select-provider').empty(); $('#select-provider').empty();
// Automatically update the service duration. // Automatically update the service duration.
$.each(GlobalVariables.availableServices, function (indexService, service) { $.each(GlobalVariables.availableServices, function (indexService, availableService) {
if (service.id == sid) { if (Number(availableService.id) === serviceId) {
var start = $('#start-datetime').datetimepicker('getDate'); var start = $('#start-datetime').datetimepicker('getDate');
$('#end-datetime').datetimepicker('setDate', new Date(start.getTime() + service.duration * 60000)); $('#end-datetime').datetimepicker('setDate', new Date(start.getTime() + availableService.duration * 60000));
return false; // break loop return false; // break loop
} }
}); });
// Update the providers select box. // Update the providers select box.
$.each(GlobalVariables.availableProviders, function (indexProvider, provider) { $.each(GlobalVariables.availableProviders, function (indexProvider, provider) {
$.each(provider.services, function (indexService, serviceId) { $.each(provider.services, function (indexService, providerServiceId) {
if (GlobalVariables.user.role_slug === Backend.DB_SLUG_PROVIDER && parseInt(provider.id) !== GlobalVariables.user.id) { if (GlobalVariables.user.role_slug === Backend.DB_SLUG_PROVIDER && Number(provider.id) !== GlobalVariables.user.id) {
return true; // continue return true; // continue
} }
@ -311,7 +307,7 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
} }
// If the current provider is able to provide the selected service, add him to the listbox. // If the current provider is able to provide the selected service, add him to the listbox.
if (serviceId == sid) { if (Number(providerServiceId) === Number(serviceId)) {
var optionHtml = '<option value="' + provider.id + '">' var optionHtml = '<option value="' + provider.id + '">'
+ provider.first_name + ' ' + provider.last_name + provider.first_name + ' ' + provider.last_name
+ '</option>'; + '</option>';
@ -360,8 +356,10 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
$.each(GlobalVariables.availableProviders, function (index, provider) { $.each(GlobalVariables.availableProviders, function (index, provider) {
var canProvideService = false; var canProvideService = false;
$.each(provider.services, function (index, serviceId) { var serviceId = $dialog.find('#select-service').val();
if (serviceId == $dialog.find('#select-service').val()) {
$.each(provider.services, function (index, providerServiceId) {
if (Number(providerServiceId) === Number(serviceId)) {
canProvideService = true; canProvideService = true;
return false; return false;
} }
@ -381,9 +379,10 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
// Setup start and datetimepickers. // Setup start and datetimepickers.
// Get the selected service duration. It will be needed in order to calculate the appointment end datetime. // Get the selected service duration. It will be needed in order to calculate the appointment end datetime.
var serviceId = $dialog.find('#select-service').val();
var serviceDuration = 0; var serviceDuration = 0;
$.each(GlobalVariables.availableServices, function (index, service) { $.each(GlobalVariables.availableServices, function (index, service) {
if (service.id == $dialog.find('#select-service').val()) { if (Number(service.id) === Number(serviceId)) {
serviceDuration = service.duration; serviceDuration = service.duration;
return false; return false;
} }
@ -438,13 +437,13 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
minuteText: EALang.minutes, minuteText: EALang.minutes,
firstDay: firstWeekDayNumber, firstDay: firstWeekDayNumber,
onClose: function () { onClose: function () {
var sid = $('#select-service').val(); var serviceId = $('#select-service').val();
// Automatically update the #end-datetime DateTimePicker based on service duration. // Automatically update the #end-datetime DateTimePicker based on service duration.
$.each(GlobalVariables.availableServices, function (indexService, service) { $.each(GlobalVariables.availableServices, function (indexService, availableService) {
if (service.id == sid) { if (Number(availableService.id) === Number(serviceId)) {
var start = $('#start-datetime').datetimepicker('getDate'); var start = $('#start-datetime').datetimepicker('getDate');
$('#end-datetime').datetimepicker('setDate', new Date(start.getTime() + service.duration * 60000)); $('#end-datetime').datetimepicker('setDate', new Date(start.getTime() + availableService.duration * 60000));
return false; // break loop return false; // break loop
} }
}); });
@ -501,20 +500,20 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
var missingRequiredField = false; var missingRequiredField = false;
$dialog.find('.required').each(function () { $dialog.find('.required').each(function () {
if ($(this).val() == '' || $(this).val() == null) { if ($(this).val() === '' || $(this).val() === null) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequiredField = true; missingRequiredField = true;
} }
}); });
if (missingRequiredField) { if (missingRequiredField) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
// Check email address. // Check email address.
if (!GeneralFunctions.validateEmail($dialog.find('#email').val())) { if (!GeneralFunctions.validateEmail($dialog.find('#email').val())) {
$dialog.find('#email').closest('.form-group').addClass('has-error'); $dialog.find('#email').closest('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
// Check appointment start and end time. // Check appointment start and end time.
@ -522,12 +521,12 @@ window.BackendCalendarAppointmentsModal = window.BackendCalendarAppointmentsModa
var end = $('#end-datetime').datetimepicker('getDate'); var end = $('#end-datetime').datetimepicker('getDate');
if (start > end) { if (start > end) {
$dialog.find('#start-datetime, #end-datetime').closest('.form-group').addClass('has-error'); $dialog.find('#start-datetime, #end-datetime').closest('.form-group').addClass('has-error');
throw EALang.start_date_before_end_error; throw new Error(EALang.start_date_before_end_error);
} }
return true; return true;
} catch (exc) { } catch (error) {
$dialog.find('.modal-message').addClass('alert-danger').text(exc).removeClass('hidden'); $dialog.find('.modal-message').addClass('alert-danger').text(error.message).removeClass('hidden');
return false; return false;
} }
} }

View file

@ -67,7 +67,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
var $dialog; var $dialog;
if (lastFocusedEventData.data.is_unavailable == false) { if (lastFocusedEventData.data.is_unavailable === '0') {
var appointment = lastFocusedEventData.data; var appointment = lastFocusedEventData.data;
$dialog = $('#manage-appointment'); $dialog = $('#manage-appointment');
@ -132,45 +132,54 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$calendarPage.on('click', '.delete-popover', function () { $calendarPage.on('click', '.delete-popover', function () {
$(this).parents().eq(2).remove(); // Hide the popover. $(this).parents().eq(2).remove(); // Hide the popover.
var url;
var data;
// If id_role parameter exists the popover is an extra working day. // If id_role parameter exists the popover is an extra working day.
if (lastFocusedEventData.data.hasOwnProperty('id_roles')) { if (lastFocusedEventData.data.hasOwnProperty('id_roles')) {
// Do not display confirmation prompt. // Do not display confirmation prompt.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_extra_period'; url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_extra_period';
var data = {
data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
extra_period: lastFocusedEventData.start.format('YYYY-MM-DD'), extra_period: lastFocusedEventData.start.format('YYYY-MM-DD'),
provider_id: lastFocusedEventData.data.id provider_id: lastFocusedEventData.data.id
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#message_box').dialog('close'); .done(function () {
$('#message_box').dialog('close');
var extraWorkingPlan = jQuery.parseJSON(lastFocusedEventData.data.settings.extra_working_plan); var extraWorkingPlan = jQuery.parseJSON(lastFocusedEventData.data.settings.extra_working_plan);
delete extraWorkingPlan[lastFocusedEventData.start.format('YYYY-MM-DD')]; delete extraWorkingPlan[lastFocusedEventData.start.format('YYYY-MM-DD')];
lastFocusedEventData.data.settings.extra_working_plan = JSON.stringify(extraWorkingPlan); lastFocusedEventData.data.settings.extra_working_plan = JSON.stringify(extraWorkingPlan);
// Refresh calendar event items. // Refresh calendar event items.
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
} }
else if (lastFocusedEventData.data.is_unavailable == false) { else if (lastFocusedEventData.data.is_unavailable === '0') {
var buttons = [ var buttons = [
{ {
text: 'OK', text: 'OK',
click: function () { click: function () {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_appointment'; url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_appointment';
var data = {
data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
appointment_id: lastFocusedEventData.data.id, appointment_id: lastFocusedEventData.data.id,
delete_reason: $('#delete-reason').val() delete_reason: $('#delete-reason').val()
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#message_box').dialog('close'); .done(function () {
$('#message_box').dialog('close');
// Refresh calendar event items. // Refresh calendar event items.
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
} }
}, },
{ {
@ -189,18 +198,21 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$('#delete-reason').css('width', '100%'); $('#delete-reason').css('width', '100%');
} else { } else {
// Do not display confirmation prompt. // Do not display confirmation prompt.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_unavailable'; url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_unavailable';
var data = {
data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
unavailable_id: lastFocusedEventData.data.id unavailable_id: lastFocusedEventData.data.id
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#message_box').dialog('close'); .done(function () {
$('#message_box').dialog('close');
// Refresh calendar event items. // Refresh calendar event items.
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
} }
}); });
@ -223,7 +235,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
var providerId = $('#select-filter-item').val(); var providerId = $('#select-filter-item').val();
var provider = GlobalVariables.availableProviders.filter(function(availableProvider) { var provider = GlobalVariables.availableProviders.filter(function(availableProvider) {
return availableProvider.id == providerId; return Number(availableProvider.id) === Number(providerId);
}).shift(); }).shift();
if (provider && provider.timezone) { if (provider && provider.timezone) {
@ -278,10 +290,10 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
if ($(this).hasClass('fc-unavailable') || $parent.hasClass('fc-unavailable') || $altParent.hasClass('fc-unavailable')) { if ($(this).hasClass('fc-unavailable') || $parent.hasClass('fc-unavailable') || $altParent.hasClass('fc-unavailable')) {
displayEdit = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom')) displayEdit = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom'))
&& GlobalVariables.user.privileges.appointments.edit == true) && GlobalVariables.user.privileges.appointments.edit === true)
? '' : 'hide'; ? '' : 'hide';
displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom')) displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom'))
&& GlobalVariables.user.privileges.appointments.delete == true) && GlobalVariables.user.privileges.appointments.delete === true)
? '' : 'hide'; // Same value at the time. ? '' : 'hide'; // Same value at the time.
var notes = ''; var notes = '';
@ -309,7 +321,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
'</center>'; '</center>';
} else if ($(this).hasClass('fc-extra') || $parent.hasClass('fc-extra') || $altParent.hasClass('fc-extra')) { } else if ($(this).hasClass('fc-extra') || $parent.hasClass('fc-extra') || $altParent.hasClass('fc-extra')) {
displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom')) displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom'))
&& GlobalVariables.user.privileges.appointments.delete == true) && GlobalVariables.user.privileges.appointments.delete === true)
? '' : 'hide'; // Same value at the time. ? '' : 'hide'; // Same value at the time.
var provider = ''; var provider = '';
@ -341,9 +353,9 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
'</center>'; '</center>';
} else { } else {
displayEdit = (GlobalVariables.user.privileges.appointments.edit == true) displayEdit = (GlobalVariables.user.privileges.appointments.edit === true)
? '' : 'hide'; ? '' : 'hide';
displayDelete = (GlobalVariables.user.privileges.appointments.delete == true) displayDelete = (GlobalVariables.user.privileges.appointments.delete === true)
? '' : 'hide'; ? '' : 'hide';
html = html =
@ -416,7 +428,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
* @see updateAppointmentData() * @see updateAppointmentData()
*/ */
function _calendarEventResize(event, delta, revertFunc, jsEvent, ui, view) { function _calendarEventResize(event, delta, revertFunc, jsEvent, ui, view) {
if (GlobalVariables.user.privileges.appointments.edit == false) { if (GlobalVariables.user.privileges.appointments.edit === false) {
revertFunc(); revertFunc();
Backend.displayNotification(EALang.no_privileges_edit_appointments); Backend.displayNotification(EALang.no_privileges_edit_appointments);
return; return;
@ -428,7 +440,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$('#notification').hide('bind'); $('#notification').hide('bind');
} }
if (event.data.is_unavailable == false) { if (event.data.is_unavailable === false) {
// Prepare appointment data. // Prepare appointment data.
event.data.end_datetime = Date.parseExact( event.data.end_datetime = Date.parseExact(
event.data.end_datetime, 'yyyy-MM-dd HH:mm:ss') event.data.end_datetime, 'yyyy-MM-dd HH:mm:ss')
@ -458,10 +470,12 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
appointment_data: JSON.stringify(appointment) appointment_data: JSON.stringify(appointment)
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.appointment_updated, [ Backend.displayNotification(EALang.appointment_updated, [
@ -477,7 +491,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
}; };
// Update appointment data. // Update appointment data.
BackendCalendarApi.saveAppointment(appointment, undefined, successCallback); BackendCalendarApi.saveAppointment(appointment, null, successCallback);
} else { } else {
// Update unavailable time period. // Update unavailable time period.
var unavailable = { var unavailable = {
@ -499,15 +513,18 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
.toString('yyyy-MM-dd HH:mm:ss'); .toString('yyyy-MM-dd HH:mm:ss');
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
unavailable: JSON.stringify(unavailable) unavailable: JSON.stringify(unavailable)
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.unavailable_updated, [ Backend.displayNotification(EALang.unavailable_updated, [
@ -559,7 +576,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
* on the calendar. We need to update the database with this change. This is done via an ajax call. * on the calendar. We need to update the database with this change. This is done via an ajax call.
*/ */
function _calendarEventDrop(event, delta, revertFunc, jsEvent, ui, view) { function _calendarEventDrop(event, delta, revertFunc, jsEvent, ui, view) {
if (GlobalVariables.user.privileges.appointments.edit == false) { if (GlobalVariables.user.privileges.appointments.edit === false) {
revertFunc(); revertFunc();
Backend.displayNotification(EALang.no_privileges_edit_appointments); Backend.displayNotification(EALang.no_privileges_edit_appointments);
return; return;
@ -569,7 +586,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$('#notification').hide('bind'); $('#notification').hide('bind');
} }
if (event.data.is_unavailable == false) { if (event.data.is_unavailable === '0') {
// Prepare appointment data. // Prepare appointment data.
var appointment = GeneralFunctions.clone(event.data); var appointment = GeneralFunctions.clone(event.data);
@ -609,15 +626,18 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
event.data.end_datetime = appointment.end_datetime; event.data.end_datetime = appointment.end_datetime;
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_appointment'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_appointment';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
appointment_data: JSON.stringify(appointment) appointment_data: JSON.stringify(appointment)
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.appointment_updated, [ Backend.displayNotification(EALang.appointment_updated, [
@ -631,7 +651,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
}; };
// Update appointment data. // Update appointment data.
BackendCalendarApi.saveAppointment(appointment, undefined, successCallback); BackendCalendarApi.saveAppointment(appointment, null, successCallback);
} else { } else {
// Update unavailable time period. // Update unavailable time period.
var unavailable = { var unavailable = {
@ -662,10 +682,12 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
unavailable: JSON.stringify(unavailable) unavailable: JSON.stringify(unavailable)
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.unavailable_updated, [ Backend.displayNotification(EALang.unavailable_updated, [
@ -744,6 +766,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
*/ */
function _refreshCalendarAppointments($calendar, recordId, filterType, startDate, endDate) { function _refreshCalendarAppointments($calendar, recordId, filterType, startDate, endDate) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_get_calendar_appointments'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_get_calendar_appointments';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
record_id: recordId, record_id: recordId,
@ -752,232 +775,95 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
filter_type: filterType filter_type: filterType
}; };
$('#loading').css('visibility', 'hidden'); $('#loading').css('visibility', 'hidden');
return $.post(url, data, function (response) { return $.post(url, data)
// Add appointments to calendar. .done(function (response) {
var calendarEvents = []; // Add appointments to calendar.
var $calendar = $('#calendar'); var calendarEvents = [];
var $calendar = $('#calendar');
$.each(response.appointments, function (index, appointment) { $.each(response.appointments, function (index, appointment) {
var event = { var event = {
id: appointment.id, id: appointment.id,
title: appointment.service.name + ' - ' title: appointment.service.name + ' - '
+ appointment.customer.first_name + ' ' + appointment.customer.first_name + ' '
+ appointment.customer.last_name, + appointment.customer.last_name,
start: moment(appointment.start_datetime), start: moment(appointment.start_datetime),
end: moment(appointment.end_datetime), end: moment(appointment.end_datetime),
allDay: false, allDay: false,
data: appointment // Store appointment data for later use. data: appointment // Store appointment data for later use.
}; };
calendarEvents.push(event); calendarEvents.push(event);
}); });
$calendar.fullCalendar('removeEvents'); $calendar.fullCalendar('removeEvents');
$calendar.fullCalendar('addEventSource', calendarEvents); $calendar.fullCalendar('addEventSource', calendarEvents);
var weekDays = [ var weekDays = [
'sunday', 'sunday',
'monday', 'monday',
'tuesday', 'tuesday',
'wednesday', 'wednesday',
'thursday', 'thursday',
'friday', 'friday',
'saturday' 'saturday'
]; ];
// :: ADD PROVIDER'S UNAVAILABLE TIME PERIODS // :: ADD PROVIDER'S UNAVAILABLE TIME PERIODS
var calendarView = $calendar.fullCalendar('getView').name; var calendarView = $calendar.fullCalendar('getView').name;
if (filterType === FILTER_TYPE_PROVIDER && calendarView !== 'month') { if (filterType === FILTER_TYPE_PROVIDER && calendarView !== 'month') {
$.each(GlobalVariables.availableProviders, function (index, provider) { $.each(GlobalVariables.availableProviders, function (index, provider) {
if (provider.id == recordId) { if (Number(provider.id) === Number(recordId)) {
var workingPlan={}; var workingPlan={};
var workingPlanBulk = jQuery.parseJSON(provider.settings.working_plan); var workingPlanBulk = jQuery.parseJSON(provider.settings.working_plan);
var extraWorkingPlan = jQuery.parseJSON(provider.settings.extra_working_plan); var extraWorkingPlan = jQuery.parseJSON(provider.settings.extra_working_plan);
var unavailablePeriod; var unavailablePeriod;
// Sort the working plan starting with the first day as set in General settings to correctly // Sort the working plan starting with the first day as set in General settings to correctly
// align breaks in the calendar display. // align breaks in the calendar display.
var firstWeekdayNumber = GeneralFunctions.getWeekDayId(GlobalVariables.firstWeekday); var firstWeekdayNumber = GeneralFunctions.getWeekDayId(GlobalVariables.firstWeekday);
workingPlan = GeneralFunctions.sortWeekDictionary(workingPlanBulk, firstWeekdayNumber); workingPlan = GeneralFunctions.sortWeekDictionary(workingPlanBulk, firstWeekdayNumber);
switch (calendarView) { switch (calendarView) {
case 'agendaDay': case 'agendaDay':
var selectedDayName = GeneralFunctions var selectedDayName = GeneralFunctions
.getWeekdayName(parseInt($calendar.fullCalendar('getView').start.format('d'))); .getWeekdayName(parseInt($calendar.fullCalendar('getView').start.format('d')));
// Add custom unavailable periods. // Add custom unavailable periods.
$.each(response.unavailables, function (index, unavailable) { $.each(response.unavailables, function (index, unavailable) {
var notes = unavailable.notes ? ' - ' + unavailable.notes : ''; var notes = unavailable.notes ? ' - ' + unavailable.notes : '';
if (unavailable.notes.length > 30) { if (unavailable.notes.length > 30) {
notes = unavailable.notes.substring(0, 30) + '...' notes = unavailable.notes.substring(0, 30) + '...'
} }
var unavailablePeriod = { var unavailablePeriod = {
title: EALang.unavailable + notes, title: EALang.unavailable + notes,
start: moment(unavailable.start_datetime), start: moment(unavailable.start_datetime),
end: moment(unavailable.end_datetime), end: moment(unavailable.end_datetime),
allDay: false,
color: '#879DB4',
editable: true,
className: 'fc-unavailable fc-custom',
data: unavailable
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false);
});
// Non-working day.
if (workingPlan[selectedDayName] == null) {
// Extra working plan day.
var selectedDay = $calendar.fullCalendar('getView').intervalStart.clone();
selectedDay.locale('en');
if (extraWorkingPlan != null && selectedDay.format() in extraWorkingPlan) {
workingPlan[selectedDay.format('dddd').toLowerCase()] = extraWorkingPlan[selectedDay.format('YYYY-MM-DD')];
var start_extra = selectedDay.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[selectedDay.format('YYYY-MM-DD')].start;
var end_extra = selectedDay.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[selectedDay.format('YYYY-MM-DD')].end;
var extraPeriod = {
title: EALang.extra_period,
start: moment(start_extra, 'YYYY-MM-DD HH:mm', true),
end: moment(end_extra, 'YYYY-MM-DD HH:mm', true).add(1, 'day'),
allDay: true,
color: '#879DB4',
editable: false,
className: 'fc-extra fc-custom',
data: provider
};
$calendar.fullCalendar('renderEvent', extraPeriod, false);
} else {
unavailablePeriod = {
title: EALang.not_working,
start: $calendar.fullCalendar('getView').intervalStart.clone(),
end: $calendar.fullCalendar('getView').intervalEnd.clone(),
allDay: false, allDay: false,
color: '#BEBEBE', color: '#879DB4',
editable: false, editable: true,
className: 'fc-unavailable' className: 'fc-unavailable fc-custom',
data: unavailable
}; };
$calendar.fullCalendar('renderEvent', unavailablePeriod, false); $calendar.fullCalendar('renderEvent', unavailablePeriod, false);
});
return; // Go to next loop. // Non-working day.
} if (workingPlan[selectedDayName] === null) {
} // Extra working plan day.
var selectedDay = $calendar.fullCalendar('getView').intervalStart.clone();
selectedDay.locale('en');
if (extraWorkingPlan && selectedDay.format() in extraWorkingPlan) {
workingPlan[selectedDay.format('dddd').toLowerCase()] = extraWorkingPlan[selectedDay.format('YYYY-MM-DD')];
// Add unavailable period before work starts. var start_extra = selectedDay.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[selectedDay.format('YYYY-MM-DD')].start;
var calendarDateStart = moment($calendar.fullCalendar('getView').start.format('YYYY-MM-DD') + ' 00:00:00'); var end_extra = selectedDay.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[selectedDay.format('YYYY-MM-DD')].end;
var startHour = workingPlan[selectedDayName].start.split(':');
var workDateStart = calendarDateStart.clone();
workDateStart.hour(parseInt(startHour[0]));
workDateStart.minute(parseInt(startHour[1]));
if (calendarDateStart < workDateStart) {
var unavailablePeriodBeforeWorkStarts = {
title: EALang.not_working,
start: calendarDateStart,
end: workDateStart,
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable'
};
$calendar.fullCalendar('renderEvent', unavailablePeriodBeforeWorkStarts, false);
}
// Add unavailable period after work ends.
var calendarDateEnd = moment($calendar.fullCalendar('getView').end.format('YYYY-MM-DD') + ' 00:00:00');
var endHour = workingPlan[selectedDayName].end.split(':');
var workDateEnd = calendarDateStart.clone();
workDateEnd.hour(parseInt(endHour[0]));
workDateEnd.minute(parseInt(endHour[1]));
if (calendarDateEnd > workDateEnd) {
var unavailablePeriodAfterWorkEnds = {
title: EALang.not_working,
start: workDateEnd,
end: calendarDateEnd,
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable'
};
$calendar.fullCalendar('renderEvent', unavailablePeriodAfterWorkEnds, false);
}
// Add unavailable periods for breaks.
var breakStart;
var breakEnd;
$.each(workingPlan[selectedDayName].breaks, function (index, currentBreak) {
var breakStartString = currentBreak.start.split(':');
breakStart = calendarDateStart.clone();
breakStart.hour(parseInt(breakStartString[0]));
breakStart.minute(parseInt(breakStartString[1]));
var breakEndString = currentBreak.end.split(':');
breakEnd = calendarDateStart.clone();
breakEnd.hour(parseInt(breakEndString[0]));
breakEnd.minute(parseInt(breakEndString[1]));
var unavailablePeriod = {
title: EALang.break,
start: breakStart,
end: breakEnd,
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable fc-break'
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false);
});
break;
case 'agendaWeek':
var currentDateStart = $calendar.fullCalendar('getView').start.clone();
var currentDateEnd = currentDateStart.clone().add(1, 'days');
// Add custom unavailable periods (they are always displayed on the calendar, even if
// the provider won't work on that day).
$.each(response.unavailables, function (index, unavailable) {
var notes = unavailable.notes ? ' - ' + unavailable.notes : '';
if (unavailable.notes.length > 30) {
notes = unavailable.notes.substring(0, 30) + '...'
}
unavailablePeriod = {
title: EALang.unavailable + notes,
start: moment(unavailable.start_datetime),
end: moment(unavailable.end_datetime),
allDay: false,
color: '#879DB4',
editable: true,
className: 'fc-unavailable fc-custom',
data: unavailable
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false);
});
$.each(workingPlan, function (index, workingDay) {
if (workingDay == null) {
// Check if the day is an extra working day added to the working plan
if (extraWorkingPlan != null && currentDateStart.format('YYYY-MM-DD') in extraWorkingPlan) {
workingDay = extraWorkingPlan[currentDateStart.format('YYYY-MM-DD')]
var start_extra = currentDateStart.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[currentDateStart.format('YYYY-MM-DD')].start;
var end_extra = currentDateStart.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[currentDateStart.format('YYYY-MM-DD')].end;
var extraPeriod = { var extraPeriod = {
title: EALang.extra_period, title: EALang.extra_period,
@ -992,87 +878,83 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$calendar.fullCalendar('renderEvent', extraPeriod, false); $calendar.fullCalendar('renderEvent', extraPeriod, false);
} else { } else {
// Add a full day unavailable event.
unavailablePeriod = { unavailablePeriod = {
title: EALang.not_working, title: EALang.not_working,
start: moment(currentDateStart.format('YYYY-MM-DD')), start: $calendar.fullCalendar('getView').intervalStart.clone(),
end: moment(currentDateEnd.format('YYYY-MM-DD')), end: $calendar.fullCalendar('getView').intervalEnd.clone(),
allDay: false, allDay: false,
color: '#BEBEBE', color: '#BEBEBE',
editable: false, editable: false,
className: 'fc-unavailable' className: 'fc-unavailable'
}; };
$calendar.fullCalendar('renderEvent', unavailablePeriod, true); $calendar.fullCalendar('renderEvent', unavailablePeriod, false);
currentDateStart.add(1, 'days');
currentDateEnd.add(1, 'days');
return; // Go to the next loop. return; // Go to next loop.
} }
} }
var start;
var end;
// Add unavailable period before work starts. // Add unavailable period before work starts.
var workingDayStartString = workingDay.start.split(':'); var calendarDateStart = moment($calendar.fullCalendar('getView').start.format('YYYY-MM-DD') + ' 00:00:00');
start = currentDateStart.clone(); var startHour = workingPlan[selectedDayName].start.split(':');
start.hour(parseInt(workingDayStartString[0])); var workDateStart = calendarDateStart.clone();
start.minute(parseInt(workingDayStartString[1])); workDateStart.hour(parseInt(startHour[0]));
workDateStart.minute(parseInt(startHour[1]));
if (currentDateStart < start) { if (calendarDateStart < workDateStart) {
unavailablePeriod = { var unavailablePeriodBeforeWorkStarts = {
title: EALang.not_working, title: EALang.not_working,
start: moment(currentDateStart.format('YYYY-MM-DD') + ' 00:00:00'), start: calendarDateStart,
end: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + workingDay.start + ':00'), end: workDateStart,
allDay: false, allDay: false,
color: '#BEBEBE', color: '#BEBEBE',
editable: false, editable: false,
className: 'fc-unavailable' className: 'fc-unavailable'
}; };
$calendar.fullCalendar('renderEvent', unavailablePeriodBeforeWorkStarts, false);
$calendar.fullCalendar('renderEvent', unavailablePeriod, true);
} }
// Add unavailable period after work ends. // Add unavailable period after work ends.
var workingDayEndString = workingDay.end.split(':'); var calendarDateEnd = moment($calendar.fullCalendar('getView').end.format('YYYY-MM-DD') + ' 00:00:00');
end = currentDateStart.clone(); var endHour = workingPlan[selectedDayName].end.split(':');
end.hour(parseInt(workingDayEndString[0])); var workDateEnd = calendarDateStart.clone();
end.minute(parseInt(workingDayEndString[1]));
if (currentDateEnd > end) { workDateEnd.hour(parseInt(endHour[0]));
unavailablePeriod = { workDateEnd.minute(parseInt(endHour[1]));
if (calendarDateEnd > workDateEnd) {
var unavailablePeriodAfterWorkEnds = {
title: EALang.not_working, title: EALang.not_working,
start: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + workingDay.end + ':00'), start: workDateEnd,
end: moment(currentDateEnd.format('YYYY-MM-DD') + ' 00:00:00'), end: calendarDateEnd,
allDay: false, allDay: false,
color: '#BEBEBE', color: '#BEBEBE',
editable: false, editable: false,
className: 'fc-unavailable' className: 'fc-unavailable'
}; };
$calendar.fullCalendar('renderEvent', unavailablePeriod, false); $calendar.fullCalendar('renderEvent', unavailablePeriodAfterWorkEnds, false);
} }
// Add unavailable periods during day breaks. // Add unavailable periods for breaks.
var breakStart; var breakStart;
var breakEnd; var breakEnd;
$.each(workingDay.breaks, function (index, currentBreak) { $.each(workingPlan[selectedDayName].breaks, function (index, currentBreak) {
var breakStartString = currentBreak.start.split(':'); var breakStartString = currentBreak.start.split(':');
breakStart = currentDateStart.clone(); breakStart = calendarDateStart.clone();
breakStart.hour(parseInt(breakStartString[0])); breakStart.hour(parseInt(breakStartString[0]));
breakStart.minute(parseInt(breakStartString[1])); breakStart.minute(parseInt(breakStartString[1]));
var breakEndString = currentBreak.end.split(':'); var breakEndString = currentBreak.end.split(':');
breakEnd = currentDateStart.clone(); breakEnd = calendarDateStart.clone();
breakEnd.hour(parseInt(breakEndString[0])); breakEnd.hour(parseInt(breakEndString[0]));
breakEnd.minute(parseInt(breakEndString[1])); breakEnd.minute(parseInt(breakEndString[1]));
var unavailablePeriod = { var unavailablePeriod = {
title: EALang.break, title: EALang.break,
start: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + currentBreak.start), start: breakStart,
end: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + currentBreak.end), end: breakEnd,
allDay: false, allDay: false,
color: '#BEBEBE', color: '#BEBEBE',
editable: false, editable: false,
@ -1082,16 +964,157 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false); $calendar.fullCalendar('renderEvent', unavailablePeriod, false);
}); });
currentDateStart.add(1, 'days'); break;
currentDateEnd.add(1, 'days');
});
break; case 'agendaWeek':
var currentDateStart = $calendar.fullCalendar('getView').start.clone();
var currentDateEnd = currentDateStart.clone().add(1, 'days');
// Add custom unavailable periods (they are always displayed on the calendar, even if
// the provider won't work on that day).
$.each(response.unavailables, function (index, unavailable) {
var notes = unavailable.notes ? ' - ' + unavailable.notes : '';
if (unavailable.notes.length > 30) {
notes = unavailable.notes.substring(0, 30) + '...'
}
unavailablePeriod = {
title: EALang.unavailable + notes,
start: moment(unavailable.start_datetime),
end: moment(unavailable.end_datetime),
allDay: false,
color: '#879DB4',
editable: true,
className: 'fc-unavailable fc-custom',
data: unavailable
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false);
});
$.each(workingPlan, function (index, workingDay) {
if (workingDay === null) {
// Check if the day is an extra working day added to the working plan
if (extraWorkingPlan && currentDateStart.format('YYYY-MM-DD') in extraWorkingPlan) {
workingDay = extraWorkingPlan[currentDateStart.format('YYYY-MM-DD')]
var start_extra = currentDateStart.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[currentDateStart.format('YYYY-MM-DD')].start;
var end_extra = currentDateStart.format('YYYY-MM-DD') + ' ' + extraWorkingPlan[currentDateStart.format('YYYY-MM-DD')].end;
var extraPeriod = {
title: EALang.extra_period,
start: moment(start_extra, 'YYYY-MM-DD HH:mm', true),
end: moment(end_extra, 'YYYY-MM-DD HH:mm', true).add(1, 'day'),
allDay: true,
color: '#879DB4',
editable: false,
className: 'fc-extra fc-custom',
data: provider
};
$calendar.fullCalendar('renderEvent', extraPeriod, false);
} else {
// Add a full day unavailable event.
unavailablePeriod = {
title: EALang.not_working,
start: moment(currentDateStart.format('YYYY-MM-DD')),
end: moment(currentDateEnd.format('YYYY-MM-DD')),
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable'
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, true);
currentDateStart.add(1, 'days');
currentDateEnd.add(1, 'days');
return; // Go to the next loop.
}
}
var start;
var end;
// Add unavailable period before work starts.
var workingDayStartString = workingDay.start.split(':');
start = currentDateStart.clone();
start.hour(parseInt(workingDayStartString[0]));
start.minute(parseInt(workingDayStartString[1]));
if (currentDateStart < start) {
unavailablePeriod = {
title: EALang.not_working,
start: moment(currentDateStart.format('YYYY-MM-DD') + ' 00:00:00'),
end: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + workingDay.start + ':00'),
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable'
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, true);
}
// Add unavailable period after work ends.
var workingDayEndString = workingDay.end.split(':');
end = currentDateStart.clone();
end.hour(parseInt(workingDayEndString[0]));
end.minute(parseInt(workingDayEndString[1]));
if (currentDateEnd > end) {
unavailablePeriod = {
title: EALang.not_working,
start: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + workingDay.end + ':00'),
end: moment(currentDateEnd.format('YYYY-MM-DD') + ' 00:00:00'),
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable'
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false);
}
// Add unavailable periods during day breaks.
var breakStart;
var breakEnd;
$.each(workingDay.breaks, function (index, currentBreak) {
var breakStartString = currentBreak.start.split(':');
breakStart = currentDateStart.clone();
breakStart.hour(parseInt(breakStartString[0]));
breakStart.minute(parseInt(breakStartString[1]));
var breakEndString = currentBreak.end.split(':');
breakEnd = currentDateStart.clone();
breakEnd.hour(parseInt(breakEndString[0]));
breakEnd.minute(parseInt(breakEndString[1]));
var unavailablePeriod = {
title: EALang.break,
start: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + currentBreak.start),
end: moment(currentDateStart.format('YYYY-MM-DD') + ' ' + currentBreak.end),
allDay: false,
color: '#BEBEBE',
editable: false,
className: 'fc-unavailable fc-break'
};
$calendar.fullCalendar('renderEvent', unavailablePeriod, false);
});
currentDateStart.add(1, 'days');
currentDateEnd.add(1, 'days');
});
break;
}
} }
} });
}); }
} })
}, 'json')
.fail(GeneralFunctions.ajaxFailureHandler) .fail(GeneralFunctions.ajaxFailureHandler)
.always(function() { .always(function() {
$('#loading').css('visibility', '') $('#loading').css('visibility', '')
@ -1168,18 +1191,20 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$('#insert-appointment').trigger('click'); $('#insert-appointment').trigger('click');
// Preselect service & provider. // Preselect service & provider.
var service;
if ($('#select-filter-item option:selected').attr('type') === FILTER_TYPE_SERVICE) { if ($('#select-filter-item option:selected').attr('type') === FILTER_TYPE_SERVICE) {
var service = GlobalVariables.availableServices.find(function (service) { service = GlobalVariables.availableServices.find(function (service) {
return service.id == $('#select-filter-item').val() return Number(service.id) === Number($('#select-filter-item').val());
}); });
$('#select-service').val(service.id).trigger('change'); $('#select-service').val(service.id).trigger('change');
} else { } else {
var provider = GlobalVariables.availableProviders.find(function (provider) { var provider = GlobalVariables.availableProviders.find(function (provider) {
return provider.id == $('#select-filter-item').val(); return Number(provider.id) === Number($('#select-filter-item').val());
}); });
var service = GlobalVariables.availableServices.find(function (service) { service = GlobalVariables.availableServices.find(function (service) {
return provider.services.indexOf(service.id) !== -1 return provider.services.indexOf(service.id) !== -1
}); });
@ -1268,24 +1293,24 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
} }
// Check permissions. // Check permissions.
if (GlobalVariables.user.role_slug == Backend.DB_SLUG_PROVIDER) { if (GlobalVariables.user.role_slug === Backend.DB_SLUG_PROVIDER) {
$('#select-filter-item optgroup:eq(0)') $('#select-filter-item optgroup:eq(0)')
.find('option[value="' + GlobalVariables.user.id + '"]') .find('option[value="' + GlobalVariables.user.id + '"]')
.prop('selected', true); .prop('selected', true);
$('#select-filter-item').prop('disabled', true); $('#select-filter-item').prop('disabled', true);
} }
if (GlobalVariables.user.role_slug == Backend.DB_SLUG_SECRETARY) { if (GlobalVariables.user.role_slug === Backend.DB_SLUG_SECRETARY) {
$('#select-filter-item optgroup:eq(1)').remove(); $('#select-filter-item optgroup:eq(1)').remove();
} }
if (GlobalVariables.user.role_slug == Backend.DB_SLUG_SECRETARY) { if (GlobalVariables.user.role_slug === Backend.DB_SLUG_SECRETARY) {
// Remove the providers that are not connected to the secretary. // Remove the providers that are not connected to the secretary.
$('#select-filter-item option[type="provider"]').each(function (index, option) { $('#select-filter-item option[type="provider"]').each(function (index, option) {
var found = false; var found = false;
$.each(GlobalVariables.secretaryProviders, function (index, id) { $.each(GlobalVariables.secretaryProviders, function (index, secretaryProviderId) {
if ($(option).val() == id) { if (Number($(option).val()) === Number(secretaryProviderId)) {
found = true; found = true;
return false; return false;
} }
@ -1296,7 +1321,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
} }
}); });
if ($('#select-filter-item option[type="provider"]').length == 0) { if (!$('#select-filter-item option[type="provider"]').length) {
$('#select-filter-item optgroup[type="providers-group"]').remove(); $('#select-filter-item optgroup[type="providers-group"]').remove();
} }
} }
@ -1307,7 +1332,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
// Display the edit dialog if an appointment hash is provided. // Display the edit dialog if an appointment hash is provided.
if (GlobalVariables.editAppointment != null) { if (GlobalVariables.editAppointment) {
var $dialog = $('#manage-appointment'); var $dialog = $('#manage-appointment');
var appointment = GlobalVariables.editAppointment; var appointment = GlobalVariables.editAppointment;
BackendCalendarAppointmentsModal.resetAppointmentDialog(); BackendCalendarAppointmentsModal.resetAppointmentDialog();
@ -1361,7 +1386,7 @@ window.BackendCalendarDefaultView = window.BackendCalendarDefaultView || {};
} }
}); });
if ($('#select-filter-item option').length == 0) { if (!$('#select-filter-item option').length) {
$('#calendar-actions button').prop('disabled', true); $('#calendar-actions button').prop('disabled', true);
} }

View file

@ -48,7 +48,7 @@ window.BackendCalendarGoogleSync = window.BackendCalendarGoogleSync || {};
// becomes "undefined" and when it comes back to the redirect URL it changes back. So check // becomes "undefined" and when it comes back to the redirect URL it changes back. So check
// whether the variable is undefined to avoid javascript errors. // whether the variable is undefined to avoid javascript errors.
try { try {
if (windowHandle.document !== undefined) { if (windowHandle.document) {
if (windowHandle.document.URL.indexOf(redirectUrl) !== -1) { if (windowHandle.document.URL.indexOf(redirectUrl) !== -1) {
// The user has granted access to his data. // The user has granted access to his data.
windowHandle.close(); windowHandle.close();
@ -61,21 +61,24 @@ window.BackendCalendarGoogleSync = window.BackendCalendarGoogleSync || {};
// Display the calendar selection dialog. First we will get a list of the available // Display the calendar selection dialog. First we will get a list of the available
// user's calendars and then we will display a selection modal so the user can select // user's calendars and then we will display a selection modal so the user can select
// the sync calendar. // the sync calendar.
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_get_google_calendars'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_get_google_calendars';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
provider_id: $('#select-filter-item').val() provider_id: $('#select-filter-item').val()
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
$('#google-calendar').empty(); .done(function (response) {
$.each(response, function () { $('#google-calendar').empty();
var option = '<option value="' + this.id + '">' + this.summary + '</option>'; $.each(response, function () {
$('#google-calendar').append(option); var option = '<option value="' + this.id + '">' + this.summary + '</option>';
}); $('#google-calendar').append(option);
});
$('#select-google-calendar').modal('show'); $('#select-google-calendar').modal('show');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
} }
} }
} catch (Error) { } catch (Error) {
@ -90,7 +93,7 @@ window.BackendCalendarGoogleSync = window.BackendCalendarGoogleSync || {};
// Update page elements and make an AJAX call to remove the google sync setting of the // Update page elements and make an AJAX call to remove the google sync setting of the
// selected provider. // selected provider.
$.each(GlobalVariables.availableProviders, function (index, provider) { $.each(GlobalVariables.availableProviders, function (index, provider) {
if (provider.id == $('#select-filter-item').val()) { if (Number(provider.id) === Number($('#select-filter-item').val())) {
provider.settings.google_sync = '0'; provider.settings.google_sync = '0';
provider.settings.google_token = null; provider.settings.google_token = null;
@ -112,6 +115,7 @@ window.BackendCalendarGoogleSync = window.BackendCalendarGoogleSync || {};
*/ */
$('#select-calendar').click(function () { $('#select-calendar').click(function () {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_select_google_calendar'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_select_google_calendar';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
provider_id: $('#select-filter-item').val(), provider_id: $('#select-filter-item').val(),
@ -166,6 +170,7 @@ window.BackendCalendarGoogleSync = window.BackendCalendarGoogleSync || {};
// Make an ajax call to the server in order to disable the setting // Make an ajax call to the server in order to disable the setting
// from the database. // from the database.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_disable_provider_sync'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_disable_provider_sync';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
provider_id: providerId provider_id: providerId

View file

@ -145,7 +145,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
var $dialog; var $dialog;
if (lastFocusedEventData.data.is_unavailable == false) { if (lastFocusedEventData.data.is_unavailable === '0') {
var appointment = lastFocusedEventData.data; var appointment = lastFocusedEventData.data;
$dialog = $('#manage-appointment'); $dialog = $('#manage-appointment');
@ -210,44 +210,53 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
$calendar.on('click', '.delete-popover', function () { $calendar.on('click', '.delete-popover', function () {
$(this).parents().eq(2).remove(); // Hide the popover. $(this).parents().eq(2).remove(); // Hide the popover.
var url;
var data;
// If id_role parameter exists the popover is an extra working day. // If id_role parameter exists the popover is an extra working day.
if (lastFocusedEventData.data.hasOwnProperty('id_roles')) { if (lastFocusedEventData.data.hasOwnProperty('id_roles')) {
// Do not display confirmation prompt. // Do not display confirmation prompt.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_extra_period'; url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_extra_period';
var data = {
data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
extra_period: lastFocusedEventData.start.format('YYYY-MM-DD'), extra_period: lastFocusedEventData.start.format('YYYY-MM-DD'),
provider_id: lastFocusedEventData.data.id provider_id: lastFocusedEventData.data.id
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#message_box').dialog('close'); .done(function (response) {
$('#message_box').dialog('close');
var extraWorkingPlan = jQuery.parseJSON(lastFocusedEventData.data.settings.extra_working_plan); var extraWorkingPlan = jQuery.parseJSON(lastFocusedEventData.data.settings.extra_working_plan);
delete extraWorkingPlan[lastFocusedEventData.start.format('YYYY-MM-DD')]; delete extraWorkingPlan[lastFocusedEventData.start.format('YYYY-MM-DD')];
lastFocusedEventData.data.settings.extra_working_plan = JSON.stringify(extraWorkingPlan); lastFocusedEventData.data.settings.extra_working_plan = JSON.stringify(extraWorkingPlan);
// Refresh calendar event items. // Refresh calendar event items.
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
} else if (lastFocusedEventData.data.is_unavailable == false) { .fail(GeneralFunctions.ajaxFailureHandler);
} else if (lastFocusedEventData.data.is_unavailable === '0') {
var buttons = [ var buttons = [
{ {
text: 'OK', text: 'OK',
click: function () { click: function () {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_appointment'; url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_appointment';
var data = {
data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
appointment_id: lastFocusedEventData.data.id, appointment_id: lastFocusedEventData.data.id,
delete_reason: $('#delete-reason').val() delete_reason: $('#delete-reason').val()
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#message_box').dialog('close'); .done(function () {
$('#message_box').dialog('close');
// Refresh calendar event items. // Refresh calendar event items.
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
} }
}, },
{ {
@ -266,18 +275,21 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
$('#delete-reason').css('width', '100%'); $('#delete-reason').css('width', '100%');
} else { } else {
// Do not display confirmation prompt. // Do not display confirmation prompt.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_unavailable'; url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_unavailable';
var data = {
data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
unavailable_id: lastFocusedEventData.data.id unavailable_id: lastFocusedEventData.data.id
}; };
$.post(url, data, function (response) { $.post(url, data)
$('#message_box').dialog('close'); .done(function () {
$('#message_box').dialog('close');
// Refresh calendar event items. // Refresh calendar event items.
$('#select-filter-item').trigger('change'); $('#select-filter-item').trigger('change');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
} }
}); });
} }
@ -763,7 +775,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
var end = view.end.clone(); var end = view.end.clone();
var selDayName = start.toDate().toString('dddd').toLowerCase(); var selDayName = start.toDate().toString('dddd').toLowerCase();
if (workingPlan[selDayName] == null) { if (workingPlan[selDayName] === null) {
var nonWorkingDay = { var nonWorkingDay = {
title: EALang.not_working, title: EALang.not_working,
start: start, start: start,
@ -982,10 +994,10 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
if ($(this).hasClass('fc-unavailable') || $parent.hasClass('fc-unavailable') || $altParent.hasClass('fc-unavailable')) { if ($(this).hasClass('fc-unavailable') || $parent.hasClass('fc-unavailable') || $altParent.hasClass('fc-unavailable')) {
displayEdit = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom')) displayEdit = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom'))
&& GlobalVariables.user.privileges.appointments.edit == true) && GlobalVariables.user.privileges.appointments.edit === true)
? '' : 'hide'; ? '' : 'hide';
displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom')) displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom'))
&& GlobalVariables.user.privileges.appointments.delete == true) && GlobalVariables.user.privileges.appointments.delete === true)
? '' : 'hide'; // Same value at the time. ? '' : 'hide'; // Same value at the time.
var notes = ''; var notes = '';
@ -1013,7 +1025,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
'</center>'; '</center>';
} else if ($(this).hasClass('fc-extra') || $parent.hasClass('fc-extra') || $altParent.hasClass('fc-extra')) { } else if ($(this).hasClass('fc-extra') || $parent.hasClass('fc-extra') || $altParent.hasClass('fc-extra')) {
displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom')) displayDelete = (($parent.hasClass('fc-custom') || $altParent.hasClass('fc-custom'))
&& GlobalVariables.user.privileges.appointments.delete == true) && GlobalVariables.user.privileges.appointments.delete === true)
? '' : 'hide'; // Same value at the time. ? '' : 'hide'; // Same value at the time.
var provider = ''; var provider = '';
@ -1045,9 +1057,9 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
'</center>'; '</center>';
} else { } else {
displayEdit = (GlobalVariables.user.privileges.appointments.edit == true) displayEdit = (GlobalVariables.user.privileges.appointments.edit === true)
? '' : 'hide'; ? '' : 'hide';
displayDelete = (GlobalVariables.user.privileges.appointments.delete == true) displayDelete = (GlobalVariables.user.privileges.appointments.delete === true)
? '' : 'hide'; ? '' : 'hide';
html = html =
@ -1120,7 +1132,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
* @see updateAppointmentData() * @see updateAppointmentData()
*/ */
function onEventResize(event, delta, revertFunc, jsEvent, ui, view) { function onEventResize(event, delta, revertFunc, jsEvent, ui, view) {
if (GlobalVariables.user.privileges.appointments.edit == false) { if (GlobalVariables.user.privileges.appointments.edit === false) {
revertFunc(); revertFunc();
Backend.displayNotification(EALang.no_privileges_edit_appointments); Backend.displayNotification(EALang.no_privileges_edit_appointments);
return; return;
@ -1132,7 +1144,9 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
$('#notification').hide('bind'); $('#notification').hide('bind');
} }
if (event.data.is_unavailable == false) { var successCallback;
if (event.data.is_unavailable === '0') {
// Prepare appointment data. // Prepare appointment data.
event.data.end_datetime = Date.parseExact( event.data.end_datetime = Date.parseExact(
event.data.end_datetime, 'yyyy-MM-dd HH:mm:ss') event.data.end_datetime, 'yyyy-MM-dd HH:mm:ss')
@ -1147,7 +1161,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
delete appointment.service; delete appointment.service;
// Success callback // Success callback
var successCallback = function () { successCallback = function () {
// Display success notification to user. // Display success notification to user.
var undoFunction = function () { var undoFunction = function () {
appointment.end_datetime = event.data.end_datetime = Date.parseExact( appointment.end_datetime = event.data.end_datetime = Date.parseExact(
@ -1162,10 +1176,12 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
appointment_data: JSON.stringify(appointment) appointment_data: JSON.stringify(appointment)
}; };
$.post(url, data, function () { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.appointment_updated, [ Backend.displayNotification(EALang.appointment_updated, [
@ -1181,7 +1197,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
}; };
// Update appointment data. // Update appointment data.
BackendCalendarApi.saveAppointment(appointment, undefined, successCallback); BackendCalendarApi.saveAppointment(appointment, null, successCallback);
} else { } else {
// Update unavailable time period. // Update unavailable time period.
var unavailable = { var unavailable = {
@ -1194,7 +1210,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
event.data.end_datetime = unavailable.end_datetime; event.data.end_datetime = unavailable.end_datetime;
// Define success callback function. // Define success callback function.
var successCallback = function () { successCallback = function () {
// Display success notification to user. // Display success notification to user.
var undoFunction = function () { var undoFunction = function () {
unavailable.end_datetime = event.data.end_datetime = Date.parseExact( unavailable.end_datetime = event.data.end_datetime = Date.parseExact(
@ -1203,15 +1219,18 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
.toString('yyyy-MM-dd HH:mm:ss'); .toString('yyyy-MM-dd HH:mm:ss');
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
unavailable: JSON.stringify(unavailable) unavailable: JSON.stringify(unavailable)
}; };
$.post(url, data, function () { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.unavailable_updated, [ Backend.displayNotification(EALang.unavailable_updated, [
@ -1237,8 +1256,8 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
* This event handler is triggered whenever the user drags and drops an event into a different position * This event handler is triggered whenever the user drags and drops an event into a different position
* on the calendar. We need to update the database with this change. This is done via an ajax call. * on the calendar. We need to update the database with this change. This is done via an ajax call.
*/ */
function onEventDrop(event, delta, revertFunc, jsEvent, ui, view) { function onEventDrop(event, delta, revertFunc) {
if (GlobalVariables.user.privileges.appointments.edit == false) { if (GlobalVariables.user.privileges.appointments.edit === false) {
revertFunc(); revertFunc();
Backend.displayNotification(EALang.no_privileges_edit_appointments); Backend.displayNotification(EALang.no_privileges_edit_appointments);
return; return;
@ -1250,7 +1269,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
var successCallback; var successCallback;
if (event.data.is_unavailable == false) { if (event.data.is_unavailable === '0') {
// Prepare appointment data. // Prepare appointment data.
var appointment = GeneralFunctions.clone(event.data); var appointment = GeneralFunctions.clone(event.data);
@ -1290,15 +1309,18 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
event.data.end_datetime = appointment.end_datetime; event.data.end_datetime = appointment.end_datetime;
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_appointment'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_appointment';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
appointment_data: JSON.stringify(appointment) appointment_data: JSON.stringify(appointment)
}; };
$.post(url, data, function () { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.appointment_updated, [ Backend.displayNotification(EALang.appointment_updated, [
@ -1312,7 +1334,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
}; };
// Update appointment data. // Update appointment data.
BackendCalendarApi.saveAppointment(appointment, undefined, successCallback); BackendCalendarApi.saveAppointment(appointment, null, successCallback);
} else { } else {
// Update unavailable time period. // Update unavailable time period.
var unavailable = { var unavailable = {
@ -1338,15 +1360,18 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
event.data.end_datetime = unavailable.end_datetime; event.data.end_datetime = unavailable.end_datetime;
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_unavailable';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
unavailable: JSON.stringify(unavailable) unavailable: JSON.stringify(unavailable)
}; };
$.post(url, data, function () { $.post(url, data)
$('#notification').hide('blind'); .done(function () {
revertFunc(); $('#notification').hide('blind');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); revertFunc();
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
Backend.displayNotification(EALang.unavailable_updated, [ Backend.displayNotification(EALang.unavailable_updated, [
@ -1405,6 +1430,7 @@ window.BackendCalendarTableView = window.BackendCalendarTableView || {};
*/ */
function getCalendarEvents(startDate, endDate) { function getCalendarEvents(startDate, endDate) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_get_calendar_events'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_get_calendar_events';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
startDate: startDate.toString('yyyy-MM-dd'), startDate: startDate.toString('yyyy-MM-dd'),

View file

@ -169,41 +169,44 @@
* @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form. * @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form.
*/ */
CategoriesHelper.prototype.filter = function (key, selectId, display) { CategoriesHelper.prototype.filter = function (key, selectId, display) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_service_categories'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_service_categories';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key, key: key,
limit: this.filterLimit limit: this.filterLimit
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
this.filterResults = response; .done(function (response) {
this.filterResults = response;
$('#filter-categories .results').html(''); $('#filter-categories .results').html('');
$.each(response, function (index, category) { $.each(response, function (index, category) {
var html = this.getFilterHtml(category); var html = this.getFilterHtml(category);
$('#filter-categories .results').append(html); $('#filter-categories .results').append(html);
}.bind(this)); }.bind(this));
if (response.length === 0) { if (response.length === 0) {
$('#filter-categories .results').html('<em>' + EALang.no_records_found + '</em>'); $('#filter-categories .results').html('<em>' + EALang.no_records_found + '</em>');
} else if (response.length === this.filterLimit) { } else if (response.length === this.filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'well btn-block load-more text-center', 'class': 'well btn-block load-more text-center',
'text': EALang.load_more, 'text': EALang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; this.filterLimit += 20;
this.filter(key, selectId, display); this.filter(key, selectId, display);
}.bind(this) }.bind(this)
}) })
.appendTo('#filter-categories .results'); .appendTo('#filter-categories .results');
} }
if (selectId !== undefined) { if (selectId) {
this.select(selectId, display); this.select(selectId, display);
} }
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -212,19 +215,22 @@
* @param {Object} category Contains the category data. * @param {Object} category Contains the category data.
*/ */
CategoriesHelper.prototype.save = function (category) { CategoriesHelper.prototype.save = function (category) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_service_category'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_service_category';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
category: JSON.stringify(category) category: JSON.stringify(category)
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.service_category_saved); .done(function (response) {
this.resetForm(); Backend.displayNotification(EALang.service_category_saved);
$('#filter-categories .key').val(''); this.resetForm();
this.filter('', response.id, true); $('#filter-categories .key').val('');
BackendServices.updateAvailableCategories(); this.filter('', response.id, true);
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); BackendServices.updateAvailableCategories();
}.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -233,19 +239,22 @@
* @param Number} id Record ID to be deleted. * @param Number} id Record ID to be deleted.
*/ */
CategoriesHelper.prototype.delete = function (id) { CategoriesHelper.prototype.delete = function (id) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_service_category'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_service_category';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
category_id: id category_id: id
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.service_category_deleted); .done(function () {
Backend.displayNotification(EALang.service_category_deleted);
this.resetForm(); this.resetForm();
this.filter($('#filter-categories .key').val()); this.filter($('#filter-categories .key').val());
BackendServices.updateAvailableCategories(); BackendServices.updateAvailableCategories();
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -271,18 +280,18 @@
var missingRequired = false; var missingRequired = false;
$('#categories .required').each(function () { $('#categories .required').each(function () {
if ($(this).val() === '' || $(this).val() === undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
return true; return true;
} catch (message) { } catch (error) {
return false; return false;
} }
}; };
@ -333,7 +342,7 @@
$('#filter-categories .selected').removeClass('selected'); $('#filter-categories .selected').removeClass('selected');
$('#filter-categories .category-row').each(function () { $('#filter-categories .category-row').each(function () {
if ($(this).attr('data-id') == id) { if ($(this).attr('data-id') === id) {
$(this).addClass('selected'); $(this).addClass('selected');
return false; return false;
} }
@ -341,7 +350,7 @@
if (display) { if (display) {
$.each(this.filterResults, function (index, category) { $.each(this.filterResults, function (index, category) {
if (category.id == id) { if (category.id === id) {
this.display(category); this.display(category);
$('#edit-category, #delete-category').prop('disabled', false); $('#edit-category, #delete-category').prop('disabled', false);
return false; return false;

View file

@ -66,7 +66,7 @@
var customerId = $(this).attr('data-id'); var customerId = $(this).attr('data-id');
var customer = {}; var customer = {};
$.each(instance.filterResults, function (index, item) { $.each(instance.filterResults, function (index, item) {
if (item.id == customerId) { if (Number(item.id) === Number(customerId)) {
customer = item; customer = item;
return false; return false;
} }
@ -91,11 +91,11 @@
var appointmentId = $(this).attr('data-id'); var appointmentId = $(this).attr('data-id');
var appointment = {}; var appointment = {};
$.each(instance.filterResults, function (index, c) { $.each(instance.filterResults, function (index, customer) {
if (c.id === customerId) { if (customer.id === customerId) {
$.each(c.appointments, function (index, a) { $.each(customer.appointments, function (index, customerAppointment) {
if (a.id == appointmentId) { if (Number(customerAppointment.id) === Number(appointmentId)) {
appointment = a; appointment = customerAppointment;
return false; return false;
} }
}); });
@ -137,7 +137,7 @@
$('#cancel-customer').click(function () { $('#cancel-customer').click(function () {
var id = $('#customer-id').val(); var id = $('#customer-id').val();
instance.resetForm(); instance.resetForm();
if (id != '') { if (id) {
instance.select(id, true); instance.select(id, true);
} }
}); });
@ -158,7 +158,7 @@
timezone: $('#timezone').val() timezone: $('#timezone').val()
}; };
if ($('#customer-id').val() != '') { if ($('#customer-id').val()) {
customer.id = $('#customer-id').val(); customer.id = $('#customer-id').val();
} }
@ -201,18 +201,21 @@
* @param {Object} customer Contains the customer data. * @param {Object} customer Contains the customer data.
*/ */
CustomersHelper.prototype.save = function (customer) { CustomersHelper.prototype.save = function (customer) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_customer'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_customer';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
customer: JSON.stringify(customer) customer: JSON.stringify(customer)
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.customer_saved); .done(function (response) {
this.resetForm(); Backend.displayNotification(EALang.customer_saved);
$('#filter-customers .key').val(''); this.resetForm();
this.filter('', response.id, true); $('#filter-customers .key').val('');
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); this.filter('', response.id, true);
}.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -221,17 +224,20 @@
* @param {Number} id Record id to be deleted. * @param {Number} id Record id to be deleted.
*/ */
CustomersHelper.prototype.delete = function (id) { CustomersHelper.prototype.delete = function (id) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_customer'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_customer';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
customer_id: id customer_id: id
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.customer_deleted); .done(function () {
this.resetForm(); Backend.displayNotification(EALang.customer_deleted);
this.filter($('#filter-customers .key').val()); this.resetForm();
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); this.filter($('#filter-customers .key').val());
}.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -248,27 +254,27 @@
var missingRequired = false; var missingRequired = false;
$('.required').each(function () { $('.required').each(function () {
if ($(this).val() == '') { if ($(this).val() === '') {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
// Validate email address. // Validate email address.
if (!GeneralFunctions.validateEmail($('#email').val())) { if (!GeneralFunctions.validateEmail($('#email').val())) {
$('#email').closest('.form-group').addClass('has-error'); $('#email').closest('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
return true; return true;
} catch (message) { } catch (error) {
$('#form-message') $('#form-message')
.addClass('alert-danger') .addClass('alert-danger')
.text(message) .text(error.message)
.show(); .show();
return false; return false;
} }
@ -347,42 +353,45 @@
CustomersHelper.prototype.filter = function (key, selectId, display) { CustomersHelper.prototype.filter = function (key, selectId, display) {
display = display || false; display = display || false;
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_customers'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_customers';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key, key: key,
limit: this.filterLimit limit: this.filterLimit
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
this.filterResults = response; .done(function (response) {
this.filterResults = response;
$('#filter-customers .results').html(''); $('#filter-customers .results').html('');
$.each(response, function (index, customer) { $.each(response, function (index, customer) {
var html = this.getFilterHtml(customer); var html = this.getFilterHtml(customer);
$('#filter-customers .results').append(html); $('#filter-customers .results').append(html);
}.bind(this)); }.bind(this));
if (response.length == 0) { if (!response.length) {
$('#filter-customers .results').html('<em>' + EALang.no_records_found + '</em>'); $('#filter-customers .results').html('<em>' + EALang.no_records_found + '</em>');
} else if (response.length === this.filterLimit) { } else if (response.length === this.filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'well btn-block load-more text-center', 'class': 'well btn-block load-more text-center',
'text': EALang.load_more, 'text': EALang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; this.filterLimit += 20;
this.filter(key, selectId, display); this.filter(key, selectId, display);
}.bind(this) }.bind(this)
}) })
.appendTo('#filter-customers .results'); .appendTo('#filter-customers .results');
} }
if (selectId != undefined) { if (selectId) {
this.select(selectId, display); this.select(selectId, display);
} }
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -395,8 +404,7 @@
CustomersHelper.prototype.getFilterHtml = function (customer) { CustomersHelper.prototype.getFilterHtml = function (customer) {
var name = customer.first_name + ' ' + customer.last_name; var name = customer.first_name + ' ' + customer.last_name;
var info = customer.email; var info = customer.email;
info = (customer.phone_number != '' && customer.phone_number != null) info = customer.phone_number ? info + ', ' + customer.phone_number : info;
? info + ', ' + customer.phone_number : info;
var html = var html =
'<div class="entry" data-id="' + customer.id + '">' + '<div class="entry" data-id="' + customer.id + '">' +
@ -424,7 +432,7 @@
$('#filter-customers .selected').removeClass('selected'); $('#filter-customers .selected').removeClass('selected');
$('#filter-customers .entry').each(function () { $('#filter-customers .entry').each(function () {
if ($(this).attr('data-id') == id) { if (Number($(this).attr('data-id')) === Number(id)) {
$(this).addClass('selected'); $(this).addClass('selected');
return false; return false;
} }
@ -432,7 +440,7 @@
if (display) { if (display) {
$.each(this.filterResults, function (index, customer) { $.each(this.filterResults, function (index, customer) {
if (customer.id == id) { if (Number(customer.id) === Number(id)) {
this.display(customer); this.display(customer);
$('#edit-customer, #delete-customer').prop('disabled', false); $('#edit-customer, #delete-customer').prop('disabled', false);
return false; return false;

View file

@ -92,20 +92,23 @@ window.BackendServices = window.BackendServices || {};
*/ */
exports.updateAvailableCategories = function () { exports.updateAvailableCategories = function () {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_service_categories'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_service_categories';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: '' key: ''
}; };
$.post(url, data, function (response) { $.post(url, data)
GlobalVariables.categories = response; .done(function (response) {
var $select = $('#service-category'); GlobalVariables.categories = response;
$select.empty(); var $select = $('#service-category');
$.each(response, function (index, category) { $select.empty();
var option = new Option(category.name, category.id); $.each(response, function (index, category) {
$select.append(option); var option = new Option(category.name, category.id);
}); $select.append(option);
$select.append(new Option('- ' + EALang.no_category + ' -', null)).val('null'); });
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); $select.append(new Option('- ' + EALang.no_category + ' -', null)).val('null');
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
})(window.BackendServices); })(window.BackendServices);

View file

@ -190,18 +190,21 @@
* then the update operation is going to be executed. * then the update operation is going to be executed.
*/ */
ServicesHelper.prototype.save = function (service) { ServicesHelper.prototype.save = function (service) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_service'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_service';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
service: JSON.stringify(service) service: JSON.stringify(service)
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.service_saved); .done(function (response) {
this.resetForm(); Backend.displayNotification(EALang.service_saved);
$('#filter-services .key').val(''); this.resetForm();
this.filter('', response.id, true); $('#filter-services .key').val('');
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); this.filter('', response.id, true);
}.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -210,18 +213,21 @@
* @param {Number} id Record ID to be deleted. * @param {Number} id Record ID to be deleted.
*/ */
ServicesHelper.prototype.delete = function (id) { ServicesHelper.prototype.delete = function (id) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_service'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_service';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
service_id: id service_id: id
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.service_deleted); .done(function () {
Backend.displayNotification(EALang.service_deleted);
this.resetForm(); this.resetForm();
this.filter($('#filter-services .key').val()); this.filter($('#filter-services .key').val());
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -237,18 +243,18 @@
var missingRequired = false; var missingRequired = false;
$('#services .required').each(function () { $('#services .required').each(function () {
if ($(this).val() == '' || $(this).val() == undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
return true; return true;
} catch (exc) { } catch (error) {
return false; return false;
} }
}; };
@ -301,41 +307,44 @@
ServicesHelper.prototype.filter = function (key, selectId, display) { ServicesHelper.prototype.filter = function (key, selectId, display) {
display = display || false; display = display || false;
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_services'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_services';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key, key: key,
limit: this.filterLimit limit: this.filterLimit
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
this.filterResults = response; .done(function (response) {
this.filterResults = response;
$('#filter-services .results').html(''); $('#filter-services .results').html('');
$.each(response, function (index, service) { $.each(response, function (index, service) {
var html = ServicesHelper.prototype.getFilterHtml(service); var html = ServicesHelper.prototype.getFilterHtml(service);
$('#filter-services .results').append(html); $('#filter-services .results').append(html);
}); });
if (response.length === 0) { if (response.length === 0) {
$('#filter-services .results').html('<em>' + EALang.no_records_found + '</em>'); $('#filter-services .results').html('<em>' + EALang.no_records_found + '</em>');
} else if (response.length === this.filterLimit) { } else if (response.length === this.filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'well btn-block load-more text-center', 'class': 'well btn-block load-more text-center',
'text': EALang.load_more, 'text': EALang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; this.filterLimit += 20;
this.filter(key, selectId, display); this.filter(key, selectId, display);
}.bind(this) }.bind(this)
}) })
.appendTo('#filter-services .results'); .appendTo('#filter-services .results');
} }
if (selectId !== undefined) { if (selectId) {
this.select(selectId, display); this.select(selectId, display);
} }
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -371,7 +380,7 @@
$('#filter-services .selected').removeClass('selected'); $('#filter-services .selected').removeClass('selected');
$('#filter-services .service-row').each(function () { $('#filter-services .service-row').each(function () {
if ($(this).attr('data-id') == id) { if (Number($(this).attr('data-id')) === Number(id)) {
$(this).addClass('selected'); $(this).addClass('selected');
return false; return false;
} }
@ -379,7 +388,7 @@
if (display) { if (display) {
$.each(this.filterResults, function (index, service) { $.each(this.filterResults, function (index, service) {
if (service.id == id) { if (Number(service.id) === Number(id)) {
this.display(service); this.display(service);
$('#edit-service, #delete-service').prop('disabled', false); $('#edit-service, #delete-service').prop('disabled', false);
return false; return false;

View file

@ -126,7 +126,7 @@ window.BackendSettings = window.BackendSettings || {};
$('#password, #retype-password').val(''); $('#password, #retype-password').val('');
$('#calendar-view').val(GlobalVariables.settings.user.settings.calendar_view); $('#calendar-view').val(GlobalVariables.settings.user.settings.calendar_view);
if (GlobalVariables.settings.user.settings.notifications == true) { if (GlobalVariables.settings.user.settings.notifications === true) {
$('#user-notifications').addClass('active'); $('#user-notifications').addClass('active');
} else { } else {
$('#user-notifications').removeClass('active'); $('#user-notifications').removeClass('active');
@ -142,12 +142,12 @@ window.BackendSettings = window.BackendSettings || {};
} }
// Apply Privileges // Apply Privileges
if (GlobalVariables.user.privileges.system_settings.edit == false) { if (GlobalVariables.user.privileges.system_settings.edit === false) {
$('#general, #business-logic').find('select, input, textarea').prop('readonly', true); $('#general, #business-logic').find('select, input, textarea').prop('readonly', true);
$('#general, #business-logic').find('button').prop('disabled', true); $('#general, #business-logic').find('button').prop('disabled', true);
} }
if (GlobalVariables.user.privileges.user_settings.edit == false) { if (GlobalVariables.user.privileges.user_settings.edit === false) {
$('#user').find('select, input, textarea').prop('readonly', true); $('#user').find('select, input, textarea').prop('readonly', true);
$('#user').find('button').prop('disabled', true); $('#user').find('button').prop('disabled', true);
} }
@ -214,27 +214,30 @@ window.BackendSettings = window.BackendSettings || {};
$('#username').focusout(function () { $('#username').focusout(function () {
var $input = $(this); var $input = $(this);
if ($input.prop('readonly') == true || $input.val() == '') { if ($input.prop('readonly') === true || $input.val() === '') {
return; return;
} }
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
username: $input.val(), username: $input.val(),
user_id: $input.parents().eq(2).find('#user-id').val() user_id: $input.parents().eq(2).find('#user-id').val()
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
if (response == false) { .done(function (response) {
$input.closest('.form-group').addClass('has-error'); if (response === 'false') {
Backend.displayNotification(EALang.username_already_exists); $input.closest('.form-group').addClass('has-error');
$input.attr('already-exists', 'true'); Backend.displayNotification(EALang.username_already_exists);
} else { $input.attr('already-exists', 'true');
$input.closest('.form-group').removeClass('has-error'); } else {
$input.attr('already-exists', 'false'); $input.closest('.form-group').removeClass('has-error');
} $input.attr('already-exists', 'false');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); }
})
.fail(GeneralFunctions.ajaxFailureHandler);
}); });
/** /**
@ -245,16 +248,17 @@ window.BackendSettings = window.BackendSettings || {};
{ {
text: 'OK', text: 'OK',
click: function() { click: function() {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_apply_global_working_plan'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_apply_global_working_plan';
var postData = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
working_plan: JSON.stringify(exports.wp.get()), working_plan: JSON.stringify(exports.wp.get())
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.working_plans_got_updated); .done(function () {
}, 'json') Backend.displayNotification(EALang.working_plans_got_updated);
})
.fail(GeneralFunctions.ajaxFailureHandler) .fail(GeneralFunctions.ajaxFailureHandler)
.always(function() { .always(function() {
$('#message_box').dialog('close'); $('#message_box').dialog('close');

View file

@ -29,28 +29,31 @@
* @param {Array} settings Contains the system settings data. * @param {Array} settings Contains the system settings data.
*/ */
SystemSettings.prototype.save = function (settings) { SystemSettings.prototype.save = function (settings) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
settings: JSON.stringify(settings), settings: JSON.stringify(settings),
type: BackendSettings.SETTINGS_SYSTEM type: BackendSettings.SETTINGS_SYSTEM
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.settings_saved); .done(function () {
Backend.displayNotification(EALang.settings_saved);
// Update the logo title on the header. // Update the logo title on the header.
$('#header-logo span').text($('#company-name').val()); $('#header-logo span').text($('#company-name').val());
// Update variables also used in other setting tabs // Update variables also used in other setting tabs
GlobalVariables.timeFormat = $('#time-format').val(); GlobalVariables.timeFormat = $('#time-format').val();
GlobalVariables.firstWeekday = $('#first-weekday').val(); GlobalVariables.firstWeekday = $('#first-weekday').val();
// We need to refresh the working plan. // We need to refresh the working plan.
var workingPlan = BackendSettings.wp.get(); var workingPlan = BackendSettings.wp.get();
BackendSettings.wp.setup(workingPlan); BackendSettings.wp.setup(workingPlan);
BackendSettings.wp.timepickers(false); BackendSettings.wp.timepickers(false);
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); })
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -151,25 +154,25 @@
// Validate required fields. // Validate required fields.
var missingRequired = false; var missingRequired = false;
$('#general .required').each(function () { $('#general .required').each(function () {
if ($(this).val() == '' || $(this).val() == undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
// Validate company email address. // Validate company email address.
if (!GeneralFunctions.validateEmail($('#company-email').val())) { if (!GeneralFunctions.validateEmail($('#company-email').val())) {
$('#company-email').closest('.form-group').addClass('has-error'); $('#company-email').closest('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
return true; return true;
} catch (message) { } catch (error) {
Backend.displayNotification(message); Backend.displayNotification(error.message);
return false; return false;
} }
}; };

View file

@ -47,7 +47,7 @@
} }
}; };
if ($('#password').val() != '') { if ($('#password').val()) {
user.settings.password = $('#password').val(); user.settings.password = $('#password').val();
} }
@ -65,20 +65,22 @@
return; // Validation failed, do not proceed. return; // Validation failed, do not proceed.
} }
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
type: BackendSettings.SETTINGS_USER, type: BackendSettings.SETTINGS_USER,
settings: JSON.stringify(settings) settings: JSON.stringify(settings)
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
Backend.displayNotification(EALang.settings_saved); .done(function () {
Backend.displayNotification(EALang.settings_saved);
// Update footer greetings. // Update footer greetings.
$('#footer-user-display-name').text('Hello, ' + $('#first-name').val() + ' ' + $('#last-name').val() + '!'); $('#footer-user-display-name').text('Hello, ' + $('#first-name').val() + ' ' + $('#last-name').val() + '!');
})
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); .fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -95,36 +97,36 @@
// Validate required fields. // Validate required fields.
var missingRequired = false; var missingRequired = false;
$('#user .required').each(function () { $('#user .required').each(function () {
if ($(this).val() === '' || $(this).val() === undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
// Validate passwords (if provided). // Validate passwords (if provided).
if ($('#password').val() != $('#retype-password').val()) { if ($('#password').val() !== $('#retype-password').val()) {
$('#password, #retype-password').closest('.form-group').addClass('has-error'); $('#password, #retype-password').closest('.form-group').addClass('has-error');
throw EALang.passwords_mismatch; throw new Error(EALang.passwords_mismatch);
} }
// Validate user email. // Validate user email.
if (!GeneralFunctions.validateEmail($('#email').val())) { if (!GeneralFunctions.validateEmail($('#email').val())) {
$('#email').closest('.form-group').addClass('has-error'); $('#email').closest('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
if ($('#username').attr('already-exists') === 'true') { if ($('#username').attr('already-exists') === 'true') {
$('#username').closest('.form-group').addClass('has-error'); $('#username').closest('.form-group').addClass('has-error');
throw EALang.username_already_exists; throw new Error(EALang.username_already_exists);
} }
return true; return true;
} catch (exc) { } catch (error) {
Backend.displayNotification(exc); Backend.displayNotification(exc.message);
return false; return false;
} }
}; };

View file

@ -126,27 +126,31 @@ window.BackendUsers = window.BackendUsers || {};
// Update the list with the all the available providers. // Update the list with the all the available providers.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_providers'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_providers';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: '' key: ''
}; };
$.post(url, data, function (response) {
GlobalVariables.providers = response;
var html = '<div>'; $.post(url, data)
$.each(GlobalVariables.providers, function (index, provider) { .done(function (response) {
html += GlobalVariables.providers = response;
'<div class="checkbox">' +
'<label class="checkbox">' + var html = '<div>';
'<input type="checkbox" data-id="' + provider.id + '" />' + $.each(GlobalVariables.providers, function (index, provider) {
provider.first_name + ' ' + provider.last_name + html +=
'</label>' + '<div class="checkbox">' +
'</div>'; '<label class="checkbox">' +
}); '<input type="checkbox" data-id="' + provider.id + '" />' +
html += '</div>'; provider.first_name + ' ' + provider.last_name +
$('#secretary-providers').html(html); '</label>' +
$('#secretary-providers input:checkbox').prop('disabled', true); '</div>';
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); });
html += '</div>';
$('#secretary-providers').html(html);
$('#secretary-providers input:checkbox').prop('disabled', true);
})
.fail(GeneralFunctions.ajaxFailureHandler);
} }
helper.resetForm(); helper.resetForm();
@ -164,37 +168,40 @@ window.BackendUsers = window.BackendUsers || {};
$('#admin-username, #provider-username, #secretary-username').focusout(function () { $('#admin-username, #provider-username, #secretary-username').focusout(function () {
var $input = $(this); var $input = $(this);
if ($input.prop('readonly') == true || $input.val() == '') { if ($input.prop('readonly') === true || $input.val() === '') {
return; return;
} }
var userId = $input.parents().eq(2).find('.record-id').val(); var userId = $input.parents().eq(2).find('.record-id').val();
if (userId == undefined) { if (!userId) {
return; return;
} }
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
username: $input.val(), username: $input.val(),
user_id: userId user_id: userId
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
if (response == false) { .done(function (response) {
$input.closest('.form-group').addClass('has-error'); if (response === 'false') {
$input.attr('already-exists', 'true'); $input.closest('.form-group').addClass('has-error');
$input.parents().eq(3).find('.form-message').text(EALang.username_already_exists); $input.attr('already-exists', 'true');
$input.parents().eq(3).find('.form-message').show(); $input.parents().eq(3).find('.form-message').text(EALang.username_already_exists);
} else { $input.parents().eq(3).find('.form-message').show();
$input.closest('.form-group').removeClass('has-error'); } else {
$input.attr('already-exists', 'false'); $input.closest('.form-group').removeClass('has-error');
if ($input.parents().eq(3).find('.form-message').text() == EALang.username_already_exists) { $input.attr('already-exists', 'false');
$input.parents().eq(3).find('.form-message').hide(); if ($input.parents().eq(3).find('.form-message').text() === EALang.username_already_exists) {
$input.parents().eq(3).find('.form-message').hide();
}
} }
} })
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); .fail(GeneralFunctions.ajaxFailureHandler);
}); });
} }

View file

@ -181,7 +181,7 @@
$('#admins').on('click', '#cancel-admin', function () { $('#admins').on('click', '#cancel-admin', function () {
var id = $('#admin-id').val(); var id = $('#admin-id').val();
this.resetForm(); this.resetForm();
if (id != '') { if (id) {
this.select(id, true); this.select(id, true);
} }
}.bind(this)); }.bind(this));
@ -195,6 +195,7 @@
*/ */
AdminsHelper.prototype.save = function (admin) { AdminsHelper.prototype.save = function (admin) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_admin'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_admin';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
admin: JSON.stringify(admin) admin: JSON.stringify(admin)
@ -217,6 +218,7 @@
*/ */
AdminsHelper.prototype.delete = function (id) { AdminsHelper.prototype.delete = function (id) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_admin'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_admin';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
admin_id: id admin_id: id
@ -244,45 +246,45 @@
var missingRequired = false; var missingRequired = false;
$('#admins .required').each(function () { $('#admins .required').each(function () {
if ($(this).val() == '' || $(this).val() == undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw 'Fields with * are required.'; throw new Error('Fields with * are required.');
} }
// Validate passwords. // Validate passwords.
if ($('#admin-password').val() != $('#admin-password-confirm').val()) { if ($('#admin-password').val() !== $('#admin-password-confirm').val()) {
$('#admin-password, #admin-password-confirm').closest('.form-group').addClass('has-error'); $('#admin-password, #admin-password-confirm').closest('.form-group').addClass('has-error');
throw EALang.passwords_mismatch; throw new Error(EALang.passwords_mismatch);
} }
if ($('#admin-password').val().length < BackendUsers.MIN_PASSWORD_LENGTH if ($('#admin-password').val().length < BackendUsers.MIN_PASSWORD_LENGTH
&& $('#admin-password').val() != '') { && $('#admin-password').val() !== '') {
$('#admin-password, #admin-password-confirm').closest('.form-group').addClass('has-error'); $('#admin-password, #admin-password-confirm').closest('.form-group').addClass('has-error');
throw EALang.password_length_notice.replace('$number', BackendUsers.MIN_PASSWORD_LENGTH); throw new Error(EALang.password_length_notice.replace('$number', BackendUsers.MIN_PASSWORD_LENGTH));
} }
// Validate user email. // Validate user email.
if (!GeneralFunctions.validateEmail($('#admin-email').val())) { if (!GeneralFunctions.validateEmail($('#admin-email').val())) {
$('#admin-email').closest('.form-group').addClass('has-error'); $('#admin-email').closest('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
// Check if username exists // Check if username exists
if ($('#admin-username').attr('already-exists') == 'true') { if ($('#admin-username').attr('already-exists') === 'true') {
$('#admin-username').closest('.form-group').addClass('has-error'); $('#admin-username').closest('.form-group').addClass('has-error');
throw EALang.username_already_exists; throw new Error(EALang.username_already_exists);
} }
return true; return true;
} catch (message) { } catch (error) {
$('#admins .form-message') $('#admins .form-message')
.addClass('alert-danger') .addClass('alert-danger')
.text(message) .text(error.message)
.show(); .show();
return false; return false;
} }
@ -328,7 +330,7 @@
$('#admin-username').val(admin.settings.username); $('#admin-username').val(admin.settings.username);
$('#admin-calendar-view').val(admin.settings.calendar_view); $('#admin-calendar-view').val(admin.settings.calendar_view);
if (admin.settings.notifications == true) { if (admin.settings.notifications === true) {
$('#admin-notifications').addClass('active'); $('#admin-notifications').addClass('active');
} else { } else {
$('#admin-notifications').removeClass('active'); $('#admin-notifications').removeClass('active');
@ -347,41 +349,44 @@
AdminsHelper.prototype.filter = function (key, selectId, display) { AdminsHelper.prototype.filter = function (key, selectId, display) {
display = display || false; display = display || false;
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_admins'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_admins';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key, key: key,
limit: this.filterLimit limit: this.filterLimit
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
this.filterResults = response; .done(function (response) {
this.filterResults = response;
$('#filter-admins .results').html(''); $('#filter-admins .results').html('');
$.each(response, function (index, admin) { $.each(response, function (index, admin) {
var html = this.getFilterHtml(admin); var html = this.getFilterHtml(admin);
$('#filter-admins .results').append(html); $('#filter-admins .results').append(html);
}.bind(this)); }.bind(this));
if (response.length == 0) { if (!response.length) {
$('#filter-admins .results').html('<em>' + EALang.no_records_found + '</em>') $('#filter-admins .results').html('<em>' + EALang.no_records_found + '</em>')
} else if (response.length === this.filterLimit) { } else if (response.length === this.filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'well btn-block load-more text-center', 'class': 'well btn-block load-more text-center',
'text': EALang.load_more, 'text': EALang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; this.filterLimit += 20;
this.filter(key, selectId, display); this.filter(key, selectId, display);
}.bind(this) }.bind(this)
}) })
.appendTo('#filter-admins .results'); .appendTo('#filter-admins .results');
} }
if (selectId != undefined) { if (selectId) {
this.select(selectId, display); this.select(selectId, display);
} }
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -395,11 +400,9 @@
var name = admin.first_name + ' ' + admin.last_name; var name = admin.first_name + ' ' + admin.last_name;
var info = admin.email; var info = admin.email;
info = (admin.mobile_number != '' && admin.mobile_number != null) info = admin.mobile_number ? info + ', ' + admin.mobile_number : info;
? info + ', ' + admin.mobile_number : info;
info = (admin.phone_number != '' && admin.phone_number != null) info = admin.phone_number ? info + ', ' + admin.phone_number : info;
? info + ', ' + admin.phone_number : info;
var html = var html =
'<div class="admin-row entry" data-id="' + admin.id + '">' + '<div class="admin-row entry" data-id="' + admin.id + '">' +
@ -424,7 +427,7 @@
$('#filter-admins .selected').removeClass('selected'); $('#filter-admins .selected').removeClass('selected');
$('.admin-row').each(function () { $('.admin-row').each(function () {
if ($(this).attr('data-id') == id) { if (Number($(this).attr('data-id')) === Number(id)) {
$(this).addClass('selected'); $(this).addClass('selected');
return false; return false;
} }
@ -432,7 +435,7 @@
if (display) { if (display) {
$.each(this.filterResults, function (index, admin) { $.each(this.filterResults, function (index, admin) {
if (admin.id == id) { if (Number(admin.id) === Number(id)) {
this.display(admin); this.display(admin);
$('#edit-admin, #delete-admin').prop('disabled', false); $('#edit-admin, #delete-admin').prop('disabled', false);
return false; return false;

View file

@ -203,7 +203,7 @@
$('#providers').on('click', '#cancel-provider', function () { $('#providers').on('click', '#cancel-provider', function () {
var id = $('#filter-providers .selected').attr('data-id'); var id = $('#filter-providers .selected').attr('data-id');
this.resetForm(); this.resetForm();
if (id != '') { if (id) {
this.select(id, true); this.select(id, true);
} }
}.bind(this)); }.bind(this));
@ -298,44 +298,44 @@
// Validate required fields. // Validate required fields.
var missingRequired = false; var missingRequired = false;
$('#providers .required').each(function () { $('#providers .required').each(function () {
if ($(this).val() == '' || $(this).val() == undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
// Validate passwords. // Validate passwords.
if ($('#provider-password').val() != $('#provider-password-confirm').val()) { if ($('#provider-password').val() !== $('#provider-password-confirm').val()) {
$('#provider-password, #provider-password-confirm').closest('.form-group').addClass('has-error'); $('#provider-password, #provider-password-confirm').closest('.form-group').addClass('has-error');
throw EALang.passwords_mismatch; throw new Error(EALang.passwords_mismatch);
} }
if ($('#provider-password').val().length < BackendUsers.MIN_PASSWORD_LENGTH if ($('#provider-password').val().length < BackendUsers.MIN_PASSWORD_LENGTH
&& $('#provider-password').val() != '') { && $('#provider-password').val() !== '') {
$('#provider-password, #provider-password-confirm').closest('.form-group').addClass('has-error'); $('#provider-password, #provider-password-confirm').closest('.form-group').addClass('has-error');
throw EALang.password_length_notice.replace('$number', BackendUsers.MIN_PASSWORD_LENGTH); throw new Error(EALang.password_length_notice.replace('$number', BackendUsers.MIN_PASSWORD_LENGTH));
} }
// Validate user email. // Validate user email.
if (!GeneralFunctions.validateEmail($('#provider-email').val())) { if (!GeneralFunctions.validateEmail($('#provider-email').val())) {
$('#provider-email').closest('.form-group').addClass('has-error'); $('#provider-email').closest('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
// Check if username exists // Check if username exists
if ($('#provider-username').attr('already-exists') == 'true') { if ($('#provider-username').attr('already-exists') === 'true') {
$('#provider-username').closest('.form-group').addClass('has-error'); $('#provider-username').closest('.form-group').addClass('has-error');
throw EALang.username_already_exists; throw new Error(EALang.username_already_exists);
} }
return true; return true;
} catch (message) { } catch (error) {
$('#providers .form-message') $('#providers .form-message')
.addClass('alert-danger') .addClass('alert-danger')
.text(message) .text(error.message)
.show(); .show();
return false; return false;
} }
@ -395,7 +395,7 @@
$('#provider-username').val(provider.settings.username); $('#provider-username').val(provider.settings.username);
$('#provider-calendar-view').val(provider.settings.calendar_view); $('#provider-calendar-view').val(provider.settings.calendar_view);
if (provider.settings.notifications == true) { if (provider.settings.notifications === '1') {
$('#provider-notifications').addClass('active'); $('#provider-notifications').addClass('active');
} else { } else {
$('#provider-notifications').removeClass('active'); $('#provider-notifications').removeClass('active');
@ -414,7 +414,7 @@
$('#provider-services input:checkbox').prop('checked', false); $('#provider-services input:checkbox').prop('checked', false);
$.each(provider.services, function (index, serviceId) { $.each(provider.services, function (index, serviceId) {
$('#provider-services input:checkbox').each(function () { $('#provider-services input:checkbox').each(function () {
if ($(this).attr('data-id') == serviceId) { if (Number($(this).attr('data-id')) === Number(serviceId)) {
$(this).prop('checked', true); $(this).prop('checked', true);
// Add dedicated service-provider link. // Add dedicated service-provider link.
dedicatedUrl = GlobalVariables.baseUrl + '/index.php?provider=' + encodeURIComponent(provider.id) dedicatedUrl = GlobalVariables.baseUrl + '/index.php?provider=' + encodeURIComponent(provider.id)
@ -446,41 +446,43 @@
ProvidersHelper.prototype.filter = function (key, selectId, display) { ProvidersHelper.prototype.filter = function (key, selectId, display) {
display = display || false; display = display || false;
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_providers'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_providers';
var postData = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key, key: key,
limit: this.filterLimit limit: this.filterLimit
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
this.filterResults = response; .done(function (response) {
this.filterResults = response;
$('#filter-providers .results').html(''); $('#filter-providers .results').html('');
$.each(response, function (index, provider) { $.each(response, function (index, provider) {
var html = this.getFilterHtml(provider); var html = this.getFilterHtml(provider);
$('#filter-providers .results').append(html); $('#filter-providers .results').append(html);
}.bind(this)); }.bind(this));
if (response.length == 0) { if (!response.length) {
$('#filter-providers .results').html('<em>' + EALang.no_records_found + '</em>') $('#filter-providers .results').html('<em>' + EALang.no_records_found + '</em>')
} else if (response.length === this.filterLimit) { } else if (response.length === this.filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'well btn-block load-more text-center', 'class': 'well btn-block load-more text-center',
'text': EALang.load_more, 'text': EALang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; this.filterLimit += 20;
this.filter(key, selectId, display); this.filter(key, selectId, display);
}.bind(this) }.bind(this)
}) })
.appendTo('#filter-providers .results'); .appendTo('#filter-providers .results');
} }
if (selectId != undefined) { if (selectId) {
this.select(selectId, display); this.select(selectId, display);
} }
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -494,11 +496,9 @@
var name = provider.first_name + ' ' + provider.last_name, var name = provider.first_name + ' ' + provider.last_name,
info = provider.email; info = provider.email;
info = (provider.mobile_number != '' && provider.mobile_number != null) info = provider.mobile_number ? info + ', ' + provider.mobile_number : info;
? info + ', ' + provider.mobile_number : info;
info = (provider.phone_number != '' && provider.phone_number != null) info = provider.phone_number ? info + ', ' + provider.phone_number : info;
? info + ', ' + provider.phone_number : info;
var html = var html =
'<div class="provider-row entry" data-id="' + provider.id + '">' + '<div class="provider-row entry" data-id="' + provider.id + '">' +
@ -587,7 +587,7 @@
// Select record in filter results. // Select record in filter results.
$('#filter-providers .provider-row').each(function () { $('#filter-providers .provider-row').each(function () {
if ($(this).attr('data-id') == id) { if (Number($(this).attr('data-id')) === Number(id)) {
$(this).addClass('selected'); $(this).addClass('selected');
return false; return false;
} }
@ -596,7 +596,7 @@
// Display record in form (if display = true). // Display record in form (if display = true).
if (display) { if (display) {
$.each(this.filterResults, function (index, provider) { $.each(this.filterResults, function (index, provider) {
if (provider.id == id) { if (Number(provider.id) === Number(id)) {
this.display(provider); this.display(provider);
$('#edit-provider, #delete-provider').prop('disabled', false); $('#edit-provider, #delete-provider').prop('disabled', false);
return false; return false;

View file

@ -194,7 +194,7 @@
$('#secretaries').on('click', '#cancel-secretary', function () { $('#secretaries').on('click', '#cancel-secretary', function () {
var id = $('#secretary-id').val(); var id = $('#secretary-id').val();
this.resetForm(); this.resetForm();
if (id != '') { if (id) {
this.select(id, true); this.select(id, true);
} }
}.bind(this)); }.bind(this));
@ -208,6 +208,7 @@
*/ */
SecretariesHelper.prototype.save = function (secretary) { SecretariesHelper.prototype.save = function (secretary) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_secretary'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_secretary';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
secretary: JSON.stringify(secretary) secretary: JSON.stringify(secretary)
@ -230,6 +231,7 @@
*/ */
SecretariesHelper.prototype.delete = function (id) { SecretariesHelper.prototype.delete = function (id) {
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_secretary'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_secretary';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
secretary_id: id secretary_id: id
@ -257,45 +259,45 @@
// Validate required fields. // Validate required fields.
var missingRequired = false; var missingRequired = false;
$('#secretaries .required').each(function () { $('#secretaries .required').each(function () {
if ($(this).val() == '' || $(this).val() == undefined) { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw 'Fields with * are required.'; throw new Error('Fields with * are required.');
} }
// Validate passwords. // Validate passwords.
if ($('#secretary-password').val() != $('#secretary-password-confirm').val()) { if ($('#secretary-password').val() !== $('#secretary-password-confirm').val()) {
$('#secretary-password, #secretary-password-confirm').closest('.form-group').addClass('has-error'); $('#secretary-password, #secretary-password-confirm').closest('.form-group').addClass('has-error');
throw 'Passwords mismatch!'; throw new Error('Passwords mismatch!');
} }
if ($('#secretary-password').val().length < BackendUsers.MIN_PASSWORD_LENGTH if ($('#secretary-password').val().length < BackendUsers.MIN_PASSWORD_LENGTH
&& $('#secretary-password').val() != '') { && $('#secretary-password').val() !== '') {
$('#secretary-password, #secretary-password-confirm').closest('.form-group').addClass('has-error'); $('#secretary-password, #secretary-password-confirm').closest('.form-group').addClass('has-error');
throw 'Password must be at least ' + BackendUsers.MIN_PASSWORD_LENGTH throw new Error('Password must be at least ' + BackendUsers.MIN_PASSWORD_LENGTH
+ ' characters long.'; + ' characters long.');
} }
// Validate user email. // Validate user email.
if (!GeneralFunctions.validateEmail($('#secretary-email').val())) { if (!GeneralFunctions.validateEmail($('#secretary-email').val())) {
$('#secretary-email').closest('.form-group').addClass('has-error'); $('#secretary-email').closest('.form-group').addClass('has-error');
throw 'Invalid email address!'; throw new Error('Invalid email address!');
} }
// Check if username exists // Check if username exists
if ($('#secretary-username').attr('already-exists') == 'true') { if ($('#secretary-username').attr('already-exists') === 'true') {
$('#secretary-username').closest('.form-group').addClass('has-error'); $('#secretary-username').closest('.form-group').addClass('has-error');
throw 'Username already exists.'; throw new Error('Username already exists.');
} }
return true; return true;
} catch (message) { } catch (error) {
$('#secretaries .form-message') $('#secretaries .form-message')
.addClass('alert-danger') .addClass('alert-danger')
.text(message) .text(error.message)
.show(); .show();
return false; return false;
} }
@ -344,7 +346,7 @@
$('#secretary-username').val(secretary.settings.username); $('#secretary-username').val(secretary.settings.username);
$('#secretary-calendar-view').val(secretary.settings.calendar_view); $('#secretary-calendar-view').val(secretary.settings.calendar_view);
if (secretary.settings.notifications == true) { if (secretary.settings.notifications === '1') {
$('#secretary-notifications').addClass('active'); $('#secretary-notifications').addClass('active');
} else { } else {
$('#secretary-notifications').removeClass('active'); $('#secretary-notifications').removeClass('active');
@ -353,7 +355,7 @@
$('#secretary-providers input:checkbox').prop('checked', false); $('#secretary-providers input:checkbox').prop('checked', false);
$.each(secretary.providers, function (index, providerId) { $.each(secretary.providers, function (index, providerId) {
$('#secretary-providers input:checkbox').each(function () { $('#secretary-providers input:checkbox').each(function () {
if ($(this).attr('data-id') == providerId) { if (Number($(this).attr('data-id')) === Number(providerId)) {
$(this).prop('checked', true); $(this).prop('checked', true);
} }
}); });
@ -371,41 +373,44 @@
SecretariesHelper.prototype.filter = function (key, selectId, display) { SecretariesHelper.prototype.filter = function (key, selectId, display) {
display = display || false; display = display || false;
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_secretaries'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_secretaries';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
key: key, key: key,
limit: this.filterLimit limit: this.filterLimit
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
this.filterResults = response; .done(function (response) {
this.filterResults = response;
$('#filter-secretaries .results').html(''); $('#filter-secretaries .results').html('');
$.each(response, function (index, secretary) { $.each(response, function (index, secretary) {
var html = this.getFilterHtml(secretary); var html = this.getFilterHtml(secretary);
$('#filter-secretaries .results').append(html); $('#filter-secretaries .results').append(html);
}.bind(this)); }.bind(this));
if (response.length == 0) { if (!response.length) {
$('#filter-secretaries .results').html('<em>' + EALang.no_records_found + '</em>') $('#filter-secretaries .results').html('<em>' + EALang.no_records_found + '</em>')
} else if (response.length === this.filterLimit) { } else if (response.length === this.filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'well btn-block load-more text-center', 'class': 'well btn-block load-more text-center',
'text': EALang.load_more, 'text': EALang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; this.filterLimit += 20;
this.filter(key, selectId, display); this.filter(key, selectId, display);
}.bind(this) }.bind(this)
}) })
.appendTo('#filter-secretaries .results'); .appendTo('#filter-secretaries .results');
} }
if (selectId != undefined) { if (selectId) {
this.select(selectId, display); this.select(selectId, display);
} }
}.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler); }.bind(this))
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -419,11 +424,9 @@
var name = secretary.first_name + ' ' + secretary.last_name; var name = secretary.first_name + ' ' + secretary.last_name;
var info = secretary.email; var info = secretary.email;
info = (secretary.mobile_number != '' && secretary.mobile_number != null) info = secretary.mobile_number ? info + ', ' + secretary.mobile_number : info;
? info + ', ' + secretary.mobile_number : info;
info = (secretary.phone_number != '' && secretary.phone_number != null) info = secretary.phone_number ? info + ', ' + secretary.phone_number : info;
? info + ', ' + secretary.phone_number : info;
var html = var html =
'<div class="secretary-row entry" data-id="' + secretary.id + '">' + '<div class="secretary-row entry" data-id="' + secretary.id + '">' +
@ -447,7 +450,7 @@
$('#filter-secretaries .selected').removeClass('selected'); $('#filter-secretaries .selected').removeClass('selected');
$('#filter-secretaries .secretary-row').each(function () { $('#filter-secretaries .secretary-row').each(function () {
if ($(this).attr('data-id') == id) { if (Number($(this).attr('data-id')) === Number(id)) {
$(this).addClass('selected'); $(this).addClass('selected');
return false; return false;
} }
@ -455,7 +458,7 @@
if (display) { if (display) {
$.each(this.filterResults, function (index, admin) { $.each(this.filterResults, function (index, admin) {
if (admin.id == id) { if (Number(admin.id) === Number(id)) {
this.display(admin); this.display(admin);
$('#edit-secretary, #delete-secretary').prop('disabled', false); $('#edit-secretary, #delete-secretary').prop('disabled', false);
return false; return false;

View file

@ -57,7 +57,7 @@ window.FrontendBook = window.FrontendBook || {};
bindEventHandlers = bindEventHandlers || true; bindEventHandlers = bindEventHandlers || true;
manageMode = manageMode || false; manageMode = manageMode || false;
if (window.console === undefined) { if (window.console) {
window.console = function () { window.console = function () {
}; // IE compatibility }; // IE compatibility
} }
@ -230,14 +230,13 @@ window.FrontendBook = window.FrontendBook || {};
* become visible. * become visible.
*/ */
$('#select-service').change(function () { $('#select-service').change(function () {
var currServiceId = $('#select-service').val(); var serviceId = $('#select-service').val();
$('#select-provider').empty(); $('#select-provider').empty();
$.each(GlobalVariables.availableProviders, function (indexProvider, provider) { $.each(GlobalVariables.availableProviders, function (indexProvider, provider) {
$.each(provider.services, function (indexService, serviceId) { $.each(provider.services, function (indexService, providerServiceId) {
// If the current provider is able to provide the selected service, // If the current provider is able to provide the selected service, add him to the listbox.
// add him to the listbox. if (Number(providerServiceId) === Number(serviceId)) {
if (serviceId == currServiceId) {
var optionHtml = '<option value="' + provider.id + '">' var optionHtml = '<option value="' + provider.id + '">'
+ provider.first_name + ' ' + provider.last_name + provider.first_name + ' ' + provider.last_name
+ '</option>'; + '</option>';
@ -266,15 +265,15 @@ window.FrontendBook = window.FrontendBook || {};
$('.button-next').click(function () { $('.button-next').click(function () {
// If we are on the first step and there is not provider selected do not continue // If we are on the first step and there is not provider selected do not continue
// with the next step. // with the next step.
if ($(this).attr('data-step_index') === '1' && $('#select-provider').val() == null) { if ($(this).attr('data-step_index') === '1' && !$('#select-provider').val()) {
return; return;
} }
// If we are on the 2nd tab then the user should have an appointment hour // If we are on the 2nd tab then the user should have an appointment hour
// selected. // selected.
if ($(this).attr('data-step_index') === '2') { if ($(this).attr('data-step_index') === '2') {
if ($('.selected-hour').length == 0) { if (!$('.selected-hour').length) {
if ($('#select-hour-prompt').length == 0) { if (!$('#select-hour-prompt').length) {
$('#available-hours').append('<br><br>' $('#available-hours').append('<br><br>'
+ '<span id="select-hour-prompt" class="text-danger">' + '<span id="select-hour-prompt" class="text-danger">'
+ EALang.appointment_hour_missing + EALang.appointment_hour_missing
@ -466,37 +465,37 @@ window.FrontendBook = window.FrontendBook || {};
// Validate required fields. // Validate required fields.
var missingRequiredField = false; var missingRequiredField = false;
$('.required').each(function () { $('.required').each(function () {
if ($(this).val() == '') { if (!$(this).val()) {
$(this).parents('.form-group').addClass('has-error'); $(this).parents('.form-group').addClass('has-error');
missingRequiredField = true; missingRequiredField = true;
} }
}); });
if (missingRequiredField) { if (missingRequiredField) {
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
var $acceptToTermsAndConditions = $('#accept-to-terms-and-conditions'); var $acceptToTermsAndConditions = $('#accept-to-terms-and-conditions');
if ($acceptToTermsAndConditions.length && !$acceptToTermsAndConditions.prop('checked')) { if ($acceptToTermsAndConditions.length && !$acceptToTermsAndConditions.prop('checked')) {
$acceptToTermsAndConditions.parents('label').addClass('text-danger'); $acceptToTermsAndConditions.parents('label').addClass('text-danger');
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
var $acceptToPrivacyPolicy = $('#accept-to-privacy-policy'); var $acceptToPrivacyPolicy = $('#accept-to-privacy-policy');
if ($acceptToPrivacyPolicy.length && !$acceptToPrivacyPolicy.prop('checked')) { if ($acceptToPrivacyPolicy.length && !$acceptToPrivacyPolicy.prop('checked')) {
$acceptToPrivacyPolicy.parents('label').addClass('text-danger'); $acceptToPrivacyPolicy.parents('label').addClass('text-danger');
throw EALang.fields_are_required; throw new Error(EALang.fields_are_required);
} }
// Validate email address. // Validate email address.
if (!GeneralFunctions.validateEmail($('#email').val())) { if (!GeneralFunctions.validateEmail($('#email').val())) {
$('#email').parents('.form-group').addClass('has-error'); $('#email').parents('.form-group').addClass('has-error');
throw EALang.invalid_email; throw new Error(EALang.invalid_email);
} }
return true; return true;
} catch (exc) { } catch (error) {
$('#form-message').text(exc); $('#form-message').text(error.message);
return false; return false;
} }
} }
@ -517,12 +516,12 @@ window.FrontendBook = window.FrontendBook || {};
selectedDate = GeneralFunctions.formatDate(selectedDate, GlobalVariables.dateFormat); selectedDate = GeneralFunctions.formatDate(selectedDate, GlobalVariables.dateFormat);
} }
var selServiceId = $('#select-service').val(); var serviceId = $('#select-service').val();
var servicePrice = ''; var servicePrice = '';
var serviceCurrency = ''; var serviceCurrency = '';
$.each(GlobalVariables.availableServices, function (index, service) { $.each(GlobalVariables.availableServices, function (index, service) {
if (service.id == selServiceId && service.price != '' && service.price != null && service.price != '0.00' && service.price != '0,00') { if (Number(service.id) === Number(serviceId) && Number(service.price) > 0) {
servicePrice = '<br>' + service.price; servicePrice = '<br>' + service.price;
serviceCurrency = service.currency; serviceCurrency = service.currency;
return false; // break loop return false; // break loop
@ -568,9 +567,9 @@ window.FrontendBook = window.FrontendBook || {};
// Update appointment form data for submission to server when the user confirms // Update appointment form data for submission to server when the user confirms
// the appointment. // the appointment.
var postData = {}; var data = {};
postData.customer = { data.customer = {
last_name: $('#last-name').val(), last_name: $('#last-name').val(),
first_name: $('#first-name').val(), first_name: $('#first-name').val(),
email: $('#email').val(), email: $('#email').val(),
@ -581,7 +580,7 @@ window.FrontendBook = window.FrontendBook || {};
timezone: $('#select-timezone').val() timezone: $('#select-timezone').val()
}; };
postData.appointment = { data.appointment = {
start_datetime: $('#select-date').datepicker('getDate').toString('yyyy-MM-dd') start_datetime: $('#select-date').datepicker('getDate').toString('yyyy-MM-dd')
+ ' ' + Date.parse($('.selected-hour').text()).toString('HH:mm') + ':00', + ' ' + Date.parse($('.selected-hour').text()).toString('HH:mm') + ':00',
end_datetime: _calcEndDatetime(), end_datetime: _calcEndDatetime(),
@ -591,14 +590,14 @@ window.FrontendBook = window.FrontendBook || {};
id_services: $('#select-service').val() id_services: $('#select-service').val()
}; };
postData.manage_mode = FrontendBook.manageMode; data.manage_mode = FrontendBook.manageMode;
if (FrontendBook.manageMode) { if (FrontendBook.manageMode) {
postData.appointment.id = GlobalVariables.appointmentData.id; data.appointment.id = GlobalVariables.appointmentData.id;
postData.customer.id = GlobalVariables.customerData.id; data.customer.id = GlobalVariables.customerData.id;
} }
$('input[name="csrfToken"]').val(GlobalVariables.csrfToken); $('input[name="csrfToken"]').val(GlobalVariables.csrfToken);
$('input[name="post_data"]').val(JSON.stringify(postData)); $('input[name="post_data"]').val(JSON.stringify(data));
}; };
/** /**
@ -609,12 +608,13 @@ window.FrontendBook = window.FrontendBook || {};
*/ */
function _calcEndDatetime() { function _calcEndDatetime() {
// Find selected service duration. // Find selected service duration.
var selServiceDuration = undefined; var serviceId = $('#select-service').val();
var serviceDuration;
$.each(GlobalVariables.availableServices, function (index, service) { $.each(GlobalVariables.availableServices, function (index, service) {
if (service.id == $('#select-service').val()) { if (Number(service.id) === Number(serviceId)) {
selServiceDuration = service.duration; serviceDuration = service.duration;
return false; // Stop searching ... return false;
} }
}); });
@ -622,10 +622,10 @@ window.FrontendBook = window.FrontendBook || {};
var startDatetime = $('#select-date').datepicker('getDate').toString('dd-MM-yyyy') var startDatetime = $('#select-date').datepicker('getDate').toString('dd-MM-yyyy')
+ ' ' + Date.parse($('.selected-hour').text()).toString('HH:mm'); + ' ' + Date.parse($('.selected-hour').text()).toString('HH:mm');
startDatetime = Date.parseExact(startDatetime, 'dd-MM-yyyy HH:mm'); startDatetime = Date.parseExact(startDatetime, 'dd-MM-yyyy HH:mm');
var endDatetime = undefined; var endDatetime;
if (selServiceDuration !== undefined && startDatetime !== null) { if (serviceDuration && startDatetime) {
endDatetime = startDatetime.add({'minutes': parseInt(selServiceDuration)}); endDatetime = startDatetime.add({'minutes': parseInt(serviceDuration)});
} else { } else {
endDatetime = new Date(); endDatetime = new Date();
} }
@ -687,22 +687,22 @@ window.FrontendBook = window.FrontendBook || {};
var html = ''; var html = '';
$.each(GlobalVariables.availableServices, function (index, service) { $.each(GlobalVariables.availableServices, function (index, service) {
if (service.id == serviceId) { // Just found the service. if (Number(service.id) === Number(serviceId)) {
html = '<strong>' + service.name + ' </strong>'; html = '<strong>' + service.name + ' </strong>';
if (service.description != '' && service.description != null) { if (service.description) {
html += '<br>' + service.description + '<br>'; html += '<br>' + service.description + '<br>';
} }
if (service.duration != '' && service.duration != null) { if (service.duration) {
html += '[' + EALang.duration + ' ' + service.duration + ' ' + EALang.minutes + ']'; html += '[' + EALang.duration + ' ' + service.duration + ' ' + EALang.minutes + ']';
} }
if (service.price != '' && service.price != null && service.price != '0.00' && service.price != '0,00') { if (Number(service.price) > 0) {
html += '[' + EALang.price + ' ' + service.price + ' ' + service.currency + ']'; html += '[' + EALang.price + ' ' + service.price + ' ' + service.currency + ']';
} }
if (service.location != '' && service.location != null) { if (service.location) {
html += '[' + EALang.location + ' ' + service.location + ']'; html += '[' + EALang.location + ' ' + service.location + ']';
} }
@ -712,13 +712,9 @@ window.FrontendBook = window.FrontendBook || {};
} }
}); });
$div.html(html); $div
.html(html)
if (html != '') { .toggle(html);
$div.show();
} else {
$div.hide();
}
} }
})(window.FrontendBook); })(window.FrontendBook);

View file

@ -37,90 +37,101 @@ window.FrontendBookApi = window.FrontendBookApi || {};
exports.getAvailableHours = function (selDate) { exports.getAvailableHours = function (selDate) {
$('#available-hours').empty(); $('#available-hours').empty();
// Find the selected service duration (it is going to be send within the "postData" object). // Find the selected service duration (it is going to be send within the "data" object).
var selServiceDuration = 15; // Default value of duration (in minutes). var serviceId = $('#select-service').val();
$.each(GlobalVariables.availableServices, function (index, service) {
if (service.id == $('#select-service').val()) { // Default value of duration (in minutes).
selServiceDuration = service.duration; var serviceDuration = 15;
}
}); var service = GlobalVariables.availableServices.filter(function(availableService) {
return Number(availableService.id) === Number(serviceId);
}).shift();
if (service) {
serviceDuration = service.duration;
}
// If the manage mode is true then the appointment's start date should return as available too. // If the manage mode is true then the appointment's start date should return as available too.
var appointmentId = FrontendBook.manageMode ? GlobalVariables.appointmentData.id : undefined; var appointmentId = FrontendBook.manageMode ? GlobalVariables.appointmentData.id : null;
// Make ajax post request and get the available hours. // Make ajax post request and get the available hours.
var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_get_available_hours'; var url = GlobalVariables.baseUrl + '/index.php/appointments/ajax_get_available_hours';
var postData = {
var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
service_id: $('#select-service').val(), service_id: $('#select-service').val(),
provider_id: $('#select-provider').val(), provider_id: $('#select-provider').val(),
selected_date: selDate, selected_date: selDate,
service_duration: selServiceDuration, service_duration: serviceDuration,
manage_mode: FrontendBook.manageMode, manage_mode: FrontendBook.manageMode,
appointment_id: appointmentId appointment_id: appointmentId
}; };
$.post(postUrl, postData, function (response) { $.post(url, data)
// The response contains the available hours for the selected provider and .done(function (response) {
// service. Fill the available hours div with response data. // The response contains the available hours for the selected provider and
if (response.length > 0) { // service. Fill the available hours div with response data.
var providerId = $('#select-provider').val(); if (response.length > 0) {
var providerId = $('#select-provider').val();
if (providerId === 'any-provider') { if (providerId === 'any-provider') {
providerId = GlobalVariables.availableProviders[0].id; // Use first available provider. providerId = GlobalVariables.availableProviders[0].id; // Use first available provider.
}
var provider = GlobalVariables.availableProviders.filter(function(availableProvider) {
return providerId == availableProvider.id;
}).shift();
if (!provider) {
throw new Error('Could not find provider.');
}
var providerTimezone = provider.timezone;
var selectedTimezone = $('#select-timezone').val();
var currColumn = 1;
$('#available-hours').html('<div style="width:80px; float:left;"></div>');
var timeFormat = GlobalVariables.timeFormat === 'regular' ? 'h:mm a' : 'HH:mm';
$.each(response, function (index, availableHour) {
if ((currColumn * 10) < (index + 1)) {
currColumn++;
$('#available-hours').append('<div style="width:80px; float:left;"></div>');
} }
var availableHourMoment = moment var provider = GlobalVariables.availableProviders.filter(function(availableProvider) {
.tz(selDate + ' ' + availableHour + ':00', providerTimezone) return Number(providerId) === Number(availableProvider.id);
.tz(selectedTimezone); }).shift();
$('#available-hours div:eq(' + (currColumn - 1) + ')').append( if (!provider) {
'<span class="available-hour">' + availableHourMoment.format(timeFormat) + '</span><br/>'); throw new Error('Could not find provider.');
}); }
var providerTimezone = provider.timezone;
var selectedTimezone = $('#select-timezone').val();
var currColumn = 1;
$('#available-hours').html('<div style="width:80px; float:left;"></div>');
var timeFormat = GlobalVariables.timeFormat === 'regular' ? 'h:mm a' : 'HH:mm';
response.forEach(function (availableHour, index) {
if ((currColumn * 10) < (index + 1)) {
currColumn++;
$('#available-hours').append('<div style="width:80px; float:left;"></div>');
}
var availableHourMoment = moment
.tz(selDate + ' ' + availableHour + ':00', providerTimezone)
.tz(selectedTimezone);
$('#available-hours div:eq(' + (currColumn - 1) + ')').append(
'<span class="available-hour">' + availableHourMoment.format(timeFormat) + '</span><br/>');
});
if (FrontendBook.manageMode) {
// Set the appointment's start time as the default selection.
$('.available-hour')
.removeClass('selected-hour')
.filter(function () {
return $(this).text() === Date.parseExact(
GlobalVariables.appointmentData.start_datetime,
'yyyy-MM-dd HH:mm:ss').toString(timeFormat);
})
.addClass('selected-hour');
} else {
// Set the first available hour as the default selection.
$('.available-hour:eq(0)').addClass('selected-hour');
}
FrontendBook.updateConfirmFrame();
if (FrontendBook.manageMode) {
// Set the appointment's start time as the default selection.
$('.available-hour').removeClass('selected-hour');
$('.available-hour').filter(function () {
return $(this).text() === Date.parseExact(
GlobalVariables.appointmentData.start_datetime,
'yyyy-MM-dd HH:mm:ss').toString(timeFormat);
}).addClass('selected-hour');
} else { } else {
// Set the first available hour as the default selection. $('#available-hours').text(EALang.no_available_hours);
$('.available-hour:eq(0)').addClass('selected-hour');
} }
})
FrontendBook.updateConfirmFrame(); .fail(GeneralFunctions.ajaxFailureHandler);
} else {
$('#available-hours').text(EALang.no_available_hours);
}
}, 'json').fail(GeneralFunctions.ajaxFailureHandler);
}; };
/** /**
@ -141,26 +152,27 @@ window.FrontendBookApi = window.FrontendBookApi || {};
} }
var formData = jQuery.parseJSON($('input[name="post_data"]').val()); var formData = jQuery.parseJSON($('input[name="post_data"]').val());
var postData = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
post_data: formData post_data: formData
}; };
if ($captchaText.length > 0) { if ($captchaText.length > 0) {
postData.captcha = $captchaText.val(); data.captcha = $captchaText.val();
} }
if (GlobalVariables.manageMode) { if (GlobalVariables.manageMode) {
postData.exclude_appointment_id = GlobalVariables.appointmentData.id; data.exclude_appointment_id = GlobalVariables.appointmentData.id;
} }
var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_register_appointment'; var url = GlobalVariables.baseUrl + '/index.php/appointments/ajax_register_appointment';
var $layer = $('<div/>'); var $layer = $('<div/>');
$.ajax({ $.ajax({
url: postUrl, url: url,
method: 'post', method: 'post',
data: postData, data: data,
dataType: 'json', dataType: 'json',
beforeSend: function (jqxhr, settings) { beforeSend: function (jqxhr, settings) {
$layer $layer
@ -221,9 +233,10 @@ window.FrontendBookApi = window.FrontendBookApi || {};
return; return;
} }
var appointmentId = FrontendBook.manageMode ? GlobalVariables.appointmentData.id : undefined; var appointmentId = FrontendBook.manageMode ? GlobalVariables.appointmentData.id : null;
var url = GlobalVariables.baseUrl + '/index.php/appointments/ajax_get_unavailable_dates'; var url = GlobalVariables.baseUrl + '/index.php/appointments/ajax_get_unavailable_dates';
var data = { var data = {
provider_id: providerId, provider_id: providerId,
service_id: serviceId, service_id: serviceId,
@ -279,7 +292,7 @@ window.FrontendBookApi = window.FrontendBookApi || {};
// Grey out unavailable dates. // Grey out unavailable dates.
$('#select-date .ui-datepicker-calendar td:not(.ui-datepicker-other-month)').each(function (index, td) { $('#select-date .ui-datepicker-calendar td:not(.ui-datepicker-other-month)').each(function (index, td) {
selectedDate.set({day: index + 1}); selectedDate.set({day: index + 1});
if ($.inArray(selectedDate.toString('yyyy-MM-dd'), unavailableDates) != -1) { if (unavailableDates.indexOf(selectedDate.toString('yyyy-MM-dd')) !== -1) {
$(td).addClass('ui-datepicker-unselectable ui-state-disabled'); $(td).addClass('ui-datepicker-unselectable ui-state-disabled');
} }
}); });
@ -294,6 +307,7 @@ window.FrontendBookApi = window.FrontendBookApi || {};
*/ */
exports.saveConsent = function (consent) { exports.saveConsent = function (consent) {
var url = GlobalVariables.baseUrl + '/index.php/consents/ajax_save_consent'; var url = GlobalVariables.baseUrl + '/index.php/consents/ajax_save_consent';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
consent: consent consent: consent
@ -309,14 +323,17 @@ window.FrontendBookApi = window.FrontendBookApi || {};
*/ */
exports.deletePersonalInformation = function (customerToken) { exports.deletePersonalInformation = function (customerToken) {
var url = GlobalVariables.baseUrl + '/index.php/privacy/ajax_delete_personal_information'; var url = GlobalVariables.baseUrl + '/index.php/privacy/ajax_delete_personal_information';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
customer_token: customerToken customer_token: customerToken
}; };
$.post(url, data, function (response) { $.post(url, data)
location.href = GlobalVariables.baseUrl; .done(function () {
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); location.href = GlobalVariables.baseUrl;
})
.fail(GeneralFunctions.ajaxFailureHandler);
}; };
})(window.FrontendBookApi); })(window.FrontendBookApi);

View file

@ -37,7 +37,7 @@ $(document).ready(function () {
function handleAuthResult(authResult) { function handleAuthResult(authResult) {
try { try {
if (authResult.error) { if (authResult.error) {
throw 'Could not authorize user.'; throw new Error('Could not authorize user.');
} }
// The user has granted access, add the appointment to his calendar. // The user has granted access, add the appointment to his calendar.
@ -79,7 +79,7 @@ $(document).ready(function () {
request.execute(function (response) { request.execute(function (response) {
if (response.error) { if (response.error) {
throw 'Could not add the event to Google Calendar.'; throw new Error('Could not add the event to Google Calendar.');
} }
$('#success-frame').append( $('#success-frame').append(
@ -98,14 +98,14 @@ $(document).ready(function () {
$('#add-to-google-calendar').hide(); $('#add-to-google-calendar').hide();
}); });
}); });
} catch (exc) { } catch (error) {
// The user denied access or something else happened, display corresponding message on the screen. // The user denied access or something else happened, display corresponding message on the screen.
$('#success-frame').append( $('#success-frame').append(
'<div class="alert alert-danger col-xs-12">' + '<div class="alert alert-danger col-xs-12">' +
'<h4>' + EALang.oops_something_went_wrong + '</h4>' + '<h4>' + EALang.oops_something_went_wrong + '</h4>' +
'<p>' + '<p>' +
EALang.could_not_add_to_google_calendar + EALang.could_not_add_to_google_calendar +
'<pre>' + exc + '</pre>' + '<pre>' + error.message + '</pre>' +
'</p>' + '</p>' +
'</div>'); '</div>');
} }

View file

@ -31,15 +31,15 @@ window.GeneralFunctions = window.GeneralFunctions || {};
* @param {Array} buttons Contains the dialog buttons along with their functions. * @param {Array} buttons Contains the dialog buttons along with their functions.
*/ */
exports.displayMessageBox = function (title, message, buttons) { exports.displayMessageBox = function (title, message, buttons) {
if (title === undefined || title === '') { if (!title) {
title = '- No Title Provided -'; title = '- No Title Provided -';
} }
if (message === undefined || message === '') { if (!message) {
message = '- No Message Provided -'; message = '- No Message Provided -';
} }
if (buttons === undefined) { if (!buttons) {
buttons = [ buttons = [
{ {
text: EALang.close, text: EALang.close,
@ -170,19 +170,22 @@ window.GeneralFunctions = window.GeneralFunctions || {};
*/ */
exports.clone = function (originalObject) { exports.clone = function (originalObject) {
// Handle the 3 simple types, and null or undefined // Handle the 3 simple types, and null or undefined
if (null == originalObject || 'object' != typeof originalObject) if (!originalObject || typeof originalObject !== 'object') {
return originalObject; return originalObject;
}
var copy;
// Handle Date // Handle Date
if (originalObject instanceof Date) { if (originalObject instanceof Date) {
var copy = new Date(); copy = new Date();
copy.setTime(originalObject.getTime()); copy.setTime(originalObject.getTime());
return copy; return copy;
} }
// Handle Array // Handle Array
if (originalObject instanceof Array) { if (originalObject instanceof Array) {
var copy = []; copy = [];
for (var i = 0, len = originalObject.length; i < len; i++) { for (var i = 0, len = originalObject.length; i < len; i++) {
copy[i] = GeneralFunctions.clone(originalObject[i]); copy[i] = GeneralFunctions.clone(originalObject[i]);
} }
@ -191,7 +194,7 @@ window.GeneralFunctions = window.GeneralFunctions || {};
// Handle Object // Handle Object
if (originalObject instanceof Object) { if (originalObject instanceof Object) {
var copy = {}; copy = {};
for (var attr in originalObject) { for (var attr in originalObject) {
if (originalObject.hasOwnProperty(attr)) if (originalObject.hasOwnProperty(attr))
copy[attr] = GeneralFunctions.clone(originalObject[attr]); copy[attr] = GeneralFunctions.clone(originalObject[attr]);
@ -309,10 +312,12 @@ window.GeneralFunctions = window.GeneralFunctions || {};
$(document).on('click', 'li.language', function () { $(document).on('click', 'li.language', function () {
// Change language with ajax call and refresh page. // Change language with ajax call and refresh page.
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_change_language'; var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_change_language';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
language: $(this).attr('data-language') language: $(this).attr('data-language')
}; };
$.post(url, data) $.post(url, data)
done(function () { done(function () {
document.location.reload(true); document.location.reload(true);

View file

@ -14,6 +14,7 @@ $(function () {
var MIN_PASSWORD_LENGTH = 7; var MIN_PASSWORD_LENGTH = 7;
var $install = $('#install');
var $alert = $('.alert'); var $alert = $('.alert');
$(document).ajaxStart(function () { $(document).ajaxStart(function () {
@ -27,12 +28,13 @@ $(function () {
/** /**
* Event: Install Easy!Appointments Button "Click" * Event: Install Easy!Appointments Button "Click"
*/ */
$('#install').click(function () { $install.click(function () {
if (!validate()) { if (!validate()) {
return; return;
} }
var url = GlobalVariables.baseUrl + '/index.php/installation/ajax_install'; var url = GlobalVariables.baseUrl + '/index.php/installation/ajax_install';
var data = { var data = {
csrfToken: GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
admin: getAdminData(), admin: getAdminData(),
@ -75,45 +77,45 @@ $(function () {
// Check for empty fields. // Check for empty fields.
var missingRequired = false; var missingRequired = false;
$('input').each(function () { $('input').each(function () {
if ($(this).val() == '') { if (!$(this).val()) {
$(this).closest('.form-group').addClass('has-error'); $(this).closest('.form-group').addClass('has-error');
missingRequired = true; missingRequired = true;
} }
}); });
if (missingRequired) { if (missingRequired) {
throw 'All the page fields are required.'; throw new Error('All the page fields are required.');
} }
// Validate Passwords // Validate Passwords
if ($('#password').val() != $('#retype-password').val()) { if ($('#password').val() !== $('#retype-password').val()) {
$('#password').closest('.form-group').addClass('has-error'); $('#password').closest('.form-group').addClass('has-error');
$('#retype-password').closest('.form-group').addClass('has-error'); $('#retype-password').closest('.form-group').addClass('has-error');
throw 'Passwords do not match!'; throw new Error('Passwords do not match!');
} }
if ($('#password').val().length < MIN_PASSWORD_LENGTH) { if ($('#password').val().length < MIN_PASSWORD_LENGTH) {
$('#password').closest('.form-group').addClass('has-error'); $('#password').closest('.form-group').addClass('has-error');
$('#retype-password').closest('.form-group').addClass('has-error'); $('#retype-password').closest('.form-group').addClass('has-error');
throw 'The password must be at least ' + MIN_PASSWORD_LENGTH + ' characters long.'; throw new Error('The password must be at least ' + MIN_PASSWORD_LENGTH + ' characters long.');
} }
// Validate Email // Validate Email
if (!GeneralFunctions.validateEmail($('#email').val())) { if (!GeneralFunctions.validateEmail($('#email').val())) {
$('#email').closest('.form-group').addClass('has-error'); $('#email').closest('.form-group').addClass('has-error');
throw 'The email address is invalid!'; throw new Error('The email address is invalid!');
} }
if (!GeneralFunctions.validateEmail($('#company-email').val())) { if (!GeneralFunctions.validateEmail($('#company-email').val())) {
$('#company-email').closest('.form-group').addClass('has-error'); $('#company-email').closest('.form-group').addClass('has-error');
throw 'The email address is invalid!'; throw new Error('The email address is invalid!');
} }
return true; return true;
} catch (error) { } catch (error) {
$alert $alert
.addClass('alert-danger') .addClass('alert-danger')
.text(error) .text(error.message)
.show(); .show();
return false; return false;
@ -126,7 +128,7 @@ $(function () {
* @return {Object} * @return {Object}
*/ */
function getAdminData() { function getAdminData() {
var admin = { return {
first_name: $('#first-name').val(), first_name: $('#first-name').val(),
last_name: $('#last-name').val(), last_name: $('#last-name').val(),
email: $('#email').val(), email: $('#email').val(),
@ -134,8 +136,6 @@ $(function () {
username: $('#username').val(), username: $('#username').val(),
password: $('#password').val() password: $('#password').val()
}; };
return admin;
} }
/** /**
@ -144,20 +144,18 @@ $(function () {
* @return {Object} * @return {Object}
*/ */
function getCompanyData() { function getCompanyData() {
var company = { return {
company_name: $('#company-name').val(), company_name: $('#company-name').val(),
company_email: $('#company-email').val(), company_email: $('#company-email').val(),
company_link: $('#company-link').val() company_link: $('#company-link').val()
}; };
return company;
} }
// Validate the base URL setting (must not contain any trailing slash). // Validate the base URL setting (must not contain any trailing slash).
if (GlobalVariables.baseUrl.slice(-1) === '/') { if (GlobalVariables.baseUrl.slice(-1) === '/') {
GeneralFunctions.displayMessageBox('Misconfiguration Detected', 'Please remove any trailing slashes from your ' GeneralFunctions.displayMessageBox('Misconfiguration Detected', 'Please remove any trailing '
+ 'BASE_URL setting of the root config.php file and try again.'); + 'slashes from your BASE_URL setting of the root config.php file and try again.');
$('#install') $install
.prop('disabled', true) .prop('disabled', true)
.fadeTo('0.4'); .fadeTo('0.4');
} }

View file

@ -13,6 +13,7 @@ $(function () {
event.preventDefault(); event.preventDefault();
var url = GlobalVariables.baseUrl + '/index.php/user/ajax_check_login'; var url = GlobalVariables.baseUrl + '/index.php/user/ajax_check_login';
var data = { var data = {
'csrfToken': GlobalVariables.csrfToken, 'csrfToken': GlobalVariables.csrfToken,
'username': $('#username').val(), 'username': $('#username').val(),

View file

@ -70,7 +70,7 @@
$('.working-plan tbody').append(tr); $('.working-plan tbody').append(tr);
if (workingDay != null) { if (workingDay) {
$('#' + index).prop('checked', true); $('#' + index).prop('checked', true);
$('#' + index + '-start').val(Date.parse(workingDay.start).toString(GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm').toUpperCase()); $('#' + index + '-start').val(Date.parse(workingDay.start).toString(GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm').toUpperCase());
$('#' + index + '-end').val(Date.parse(workingDay.end).toString(GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm').toUpperCase()); $('#' + index + '-end').val(Date.parse(workingDay.end).toString(GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm').toUpperCase());
@ -125,7 +125,7 @@
*/ */
WorkingPlan.prototype.setupExtraPeriods = function (extraWorkingPlan) { WorkingPlan.prototype.setupExtraPeriods = function (extraWorkingPlan) {
$.each(extraWorkingPlan, function (index, extraWorkingDay) { $.each(extraWorkingPlan, function (index, extraWorkingDay) {
if (extraWorkingDay != null) { if (extraWorkingDay) {
$('#' + index).prop('checked', true); $('#' + index).prop('checked', true);
$('#' + index + '-start').val(Date.parse(extraWorkingDay.start).toString(GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm').toUpperCase()); $('#' + index + '-start').val(Date.parse(extraWorkingDay.start).toString(GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm').toUpperCase());
@ -245,10 +245,10 @@
* *
* Enable or disable the time selection for each day. * Enable or disable the time selection for each day.
*/ */
$('.working-plan tbody').on( "click", "input:checkbox", function (event) { $('.working-plan tbody').on( "click", "input:checkbox", function () {
var id = $(this).attr('id'); var id = $(this).attr('id');
if ($(this).prop('checked') == true) { if ($(this).prop('checked') === true) {
$('#' + id + '-start').prop('disabled', false).val('9:00 AM'); $('#' + id + '-start').prop('disabled', false).val('9:00 AM');
$('#' + id + '-end').prop('disabled', false).val('6:00 PM'); $('#' + id + '-end').prop('disabled', false).val('6:00 PM');
} else { } else {
@ -303,7 +303,7 @@
// Reset previous editable tds // Reset previous editable tds
var $previousEdt = $(this).closest('table').find('.editable').get(); var $previousEdt = $(this).closest('table').find('.editable').get();
$.each($previousEdt, function (index, editable) { $.each($previousEdt, function (index, editable) {
if (editable.reset !== undefined) { if (editable.reset) {
editable.reset(); editable.reset();
} }
}); });
@ -436,7 +436,7 @@
// Reset previous editable tds // Reset previous editable tds
var $previousEdt = $(this).closest('table').find('.editable').get(); var $previousEdt = $(this).closest('table').find('.editable').get();
$.each($previousEdt, function (index, editable) { $.each($previousEdt, function (index, editable) {
if (editable.reset !== undefined) { if (editable.reset) {
editable.reset(); editable.reset();
} }
}); });
@ -565,7 +565,7 @@
var workingPlan = {}; var workingPlan = {};
$('.working-plan input:checkbox').each(function (index, checkbox) { $('.working-plan input:checkbox').each(function (index, checkbox) {
var id = $(checkbox).attr('id'); var id = $(checkbox).attr('id');
if ($(checkbox).prop('checked') == true) { if ($(checkbox).prop('checked') === true) {
workingPlan[id] = { workingPlan[id] = {
start: Date.parse($('#' + id + '-start').val()).toString('HH:mm'), start: Date.parse($('#' + id + '-start').val()).toString('HH:mm'),
end: Date.parse($('#' + id + '-end').val()).toString('HH:mm'), end: Date.parse($('#' + id + '-end').val()).toString('HH:mm'),
@ -575,7 +575,7 @@
$('.breaks tr').each(function (index, tr) { $('.breaks tr').each(function (index, tr) {
var day = this.convertDayToValue($(tr).find('.break-day').text()); var day = this.convertDayToValue($(tr).find('.break-day').text());
if (day == id) { if (day === id) {
var start = $(tr).find('.break-start').text(); var start = $(tr).find('.break-start').text();
var end = $(tr).find('.break-end').text(); var end = $(tr).find('.break-end').text();
@ -626,12 +626,12 @@
/** /**
* Enables or disables the timepicker functionality from the working plan input text fields. * Enables or disables the timepicker functionality from the working plan input text fields.
* *
* @param {Boolean} disabled (OPTIONAL = false) If true then the timepickers will be disabled. * @param {Boolean} [disabled] If true then the timepickers will be disabled.
*/ */
WorkingPlan.prototype.timepickers = function (disabled) { WorkingPlan.prototype.timepickers = function (disabled) {
disabled = disabled || false; disabled = disabled || false;
if (disabled == false) { if (disabled === false) {
// Set timepickers where needed. // Set timepickers where needed.
$('.working-plan input:text').timepicker({ $('.working-plan input:text').timepicker({
timeFormat: GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm', timeFormat: GlobalVariables.timeFormat === 'regular' ? 'h:mm tt' : 'HH:mm',