//	FindinSite-CD-JS-HelpIndex search code
//	Copyright (C) 2016 PHD Computer Consultants Ltd
//
//	Alter current version below
//		7.109	12-Oct-2016
//
//	The search database JS files can be loaded in two ways:
//	A:	Specify an ordered list of files in a global array named contentsdbs, eg specified in a JS file like this
//				<script src="contents_dbs.js"></script>
//			where each element is
//				{ src:"toc1.js", id:"toc1varname"},
//	B:	Use one or more script tags in the calling page like this:
//				<script async class="contentsdb" id="toc1varname" src="toc1.js" data-weight="0"></script>
//				<script async class="contentsdb" id="toc2varname" src="toc2.js" data-weight="1"></script>
//
//	Currently requires jQuery to handle events triggered by database load(s)
//	Alternative approach is outlined here: http://blog.garstasio.com/you-dont-need-jquery/events/

/*global window */
/*global fishiLogging,fishi_dbs,fisFreezeDb */
/*jslint continue: true, plusplus: true, todo: true, vars: true, white: true */

var fishi_dbs = fishi_dbs || [];

var fishi = function ($) {
    "use strict";

    var noSessionDebug = false;

    // PRIVATE variables made PUBLIC at end

    var version = "v7.109";
    var versionDate = new Date(2016, 10 - 1, 12);	// Month in range 0..11
    var config = {
        baseurl: '',
        dbcount: 0
    };

    // MODULE WORKING VARIABLES: assumes we are not called re-entrantly
    var showProgress;	// callback to show progress
    var deferSearch = null;

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

    /////////////////////////////////////
    // No longer in use
    function getGlobalName(ofind) {
        try {
            for (var o in window) {
                if (window[o] === ofind) {
                    return o;
                }
            }
        } catch (e) { }
        return null;
    }

    /////////////////////////////////////
    function showLoadingProgress() {
        if (!showProgress) return;
        var loadedDbcount = fishi_dbs.length;
        //showProgress("Loaded " + loadedDbcount + " of " + config.dbcount + " search databases");
    }

    /////////////////////////////////////
    showProgress = function (info) {
        log(info);
    };

    /////////////////////////////////////
    // Startup: initiate loading of databases if necessary
    $(function () {
        if ((typeof contentsdbs !== 'undefined') && $.isArray(contentsdbs)) {
            // contentsdbs defines which database JS files to load
            fishi.config.dbcount = contentsdbs.length;

            for (var dbno = 0; dbno < contentsdbs.length; dbno++) {
                // http://stackoverflow.com/a/25897833/1541015
                var dbdef = contentsdbs[dbno];
                dbdef.src = fishi.config.baseurl + dbdef.src;
                var baseurl = '';
                var endbaseurl = dbdef.src.lastIndexOf("/");
                if (endbaseurl !== -1) {
                    baseurl = dbdef.src.substr(0, endbaseurl + 1);
                }
                try {
                    if (!noSessionDebug) {
                        if (sessionStorage && JSON) {
                            var varname = dbdef.id;
                            if (sessionStorage.getItem(varname + 'Set') === '1') {
                                var db = JSON.parse(sessionStorage.getItem(varname));
                                db.baseurl = baseurl;
                                dbLoaded(db);
                                continue;
                            }
                        }
                    }
                } catch (ex) { }

                var s = document.createElement('script');
                s.type = "text/javascript";
                s.async = true;
                s.setAttribute("data-weight", dbno);
                s.src = dbdef.src;
                s.id = dbdef.id;
                s.setAttribute("data-baseurl", baseurl);
                var fs = document.getElementsByTagName('script')[0];
                fs.parentNode.insertBefore(s, fs);
            }

        } else {
            // contents JS files loaded by calling page
            fishi.config.dbcount = $('.contentsdb').length;
            if (fishi.config.dbcount == 0) {

                if (window.console && window.console.log) {
                    window.console.log("fishi: no contents database JS files defined.");
                }
                fishi.config.dbcount = 1;
            }
            // All dbs may already have loaded, so:
            processIfAllDbsLoaded();
        }
    }
	);

    /////////////////////////////////////
    function getData(db, prop, attr, def) {
        var ele = $('#' + db.varname);
        if (ele.length === 1) {
            db[prop] = ele.data(attr);
        } else {
            db[prop] = def;
        }
    }

    /////////////////////////////////////
    function dbLoaded(db) {
        var dbno = fishi_dbs.push(db) - 1;

        if (!('weight' in db)) { getData(db, 'weight', 'weight', 0); }
        if (!('baseurl' in db)) { getData(db, 'baseurl', 'baseurl', ""); }
        //console.log("fishi: " + new Date().toISOString() + " db loaded " + db.weight + " - " + db.baseurl);

        try {
            if (!noSessionDebug) {
                if (sessionStorage && JSON) {
                    if (sessionStorage.getItem(db.varname + 'Set') !== '1') {
                        sessionStorage.setItem(db.varname, JSON.stringify(db));
                        sessionStorage.setItem(db.varname + 'Set', '1');
                    }
                }
            }
        } catch (ex) { }

        showLoadingProgress();
        processIfAllDbsLoaded();
    }

    /////////////////////////////////////
    // Handle database loaded event
    $(document).on("fishidbloaded", function (e) {
        dbLoaded(e.db);
    });

    /////////////////////////////////////
    // If all expected databases loaded, sort received dbs and trigger event 
    function processIfAllDbsLoaded() {
        if (fishi_dbs.length == config.dbcount) {
            fishi_dbs.sort(function (dba, dbb) { return dba.weight - dbb.weight });
            $.event.trigger({ type: "fishidballloaded" });
        }
    }

    /////////////////////////////////////
    // PUBLIC methods
    return {
        version: version,
        versionDate: versionDate,
        config: config
    };
    /////////////////////////////////////
}(jQuery);