//	FindinSite-CD-JS-HelpIndex search code
//	Copyright (C) 2016 PHD Computer Consultants Ltd
//
//	Version details
//		7.109	12-Oct-2016
//
/*global document, setTimeout */
/*global findinsite, fishiLogging */
/*jslint continue: true, plusplus: true, todo: true, vars: true, white: true */

var fishi_dbs = fishi_dbs || [];

var fishi_page = function () {
    "use strict";

    // PRIVATE variables made PUBLIC at end
    var config = {
        idTree: false,
        idIndexList: false,
        idIndexFilter: false,
        baseurl: ''
    };

    // TOC
    var userSearch = false;
    var eleSearch = null;
    var eleResults = null;

    var doSearch;

    var here = false;

    // INDEX
    var indices = [];

    /////////////////////////////////////
    function log(msg) {
        if (typeof fishiLogging !== 'undefined') {
            if (fishiLogging && window.console && window.console.log) {
                window.console.log(new Date().toISOString() + " " + msg);
            }
        }
    }

    /////////////////////////////////////
    function fail(msg) {
        if (eleResults) {
            eleResults.innerHTML += "<p><strong>" + msg + "</strong></p>";
        }
        return false;
    }

    /////////////////////////////////////
    function escapeHTML(string) {
        var pre, text;
        pre = document.createElement('pre');
        text = document.createTextNode(string);
        pre.appendChild(text);
        return pre.innerHTML;
    }

    /////////////////////////////////////
    var gotSubMenu = false;
    function addSubmenus(db, addto, totop, parent) {
        if ((typeof parent.tree === 'undefined') || !$.isArray(parent.tree)) { return; }
        if (parent.tree.length === 0) { return; }
        if (!totop) {
            addto.addClass('fishi-dd');
        }
        if (!gotSubMenu) {
            addto.addClass('fishi-first');
            gotSubMenu = true;
        }
        var childmenu = $('<ul>', { class: 'fishi-dd-menu' });
        for (var childno = 0; childno < parent.tree.length; childno++) {
            var child = parent.tree[childno];
            var childHasChildren = (typeof child.tree === 'undefined') || !$.isArray(child.tree);

            var childmenuli = $('<li>');
            var url = db.baseurl;
            if (db.baseurls.length > 0) { url += db.baseurls[0]; }
            url += child.url;
            var uri = new URI(url, here).toString(); // normalises
            var onactive = (uri == here);

            var childmenulia = $('<a>', { href: url });
            if (onactive) {
                childmenulia.addClass("fishi-active");
            }
            var childtitle = child.title;
            if (!childHasChildren) {
                childtitle = "<b class='pull-right fishi-arrow'>►</b>" + childtitle;
            }
            childmenulia.html(childtitle);
            childmenuli.html(childmenulia);

            addSubmenus(db, childmenuli, false, child);

            childmenu.append(childmenuli);
        }
        if (totop) {
            addto.append(childmenu.children());
        } else {
            addto.append(childmenu);
        }
    }

    /////////////////////////////////////
    /////////////////////////////////////
    // Handle all databases loaded event
    $(document).on("fishidballloaded", function (e) {
        var db, dbno, topmenuli, url, topmenulia;
        var ix, option, index;

        //console.log("HREF=" + location.href);
        here = new URI(location.href).fragment('').toString();

        // TOC
        if (config.idTree) {
            //$(config.idTree).html('');
            for (dbno = 0; dbno < fishi_dbs.length; dbno++) {
                db = fishi_dbs[dbno];

                if (!(('url' in db) && ('title' in db))) {
                    addSubmenus(db, $(config.idTree), true, db);
                } else {
                    topmenuli = $('<li>');
                    url = db.baseurl;
                    if (db.baseurls.length > 0) { url += db.baseurls[0]; }
                    url += db.url;
                    topmenulia = $('<a>', { href: url });
                    topmenulia.html("<b class='pull-right fishi-arrow'>►</b>" + db.title);
                    topmenuli.html(topmenulia);

                    addSubmenus(db, topmenuli, false, db);

                    $(config.idTree).append(topmenuli);
                }
            }

            $('.fishi-arrow').on('click', function () { return toggle2($(this).parent(), false); });
            $('.fishi-dd > a').on('click', function () { return toggle2($(this), true); });
            if (fishi_dbs.length === 1) { toggle2($('.fishi-first > a'), false); }
            var toOpen = $('.fishi-active').parents('.fishi-dd');
            toOpen.each(function () {
                var me = $(this);
                var eh = $('a', me).first();
                $('b:first', eh).text('▼');	//U+25BC
                var submenu = $("ul:first", me);
                submenu.toggle();
            });

        }

        // INDEX
        indices = [];
        if (config.idIndexFilter && config.idIndexList) {

            for (dbno = 0; dbno < fishi_dbs.length; dbno++) {
                db = fishi_dbs[dbno];
                addIndex(db);
            }

            indices.sort(function (i1, i2) {
                return i1.wlc.localeCompare(i2.wlc);
            });

            updateIndexDisplay();

            $(config.idIndexList).change(indexChanged);
            $(config.idIndexList).keyup(indexKey);
            $(config.idIndexList).dblclick(indexDblClick);

            $(config.idIndexFilter).change(filterChanged);
            $(config.idIndexFilter).keyup(filterChanged);
        }


    });

    /////////////////////////////////////
    function toggle2(me, openLink) {
        if (me.length === 0) return false;
        var submenu = $("ul:first", me.parent());
        if (submenu.is(':visible')) {
            if (openLink) { return true; }
            $('b:first', me).text('►');	//U+25BA
        }
        else {
            if (openLink) { return true; }
            $('b:first', me).text('▼');	//U+25BC
        }

        submenu.toggle();
        return false;
    }

    /////////////////////////////////////

    function addIndex(item) {
        var i, ix, index, w, wlc, page;

        // Add our index entries
        if (item.url && $.isArray(item.index)) {
            for (i = 0; i < item.index.length; i++) {
                w = item.index[i];
                wlc = w.toLowerCase();
                page = { url: item.url, title: item.title };
                // See if lc index already exists
                var found = false;
                for (ix = 0; ix < indices.length; ix++) {
                    index = indices[ix];
                    if (index.wlc == wlc) {
                        index.pages.push(page);
                        found = true;
                    }

                }
                // If not, add index now
                if (!found) {
                    index = { w: w, wlc: wlc, pages: [page] };
                    indices.push(index);
                }
            }
        }

        // Add child index entries
        if ($.isArray(item.tree)) {
            for (i = 0; i < item.tree.length; i++) {
                addIndex(item.tree[i]);
            }
        }
    }

    /////////////////////////////////////
    function indexChanged() {
        /*var opt = $("option:selected", this);
		var ix = opt.attr('value');
		var index = indices[ix];
		var line = $("<p>");
		line.text(JSON.stringify(index));
		$('#debug').append(line);*/
    }

    /////////////////////////////////////
    function indexKey(e) {
        if (e.keyCode == 13) {
            showIndexPage();
        }
        else if (e.keyCode >= 48 && e.keyCode <= 90) {
            $(config.idIndexFilter).val($(config.idIndexFilter).val() + String.fromCharCode(e.keyCode).toLowerCase());
            filterChanged();
        } else if (e.keyCode == 8) {
            var filter = $(config.idIndexFilter).val();
            if (filter.length > 0) {
                $(config.idIndexFilter).val(filter.substring(0, filter.length - 1));
                filterChanged();
            }
        }
    }

    function indexDblClick() {
        showIndexPage();
    }

    function showIndexPage() {
        var option;
        var opt = $("option:selected", this);
        var ix = opt.attr('value');
        var index = indices[ix];
        if (index.pages.length == 1) {
            var line = $("<p>");
            line.text("show " + index.pages.length + " - " + JSON.stringify(index.pages[0]));
            $('#debug').append(line);
            return;
        }
        for (var pno = index.pages.length - 1; pno >= 0 ; pno--) {
            var wToShow = "&nbsp;&nbsp;&nbsp;&nbsp;" + index.pages[pno].title;

            option = $('<option>', {
                'value': ix
            });
            option.html(wToShow);
            opt.after(option);
        }

    }

    /////////////////////////////////////
    function filterChanged() {
        updateIndexDisplay();
    }

    /////////////////////////////////////
    function updateIndexDisplay() {
        var ix, index, option, last, wToShow, count;
        var filter = $(config.idIndexFilter).val().toLowerCase();
        if (filter.length === 0) {
            filter = false;
        }
        $(config.idIndexList).html("");
        last = false;
        for (ix = 0; ix < indices.length; ix++) {
            index = indices[ix];
            if (filter) {
                if (index.wlc.indexOf(filter) === -1) {
                    continue;
                }
            }
            wToShow = index.w;
            if (last) {
                if (index.wlc.length > last.length) {
                    if (index.wlc.substring(0, last.length + 1) == last + ",") {
                        wToShow = "&nbsp;&nbsp;" + index.w.substring(last.length + 1).trim();
                    }
                }
            }
            option = $('<option>', {
                'value': ix
            });
            option.html(wToShow);
            last = index.wlc;
            $(config.idIndexList).append(option);
        }

        count = $("option", config.idIndexList).length;
        $(config.idIndexList).attr('size', count);
        $("option:first", config.idIndexList).attr('selected', true);
    }

    /////////////////////////////////////
    // PUBLIC methods
    return {
        config: config
    };
    /////////////////////////////////////
}();