<template>

    <section class="inline-template-wrapper">

    <div class="prescriptionsLoading" :class="[loading ? 'isLoading' : '']">

        <div class="loadingIcon">
            <picture class="imageWrap">
                <img src="/sites/default/images/logo.png" alt="Logo">
            </picture>
            <div class="loadingText" v-html="loadingText"></div>
        </div> <!-- .loadingIcon -->

    </div> <!-- .prescriptionsLoading -->

    <div class="pages">


        <section
                v-for="(page, pageIndex) in pages"
                v-show="(currentPage === pageIndex) || debugModePages" class="page"
        >

            <div class="pageHeading">

                <div class="iconWrap">
                    <div class="icon">
                        <img src="/sites/default/images/svgs/doctor.svg" />
                    </div> <!-- .icon -->
                </div> <!-- .iconWrap -->
                <h2 v-html="pages[pageIndex].title"></h2>
                <p v-html="pages[pageIndex].introContent"></p>

            </div> <!-- .pageHeading -->


            <div class="innerPageContent" :class="[loading ? 'isLoading' : '']">

                <div class="medicationsPage nhsPrescriptions" v-if="pageIndex === 0">

                    <nhs-medications
                        :url-get-available-nhs-medications="urlGetAvailableNhsMedications"
                        :url-save-prescription="urlSavePrescription"
                        :url-get-prescription-data="urlGetPrescriptionData"
                        :url-check-medication-name-is-valid="urlCheckMedicationNameIsValid"
                        @set-page-has-errors="setPageHasErrors(pageIndex)"
                        @clear-page-has-errors="clearPageHasErrors(pageIndex)"
                        :formdata="formdata"
                        :errors="errors || {}"
                    ></nhs-medications>

                </div> <!-- .nhsPrescriptions -->

                <div class="medicationsPage nhsPrescriptions" v-if="pageIndex === 1">


                    <div class="innerUserDetailsWrap">

                        <form action="" autocomplete="off">

                            <div class="userDetails">

                                <div class="formGrid">

                                    <div class="fieldFull" v-if="(logged_in_member.is_referrer && logged_in_member.referred_members.length > 0)">
                                        <div class="row" :class="[errors.email ? 'errorWrap' : '']">
                                            <label for="your_patients" class="fieldLabel">Existing patient emails</label>
                                            <div class="inputWrap">

                                                <chosen
                                                        id="your_patients"
                                                        :options="logged_in_member.referred_members"
                                                        placeholder="Select patient"
                                                        v-model="formdata.existing_patient_id"
                                                        class="no-chosen"
                                                        @input="getMemberData()"
                                                        label="full_name_with_dob"

                                                ></chosen>

                                                <div class="assistiveText">Your existing patients</div>
                                                <div class="validationMessage" v-if="errors.email" v-html="errors.email"></div>
                                            </div>
                                        </div>
                                    </div> <!-- .fieldRight -->

                                </div> <!-- .formGrid -->


                                <div class="formGrid">

                                    <div class="fieldLeft">
                                        <div class="row fieldIcon iconUser" :class="[errors.firstname ? 'errorWrap' : '']">
                                            <label for="firstName" class="fieldLabel">First Name</label>
                                            <div class="inputWrap">
                                                <input
                                                        type="text"
                                                        id="firstName"
                                                        placeholder="First name"
                                                        v-model="formdata.nhs_member.firstname"
                                                        @input="updateNameTitles('firstname');"
                                                >
                                                <div class="assistiveText">Exactly as printed on prescriptions</div>
                                                <div class="validationMessage" v-if="errors.firstname" v-html="errors.firstname"></div>
                                            </div>
                                        </div>
                                    </div> <!-- .fieldLeft -->

                                    <div class="fieldRight">
                                        <div class="row fieldIcon iconUser" :class="[errors.lastname ? 'errorWrap' : '']">
                                            <label for="lastName" class="fieldLabel">Last Name</label>
                                            <div class="inputWrap">
                                                <input
                                                        type="text"
                                                        id="lastName"
                                                        placeholder="Last name"
                                                        v-model="formdata.nhs_member.lastname"
                                                        @input="clearError('lastname')"
                                                >
                                                <div class="assistiveText">Exactly as printed on prescriptions</div>
                                                <div class="validationMessage" v-if="errors.lastname" v-html="errors.lastname"></div>
                                            </div>
                                        </div>
                                    </div> <!-- .fieldRight -->

                                </div> <!-- .formGrid -->


                                <div class="formGrid">


                                    <div class="fieldRight" v-show="logged_in_member.is_patient_email_visible">
                                        <div class="row fieldIcon iconEmail" :class="[errors.email ? 'errorWrap' : '']">
                                            <label for="cardholder_email" class="fieldLabel">Email</label>
                                            <div class="inputWrap">
                                                <input
                                                        type="email"
                                                        id="cardholder_email"
                                                        placeholder="Email"
                                                        v-model="formdata.member.email"
                                                        @input="clearError('email')"
                                                        :readonly="formdata.member.id && formdata.member.id == logged_in_member.id"
                                                >
                                                <div class="assistiveText">To be used to access account</div>
                                                <div class="validationMessage" v-if="errors.email" v-html="errors.email"></div>
                                            </div>
                                        </div>
                                    </div> <!-- .fieldRight -->

                                    <div class="fieldRight" v-show="logged_in_member.is_patient_phone_number_visible">
                                        <div class="row fieldIcon iconPhone" :class="[errors.contact_no ? 'errorWrap' : '']">
                                            <label for="phoneNo" class="fieldLabel">Mobile number</label>
                                            <div class="inputWrap">
                                                <input
                                                        type="tel"
                                                        id="phoneNo"
                                                        placeholder="Mobile number"
                                                        v-model="formdata.member.contact_no"
                                                        @input="clearError('phoneNo')"
                                                >
                                                <div class="assistiveText"></div>
                                                <div class="validationMessage" v-if="errors.contact_no" v-html="errors.contact_no"></div>
                                            </div>
                                        </div>
                                    </div> <!-- .fieldLeft -->

                                </div> <!-- .formGrid -->

                            </div> <!-- .userDeatails -->

                        </form>

                    </div><!-- .innerUserDetailsWrap -->



                </div><!-- .nhsPrescriptions -->

                <div class="mapsPage nhsPrescriptions" v-if="pageIndex === 2">

                    <surgery-map-search
                        :data="formdata.nhs_member"
                        :errors="errors"
                        :url-get-available-doctor-surgeries="urlGetAvailableDoctorSurgeries"
                        @clear-page-has-errors="clearPageHasErrors(pageIndex)"
                    ></surgery-map-search>

                </div><!-- .nhsPrescriptions -->

                <div class="medicationsPage nhsPrescriptions" v-if="pageIndex === 3">

                    <div class="innerUserDetailsWrap">

                        <form action="" autocomplete="off">

                            <div class="userFormTop">

                                <div class="row fieldIcon iconId" :class="[errors.nhs_number ? 'errorWrap' : '']">

                                    <div class="inputWrap">

                                        <input
                                                type="text"
                                                id="nhs_number"
                                                placeholder="NHS Number"
                                                v-model="formdata.nhs_member.nhs_number"
                                                @input="formatNhsNumber(formdata.nhs_member.nhs_number)"
                                        >
                                        <div class="validationMessage" v-if="errors.nhs_number" v-html="errors.nhs_number"></div>

                                    </div><!-- .inputWrap -->

                                </div><!-- .row -->

                                <div class="row" :class="[errors.dob ? 'errorWrap' : '']">

                                    <div class="inputWrap">

                                        <div class="datepickerWrap">

                                            <datepicker
                                                    class="datepicker"
                                                    v-model="formdata.nhs_member.dob"
                                                    @input="clearError('dob')"
                                                    @blur="clearError('dob')"
                                                    :options="{
                                                        dateFormat: 'dd/mm/yy',
                                                        altFormat: 'yy-mm-dd',
                                                        maxDate: '0d',
                                                    }"
                                                    placeholder="D.O.B"
                                                    id="nhs_member_dob"
                                            ></datepicker>

                                        </div>


                                    </div><!-- .inputWrap -->

                                    <div class="validationMessage" v-if="errors.dob" v-html="errors.dob"></div>

                                </div><!-- .row -->

                            </div> <!-- .userFormTop -->


                            <single-checkbox
                                id="nhs_member_is_vulnerable"
                                label="Would you like to enroll the person to our Vulnerable Patient Programme?"
                                v-model="formdata.nhs_member.is_vulnerable"
                                v-if="logged_in_member.is_referrer"
                            ></single-checkbox>


                            <nhs-prescription-exemptions
                                :data="formdata.nhs_member"
                                :errors="errors"
                                :url-get-available-exemption-reasons="urlGetAvailableExemptionReasons"
                            ></nhs-prescription-exemptions>


                            <multi-select-checkbox
                                :title="text.categoriesText"
                                :url-get-available-options="urlGetAvailableMedicalCategories"
                                :selected-options="formdata.nhs_member.medical_categories || []"
                            ></multi-select-checkbox>


                            <member-address
                                title="Home address"
                                :data="formdata.member_addresses.billing"
                                :errors="errors.address_billing || {}"
                                @clear-page-has-errors="clearPageHasErrors(pageIndex)"
                            ></member-address>


                            <member-address
                                title="Delivery address"
                                :data="formdata.member_addresses.shipping"
                                :errors="errors.address_shipping || {}"
                                @clear-page-has-errors="clearPageHasErrors(pageIndex)"
                                :toggle-message-data="formdata.prescription"
                                :toggle-message-checkbox="text.shippingToggleText"
                                toggle-message-details="If you have small children, pets or others who could be at risk at the property, please consider using a different delivery address. Please note controlled drugs and refrigerated items will require a signature upon delivery."
                            ></member-address>

                        </form>

                    </div> <!-- .innerPatientWrap -->


                </div>

                <div class="medicationsPage nhsPrescriptions" v-if="pageIndex === 3">


                    <div class="accountCreation">

                        <div v-if="! (logged_in_member.is_referrer || formdata.member.is_activated)">

                            <div class="pageHeading">

                            <h2>Create your account</h2>
                            <p>Please enter a password below to use for your account</p>

                            </div> <!-- .pageHeading -->

                            <div class="passwordTerms">

                                <form action="" autocomplete="off">

                                    <div class="passwordFields">

                                        <div class="row fieldIcon iconPassword" :class="[errors.password ? 'errorWrap' : '']">
                                            <div class="inputWrap">
                                                <input
                                                        type="password"
                                                        id="password"
                                                        placeholder="Password"
                                                        v-model="formdata.member.password"
                                                        @input="clearError('password')"
                                                >
                                                <div class="validationMessage" v-if="errors.password" v-html="errors.password"></div>
                                            </div>
                                        </div>

                                        <div class="row fieldIcon iconPassword" :class="[errors.password2 ? 'errorWrap' : '']">
                                            <div class="inputWrap">
                                                <input
                                                        type="password"
                                                        id="password2"
                                                        placeholder="Re-enter password"
                                                        v-model="formdata.member.password2"
                                                        @input="clearError('password2')"
                                                >
                                                <div class="validationMessage" v-if="errors.password2" v-html="errors.password2"></div>
                                            </div>
                                        </div>

                                    </div> <!-- .passwordFiels -->

                                </form>

                            </div>

                        </div> <!-- .passwordTerms -->

                        <div>

                            <div class="additionalOptions">

                                <h5 class="formTitle" v-text="config_get_string('page_4', 'dataTitle')"></h5>

                                <div class="highlightBox">


                                    <div class="row" :class="[errors.has_nominated_client_as_pharmacy_of_choice ? 'errorWrap' : '']">

                                        <div class="inputWrap">

                                            <input
                                                    type="checkbox"
                                                    id="nominated_vyne"
                                                    name="nominated_vyne"
                                                    :true-value="1"
                                                    :false-value="0"
                                                    v-model="formdata.member.has_nominated_client_as_pharmacy_of_choice"
                                                    @change="clearError('has_nominated_client_as_pharmacy_of_choice')"
                                            >

                                            <label for="nominated_vyne">
                                                By ticking this box you agree to nominate us as your pharmacy or DAC of choice,
                                                based on the items you’ve ordered. By doing so, you consent for us to process
                                                the data above in order to request and process your NHS prescriptions. To find
                                                out more about nominations and view
                                                our <a href="/customer-care/terms-and-conditions" target="_blank">terms and conditions</a>.
                                                <i class="hoverFX"></i>
                                            </label>

                                        </div> <!-- .inputWrap -->

                                    </div>


                                    <div class="row" :class="[errors.confirmed_terms_at ? 'errorWrap' : '']">

                                        <div class="inputWrap">

                                            <input
                                                    type="checkbox"
                                                    id="has_confirmed_terms"
                                                    name="has_confirmed_terms"
                                                    :true-value="1"
                                                    :false-value="0"
                                                    v-model="formdata.member.has_confirmed_terms"
                                                    @change="clearError('confirmed_terms_at')"
                                            >

                                            <label for="has_confirmed_terms">
                                                Please confirm that you have read and agree with our <a href="/customer-care/terms-and-conditions">terms and conditions</a>.
                                                <i class="hoverFX"></i>
                                            </label>

                                        </div> <!-- .inputWrap -->

                                    </div>

                                </div> <!-- .highlightBox -->

                            </div> <!-- .additionalOptions -->


                        </div> <!-- .passwordTerms -->


                    </div> <!-- .accountCreation -->



                </div>

            </div> <!-- .innerPageContent -->


            <div class="errorBlock" v-if="pages[pageIndex].hasErrors">

                <div class="error" v-if="pageIndex == 0">
                    To continue, please ensure you have added and saved your prescription medication(s) above.
                </div> <!-- .error -->

                <div class="error" v-if="pageIndex == 1">
                    To continue, please ensure you have completed all the required fields above.
                </div> <!-- .error -->

                <div class="error" v-if="pageIndex == 2">
                    To continue, please enter your postcode and select your GP surgery from the map or list above.
                </div> <!-- .error -->

                <div class="error" v-if="pageIndex == 3">
                    To continue, please ensure you have completed all the required fields above.
                </div> <!-- .error -->

                <div class="error" v-if="pageError" v-html="pageError"></div> <!-- .error -->

                <div class="error" v-if="pageIndex == 4 && !pageError">
                    To continue, please ensure you have completed all the required fields above.
                </div> <!-- .error -->

            </div> <!-- .errorBlock -->





            <div
                    class="buttonWrapper"
                    v-if="formdata.prescription.copy_of_prescription_id"
            >
                <a
                        href="#"
                        @click.prevent="savePageData(lastPageIndex - 1)"
                        v-html="pages[lastPageIndex - 1].proceedButtonText"
                        rel="next"
                        class="next button"
                ></a>
            </div> <!-- .buttonWrapper -->


            <div
                    class="buttonWrapper"
                    v-if="pages[pageIndex].proceedButtonText || pages[pageIndex].goBackButtonText"
            >

                <a
                        href="#"
                        @click.prevent="gotoPrevPage()"
                        v-html="pages[pageIndex].goBackButtonText"
                        v-if="pages[pageIndex].goBackButtonText"
                        rel="prev"
                        class="prev button"
                ></a>

                <a
                        href="#"
                        @click.prevent="savePageData(pageIndex)"
                        v-html="pages[pageIndex].proceedButtonText"
                        v-if="pages[pageIndex].proceedButtonText"
                        rel="next"
                        class="next button"
                        :disabled="!pages[pageIndex].canProceed"
                ></a>

            </div> <!-- .buttonWrapper -->




        </section>

    </div> <!-- .pages -->

    </section>

