HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers75/roost-interieurbouw.nl/wwwroot/js/chocolateFactory.js
/* ==========================================================================
 | Prevent Bots handler
 |
 | We named this chocolate factory and belonging confusing js hooks
 | to prevent smart bots from blocking these variable or functions.
 |
 | The form wrapper should have the 'js-chococlate-factory'.
 | The desired submit element should have the 'js-golden-ticket'.
 | All form fields should have a wrapper around it with 'form-element', this is for marking the error.
 |
 ========================================================================== */

/*
 * Simple isset method for this does not exist in javascript
 */
const isset = function (obj) {
    return typeof obj !== 'undefined' && obj !== null;
};

const Ajax = {
    get: function(url, callback) {

    },
    post: function(url, data, callback) {
        let xhr = new XMLHttpRequest();
        let token = document.querySelector('meta[name="csrf-token"]').content;

        xhr.open('post', url, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.setRequestHeader('X-CSRF-TOKEN', token);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if(xhr.status === 200) {
                    callback(xhr);
                } else {
                    console.error('Ajax: Could complete request. '+xhr.statusText);
                }
            }
        };
        xhr.send( JSON.stringify(data));
    }
};

/**
 * Capitalize the first letter of the string
 * @param string
 * @returns {string}
 */
const capitalizeFirstLetter = function (string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
};

