const BinaryPjax          = require('./binary_pjax');
const pages_config        = require('./binary_pages');
const Client              = require('./client');
const GTM                 = require('./gtm');
const Header              = require('./header');
const Login               = require('./login');
const Page                = require('./page');
const BinarySocket        = require('./socket');
const BinarySocketGeneral = require('./socket_general');
const getElementById      = require('../../_common/common_functions').getElementById;
const localize            = require('../../_common/localize').localize;
const ScrollToAnchor      = require('../../_common/scroll_to_anchor');
const isStorageSupported  = require('../../_common/storage').isStorageSupported;
const urlFor              = require('../../_common/url').urlFor;
const applyToAllElements  = require('../../_common/utility').applyToAllElements;
const createElement       = require('../../_common/utility').createElement;

const BinaryLoader = (() => {
    let container;
    let active_script = null;

    const init = () => {
        if (!/\.html$/i.test(window.location.pathname)) {
            window.location.pathname += '.html';
            return;
        }

        if (!isStorageSupported(localStorage) || !isStorageSupported(sessionStorage)) {
            Header.displayNotification(localize('[_1] requires your browser\'s web storage to be enabled in order to function properly. Please enable it or exit private browsing mode.', ['Binary.com']),
                true, 'STORAGE_NOT_SUPPORTED');
            getElementById('btn_login').classList.add('button-disabled');
        }

        Page.showNotificationOutdatedBrowser();

        Client.init();
        BinarySocket.init(BinarySocketGeneral.initOptions());

        container = getElementById('content-holder');
        container.addEventListener('binarypjax:before', beforeContentChange);
        container.addEventListener('binarypjax:after',  afterContentChange);
        BinaryPjax.init(container, '#content');
    };

    const beforeContentChange = () => {
        if (active_script) {
            BinarySocket.removeOnDisconnect();
            if (typeof active_script.onUnload === 'function') {
                active_script.onUnload();
            }
            active_script = null;
        }
    };

    const afterContentChange = (e) => {
        Page.onLoad();
        GTM.pushDataLayer();

        BinarySocket.wait('website_status').then((response) => {
            // eu countries code
            if (/^(al|ad|at|by|be|ba|bg|hr|cy|cz|dk|ee|fo|fi|fr|de|gi|gr|hu|is|ie|im|it|ru|lv|li|lt|lu|mk|mt|md|mc|me|nl|no|pl|pt|ro|sm|sk|si|es|se|ch|ua|va)$/.test(response.website_status.clients_country)) {
                applyToAllElements('.eu-show', (el) => { el.setVisibility(1); });
                applyToAllElements('.eu-hide', (el) => { el.setVisibility(0); });
                if (/get_started_tabs=mt5/.test(window.location.href)) {
                    BinaryPjax.load(urlFor('get-started'));
                }
            } else {
                applyToAllElements('.eu-hide', (el) => { el.setVisibility(1); });
            }
        });

        if (Client.isLoggedIn()) {
            if (!Client.hasCostaricaAccount()) {
                applyToAllElements('.only-cr', (el) => { el.setVisibility(0); });
                // Fix issue with tabs.
                if (/get_started_tabs=lookback/.test(window.location.href)) {
                    BinaryPjax.load(urlFor('get-started'));
                }
            }
        }

        const this_page = e.detail.getAttribute('data-page');
        if (this_page in pages_config) {
            loadHandler(pages_config[this_page]);
        } else if (/\/get-started\//i.test(window.location.pathname)) {
            loadHandler(pages_config['get-started']);
        }

        ScrollToAnchor.init();
    };

    const error_messages = {
        login       : () => localize('Please [_1]log in[_2] or [_3]sign up[_2] to view this page.', [`<a href="${'javascript:;'}">`, '</a>', `<a href="${urlFor()}">`]),
        only_virtual: 'Sorry, this feature is available to virtual accounts only.',
        only_real   : 'This feature is not relevant to virtual-money accounts.',
    };

    const loadHandler = (config) => {
        active_script = config.module;
        if (config.is_authenticated) {
            if (!Client.isLoggedIn()) {
                displayMessage(error_messages.login());
            } else {
                BinarySocket.wait('authorize')
                    .then((response) => {
                        if (response.error) {
                            displayMessage(error_messages.login());
                        } else if (config.only_virtual && !Client.get('is_virtual')) {
                            displayMessage(error_messages.only_virtual);
                        } else if (config.only_real && Client.get('is_virtual')) {
                            displayMessage(error_messages.only_real);
                        } else {
                            loadActiveScript(config);
                        }
                    });
            }
        } else if (config.not_authenticated && Client.isLoggedIn()) {
            BinaryPjax.load(Client.defaultRedirectUrl(), true);
        } else {
            loadActiveScript(config);
        }
        BinarySocket.setOnDisconnect(active_script.onDisconnect);
    };

    const loadActiveScript = (config) => {
        if (active_script && typeof active_script.onLoad === 'function') {
            // only pages that call formatMoney should wait for website_status
            if (config.needs_currency) {
                BinarySocket.wait('website_status').then(() => {
                    active_script.onLoad();
                });
            } else {
                active_script.onLoad();
            }
        }
    };

    const displayMessage = (message) => {
        const content = container.querySelector('#content .container');
        if (!content) {
            return;
        }

        const div_container = createElement('div', { class: 'logged_out_title_container', html: content.getElementsByTagName('h1')[0] });
        const div_notice    = createElement('p', { class: 'center-text notice-msg', html: localize(message) });

        div_container.appendChild(div_notice);

        content.html(div_container);

        const link = content.getElementsByTagName('a')[0];
        if (link) {
            link.addEventListener('click', () => { Login.redirectToLogin(); });
        }
    };

    return {
        init,
    };
})();

module.exports = BinaryLoader;

@@ -605,16 +605,83 @@
 calize;%0A
+const QueryString         = require('../../_common/query_string');%0A
 const Sc
@@ -2146,32 +2146,223 @@
 hange = () =%3E %7B%0A
+        console.log('before content change');%0A        QueryString.setQueryStringWithoutReload(%0A            QueryString.removeParamFromQueryString(window.location.search, 'anchor')%0A        );%0A
         if (acti
@@ -2625,32 +2625,77 @@
 ange = (e) =%3E %7B%0A
+        console.log('after content change');%0A
         Page.onL

remove anchor from query string before page change