// MIT License:
//
// Copyright (c) 2016-2017, Alexander I. Chebykin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * CAI CP v.1
 *
 * @module     : Help subsystem
 * @author     : Alexander I. Chebykin <alex.chebykin@gmail.com>
 * @copyright  : Copyright (c) 2016-2017 Alexander I. Chebykin
 * @version    : 0.9
 * @build date : 2017-06-16
 * @license    : MIT
 * @link       : https://github.com/CAI79/CAI-CP
 ******************************************************************/

(function () {
    'use strict';

    /**
    * Return GET parameter
    *
    * @param  {string} key Key name
    * 
    * returns {string}
    */
    function $_GET(key) {
        var s = window.location.search;

        s = s.match(new RegExp(key + '=([^&=]+)'));

        return s ? s[1] : false;
    }

    /**
     * HelpSystem constructor
     *
     * @returns {undefined}
     */
    function HelpSystem() {
        this.locale = 'en';
    }

    /**
     * 
     * @param   {int}      init_level Initialization level: 1 - select locale
     *                                                      2 - redirect to localized resource
     *                                                      3 - load version info
     *                                                      4 - set event handlers
     * 
     * @returns {undefined}
     */
    HelpSystem.prototype.init = function (init_level) {
        var help_instance = this;

        switch (init_level) {
        case 1:
            if ($_GET('lang') !== '') {
                this.locale = $_GET('lang');
            } else {
                var request = new XMLHttpRequest(),
                    res_data;

                if (!~location.href.indexOf('locale')) {
                    request.open('GET', '../json/settings.json');
                } else {
                    request.open('GET', '../../../json/settings.json');
                }
                request.send();

                request.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        if (this.status === 200) {
                            res_data = JSON.parse(this.responseText);

                            help_instance.locale = res_data.lang;
                        }
                    }
                };
            }
            this.init(2);
            break;
        case 2:
            if (!~location.href.indexOf('locale')) {
                location.href = 'locale/' + this.locale + location.hash;
                return;
            } else {
                this.init(3);
            }
            break;
        case 3:
            var request = new XMLHttpRequest(),
                res_data;

            if (!~location.href.indexOf('locale')) { 
                request.open('GET', '../json/version.json');
            } else {
                request.open('GET', '../../../json/version.json');
            }
            request.send();

            request.onreadystatechange = function (e) {
                if (this.readyState === 4) {
                    if (this.status === 200) {
                        res_data = JSON.parse(this.responseText);

                        var vers      = document.getElementsByClassName('span_ver'),
                            ver_dates = document.getElementsByClassName('span_ver_date');

                        for (var i = 0; i < vers.length; i++) {
                            vers[i].textContent = res_data.version;
                        }
                        for (var i = 0; i < ver_dates.length; i++) {
                            ver_dates[i].textContent = new Date(res_data.build_date).toLocaleDateString();
                        }
                    }
                }	
            };
            this.init(4);
            break;
        case 4:
            var nav_list = document.getElementsByTagName('nav'),
                toc_lis  = document.getElementById('menu_toc').getElementsByTagName('li');

            // Show menu
            for (var i = 0; i < nav_list.length; i++) {
                nav_list[i].classList.remove('hidden');
            }

            // Add event listeners
            for (var i = 0; i < toc_lis.length; i++) {
                toc_lis[i].getElementsByTagName('div')[0].addEventListener('click', function (event) {
                    help_instance.select_topic(this.parentElement.id.substr(4));
                });
            }

            if (location.hash !== '') {
                help_instance.select_topic(location.hash.substr(1));
            } else {
                help_instance.select_topic('start');
            }
        }
    };

    /**
     * 
     * @param   {string}    topic_id Topic identifier
     * 
     * @returns {undefined}
     */
    HelpSystem.prototype.select_topic = function (topic_id) {
        var articles = document.getElementsByTagName('article'),
            toc_divs = document.getElementsByClassName('div_toc');

        for (var j = 0; j < toc_divs.length; j++) {
            toc_divs[j].classList.remove('mnu_selected');
        }

        document.getElementById('mnu_' + topic_id).getElementsByTagName('div')[0].classList.add('mnu_selected');

        for (var j = 0; j < articles.length; j++) {
            if (articles[j].id === 'art_' + topic_id) {
                articles[j].classList.remove('hidden');
            } else {
                articles[j].classList.add('hidden');
            }
        }
        location.hash = topic_id;
    };

    document.addEventListener('DOMContentLoaded', function () {
        'use strict';

        /**
         * Initialize help object
         */
        var help = new HelpSystem();

        help.init(1);

    });

}());