</template>


<script>

import config from '../../../../plugins/NHS/js/components/config.js';


export default {

    props: [
        "loggedInMember",

        "urlGetAvailableExemptionReasons",
        "urlGetAvailableNhsMedications",
        "urlGetAvailableDoctorSurgeries",
        "urlGetAvailableMedicalCategories",

        "urlGetPrescriptionData",
        "urlGetMemberData",

        "urlCheckMedicationNameIsValid",

        "urlNhsPrescriptionsCreate",
        "urlSavePrescription",
        "urlSubmit",
    ],

    data: function () {

        return {

            debugModePages: false, //Shows all pages at once

            logged_in_member: {
                id: null,
                is_referrer: false,
                referred_members: [],
            },

            text: {
                categoriesText: '',
                shippingToggleText: '',
                shippingToggleContent: '',
                newPrescriptionText: '',
                newPrescriptionButtonText: ''
            },

            loading: true,
            currentPage: 0,
            pageTransitionDelay: 500,
            errors: {},
            pageError: false,

            formdata: {
                existing_patient_id: null,

                prescription: {
                    "id": null,
                    "uuid": "",
                    "copy_of_prescription_id": null,
                    "nhs_member_id": null,
                    "status": "",
                    "created_at": "",
                    "updated_at": "",
                    "items": [],
                    "shipping_same_as_billing": 0,
                },

                nhs_member: {
                    "id": null,
                    "member_id": null,
                    "doctor_surgery": null,
                    "firstname": "",
                    "lastname": "",
                    "dob": "",
                    "nhs_number": "",
                    "gender": "",
                    "reminder_date": "",
                    "is_pay_for_prescriptions": 0,
                    "pay_explanation": "",
                    "exemption_expiry_date": null,
                    "is_property_safe": 0,
                    "is_patient": 0,
                    "is_vulnerable": 0,
                    "is_hcp": 0,
                    "is_professional_carer": 0,
                    "created_at": "",
                    "updated_at": "",
                    "medical_categories": [],
                },

                member: {
                    "id": null,
                    "referrer_member_id": null,
                    "magento_entity_id": null,
                    "email": "",
                    "contact_no": "",
                    "hash": "",
                    "conditions": "",
                    "medications": "",
                    "allergies": "",
                    "basket_id": 0,
                    "optout": 0,
                    "prescription_reminder_email": false,
                    "prescription_reminder_sms": false,
                    "last_login": "0000-00-00 00:00:00",
                    "last_failed_login": "0000-00-00 00:00:00",
                    "failed_login_count": 0,
                    "created_at": "",
                    "updated_at": "",
                    "first_login": null,
                    "account_verified": null,
                    "verification_code": "",
                    "verification_code_expiry": "0000-00-00 00:00:00",
                    "phone_prefix": "",
                    "passed_id_check": null,
                    "dob_date": null,
                    "dob_month": null,
                    "dob_year": null,
                    "gender": "",
                    "doctor_surgery": "",
                    "has_nominated_client_as_pharmacy_of_choice": 0,
                    "has_confirmed_terms": 0,
                    "password": "",
                    "password2": "",
                    "is_activated": "",
                },

                member_addresses: {
                    billing: {
                        address1: '',
                        address2: '',
                        city: '',
                        postcode: ''
                    },
                    shipping: {
                        address1: '',
                        address2: '',
                        city: '',
                        postcode: ''
                    },
                },

                prescription_items: [],

            },

            genders: [
                {
                    value: 'Male',
                    label: 'Male'
                },
                {
                    value: 'Female',
                    label: 'Female'
                },
                {
                    value: 'Other',
                    label: 'Other'
                }
            ],
            loadingTextDefault: 'Loading',
            loadingText: 'Loading',

        };
    },

    created: function () {

        this.logged_in_member = JSON.parse(this.loggedInMember);

        config.setMemberType(this.useMemberType());

        this.updateConfigText();

        //this.$dispatch('initSidebarNav', this.pages, this.currentPage);

        //Load patient data
        this.getMemberData();
        this.getPrescriptionData();

        //Talk to the sidebar
        this.updateSidebar();

        EventBus.$emit('initSidebarNav', this.pages, this.currentPage);

        EventBus.$on('set_page', function(pageNum) {
            if (vm.allowSetPage) {
                vm.currentPage = pageNum;
            }
        });

    },

    mounted: function() {

        var vm = this;

        //events
        EventBus.$emit('startGoogleMaps', this.currentPage);

        setTimeout(function(){
            vm.loading = false;
        },vm.pageTransitionDelay);



    },


    computed: {

        pages: function() {
            return [
                {
                    pageNum: 1,
                    pageID: 'medication',
                    title: config.get_string("page_1", "title"),
                    introContent: config.get_string("page_1", "introContent"),
                    navTitle: config.get_string("page_1", "navTitle"),
                    navSubtitle: config.get_string("page_1", "navSubtitle"),
                    proceedButtonText: config.get_string("page_1", "proceedButtonText"),
                    goBackButtonText: false,
                    canProceed: true,
                    hasErrors: false,
                    formFields: [
                        'prescription_items',
                        'prescription_items_error',
                    ],
                },
                {
                    pageNum: 2,
                    pageID: 'user_details',
                    title: config.get_string("page_2", "title"),
                    introContent: config.get_string("page_2", "introContent"),
                    navTitle: config.get_string("page_2", "navTitle"),
                    navSubtitle: config.get_string("page_2", "navSubtitle"),
                    proceedButtonText: 'Next: Find a GP',
                    goBackButtonText: 'Prev: Choose a prescription',
                    canProceed: true,
                    hasErrors: false,
                    formFields: [
                        'billing_firstname',
                        'billing_lastname',
                        'firstname',
                        'lastname',
                        'contact_no',
                        'email',
                    ],
                    trackingCheckoutStepName: 'landed_on_basic_details_page',
                },
                {
                    pageNum: 3,
                    pageID: 'gp',
                    title: 'Find your GP',
                    title: config.get_string("page_3", "title"),
                    introContent: config.get_string("page_3", "introContent"),
                    navTitle: config.get_string("page_3", "navTitle"),
                    navSubtitle: config.get_string("page_3", "navSubtitle"),
                    proceedButtonText: config.get_string("page_3", "proceedButtonText"),
                    goBackButtonText: config.get_string("page_3", "backButtonText"),
                    canProceed: true,
                    hasErrors: false,
                    formFields: [ 'doctor_surgery' ],
                    trackingCheckoutStepName: 'landed_on_find_gp_page',
                },
                {
                    pageNum: 4,
                    pageID: 'user_address_details',
                    title: config.get_string("page_4", "title"),
                    introContent: config.get_string("page_4", "introContent"),
                    navTitle: config.get_string("page_4", "navTitle"),
                    navSubtitle: config.get_string("page_4", "navSubtitle"),
                    proceedButtonText: 'Next: Confirm and submit',
                    goBackButtonText: 'Prev: Find a GP',
                    canProceed: true,
                    hasErrors: false,
                    formFields: [
                        'dob',
                        'nhs_member_id',
                        'address_shipping',
                        'address_billing',
                        'password',
                        'nhs_number',
                        'confirmed_terms_at',
                        'has_nominated_client_as_pharmacy_of_choice',
                    ],
                    showNewPrecriptionButton: this.logged_in_member.is_referrer ? true : false,
                    trackingCheckoutStepName: 'landed_on_additional_details_page',
                },
                {
                    pageNum: 5,
                    isExternal: true,
                    url: this.urlSubmit,
                },
            ];
        },

        lastPageIndex: function() {
            return (this.pages.length - 1);
        },

        memberType: function() {
            this.useMemberType();
        },

    },


    methods: {

        config_get_string: function(page_key, string_key) {
            return config.get_string(page_key, string_key);
        },

        updateConfigText: function() {
            for(var i in this.text) {
                this.text[i] = config.get_string("page_4", i);
            }
        },

        useMemberType: function() {
            if (this.logged_in_member.is_referrer) {
                return 'referrer';
            } else {
                return 'patient';
            }
        },

        setPageHasErrors: function(pageIndex) {
            this.pages[pageIndex].hasErrors = true;
            this.pages[pageIndex].canProceed = false;
        },

        clearPageHasErrors: function(pageIndex) {
            this.pages[pageIndex].hasErrors = false;
            this.pages[pageIndex].canProceed = true;
        },


        hasFoundErrorsOnCurrentPage: function(invalid_fields) {

            let found_errors = false;
            let current_page = this.pages[this.currentPage];

            if (invalid_fields) {

                for (let invalid_field in invalid_fields) {
                    if (current_page.formFields.includes(invalid_field)) {
                        found_errors = true;
                    }
                }

            }

            return found_errors;
        },


        setErrors: function(error_data) {
            this.errors = error_data;
        },


        /*
        * Send page data to server
        */
        savePageData: function(pageIndex) {

            var vm = this,
                page = vm.pages[pageIndex];

            if(!vm.loading) {

                vm.loading = true;

                this.$http.post(this.urlSavePrescription, {
                    page_id: JSON.stringify(page.pageID),
                    formdata: vm.formdata
                })
                    .then(function (res) {

                        vm.setErrors(res.data.errors);

                        if (this.hasFoundErrorsOnCurrentPage(res.data.errors)) {

                            page.canProceed = false;
                            page.hasErrors = true;
                            vm.loading = false;

                            // Prescription item errors are handled differently.
                            if (res.data.errors.prescription_items) {
                                this.formdata.prescription_items = res.data.errors.prescription_items;
                            }

                        } else {

                            page.canProceed = true;
                            page.hasErrors = false;
                            vm.gotoNextPage(pageIndex);

                        }

                    })
                    .catch(function (error) {

                        if (error.status == 403) { // Forbidden
                            this.loading = true;
                            window.location.reload();
                            return;
                        }

                        vm.pages[pageIndex].canProceed = true;
                        vm.pages[pageIndex].hasErrors = true;
                        vm.loading = false;
                    });
            }
        },


        /*
        * Format the nhs number field
         */
        formatNhsNumber: function(val) {

            var vm = this,
                newVal = '',
                returnVal = '';

            //Clear errors
            vm.clearError('nhs_number');


            val = $.trim(val);

            if(val.length > 0) {
                newVal = val.replace(/ /g,'').replace(/[^0-9]/g, '');
            }

            for(var x = 0; x<newVal.length; x++) {

                if(x < 10) {

                    if (x === 3 || x === 6) {
                        returnVal += ' ';
                    }

                    returnVal += newVal[x];

                }
            }

            vm.formdata.nhs_member.nhs_number = returnVal;
            return vm.formdata.nhs_member.nhs_number;
        },


        /*
        * Get data for members and nhs members
        */
        getMemberData: function() {

            var vm = this;
            vm.loading = true;


            this.$http.post(this.urlGetMemberData, {
                nhs_member_id: this.formdata.existing_patient_id,
            })
                .then(function (res) {

                    vm.canProceed = true;

                    if (res.data) {
                        vm.formdata.nhs_member = res.data;

                        let member_data = res.data.member;
                        if (member_data.confirmed_terms_at) {
                            member_data.has_confirmed_terms = 1;
                        }
                        vm.formdata.member = member_data;

                        if (member_data.address_billing) {
                            vm.formdata.member_addresses.billing = member_data.address_billing;
                        }
                        if (member_data.address_shipping) {
                            vm.formdata.member_addresses.shipping = member_data.address_shipping;
                        }
                    }

                    //Toggle shipping address
                    vm.toggleShipping();

                    vm.loading = false;

                })
                .catch(function (error) {
                    vm.loading = false;
                });


        },


        /*
        * Clear errors from form fields
        */
        clearError: function(errorKey) {

            var vm = this;
            vm.pages[vm.currentPage].canProceed = true;


            if(vm.errors.hasOwnProperty(errorKey)) {
                Vue.delete(vm.errors, errorKey);
            }

            if(!Object.keys(vm.errors).length) {
                vm.pages[vm.currentPage].hasErrors = false;
            }

            vm.pageError = false;

        },

        /*
        * Clear patient errors from form fields
        */
        clearPatientError: function(index, errorKey) {

            var vm = this,
                errors = true;
            vm.pages[vm.currentPage].canProceed = true;


            if(vm.errors.hasOwnProperty('patients')) {

                if(typeof vm.errors.patients[index] != 'undefined') {

                    if (vm.errors.patients[index].hasOwnProperty(errorKey)) {
                        Vue.delete(vm.errors.patients[index], errorKey);
                    }

                    if(!Object.keys(vm.errors.patients[index]).length) {
                        Vue.delete(vm.errors.patients, index);
                    }

                }

                for(var x=0; x<vm.errors.patients.length; x++) {
                    if(typeof vm.errors.patients[x] == 'undefined') {
                        errors = false;
                    }

                }

            }

            if(!errors) {
                vm.pages[vm.currentPage].hasErrors = false;
            }


        },

        /*
        * Return patient error
        */
        patientError: function(index, errorKey) {

            var vm = this,
                error = false;

            if(vm.errors.hasOwnProperty('patients')) {

                if(typeof vm.errors.patients[index] != 'undefined') {

                    if (vm.errors.patients[index].hasOwnProperty(errorKey)) {
                        error = vm.errors.patients[index][errorKey];
                    }

                }

            }

            return error;

        },

        /*
        * Clear address errors from form fields
        */
        clearAddressError: function(type, errorKey) {

            var vm = this,
                errors = true;

            vm.pages[vm.currentPage].canProceed = true;


            if(vm.errors.hasOwnProperty(type)) {

                if(vm.errors[type].hasOwnProperty(errorKey)) {

                    if(vm.errors[type][errorKey] != 'undefined') {
                        Vue.delete(vm.errors[type], errorKey);
                    }

                }

            }


            if(typeof vm.errors[type] != 'undefined') {
                if (!Object.keys(vm.errors[type]).length) {
                    Vue.delete(vm.errors, type);
                }
            }


            if(!vm.errors.hasOwnProperty('billing') && !vm.errors.hasOwnProperty('shipping')) {
                vm.pages[vm.currentPage].hasErrors = false;
            }

        },

        /*
        * Return address error
        */
        addressError: function(type, errorKey) {

            var vm = this,
                error = false;

            if(vm.errors.hasOwnProperty(type)) {

                if(vm.errors[type].hasOwnProperty(errorKey)) {

                    if(typeof vm.errors[type][errorKey] != 'undefined') {
                        error = vm.errors[type][errorKey];
                    }

                }

            }

            return error;

        },


        /*
        * Set user's name on the gp page title
        */
        setGPtitle: function() {

            var pageIndex = this.getPageByID('gp', true),
                gpPage = this.pages[pageIndex],
                title = gpPage.title,
                userName = this.formdata.nhs_member.firstname;

            if(typeof userName != 'undefined') {

                if(userName.length > 0) {
                    var name = userName.charAt(0).toUpperCase() + userName.slice(1);
                    this.pages[pageIndex].title = 'Hi ' + name + ', lets find your GP';

                    if(logged_in_member.is_referrer) {
                        this.pages[pageIndex].title = 'Hi ' + name + ', lets find your patient\'s GP';
                    }
                    return;
                }

            }

            this.pages[pageIndex].title = 'Find your GP';

        },

        /*
        * Set user's name on the details page title
        */
        setDetailstitle: function() {

            var pageIndex = this.getPageByID('user_address_details', true),
                userName = this.formdata.nhs_member.firstname;

            if(typeof userName != 'undefined') {

                if(userName.length > 0) {
                    var name = userName.charAt(0).toUpperCase() + userName.slice(1);
                    this.pages[pageIndex].title = 'Tell us a little more about you ' + name;

                    if(logged_in_member.is_referrer) {
                        this.pages[pageIndex].title = 'Tell us a little more about your patient ';
                    }

                    return;
                }

            }

            this.pages[pageIndex].title = 'More about you';

        },

        /*
        * Adds username to titles
         */
        updateNameTitles: function(errorKey) {

            this.clearError(errorKey)
            //this.setGPtitle();
            //this.setDetailstitle();

        },



        /*
        * Get page by pageID
        * Setting returnIndex to true will return the page index
         */
        getPageByID: function(pageID, returnIndex) {

            var page = false,
                index = -1;

            for(let i=0; i<this.pages.length; i++) {

                var p = this.pages[i];

                if(p.pageID == pageID) {

                    index = i;
                    page = p;
                    break;
                }

            }

            if(!returnIndex) {
                return page;
            }else{
                return index;
            }

        },


        //Validation

        /*
        * Stop page from proceeding to the next if there are errors on the page
         */
        canProceed: function() {

            return true;

            var page = this.pages[this.currentPage];

            if(page.hasErrors) {
                page.canProceed = false;
            }else{
                page.canProceed = true;
            }

            return page.canProceed;

        },



        //Page Functionality


        gotoPage: function(pageIndex) {

            var vm = this;

            if (this.pageExists(pageIndex)) {

                if (this.pages[pageIndex].isExternal) {

                    this.loading = true;
                    window.location = this.urlSubmit;
                    return;

                } else {

                    if (! this.pages[pageIndex].hasErrors) {
                        this.currentPage = pageIndex;
                        this.updateSidebar(this.currentPage);

                        window.ee.sendEvent('checkout', {
                            stepName: this.pages[this.currentPage].trackingCheckoutStepName,
                        });

                    } else {
                        this.pages[pageIndex].canProceed = false;
                    }

                }

            }

            if(!vm.debugModePages) {

                $('html,body').animate({
                    scrollTop: 0
                }, 1000, function () {
                    vm.loading = false;
                });

            }else{
                vm.loading = false;
            }


        },


        gotoNextPage: function(currentPageIndex) {

            var vm = this,
                next = currentPageIndex + 1;

            if(this.canProceed) {
                vm.loading = true;

                setTimeout(function() {
                    vm.gotoPage(next);
                },vm.pageTransitionDelay);

            }else{
                setTimeout(function() {
                    vm.loading = false;
                },vm.pageTransitionDelay);
            }

        },


        gotoPrevPage: function() {

            var vm = this,
                prev = vm.currentPage - 1;

            vm.loading = true;

            setTimeout(function() {
                vm.gotoPage(prev);
            },vm.pageTransitionDelay);


        },


        updateSidebar: function() {
            EventBus.$emit('updateSidebarNav', this.currentPage);
        },


        pageExists: function(pageIndex) {

            var page = this.pages[pageIndex],
                exists = page ? true : false;

            return exists;

        },


        getPrescriptionData: function() {

            this.loading = true;

            this.$http.post(this.urlGetPrescriptionData, {
                //
            })
            .then(function (res) {

                this.canProceed = true;

                this.formdata.prescription = res.data;

                if (res.data.items) {
                    this.formdata.prescription_items = res.data.items;
                }

                this.loading = false;
            })
            .catch(function(error) {
                this.loading = false;
            });


        },

    }

}

</script>
