/**
* This namespace contains functions that implement the book appointment page
* functionality. Once the initialize() method is called the page is fully
* functional and can serve the appointment booking process.
*
* @namespace FrontendBook
*/
var FrontendBook = {
/**
* Determines the functionality of the page.
*
* @type {bool}
*/
manageMode: false,
/**
* This method initializes the book appointment page.
*
* @param {bool} bindEventHandlers (OPTIONAL) Determines whether the default
* event handlers will be binded to the dom elements.
* @param {bool} manageMode (OPTIONAL) Determines whether the customer is going
* to make changes to an existing appointment rather than booking a new one.
*/
initialize: function(bindEventHandlers, manageMode) {
if (bindEventHandlers === undefined) {
bindEventHandlers = true; // Default Value
}
if (manageMode === undefined) {
manageMode = false; // Default Value
}
FrontendBook.manageMode = manageMode;
// Initialize page's components (tooltips, datepickers etc).
$('.book-step').qtip({
position: {
my: 'top center',
at: 'bottom center'
},
style: {
classes: 'qtip-green qtip-shadow custom-qtip'
}
});
$('#select-date').datepicker({
dateFormat: 'dd-mm-yy',
firstDay: 1, // Monday
minDate: 0,
defaultDate: Date.today(),
dayNames: [EALang['sunday'], EALang['monday'], EALang['tuesday'], EALang['wednesday'], EALang['thursday'], EALang['friday'], EALang['saturday']],
dayNamesShort: [EALang['sunday'].substr(0,3), EALang['monday'].substr(0,3),
EALang['tuesday'].substr(0,3), EALang['wednesday'].substr(0,3),
EALang['thursday'].substr(0,3), EALang['friday'].substr(0,3),
EALang['saturday'].substr(0,3)],
dayNamesMin: [EALang['sunday'].substr(0,2), EALang['monday'].substr(0,2),
EALang['tuesday'].substr(0,2), EALang['wednesday'].substr(0,2),
EALang['thursday'].substr(0,2), EALang['friday'].substr(0,2),
EALang['saturday'].substr(0,2)],
monthNames: [EALang['january'], EALang['february'], EALang['march'], EALang['april'],
EALang['may'], EALang['june'], EALang['july'], EALang['august'], EALang['september'],
EALang['october'], EALang['november'], EALang['december']],
prevText: EALang['previous'],
nextText: EALang['next'],
currentText: EALang['now'],
closeText: EALang['close'],
onSelect: function(dateText, instance) {
FrontendBook.getAvailableHours(dateText);
FrontendBook.updateConfirmFrame();
}
});
// Bind the event handlers (might not be necessary every time
// we use this class).
if (bindEventHandlers) {
FrontendBook.bindEventHandlers();
}
// If the manage mode is true, the appointments data should be
// loaded by default.
if (FrontendBook.manageMode) {
FrontendBook.applyAppointmentData(GlobalVariables.appointmentData,
GlobalVariables.providerData, GlobalVariables.customerData);
} else {
$('#select-service').trigger('change'); // Load the available hours.
}
},
/**
* This method binds the necessary event handlers for the book
* appointments page.
*/
bindEventHandlers: function() {
/**
* Event: Selected Provider "Changed"
*
* Whenever the provider changes the available appointment
* date - time periods must be updated.
*/
$('#select-provider').change(function() {
FrontendBook.getAvailableHours(Date.today().toString('dd-MM-yyyy'));
FrontendBook.updateConfirmFrame();
});
/**
* Event: Selected Service "Changed"
*
* When the user clicks on a service, its available providers should
* become visible.
*/
$('#select-service').change(function() {
var currServiceId = $('#select-service').val();
$('#select-provider').empty();
$.each(GlobalVariables.availableProviders, function(indexProvider, provider) {
$.each(provider['services'], function(indexService, serviceId) {
// If the current provider is able to provide the selected service,
// add him to the listbox.
if (serviceId == currServiceId) {
var optionHtml = '';
$('#select-provider').append(optionHtml);
}
});
});
FrontendBook.getAvailableHours($('#select-date').val());
FrontendBook.updateConfirmFrame();
FrontendBook.updateServiceDescription($('#select-service').val(), $('#service-description'));
});
/**
* Event: Next Step Button "Clicked"
*
* This handler is triggered every time the user pressed the
* "next" button on the book wizard. Some special tasks might
* be perfomed, depending the current wizard step.
*/
$('.button-next').click(function() {
// If we are on the 2nd tab then the user should have an appointment hour
// selected.
if ($(this).attr('data-step_index') === '2') {
if ($('.selected-hour').length == 0) {
if ($('#select-hour-prompt').length == 0) {
$('#available-hours').append('
'
+ ''
+ EALang['appointment_hour_missing']
+ '');
}
return;
}
}
// If we are on the 3rd tab then we will need to validate the user's
// input before proceeding to the next step.
if ($(this).attr('data-step_index') === '3') {
if (!FrontendBook.validateCustomerForm()) {
return; // Validation failed, do not continue.
} else {
FrontendBook.updateConfirmFrame();
}
}
// Display the next step tab (uses jquery animation effect).
var nextTabIndex = parseInt($(this).attr('data-step_index')) + 1;
$(this).parents().eq(1).hide('fade', function() {
$('.active-step').removeClass('active-step');
$('#step-' + nextTabIndex).addClass('active-step');
$('#wizard-frame-' + nextTabIndex).show('fade');
});
});
/**
* Event: Back Step Button "Clicked"
*
* This handler is triggered every time the user pressed the
* "back" button on the book wizard.
*/
$('.button-back').click(function() {
var prevTabIndex = parseInt($(this).attr('data-step_index')) - 1;
$(this).parents().eq(1).hide('fade', function() {
$('.active-step').removeClass('active-step');
$('#step-' + prevTabIndex).addClass('active-step');
$('#wizard-frame-' + prevTabIndex).show('fade');
});
});
/**
* Event: Available Hour "Click"
*
* Triggered whenever the user clicks on an available hour
* for his appointment.
*/
$('#available-hours').on('click', '.available-hour', function() {
$('.selected-hour').removeClass('selected-hour');
$(this).addClass('selected-hour');
FrontendBook.updateConfirmFrame();
});
if (FrontendBook.manageMode) {
/**
* Event: Cancel Appointment Button "Click"
*
* When the user clicks the "Cancel" button this form is going to
* be submitted. We need the user to confirm this action because
* once the appointment is cancelled, it will be delete from the
* database.
*/
$('#cancel-appointment').click(function(event) {
var dialogButtons = {};
dialogButtons['OK'] = function() {
if ($('#cancel-reason').val() === '') {
$('#cancel-reason').css('border', '2px solid red');
return;
}
$('#cancel-appointment-form textarea').val($('#cancel-reason').val());
$('#cancel-appointment-form').submit();
};
dialogButtons[EALang['cancel']] = function() {
$('#message_box').dialog('close');
};
GeneralFunctions.displayMessageBox(EALang['cancel_appointment_title'],
EALang['write_appointment_removal_reason'], dialogButtons);
$('#message_box').append('');
$('#cancel-reason').css('width', '353px');
return false;
});
}
/**
* Event: Book Appointment Form "Submit"
*
* Before the form is submitted to the server we need to make sure that
* in the meantime the selected appointment date/time wasn't reserved by
* another customer or event.
*/
$('#book-appointment-submit').click(function(event) {
var formData = jQuery.parseJSON($('input[name="post_data"]').val());
var postData = {
'id_users_provider': formData['appointment']['id_users_provider'],
'id_services': formData['appointment']['id_services'],
'start_datetime': formData['appointment']['start_datetime'],
};
if (GlobalVariables.manageMode) {
postData.exclude_appointment_id = GlobalVariables.appointmentData.id;
}
var postUrl = GlobalVariables.baseUrl + 'appointments/ajax_check_datetime_availability';
$.post(postUrl, postData, function(response) {
////////////////////////////////////////////////////////////////////////
console.log('Check Date/Time Availability Post Response :', response);
////////////////////////////////////////////////////////////////////////
if (response.exceptions) {
response.exceptions = GeneralFunctions.parseExceptions(response.exceptions);
GeneralFunctions.displayMessageBox('Unexpected Issues', 'Unfortunately '
+ 'the check appointment time availability could not be completed. '
+ 'The following issues occurred:');
$('#message_box').append(GeneralFunctions.exceptionsToHtml(response.exceptions));
return false;
}
if (response === true) {
$('#book-appointment-form').submit();
} else {
GeneralFunctions.displayMessageBox('Appointment Hour Taken', 'Unfortunately '
+ 'the selected appointment hour is not available anymore. Please select '
+ 'another hour.');
FrontendBook.getAvailableHours($('#select-date').val());
}
}, 'json');
});
},
/**
* This function makes an ajax call and returns the available
* hours for the selected service, provider and date.
*
* @param {string} selDate The selected date of which the available
* hours we need to receive.
*/
getAvailableHours: function(selDate) {
$('#available-hours').empty();
// Find the selected service duration (it is going to
// be send within the "postData" object).
var selServiceDuration = 15; // Default value of duration (in minutes).
$.each(GlobalVariables.availableServices, function(index, service) {
if (service['id'] == $('#select-service').val()) {
selServiceDuration = service['duration'];
}
});
// 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 postData = {
'service_id': $('#select-service').val(),
'provider_id': $('#select-provider').val(),
'selected_date': selDate,
'service_duration': selServiceDuration,
'manage_mode': FrontendBook.manageMode,
'appointment_id': appointmentId
};
// Make ajax post request and get the available hours.
var ajaxurl = GlobalVariables.baseUrl + 'appointments/ajax_get_available_hours';
jQuery.post(ajaxurl, postData, function(response) {
///////////////////////////////////////////////////////////////
console.log('Get Available Hours JSON Response:', response);
///////////////////////////////////////////////////////////////
if (!GeneralFunctions.handleAjaxExceptions(response)) return;
// The response contains the available hours for the selected provider and
// service. Fill the available hours div with response data.
if (response.length > 0) {
var currColumn = 1;
$('#available-hours').html('
'
+ ''
+ $('#select-provider option:selected').text() + '
'
+ selectedDate + ' ' + $('.selected-hour').text()
+ servicePrice + ' ' + serviceCurrency
+ '' +
'
' +
EALang['phone'] + ': ' + $('#phone-number').val() +
'
' +
EALang['email'] + ': ' + $('#email').val() +
'
' +
EALang['address'] + ': ' + $('#address').val() +
'
' +
EALang['city'] + ': ' + $('#city').val() +
'
' +
EALang['zip_code'] + ': ' + $('#zip-code').val() +
'