/* ----------------------------------------------------------------------------
 * Easy!Appointments - Open Source Web Scheduler
 *
 * @package     EasyAppointments
 * @author      A.Tselegidis <alextselegidis@gmail.com>
 * @copyright   Copyright (c) 2013 - 2018, Alex Tselegidis
 * @license     http://opensource.org/licenses/GPL-3.0 - GPLv3
 * @link        http://easyappointments.org
 * @since       v1.0.0
 * ---------------------------------------------------------------------------- */

window.FrontendBook = window.FrontendBook || {};

/**
 * Frontend Book
 *
 * This module 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.
 *
 * @module FrontendBook
 */
(function (exports) {

    'use strict';

    /**
     * Contains terms and conditions consent.
     *
     * @type {Object}
     */
    var termsAndConditionsConsent;

    /**
     * Contains privacy policy consent.
     *
     * @type {Object}
     */
    var privacyPolicyConsent;

    /**
     * Determines the functionality of the page.
     *
     * @type {Boolean}
     */
    exports.manageMode = false;

    /**
     * This method initializes the book appointment page.
     *
     * @param {Boolean} bindEventHandlers (OPTIONAL) Determines whether the default
     * event handlers will be bound to the dom elements.
     * @param {Boolean} manageMode (OPTIONAL) Determines whether the customer is going
     * to make  changes to an existing appointment rather than booking a new one.
     */
    exports.initialize = function (bindEventHandlers, manageMode) {
        bindEventHandlers = bindEventHandlers || true;
        manageMode = manageMode || false;

        if (window.console === undefined) {
            window.console = function () {
            }; // IE compatibility
        }

        if (manageMode){

        } else{
            var wrapper = document.getElementById("signature-pad"),
                canvas = wrapper.querySelector("canvas"),
                signaturePad;

        function resizeCanvas() {
            var oldContent = signaturePad.toData();
            var ratio = Math.max(window.devicePixelRatio || 1, 1);
            canvas.width = canvas.offsetWidth * ratio;
            canvas.height = canvas.offsetHeight * ratio;
            canvas.getContext("2d").scale(ratio, ratio);
            signaturePad.clear();
            signaturePad.fromData(oldContent);
            document.getElementById('signature').value = "";
            document.getElementById('signature').value = signaturePad.toDataURL();

        }


        function download(filename) {
            var blob = dataURLToBlob(signaturePad.toDataURL());
            var url = window.URL.createObjectURL(blob);

            var a = document.createElement("a");
            a.style = "display: none";
            a.href = url;
            a.download = filename;

            document.body.appendChild(a);
            a.click();

            window.URL.revokeObjectURL(url);
        }


        function dataURLToBlob(dataURL) {
            var parts = dataURL.split(';base64,');
            var contentType = parts[0].split(":")[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
            var uInt8Array = new Uint8Array(rawLength);

            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }

            return new Blob([uInt8Array], {type: contentType});
        }

        function submitForm() {
            document.getElementById('signature').value = signaturePad.toDataURL();
        }


        var signaturePad = new SignaturePad(canvas);
        signaturePad.minWidth = 1;
        signaturePad.maxWidth = 5;
        signaturePad.penColor = "#000000";
        signaturePad.backgroundColor = "#FFFFFF";

        window.onresize = resizeCanvas;
        resizeCanvas();
    }
        if (GlobalVariables.displayCookieNotice) {
            cookieconsent.initialise({
                palette: {
                    popup: {
                        background: '#ffffffbd',
                        text: '#666666'
                    },
                    button: {
                        background: '#3DD481',
                        text: '#ffffff'
                    }
                },
                content: {
                    message: EALang.website_using_cookies_to_ensure_best_experience,
                    dismiss: 'OK'
                },
            });

            $('.cc-link').replaceWith(
                $('<a/>', {
                    'data-toggle': 'modal',
                    'data-target': '#cookie-notice-modal',
                    'href': '#',
                    'class': 'cc-link',
                    'text': $('.cc-link').text()
                })
            );
        }

        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: 0,
            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) {
                FrontendBookApi.getAvailableHours($(this).datepicker('getDate').toString('yyyy-MM-dd'));
                FrontendBook.updateConfirmFrame();
            },

            onChangeMonthYear: function (year, month, instance) {
                var currentDate = new Date(year, month - 1, 1);
                FrontendBookApi.getUnavailableDates($('#select-provider').val(), $('#select-service').val(),
                    currentDate.toString('yyyy-MM-dd'));
            }
        });

        // Bind the event handlers (might not be necessary every time we use this class).
        if (bindEventHandlers) {
            _bindEventHandlers();
        }

        // If the manage mode is true, the appointments data should be loaded by default.
        if (FrontendBook.manageMode) {
            _applyAppointmentData(GlobalVariables.appointmentData,
                GlobalVariables.providerData, GlobalVariables.customerData);

        } else {
            var $selectProvider = $('#select-provider');
            var $selectCompany = $('#select-company');

            var $selectService = $('#select-service');

            // Check if a specific service was selected (via URL parameter).
            /*  var selectedServiceId = GeneralFunctions.getUrlParameter(location.href, 'company');

              if (selectedServiceId && $selectProvider.find('option[value="' + selectedServiceId + '"]').length > 0) {
                  var bromillie = selectedServiceId.split("|");
                  $selectProvider.val(bromillie[1]);

              }*/

            //$selectService.trigger('change'); // Load the available hours.

            // Check if a specific provider was selected.
            var selectedcompanyid = GeneralFunctions.getUrlParameter(location.href, 'company');
            $.each(GlobalVariables.companies, function (index, company) {
                if(company.hash_id===selectedcompanyid){
                    $selectCompany.val(company.id);

                }
            });
            $selectCompany.trigger('change');

        }
    };

    /**
     * This method binds the necessary event handlers for the book appointments page.
     */
    function _bindEventHandlers() {
        /**
         * Event: Selected Provider "Changed"
         *
         * Whenever the provider changes the available appointment date - time periods must be updated.
         */
        if (FrontendBook.manageMode){
        }else{
            $('#clearsig').click(function () {
                var wrapper = document.getElementById("signature-pad"),
                    canvas = wrapper.querySelector("canvas"),
                    signaturePad;

                function resizeCanvas() {
                    var oldContent = signaturePad.toData();
                    var ratio = Math.max(window.devicePixelRatio || 1, 1);
                    canvas.width = canvas.offsetWidth * ratio;
                    canvas.height = canvas.offsetHeight * ratio;
                    canvas.getContext("2d").scale(ratio, ratio);
                    signaturePad.clear();
                    signaturePad.fromData(oldContent);
                    document.getElementById('signature').value = oldContent;

                }


                function download(filename) {
                    var blob = dataURLToBlob(signaturePad.toDataURL());
                    var url = window.URL.createObjectURL(blob);

                    var a = document.createElement("a");
                    a.style = "display: none";
                    a.href = url;
                    a.download = filename;

                    document.body.appendChild(a);
                    a.click();

                    window.URL.revokeObjectURL(url);
                }


                function dataURLToBlob(dataURL) {
                    var parts = dataURL.split(';base64,');
                    var contentType = parts[0].split(":")[1];
                    var raw = window.atob(parts[1]);
                    var rawLength = raw.length;
                    var uInt8Array = new Uint8Array(rawLength);

                    for (var i = 0; i < rawLength; ++i) {
                        uInt8Array[i] = raw.charCodeAt(i);
                    }

                    return new Blob([uInt8Array], {type: contentType});
                }

                function submitForm() {
                    document.getElementById('signature').value = signaturePad.toDataURL();
                }


                var signaturePad = new SignaturePad(canvas);
                signaturePad.minWidth = 1;
                signaturePad.maxWidth = 5;
                signaturePad.penColor = "#000000";
                signaturePad.backgroundColor = "#FFFFFF";

                window.onresize = resizeCanvas;
                resizeCanvas();
            });
    }

        /**
         * Event: Selected Service "Changed"
         *
         * When the user clicks on a service, its available providers should
         * become visible.
         */
        $('#select-service').change(function () {

            FrontendBookApi.getUnavailableDates($('#select-provider').val(), $('#select-service').val(),
                $('#select-date').datepicker('getDate').toString('yyyy-MM-dd'));
            FrontendBook.updateConfirmFrame();
            _updateServiceDescription($('#select-service').val(), $('#service-description'));
            var selecteeservice = document.getElementById('select-service').value;
        });
        $('#select-company').change(function () {
            var currcompanyid = $('#select-company').val();
            $.each(GlobalVariables.companies, function (index, company) {
                if (company.id === currcompanyid) {
                    document.body.style.backgroundColor = company.backgroundcolor;
                    document.getElementById("header").style.backgroundColor = company.topheader;
                    var x = document.getElementById("company-name").innerHTML;
                    var y = company.name;
                    var res = y.concat(' ', x);
                    // console.log(res);

                    document.getElementById("company-name").innerHTML = res;
if(company.logolink !== '' || null){

                    var image = document.getElementById("logobro");
                    if (company.width === "0" || "" || null || "") {
                        image.style.width = 'auto';


                    } else {
                        var widthdude = company.width;
                        var widthdudeone = widthdude.concat('px');
                        image.style.width = widthdudeone;
                    }

                    if (company.leng === "0" || "" || null || "") {
                        image.style.height = 'auto';


                    } else {
                        var lengdude = company.leng;
                        var lengdudeone = lengdude.concat('px');
                        image.style.height = lengdudeone;
                    }
                    image.src = GlobalVariables.baseUrl + '/uploads/' + company.logolink;
                }
                }
            });
            var currcompid = $('#select-company').val();

            $('#select-provider').empty();
            $.each(GlobalVariables.availableProviders, function (index, provider) {
                //var hasGoogleSync = provider.settings.google_sync === '1' ? 'true' : 'false';

                $.each(GlobalVariables.companies, function (indexcompany, company) {
                    if (company.id === currcompid) {
                        $.each(company.locations, function (indexlocation, locationid) {

                        if (locationid === provider.id) {

                            var optionHtml =
                                '<option value="' + provider.id + '" >'
                                + provider.first_name
                                + '</option>';
                            $('#select-provider').append(optionHtml);

                        }
                        });
                    }
                });
            });
            var currprovid = $('#select-provider').val();
            $('#select-service').empty();
            // Update the providers select box.
            $.each(GlobalVariables.availableServices, function (indexService, service) {
                $.each(service.providers, function (indexProvider, providerId) {
                    // If the current provider is able to provide the selected service,
                    // add him to the listbox.
                    if (providerId == currprovid) {
                        if (service.openclosed == 'OPEN') {
                            if(service.activeinactive == 1) {
    var optionHtml = '<option value="' + service.id + '">'
        + service.name
        + '</option>';
    $('#select-service').append(optionHtml);
}
                        } else {
                            var selectedServiceId = GeneralFunctions.getUrlParameter(location.href, 'service');
                            if (selectedServiceId === service.hash_id) {
                                                            if(service.activeinactive == 1) {

                                var optionHtml = '<option value="' + service.id + '">'
                                    + service.name
                                    + '</option>';
                                $('#select-service').append(optionHtml);
}
                            }
                        }
                    }
                });
            });


            FrontendBookApi.getUnavailableDates($('#select-provider').val(), $('#select-service').val(),
                $('#select-date').datepicker('getDate').toString('yyyy-MM-dd'));
            FrontendBook.updateConfirmFrame();
            _updateServiceDescription($('#select-service').val(), $('#service-description'));
            var selecteeservice = document.getElementById('select-service').value;


        });

        $('#select-provider').change(function () {
            var currprovid = $('#select-provider').val();
            $('#select-service').empty();

//console.log(GlobalVariables.availableProviders);
            $.each(GlobalVariables.availableServices, function (indexService, service) {
                $.each(service.providers, function (indexProvider, providerId) {
                    // If the current provider is able to provide the selected service,
                    // add him to the listbox.
                    if (providerId == currprovid) {
                        if (service.openclosed == 'OPEN') {
                            if(service.activeinactive == 1) {

                            var optionHtml = '<option value="' + service.id + '">'
                                + service.name
                                + '</option>';
                            $('#select-service').append(optionHtml);
                            }
                        } else {
                            var selectedServiceId = GeneralFunctions.getUrlParameter(location.href, 'service');
                            if (selectedServiceId === service.hash_id) {
                                                            if(service.activeinactive == 1) {
                                var optionHtml = '<option value="' + service.id + '">'
                                    + service.name
                                    + '</option>';
                                $('#select-service').append(optionHtml);
                                                            }

                            }
                        }
                    }
                });
            });




            // Add the "Any Provider" entry.
            //if ($('#select-provider option').length >= 1) {
            //$('#select-provider').append(new Option('- ' + EALang.any_provider + ' -', 'any-provider'));
            // }

            FrontendBookApi.getUnavailableDates($('#select-provider').val(), $('#select-service').val(),
                $('#select-date').datepicker('getDate').toString('yyyy-MM-dd'));
            FrontendBook.updateConfirmFrame();
            _updateServiceDescription($('#select-service').val(), $('#service-description'));
            var selecteeservice = document.getElementById('select-service').value;



        });


        /**
         * 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 performed, depending the current wizard step.
         */
        $('.button-next').click(function () {
            // If we are on the first step and there is not provider selected do not continue
            // with the next step.
            if ($(this).attr('data-step_index') === '1' && $('#select-service').val() == null) {
                return;
            }
            // 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('<br><br>'
                            + '<span id="select-hour-prompt" class="text-danger">'
                            + EALang.appointment_hour_missing
                            + '</span>');
                    }
                    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 (!_validateCustomerForm()) {
                    return; // Validation failed, do not continue.
                } else {
                        $(window).resize();
                    if(document.getElementById("file")) {
                        var fileInput = document.getElementById('file');
                        var files = document.getElementById("file").files;
                        if (files.length > 0) {
                            var reader = new FileReader();
                            reader.readAsDataURL(fileInput.files[0]);

                            reader.onload = function () {
                                document.getElementById('fileencoding').value = reader.result;
                                console.log(reader.result);//base64encoded string
                            };
                            reader.onerror = function (error) {
                                console.log('Error: ', error);
                            };
                        }
                    }
                    FrontendBook.updateConfirmFrame();

                    var $acceptToTermsAndConditions = $('#accept-to-terms-and-conditions');
                    if ($acceptToTermsAndConditions.length && $acceptToTermsAndConditions.prop('checked') === true) {
                        var newTermsAndConditionsConsent = {
                            first_name: $('#first-name').val(),
                            last_name: $('#last-name').val(),
                            email: $('#email').val(),
                            type: 'terms-and-conditions'
                        };

                        if (JSON.stringify(newTermsAndConditionsConsent) !== JSON.stringify(termsAndConditionsConsent)) {
                            termsAndConditionsConsent = newTermsAndConditionsConsent;
                            FrontendBookApi.saveConsent(termsAndConditionsConsent);
                        }
                    }

                    var $acceptToPrivacyPolicy = $('#accept-to-privacy-policy');
                    if ($acceptToPrivacyPolicy.length && $acceptToPrivacyPolicy.prop('checked') === true) {
                        var newPrivacyPolicyConsent = {
                            first_name: $('#first-name').val(),
                            last_name: $('#last-name').val(),
                            email: $('#email').val(),
                            type: 'privacy-policy'
                        };

                        if (JSON.stringify(newPrivacyPolicyConsent) !== JSON.stringify(privacyPolicyConsent)) {
                            privacyPolicyConsent = newPrivacyPolicyConsent;
                            FrontendBookApi.saveConsent(privacyPolicyConsent);
                        }
                    }
                }
            }

            // 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.
             *
             * @param {jQuery.Event} event
             */
            $('#cancel-appointment').click(function (event) {
                var buttons = [
                    {
                        text: 'OK',
                        click: function () {
                            if ($('#cancel-reason').val() === '') {
                                $('#cancel-reason').css('border', '2px solid red');
                                return;
                            }
                            if ($('#cancel-firstname').val() === '') {
                                $('#cancel-firstname').css('border', '2px solid red');
                                return;


                            }

                            if ($('#cancel-lastname').val() === '') {
                                $('#cancel-lastname').css('border', '2px solid red');
                                return;


                            }

                            $('#cancel-appointment-form textarea').val($('#cancel-reason').val());
                            $('#cancel-appointment-form input[id=cancel_firstname]').val($('#cancel-firstname').val());
                            $('#cancel-appointment-form input[id=cancel_lastname]').val($('#cancel-lastname').val());


                            $('#cancel-appointment-form').submit();
                        }
                    },
                    {
                        text: EALang.cancel,
                        click: function () {
                            $('#message_box').dialog('close');
                        }
                    }
                ];

                GeneralFunctions.displayMessageBox(EALang.cancel_appointment_title,
                    EALang.write_appointment_removal_reason, buttons);

                $('#message_box').append('<label for="cancel-firstname">First Name of patient deleting appointment  </label><input type="text" name="cancel-firstname" id="cancel-firstname" required><br><label for="cancel-lastname">Last Name of patient deleting appointment  </label><input type="text" name="cancel-lastname" id="cancel-lastname" required><br><label for="cancel-reason">Reason appointment is being cancelled:</label><textarea id="cancel-reason" rows="3"></textarea>');
                $('#cancel-reason').css('width', '100%');
                return false;
            });
            $('#delete-personal-information').on('click', function () {
                var buttons = [
                    {
                        text: EALang.delete,
                        click: function () {
                            FrontendBookApi.deletePersonalInformation(GlobalVariables.customerToken);
                        }
                    },
                    {
                        text: EALang.cancel,
                        click: function () {
                            $('#message_box').dialog('close');
                        }
                    }
                ];

                GeneralFunctions.displayMessageBox(EALang.delete_personal_information,
                    EALang.delete_personal_information_prompt, buttons);
            });
        }

        /**
         * 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.
         *
         * @param {jQuery.Event} event
         */
        $('#book-appointment-submit').click(function (event) {
            //console.log($('#g-recaptcha-response').val());
            FrontendBook.updateConfirmFrame();
            // console.log(comment);
            var captchayesorno = document.getElementById('captchayesorno').value;
            if ( captchayesorno === 'YES') {
                var comment = document.getElementById("g-recaptcha-response").value;

                if(comment === ''){

                    document.getElementById("captchamillieerror").style.display = "block";
                }else{
                    document.getElementById("captchamillieerror").style.display = "none";

                    FrontendBookApi.registerAppointment();
                }
            }else{
                FrontendBookApi.registerAppointment();

            }
        });

        /**
         * Event: Refresh captcha image.
         *
         * @param {jQuery.Event} event
         */
        $('.captcha-title small').click(function (event) {
            // $('.captcha-image').attr('src', GlobalVariables.baseUrl + '/index.php/captcha?' + Date.now());
        });


        $('#select-date').on('mousedown', '.ui-datepicker-calendar td', function (event) {
            setTimeout(function () {
                FrontendBookApi.applyPreviousUnavailableDates(); // New jQuery UI version will replace the td elements.
            }, 300); // There is no draw event unfortunately.
        })
    }

    /**
     * This function validates the customer's data input. The user cannot continue
     * without passing all the validation checks.
     *
     * @return {Boolean} Returns the validation result.
     */
    function _validateCustomerForm() {
        $('#wizard-frame-3 .has-error').removeClass('has-error');
        $('#wizard-frame-3 label.text-danger').removeClass('text-danger');

        try {
            // Validate required fields.
            var missingRequiredField = false;
            $('.required').each(function () {
                if($(this).is(':checkbox')){
                    if($(this).is(':checked')) {

                    }else{
                        $(this).parents('.form-group').addClass('has-error');
                        missingRequiredField = true;
                    }
                }
                if ($(this).val() == '') {
                    $(this).parents('.form-group').addClass('has-error');
                    missingRequiredField = true;
                }
            });
            if (missingRequiredField) {
                throw EALang.fields_are_required;
            }
            $.each(GlobalVariables.availableServices, function (index, service) {
                if (service.id == $('#select-service').val()) {
                    if (service.minimummaxonoff == 'ON') {
                        var startDateInput = $('#birth-date').val();
                        var endDateInput = new Date().toISOString().slice(0, 10);

                        // convert user input values into date object
                        var startDate = new Date(startDateInput);
                        var endDate = new Date(endDateInput);

                        // get difference between two date;
                        var difference = endDate - startDate.getTime();

                        var ageDate = new Date(difference);
                        var calculatedAge = Math.abs(ageDate.getUTCFullYear() - 1970);

                        if (calculatedAge > service.minimum && calculatedAge < service.maximum) {
                        } else {
                            throw 'You are not eligible to book an appointment';

                        }
                    }

                }
            });

            var $acceptToTermsAndConditions = $('#accept-to-terms-and-conditions');
            if ($acceptToTermsAndConditions.length && !$acceptToTermsAndConditions.prop('checked')) {
                $acceptToTermsAndConditions.parents('label').addClass('text-danger');
                throw EALang.fields_are_required;
            }

            var $acceptToPrivacyPolicy = $('#accept-to-privacy-policy');
            if ($acceptToPrivacyPolicy.length && !$acceptToPrivacyPolicy.prop('checked')) {
                $acceptToPrivacyPolicy.parents('label').addClass('text-danger');
                throw EALang.fields_are_required;
            }


            // Validate email address.
            if (!GeneralFunctions.validateEmail($('#email').val())) {
                $('#email').parents('.form-group').addClass('has-error');
                throw 'Invalid Email Address';
            }

            return true;
        } catch (exc) {
            $('#form-message').text(exc);
            return false;
        }
    }

    /**
     * Every time this function is executed, it updates the confirmation page with the latest
     * customer settings and input for the appointment booking.
     */
    exports.updateConfirmFrame = function () {
        if ($('.selected-hour').text() === '') {
            return;
        }

        // Appointment Details
        var selectedDate = $('#select-date').datepicker('getDate');

        if (selectedDate !== null) {
            selectedDate = GeneralFunctions.formatDate(selectedDate, GlobalVariables.dateFormat);
        }

        var selServiceId = $('#select-service').val();
        var servicePrice;
        var serviceCurrency;

        $.each(GlobalVariables.availableServices, function (index, service) {
            if (service.id == selServiceId) {
                //servicePrice = '<br>' + service.price;
                //serviceCurrency = service.currency;
                //return false; // break loop
            }
        });

        var html =
            '<h4>' + $('#select-service option:selected').text() + '</h4>' +
            '<p>'
            + '<strong class="text-primary">'
            + $('#select-provider option:selected').text() + '<br>'
            + selectedDate + ' ' + $('.selected-hour').text()
            //+ servicePrice + ' ' + serviceCurrency
            + '</strong>' +
            '</p>';

        $('#appointment-details').html(html);

        // Customer Details
        var firstName = GeneralFunctions.escapeHtml($('#first-name').val());
        var lastName = GeneralFunctions.escapeHtml($('#last-name').val());
        var phoneNumber = GeneralFunctions.escapeHtml($('#phone-number').val());
        var email = GeneralFunctions.escapeHtml($('#email').val());
        var address = GeneralFunctions.escapeHtml($('#address').val());
        var city = GeneralFunctions.escapeHtml($('#city').val());
        var zipCode = GeneralFunctions.escapeHtml($('#zip-code').val());

        html =
            '<h4>' + firstName + ' ' + lastName + '</h4>' +
            '<p>' +
            EALang.phone + ': ' + phoneNumber +
            '<br/>' +
            EALang.email + ': ' + email +
            '<br/>' +
            EALang.address + ': ' + address +
            '<br/>' +
            EALang.city + ': ' + city +
            '<br/>' +
            EALang.zip_code + ': ' + zipCode +
            '</p>';

        $('#customer-details').html(html);

        // Update appointment form data for submission to server when the user confirms
        // the appointment.
        var postData = {};

        postData.customer = {
            last_name: $('#last-name').val(),
            first_name: $('#first-name').val(),
            email: $('#email').val(),
            phone_number: $('#phone-number').val(),
            address: $('#address').val(),
            city: $('#city').val(),
            state: $('#state').val(),
            zip_code: $('#zip-code').val(),
            birthdate: $('#birth-date').val(),
            backgroundcolor: '',
            topheader: '',
            logolink: '',
            width: '',
            leng: '',
            linkvar: '',
            company_id_for_customer: $('#select-company').val()

        };

        postData.appointment = {
            start_datetime: $('#select-date').datepicker('getDate').toString('yyyy-MM-dd')
                + ' ' + Date.parse($('.selected-hour').text()).toString('HH:mm') + ':00',
            end_datetime: _calcEndDatetime(),
            notes: $('#notes').val(),
            is_unavailable: false,
            dontsend: 'SEND',
            id_users_provider: $('#select-provider').val(),
            id_services: $('#select-service').val(),
            id_company: $('#select-company').val(),
            max_appts: 0,
        };

        if (FrontendBook.manageMode) {
        }else {
            $.each(GlobalVariables.availableServices, function (index, service) {
                if (service.id == $('#select-service').val()) {
                    var i = 0;
                    postData.appointment.formtype = {};
                    $.each(GlobalVariables.forms, function (indexform, form) {
                        i++;
                        if (service.form == form.form_id) {
                            if (form.postdata == 1) {

                                postData.appointment.form = form.formtype;
                                postData.appointment.formid = form.form_id;
                                var label = form.label;
                                var but = '#' + form.html_id;
                                var butone = form.label;
                                // console.log(but);
                                //console.log($(but).val());
                                if($(but).is(':checkbox')) {
                                    if ($(but).is(':checked')) {
                                        postData.appointment.formtype[form.html_id] = $(but).val() + '|' + butone;
                                    }
                                }else {
                                    postData.appointment.formtype[form.html_id] = $(but).val() + '|' + butone;
                                }
                            }
                        }
                        postData.appointment.formtype.signature = $('#signature').val();

                    });
                }
            });

        }

        postData.linkvar = {

            linkvarhash: GlobalVariables.linkvar.hash,
            linkexpires: GlobalVariables.linkvar.date_expires,
        };
        postData.manage_mode = FrontendBook.manageMode;

        if (FrontendBook.manageMode) {
            postData.appointment.id = GlobalVariables.appointmentData.id;
            postData.customer.id = GlobalVariables.customerData.id;
        }
        $('input[name="csrfToken"]').val(GlobalVariables.csrfToken);
        $('input[name="post_data"]').val(JSON.stringify(postData));
        console.log(postData);

    };

    /**
     * This method calculates the end datetime of the current appointment.
     * End datetime is depending on the service$('#signature').val(); and start datetime fields.
     *
     * @return {String} Returns the end datetime in string format.
     */
    function _calcEndDatetime() {
        // Find selected service duration.
        var selServiceDuration = undefined;

        $.each(GlobalVariables.availableServices, function (index, service) {
            if (service.id == $('#select-service').val()) {
                selServiceDuration = service.duration;
                return false; // Stop searching ...
            }
        });

        // Add the duration to the start datetime.
        var startDatetime = $('#select-date').datepicker('getDate').toString('dd-MM-yyyy')
            + ' ' + Date.parse($('.selected-hour').text()).toString('HH:mm');
        startDatetime = Date.parseExact(startDatetime, 'dd-MM-yyyy HH:mm');
        var endDatetime = undefined;

        if (selServiceDuration !== undefined && startDatetime !== null) {
            endDatetime = startDatetime.add({'minutes': parseInt(selServiceDuration)});
        } else {
            endDatetime = new Date();
        }

        return endDatetime.toString('yyyy-MM-dd HH:mm:ss');
    }

    /**
     * This method applies the appointment's data to the wizard so
     * that the user can start making changes on an existing record.
     *
     * @param {Object} appointment Selected appointment's data.
     * @param {Object} provider Selected provider's data.
     * @param {Object} customer Selected customer's data.
     *
     * @return {Boolean} Returns the operation result.
     */
    function _applyAppointmentData(appointment, provider, customer) {
        try {
            // Select Service & Provider
            $('#select-company').val(appointment.id_company).trigger('change');
            $('#select-provider').val(appointment.id_users_provider).trigger('change');
            $('#select-service').val(appointment.id_services).trigger('change');

document.getElementById("select-company").disabled = true;
document.getElementById("select-provider").disabled = true;
document.getElementById("select-service").disabled = true;

            // Set Appointment Date
            $('#select-date').datepicker('setDate',
                Date.parseExact(appointment.start_datetime, 'yyyy-MM-dd HH:mm:ss'));
  FrontendBookApi.getUnavailableDates($('#select-provider').val(), $('#select-service').val(),
                appointment.start_datetime.toString('yyyy-MM-dd'));
            FrontendBook.updateConfirmFrame();
            _updateServiceDescription($('#select-service').val(), $('#service-description'));
            var selecteeservice = document.getElementById('select-service').value;
                    
            // Apply Customer's Data
            $('#last-name').val(customer.last_name);
            $('#first-name').val(customer.first_name);
            $('#email').val(customer.email);
            $('#phone-number').val(customer.phone_number);
            $('#address').val(customer.address);
            $('#city').val(customer.city);
            $('#state').val(customer.state);
            $('#zip-code').val(customer.zip_code);
            var appointmentNotes = (appointment.notes !== null)
                ? appointment.notes : '';
            $('#notes').val(appointmentNotes);
            $('#birth-date').val(customer.birthdate);


            FrontendBook.updateConfirmFrame();

            return true;
        } catch (exc) {
            return false;
        }
    }

    /**
     * This method updates a div's html content with a brief description of the
     * user selected service (only if available in db). This is useful for the
     * customers upon selecting the correct service.
     *
     * @param {Number} serviceId The selected service record id.
     * @param {Object} $div The destination div jquery object (e.g. provide $('#div-id')
     * object as value).
     */
    function _updateServiceDescription(serviceId, $div) {
        var html = '';

        $.each(GlobalVariables.availableServices, function (index, service) {
            if (service.id == serviceId) { // Just found the service.
                html = '<strong>' + service.name + ' </strong>';

                if (service.duration != '' && service.duration != null) {
                    html += '[' + EALang.duration + ' ' + service.duration + ' ' + EALang.minutes + ']';
                }

                if (service.description != '' && service.description != null) {
                    html += '<br>' + service.description.replace(/\n/g, '<br>');
                }

                if (FrontendBook.manageMode) {

                }else {
                    if (service.servicecheckbox != '' && service.servicecheckbox != null) {
                        document.getElementById('checkboxterms').innerHTML = '<input type="checkbox" class="required" name="accept-to-terms-and-conditions" id="accept-to-terms-and-conditions"><label class="control-label" id="accept_require" name="accept_require" for="accept-to-terms-and-conditions">' + service.servicecheckbox + '</label><label style="color:red">* REQUIRED</label> <br>';
                    }

                /*   document.getElementById('linkmillie').innerHTML  = '<strong>'+service.linkdescription+'</strong>';
                   document.getElementById('linktoform').textContent = service.linkname;
                   document.getElementById('linktoform').href = service.link;

                   document.getElementById('linkmillie2').innerHTML  = '<strong>'+service.linkdescription2+'</strong>' ;
                   document.getElementById('linktoform2').textContent = service.linkname2;
                   document.getElementById('linktoform2').href = service.link2;

                   document.getElementById('linkmillie3').innerHTML  = '<strong>'+service.linkdescription3+'</strong>' ;
                   document.getElementById('linktoform3').textContent = service.linkname3;
                   document.getElementById('linktoform3').href = service.link3;*/
//console.log(service.waitlistonoff);
                if (service.minimummaxonoff == 'ON') {
                    document.getElementById("birthdatelabel").innerHTML = "Birthdate* - minimum age: " +
                        +service.minimum
                        +
                        " maximum age:" +
                        ' ' + service.maximum;
                }
                document.getElementById("waitlist").innerHTML = "";
                document.getElementById("button-next-1").style.display = "block";
                document.getElementById('hrefwaitlist').textContent = "";
                document.getElementById('hrefwaitlist').href = "";
                document.getElementById("form_questions").innerHTML = "";
                if (FrontendBook.manageMode) {
                }else{
                $.each(GlobalVariables.forms, function (indexform, form) {

                    if (service.form == form.form_id) {

                        if (form.type == 'text') {
                            document.getElementById("form_questions").innerHTML += '<div class="form-group"><label for=' + '"' + form.html_id + '"' + 'class="control-label">' + form.label + '</label><br>' + '<input type="text"' + ' onchange=' + "'" + form.onchange + "'" +' id=' + '"' + form.html_id + '"' + ' name=' + '"' + form.html_name + '"' + ' class=' + '"' + form.class + '"' + 'maxlength=' + '"' + form.maxlength + '"' + '></div>';
                        }
                        
                        if (form.type == 'datetext') {
                            document.getElementById("form_questions").innerHTML += '<div class="form-group"><label for=' + '"' + form.html_id + '"' + 'class="control-label">' + form.label + '</label><br>' + '<input type="date" id=' + '"' + form.html_id + '"' + ' name=' + '"' + form.html_name + '"' + ' class=' + '"' + form.class + '"' + 'maxlength=' + '"' + form.maxlength + '"' + '></div>';
                        }
                        
                        if (form.type == 'select') {
                            var optionnamesplit = form.optionnames;
                            var optionidsplit = form.optionid;
                            var optionvaluesplit = form.optionvalues;
                            var namesplit = optionnamesplit.split(',');
                            var idsplit = optionidsplit.split(',');
                            var valuesplit = optionvaluesplit.split(',');
                            var stuff = '';
                            for (var i = 0; i < namesplit.length; i++) {
                                stuff += '<option value=' + '"' + valuesplit[i] + '"' + ' name=' + '"' + namesplit[i] + '"' + ' id=' + '"' + idsplit[i] + '"' + '>' + valuesplit[i] + '</option>';
                            }
                            document.getElementById("form_questions").innerHTML += '<div class="form-group">' + '<label for=' + '"' + form.html_id + '"' + ' class="control-label">' + form.label + '</label><br>' + '<select onchange=' + "'" + form.onchange + "'" + ' id=' + '"' + form.html_id + '"' + ' name=' + '"' + form.html_name + '"' + ' class=' + '"' + form.class + '"' + '> ' + '<option value="" name="">PLEASE SELECT</option>' +stuff;
                            document.getElementById("form_questions").innerHTML += '</select></div><br>';
                        }
                        if (form.type == 'span') {
                            document.getElementById("form_questions").innerHTML += '<p>' + form.label + '</p><br>';
                        }

                        if (form.type == 'hthree') {
                            document.getElementById("form_questions").innerHTML += '<h5>' + form.label + '</h5><br>';
                        }
                        if (form.type == 'checkbox') {
                            document.getElementById("form_questions").innerHTML += '<div class="form-group">' + '<input type="checkbox"' + ' class='+'"' + form.class + '"'+' id=' + '"' + form.html_id + '"' + ' name=' + '"' + form.html_name + '"' +' value='+'"'+form.optionvalues+'"'+ '>' + '<label for=' + '"' + form.html_id + '"' + ' class="control-label">' + form.label + '</label><br></div>';
                        }

                        if (form.type == 'fileupload') {
                            document.getElementById("form_questions").innerHTML += '<div class="form-group">' + '<label for=' + '"' + 'file' + '"' + ' class="control-label">' + form.label + '</label>' + '<input type="file"' + ' id=' + '"' + 'file' + '"' + ' name=' + '"' + 'file' + '"' + '>' + '<input type="hidden" id="fileencoding" name="fileencoding">' + '<button  class="btn btn-primary" id="filebutton" name="filebutton" onclick="document.getElementById(' + "'" + 'file' + "'" + ').value=null">Refresh Files</button>';
                        }

                        if (form.type == 'button') {
                            document.getElementById("form_questions").innerHTML += '<a href=' + '"' + form.html_name + '"' + ' class="btn btn-primary" target="_blank">' + form.label + '</a>';
                        }
                        if (form.type == 'radio') {
                            document.getElementById("form_questions").innerHTML += '<div class="form-group">' + '<label for=' + '"' + form.html_id + '"' + ' class="control-label">' + form.label + '</label>';
                            var optionnamesplit = form.optionnames;
                            var optionidsplit = form.optionid;
                            var optionvaluesplit = form.optionvalues;
                            var namesplit = optionnamesplit.split(',');
                            var idsplit = optionidsplit.split(',');
                            var valuesplit = optionvaluesplit.split(',');
                            for (var i = 0; i < valuesplit.length; i++) {
                                document.getElementById("form_questions").innerHTML += '<input type="radio" value=' + '"' + valuesplit[i] + '"' + ' name=' + '"' + form.html_id + '"' + ' id=' + '"' + idsplit[i] + '"' + '>' + '<label for=' + '"' + form.html_id + '"' + ' class="control-label">' + namesplit[i] + '</label><br>';
                            }
                            document.getElementById("form_questions").innerHTML += '</div><br>';

                        }
                    }
                });
            }

                if(service.waitlistonofffunction == 'ON'){


                    if(service.waitlistonoff == 'ON'){
                        if (FrontendBook.manageMode) {
                            document.getElementById("waitlist").innerHTML = "";
                            document.getElementById("button-next-1").style.display = "block";
                            document.getElementById('hrefwaitlist').textContent = "";
                            document.getElementById('hrefwaitlist').href = "";

                        }else{
                            document.getElementById("waitlist").innerHTML = "There are no more appointments for this service. Please go to the following link to be added to the waitlist You will be notified by email once more appointment spots open up. If you are not able to find an appointment after receiving your email, you will be asked to put yourself back on the waitlist and we will notify you once we receive more inventory.";
                            document.getElementById("button-next-1").style.display = "none";
                            document.getElementById('hrefwaitlist').textContent = "WAITLIST";
                            document.getElementById('hrefwaitlist').href = GlobalVariables.baseUrl+'/waitlist.php?service='+service.id;
                        }

                    }else{

                        document.getElementById("waitlist").innerHTML = "";
                        document.getElementById("button-next-1").style.display = "block";
                        document.getElementById('hrefwaitlist').textContent = "";
                        document.getElementById('hrefwaitlist').href = "";
                    }

                    //var selectedwaitlist = GeneralFunctions.getUrlParameter(location.href, 'linkvar');
                    console.log(GlobalVariables.linkvar.hash);
                    if(GlobalVariables.linkvar.hash !== ''){
                        document.getElementById("waitlist").innerHTML = "";
                        document.getElementById("button-next-1").style.display = "block";
                        document.getElementById('hrefwaitlist').textContent = "";
                        document.getElementById('hrefwaitlist').href = "";

                    }

                }

                }
                //if (service.price != '' && service.price != null) {
                //html += '[' + EALang.price + ' ' + service.price + ' ' + service.currency + ']';
                // }

                html += '<br>';





                return false;

            }
        });


        $div.html(html);

        if (html != '') {
            $div.show();
        } else {
            $div.hide();
        }
    }

})(window.FrontendBook);
