// DataStax load script

define(["require", "jquery"], function (require, $) {
    // initialize the DataStax environment after all required dependcies have loaded
    $(document).ready(function () {
        console.log('DataStax initialization');
        dsInit( document.getElementById('ds-product').innerHTML, document.getElementById('ds-docname').innerHTML );
    });

    function dsInit(product, doc) {
        console.log("dsInit() called");
        getVersionDropdown(product, doc);
        replaceNextPrevArrows();
        highlightSyntax();
        findCodeExamples();
        findRefExamples();
        findModals();
        getPopupSection();
        // Call function to add link to current page on docsreview
        //    only works if the user is on VPN
        loadDocsreview();
        setSwitcherLocale();
        window.toggleLocale = toggleLocale;
        redirectCheck();
        // used to wait in a separate area
        collapseContent();
        collapsibleByTitle();
        initCollapsibleByTitle();
        if (~doc.indexOf("landingpage")) {
            setExpandCards();
        }
    }
    // redirect old URLs that use hashtags
    function redirectCheck() {
        // new location of AMI install info
        if (window.location.hash === '#compatibility__datastax-ami') {
            window.location.replace('/en/install/6.7/install/installCloud.html#InstallingaDataStaxEnterpriseclusteronAmazonEC2');
        }
    }
    // highlight syntax using highlight.pack.js
    function highlightSyntax() {
        $('pre:not(.results, .release-notes)').each(function(i, block) {
            hljs.highlightBlock(block);
        });
    }
    // prepare doc for popups
    function getPopupSection() {
        // Find all the tags with a filepath-popup class
        var $filepaths = $(".filepath-popup");
        console.log('Found ' + $filepaths.length + ' filepaths.');

        // Find the hidden sections
        var $sections = $(".mfp-hide");
        console.log('Found mfp-hide sections: ' + $sections.length);

        // for each filepath-popup, link to the correct hidden section to trigger the popup
        $filepaths.each(function(i, block) {
            var filepath = $(this).text().replace(/[^[\p{L}\p{Digit}_]]+/g, '').replace(/\s+/g, '').replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
            console.log('Filepath is: ' + filepath);
            // find all links to the filepath-popup
            var $links = $(".open-popup-link:contains('"+ $(this).text()+"')");
            console.log('Found ' + filepath + ' links: ' + $links.length);
            $sections.each(function (i, block) {
                var $section = $(this);
                // if the id of the hidden section matches the filepath popup id update the link
                if ($(this).attr('id').toLocaleLowerCase().endsWith(filepath.toLocaleLowerCase())) {
                    $links.each(function(i, block) {
                        $(this).attr("data-src", "#" + $section.attr('id'));
                        console.log('Updated link to: ' + $section.attr('id'));
                    });
                }
            });
        });
    }
    // loads docsreview if on VPN and handles error if not
    function loadDocsreview() {
        var script = document.createElement('script');
        script.setAttribute("src", "/en/assets/js/linkToDrDs.js");
        document.getElementsByTagName('head')[0].appendChild(script);
        // only execute code if script loads
        script.onload = function() {
            linkToDocsreview();
        };
    }
    // formerly in toggleLocale.js
    function toggleLocale() {
        // do some URL parsing to figure out if the same topic exists in the target doc
        var pathArray = window.location.pathname.split( '/' );
        // the targetUrl will be the same topic in the new locale's doc
        var targetUrl = window.location.pathname;
        // if the targetUrl doesn't exist, redirect the user to the new locale's doc index page
        var indexUrl = '';

        // see what the current locale is, reconstruct URL with changed locale
        var currentLocale = pathArray[1];
        var newLocale;
        var bookName;
        if (currentLocale == "en") {
            newLocale = "ja";
        } else if (currentLocale == "ja") {
            newLocale = "en";
        }
        targetUrl = targetUrl.replace(currentLocale, newLocale);

        // no longer have to deal with the different URL template formats
        // the bookName is in a different location for each format

        // See if the targetUrl topic exists in the selected doc; if so, go to the topic, if not go to indexUrl
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            // if the topic exists, we'll get a 200 response
            if (this.readyState == 4) {
                if (this.status == 200) {
                    window.location = targetUrl;
                } else {
                    window.location = indexUrl;
                }
            }
        };

        // the targetUrl doesn't exist in new locale's doc, redirect
        xhr.onerror = function() {
            console.log("Current topic not in selected doc, redirect to doc home " + targetUrl);
            window.location = indexUrl;
        };

        xhr.open('GET', targetUrl, true);
        xhr.send();
    }
    function setSwitcherLocale() {
        var pathArray = window.location.pathname.split( '/' );
        var currentLocale = pathArray[1];
        if (currentLocale == 'en') {
            $('#1stLocale').text('English');
            $('#2ndLocale').text('日本語');
        } else {
            $('#1stLocale').text('日本語');
            $('#2ndLocale').text('English');
        }
        $('1stLocale').attr("selected", "selected");
    }
    // add the tags to codeblocks for making tabs
    function findCodeExamples() {
        // find groups of codeblocks and wrap them so we can create tabs
        $(':not(.codeblock) + .codeblock, * > .codeblock:first-of-type').each(function() {
            if ($(this).next()[0]) {
                var parentLang = getClass($(this), 'language-');
                var nextElement = $(this).next()[0];
                var nextLang = getClass(nextElement, 'language-');

                if ((typeof parentLang !== 'undefined') &&
                        (typeof nextLang !== 'undefined') &&
                        (parentLang.toString() !== nextLang.toString()) &&
                        (nextElement.className.indexOf('codeblock') > -1)) {
                        console.log("Making codeblock with parent " + parentLang + " and sibling " + nextLang);
                    $(this).addClass('current');
                    $(this).nextUntil(':not(.codeblock)')
                        .addBack()
                        .addClass('tab-content')
                        .wrapAll('<div class="code-tabs" />');
                } else {
                    console.log("Skipping codeblocks.");
                }
            }
        });
        // add a unique id to each code tab content block
        $('.tab-content').each(function(i, e) {
            var className = getClass($(this), 'language-');
            if (typeof className !== 'undefined') {
                className = className.replace('language-', '');
            } else {
                className = "codeblock";
            }
            $(this).prop('id', className + i);
        });
        // for each block of codeblocks, create the list for activating the tabs
        // also adds ids to associate list items with codeblocks
        $('.code-tabs').each(function() {
            var tablist = document.createElement('ul');
            tablist.className = "tabs";
            var tabs = new Map();
            $(this).find("pre[class*=' language-']").each(function() {
                var className = getClass($(this), 'language-');
                className = className.replace('language-', '');
                tabs.set($(this).prop('id'), className);
            });
            // only add the tabs if there is more than one codeblock in the group
            if (tabs.size > 1) {
                let index = 0;
                tabs.forEach((value, key) => {
                    var tabItem = document.createElement('li');
                    tabItem.innerHTML = value;
                    tabItem.setAttribute('data-tab', key);
                    tabItem.setAttribute('tabindex', '0');
                    tabItem.className = "tab-item";
                    if (index === 0) {
                        tabItem.className += " current";
                    }
                    tablist.appendChild(tabItem);
                    index++;
                });
                $(this).prepend(tablist);
            } else {
                $(this).unwrap();
            }
        });
        // Trigger the tab change
        $('ul.tabs li').click(function() {
            selectTab($(this));
        });
        // For accessibility, make it work from the keyboard
        $('ul.tabs li').on('keypress', function(e) {
            if (e.which == 13) {
                selectTab($(this));
            }
        });
    }
    // helper function for selecting code tab
    function selectTab($el) {
      var tab_id = $el.attr('data-tab');
      var language = tab_id.replace(/[0-9]/g, '');

      // remove all current classes from tabs and codeblocks
      $("ul.tabs li").removeClass('current');
      $(".code-tabs pre").removeClass('current');

      // add current to selected language on all tabs and codeblocks
      $("ul.tabs li[data-tab^='" + language + "'").addClass('current');
      $(".code-tabs pre[id^='" + language + "'").addClass('current');
    }

    // helper function to extract a classname by prefix
    function getClass(element, startsWith) {
      var result = undefined;
      $($(element).attr('class').split(' ')).each(function() {
        if (this.indexOf(startsWith) > -1) result = this;
      });
      return result;
    }
    // example modal stuff
    function findRefExamples() {
        if (document.querySelector(".refExample") !== null) {
            $(".refExample").each(function(i, e) {
            var showExample = document.createElement('button');
            showExample.setAttribute("id", "showExample" + i);
            showExample.setAttribute("name", "refExample" + i);
            showExample.setAttribute("class", "showExample");
            showExample.innerHTML = "Show example";
            $(this).attr("id", "refExample" + i);
            $(this).before(showExample);

            var sectionTitle = $("#showExample" + i).prev().find(".sectiontitle").text();

            $(this).dialog({
                autoOpen: false,
                title: sectionTitle,
                //height: 600,
                minHeight: 300,
                maxHeight: 600,
                width: 'auto',
                maxWidth: 700,
                fluid: true,
                modal: false,
                position: {
                my: "right top",
                at: "top",
                of: "#showExample" + i
                }
            });
            });
        }
        if (document.querySelector(".showExample") !== null) {
            $(".showExample").each(function(i, e) {
                $(this).button();
                var example = $(this).attr("name");
                $(this).click(function(event) {
                    event.preventDefault();
                    $("#" + example).dialog("open");
                    console.log("opening example dialog " + example);
                });
            });
        }
    }
    // process modal dialog output
    // jfb: temp disabled
    function findModals() {
        $('.legend').each(function() {
            var modalOpen = document.createElement('p');
            var openLink = document.createElement('a');
            openLink.className += " open-modal";
            openLink.setAttribute("href", "#");
            openLink.setAttribute("id", "showLegend");
            openLink.innerHTML = "Show syntax legend";
            modalOpen.appendChild(openLink);
            $(this).before(modalOpen);
            $(this).wrapAll('<div class="modal-legend" />');
        });

        // on clicking the trigger the modal dialog will popup with an overlay
        $('.open-modal').click(function(event) {
            $('.modal-legend').dialog("open");
            event.preventDefault();
        });

        // on clicking the close element the modal dialog & overlay will disappear
        $('.modal-close').click(function(event) {
            $('.modal-legend, .modal-overlay').hide();
            event.preventDefault();
        });

        // make the modal a dialog
        if (document.querySelector(".modal-legend") !== null) {
            try {
                $('.modal-legend').dialog({
                    modal: true,
                    fluid: true,
                    autoOpen: false,
                    minHeight: 400,
                    height: 400,
                    width: 'auto',
                    maxWidth: 700,
                    position: {
                        my: "left top",
                        at: "top",
                        of: "#showLegend"
                    }
                });
            } catch(error) {
                console.error('findModals error: ' + error.message)
            }
        }
    }
    // collapse command legend tables
    function collapseContent() {
        console.log("Entering collapseContent.");
        var collapsibleSections = {
            // Selectors for the nodes that contain an expand/collapse button.
            "expand_buttons": [
                // Table caption
                "table > caption > .wh_expand_btn",
                // Article title
                ".topic > .title > .wh_expand_btn",
                // Section title
                ".sectiontitle > .wh_expand_btn",
                // Index terms groups
                ".wh_term_group > .wh_first_letter > .wh_expand_btn"
            ],
            "collapse_by_default": [
                /* sections with collapseByDefault output class */
                ".collapseOnLoad .wh_expand_btn"
                // ".collapseOnLoad > caption > .wh_expand_btn"
            ]
        };
        // Collapse selected nodes.
        collapsibleSections.collapse_by_default.forEach(
            function(selector) {
                console.log("Running callback on collapseOnLoad");
                var matchedNodes = $(document).find(selector);
                // Change the button state
                matchedNodes.toggleClass("expanded");
                // Will collapse the siblings of the parent node, excepting the ones that were marked otherwise
                var siblings = matchedNodes.parent().siblings(':not(.wh_not_expandable)');
                siblings.toggle();
            }
        );
    }
    // adding collapse by title / caption to expandable / collapsible sections
    // doc-1989
    function collapsibleByTitle() {
        // Creates a new class (clickableTitle) for the parent of each .wh_expand_btn found.
        // See the related function in the Functions section below.
        $("span.wh_expand_btn").each(function() {
            //console.log("Found expand btn");
            var createId = $(this).parent().text();
            var newId = createId.replace(/\s+/g, '');
            $(this).parent()
                .css('cursor', 'pointer')
                .addClass('clickableTitle')
                .attr('id', newId);
        });
    }
    // click handler for new title classes
    // "Clicks" the element with the wh_expand_btn class
    function initCollapsibleByTitle() {
        $(document).on('click', '.clickableTitle', function(e) {
            var clickedItem = $(this).attr('id');
            //console.log('Clicked on: ' + e.target.nodeName);
            var spanTitle = e.target.nodeName == 'SPAN' && e.target.className == 'title';
            if (e.target.nodeName == 'H2' || e.target.nodeName == 'H3' || spanTitle) {
                $(this).find('.wh_expand_btn:first').click();
            }
        });
    }
    function fluidDialog() {
        var $visible = $(".ui-dialog:visible");
        // each open dialog
        $visible.each(function () {
            var $this = $(this);
            var options = $(".ui-dialog:visible").find(".ui-dialog-content").dialog("option");
            if (options.fluid) {
                var wWidth = $(window).width();
                // check window width against dialog width
                if (wWidth < options.maxWidth + 50) {
                    // keep dialog from filling entire screen
                    $this.css("max-width", "90%");
                } else {
                    // fix maxWidth bug
                    $this.css("max-width", options.maxWidth);
                }
                // reposition dialog
                $(".ui-dialog:visible").find(".ui-dialog-content").dialog("option", "position", options.position);
            }
        });
    }
    // expand cards for LP
    function setExpandCards() {
        $('.card-ds').click(function() {
            console.log("Entering click to expand card"); clickToExpandCards($(this));
        });
    }
    function clickToExpandCards($obj) {
        console.log("Entering click to expand card");
        var clickedElement = $obj;
        if (clickedElement.hasClass('expanded')) {
            clickedElement.find('.expand-list').hide();
            clickedElement.removeClass('expanded');
        } else {
            clickedElement.find('.expand-list').show();
            clickedElement.addClass('expanded');
        }
    }
    // attempted fix for dialogs on mobile devices
    // on window resize run function
    $(window).resize(function () {
        fluidDialog();
    });
    // catch dialog if opened within a viewport smaller than the dialog width
    $(document).on("dialogopen", ".ui-dialog", function (event, ui) {
        fluidDialog();
    });
});