$(function () {

    const ChocolateFactory = {

        bannedVisitor: [],

        /** Get all the chocolate factory and start
         *  Looping through those start flashing tickets
         */
        enter: function()
        {

            const chocolateFactories = document.querySelectorAll('.js-chocolate-factory');

            if(isset(chocolateFactories)){

                const amountOfChocolateFactories = chocolateFactories.length;
                for(let i = 0; i < amountOfChocolateFactories; i++){

                    const ChocolateBar = chocolateFactories[i];
                    ChocolateFactory._flashTicket(ChocolateBar);
                }
            }
        },

        /**
         * If factory has a golden ticket
         * Then we can make them go on the tour if there has been click on the ticket
         *
         * @param chocolateBar
         * @private
         */
        _flashTicket: function (chocolateBar) {

            // Try get the ticket from the chocolateBar
            const goldenTicket = chocolateBar.querySelector('.js-golden-ticket');

            // Only continue if chocolate bar has a golden ticket
            if(isset(goldenTicket)){

                goldenTicket.addEventListener('click', function () {
                    ChocolateFactory.enjoyTheTour(chocolateBar);
                });
            }
            else{
                console.log('To bad, no golden tickets has been found.');
            }
        },

        /**
         * Start the tour through the factory
         * And get the names and properties of the members of the group
         * If there are members in the group of course
         *
         * @param chocolateFactory
         */
        enjoyTheTour(chocolateFactory){

            // Ask for the tour group
            const tourGroup = chocolateFactory.querySelectorAll('input, textarea');

            if(isset(tourGroup)){

                // For each visitor we want a belonging Oompa Loompa
                let oompaLoompas = {};
                let amountOfOompaLoompas = 0;

                const tourGroupSize = tourGroup.length;
                for(let i = 0; i < tourGroupSize; i++){

                    // Get the visitor from the group
                    const visitor = tourGroup[i];

                    // Ask for its name
                    const visitorName = visitor.getAttribute('name');

                    // Check if the visitor is banned
                    if( ChocolateFactory._isVisitorBanned(visitorName)) continue;

                    oompaLoompas[ visitorName ] = ChocolateFactory._getArrangement(visitor);
                    amountOfOompaLoompas++;
                }

                // Check for insurance that there are oompa loompas
                if(amountOfOompaLoompas === 0) return;

                // Send submit request
                ChocolateFactory._finishTour(oompaLoompas, chocolateFactory);
            }
            else{
                console.log('To bad, no members to visit this factory')
            }
        },

        /**
         * Check if the visitor name isn't allow
         *
         * @param visitorName
         * @returns {boolean}
         * @private
         */
        _isVisitorBanned: function(visitorName){
            if(ChocolateFactory.bannedVisitor.indexOf(visitorName) !== -1){
                return true;
            }
            return false;
        },

        /**
         * Most get visitor have a normal arrangement
         * But sometimes there are special cases
         * Like a Selector or checkbox
         *
         * @param visitor
         * @returns {*}
         * @private
         */
        _getArrangement: function(visitor)
        {

            const visitorType = visitor.nodeName;

            switch (visitorType) {
                default:
                    return visitor.value;
            }
        },

        /**
         * Finish the tour
         * If successful show thanks message
         * Or show defined error message or fallback
         *
         * @param group
         * @param chocolateFactory
         * @returns {*|void}
         * @private
         */
        _finishTour: function(group, chocolateFactory)
        {
            group = ChocolateFactory._addWillieWonka(group);

            try {

                $.ajax({
                    method: "POST",
                    data: group,
                    url: '/contact/process-new'
                }).done(function (responseData) {

                    switch (responseData.status) {
                        case 200:
                            return ChocolateFactory._thanksForVisiting(responseData.data.redirectUrl);
                        case 422:
                            return ChocolateFactory._giveFeedbackToMembers(responseData.errors, chocolateFactory);
                        default:
                            break;
                    }

                    return ChocolateFactory._unknownGapInFactory(chocolateFactory);

                });

            }
            catch (e) {
                return ChocolateFactory._unknownGapInFactory(chocolateFactory);
            }
        },

        /**
         * Add willie wonka to the group
         * Ps... it actually the secret code!
         *
         * @param group
         * @returns {*}
         * @private
         */
        _addWillieWonka: function(group){
            group.willie = 'wonka';
            return group;
        },

        /**
         * Add the feedback to the desired area.
         * Most likely to the visitor directly, but sometime to the factory desired feedback area
         *
         * @param errors
         * @param chocolateFactory
         * @private
         */
        _giveFeedbackToMembers: function(errors, chocolateFactory){

            // Grab the factory feedback area
            const feedbackArea = chocolateFactory.querySelector('.js-error-area');

            // Clear the current html
            if(isset(feedbackArea)) feedbackArea.innerHTML = '';

            // Clear the previous marked jackets
            ChocolateFactory._clearPreviousMarkedJackets(chocolateFactory);

            Object.keys(errors).forEach(function(visitor) {

                let jacket = null;
                let visitorFeedbackArea = null;

                // Honey elements doesn't has a accessible element
                if(visitor !== '_honey' && visitor !== '_secretCode') {

                    // Grab the visitor
                    const visitorNode = chocolateFactory.querySelector('#' + visitor);

                    // Find the jacket of a visitor
                    jacket = ChocolateFactory._grabVisitorJacket(visitorNode);

                    // If found get the desired area
                    if(isset(jacket)) visitorFeedbackArea = jacket.querySelector('.js-form-element-error');

                    // Clear the current html
                    if(isset(visitorFeedbackArea)) visitorFeedbackArea.innerHTML = '';

                }

                // Get the feedback for this visitor
                const visitorFeedback = errors[visitor];

                // Spit out each line
                const visitorFeedbackAmount = visitorFeedback.length;
                for(let i = 0; i < visitorFeedbackAmount; i++){
                    const visitorFeedbackLine = visitorFeedback[i];

                    // Honey elements doesn't has a accessible element area
                    if(visitor !== '_honey' && visitor !== '_secretCode') {

                        // Mark the jacket
                        if(isset(jacket)) jacket.classList.add('has-error');

                        // Append feedback to visitor feedback area if defined
                        if(isset(visitorFeedbackArea))
                        {
                            let currentFeedbackArea = visitorFeedbackArea.innerHTML;
                            currentFeedbackArea += '<span>' + capitalizeFirstLetter(visitorFeedbackLine) + '</span>';
                            visitorFeedbackArea.innerHTML = currentFeedbackArea;
                        }
                    }

                    // Append feedback to factory feedback area if defined
                    if(isset(feedbackArea)){
                        let currentFeedbackArea = feedbackArea.innerHTML;
                        currentFeedbackArea += '<li>' + capitalizeFirstLetter(visitorFeedbackLine) + '</li>';
                        feedbackArea.innerHTML = currentFeedbackArea;
                    }
                }

            });
        },

        /**
         * Clear the previous marked jackets
         *
         * @param chocolateFactory
         * @private
         */
        _clearPreviousMarkedJackets(chocolateFactory) {

            const markedJackets = chocolateFactory.querySelectorAll('.has-error');
            const markedJacketsAmount = markedJackets.length;

            for(let i = 0; i < markedJacketsAmount; i++){
                markedJackets[i].classList.remove('has-error');
            }
        },

        /**
         * Grab the jacket of the visitor
         *
         * @param visitor
         * @returns {(() => (Node | null)) | ActiveX.IXMLDOMNode | (Node & ParentNode)}
         * @private
         */
        _grabVisitorJacket: function(visitor){

            // Check if visitor is defined
            if (!isset(visitor)) return null;

            // Do loop settings
            currentLayer = visitor;
            isJacket = false;
            safetyBreak = 0;

            // Grab the next layer till it is the jacket (or safetyBreak has been reached
            do {
                currentLayer = currentLayer.parentNode;
                if(currentLayer.classList.contains('form-element')) isJacket = true;
            } while (isJacket === false || safetyBreak >= 10);

            return currentLayer;
        },

        /**
         * Redirect the visitor to the thanks page
         *
         * @param nextStop
         * @private
         */
        _thanksForVisiting: function (nextStop) {
            window.location = nextStop;
        },

        /**
         * Unknown error occurred, log the error
         *
         * @param chocolateFactory
         * @private
         */
        _unknownGapInFactory: function (chocolateFactory) {
            console.log(chocolateFactory);
            console.log('ChocolateFactory: Unkown Error');
        },
    };

    ChocolateFactory.enter();

});