$(document).ready(function(){
        $('#send_message').click(function(e){
            
            //Stop form submission & check the validation
            e.preventDefault();
            
            // Variable declaration
            var error = false;
            var name = $('#name').val();
            var email = $('#email').val();
            var phone = $('#phone').val();
            var checkIn = $('#check-in').val();
            var checkOut = $('#check-out').val();
            var reservationType = $('input[name="reservation_type"]:checked').val() || 'room';
            var roomId = $('#room-id').val();
            var facilityId = $('#service-id').val();
            
            $('#name,#email,#phone,#message,#room-type,#service-id').on('click change', function(){
                $(this).removeClass("error_input");
            });
            
            // Form field validation
            if(name.length == 0){
                var error = true;
                $('#name').addClass("error_input");
            }else{
                $('#name').removeClass("error_input");
            }
            if(email.length == 0 || email.indexOf('@') == '-1'){
                var error = true;
                $('#email').addClass("error_input");
            }else{
                $('#email').removeClass("error_input");
            }
            if(phone.length == 0){
                var error = true;
                $('#phone').addClass("error_input");
            }else{
                $('#phone').removeClass("error_input");
            }
            if(checkIn.length == 0){
                var error = true;
                $('#check-in').addClass("error_input");
            }else{
                $('#check-in').removeClass("error_input");
            }
            if(checkOut.length == 0){
                var error = true;
                $('#check-out').addClass("error_input");
            }else{
                $('#check-out').removeClass("error_input");
            }
            if(reservationType === 'room'){
                if(!roomId || String(roomId).trim() === ''){
                    var error = true;
                    $('#room-type').addClass("error_input");
                }else{
                    $('#room-type').removeClass("error_input");
                }
            }else{
                if(!facilityId || String(facilityId).trim() === ''){
                    var error = true;
                    $('#service-id').addClass("error_input");
                }else{
                    $('#service-id').removeClass("error_input");
                }
            }
            
            // If there is no validation error, next to process the mail function
            if(error == false){
               // Disable submit button while the request is in progress.
                var defaultLabel = $('#send_message').val();
                $('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
                
                /* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to booking.php*/
                $.ajax({
                    url: "booking.php",
                    type: "POST",
                    data: $("#booking_form").serialize(),
                    timeout: 15000,
                    cache: false,
                    dataType: "json"
                }).done(function(result){
                    var status = result && result.status ? String(result.status).toLowerCase() : "";
                    var code = result && result.code ? String(result.code).toLowerCase() : "";
                    var resolvedReservationType = result && result.reservation_type
                        ? String(result.reservation_type).toLowerCase()
                        : reservationType;
                    if(status === 'success' || code === 'sent'){
                        var successTitle = resolvedReservationType === 'service'
                            ? 'Your service reservation is confirmed.'
                            : 'Your room reservation is confirmed.';
                        var successText = result && result.message
                            ? result.message
                            : 'We will contact you shortly. Refresh this page if you want to make another reservation.';

                        var formSnapshot = (typeof window.getReservationConfirmationData === 'function')
                            ? window.getReservationConfirmationData()
                            : null;
                        var bookingId = (result && result.booking_id !== null && typeof result.booking_id !== 'undefined')
                            ? ('#' + result.booking_id)
                            : '-';
                        var totalPrice = '-';
                        if(resolvedReservationType === 'service' && result && result.service_total_price !== null && typeof result.service_total_price !== 'undefined'){
                            totalPrice = '$' + Number(result.service_total_price).toFixed(2);
                        }else if(resolvedReservationType === 'room' && result && result.room_total_price !== null && typeof result.room_total_price !== 'undefined'){
                            totalPrice = '$' + Number(result.room_total_price).toFixed(2);
                        }

                        $('#reservation-success-title').text(successTitle);
                        $('#reservation-success-text').text(successText);
                        $('#confirm-booking-id').text(bookingId);
                        $('#confirm-type').text(resolvedReservationType === 'service' ? 'Service Booking' : 'Room Booking');
                        $('#confirm-checkin').text(formSnapshot && formSnapshot.checkIn ? formSnapshot.checkIn : (checkIn || '-'));
                        $('#confirm-checkout').text(formSnapshot && formSnapshot.checkOut ? formSnapshot.checkOut : (checkOut || '-'));
                        $('#confirm-guests').text(formSnapshot && formSnapshot.guests ? formSnapshot.guests : ($('#adults').val() || '-'));
                        $('#confirm-selected').text(formSnapshot && formSnapshot.selectedLabel ? formSnapshot.selectedLabel : ((resolvedReservationType === 'service' ? $('#service-id option:selected').text() : $('#room-type option:selected').text()).split('|')[0].trim() || '-'));
                        $('#confirm-total').text(totalPrice);
                        $('#confirm-status').text('Pending Confirmation');
                        //If the email is sent successfully, remove the submit button
                         $('#booking_form_wrap').remove();
                        //Display the success message
                        $('#success_message').fadeIn(500);
                    }else if(code === 'login_required'){
                        window.location.href = 'login.php?redirect=' + encodeURIComponent('reservation.php');
                    }else{
                        //Display the error message
                        $('#error_message').fadeIn(500);
                        // Enable the submit button again
                        $('#send_message').removeAttr('disabled').attr('value', defaultLabel);
                    }
                }).fail(function(xhr){
                    var responseCode = '';
                    try {
                        responseCode = xhr.responseJSON && xhr.responseJSON.code ? String(xhr.responseJSON.code).toLowerCase() : '';
                    } catch (e) {
                        responseCode = '';
                    }

                    if(responseCode === 'login_required' || xhr.status === 401){
                        window.location.href = 'login.php?redirect=' + encodeURIComponent('reservation.php');
                        return;
                    }

                    $('#error_message').fadeIn(500);
                    $('#send_message').removeAttr('disabled').attr('value', defaultLabel);
                });
            }
        });    
    });
