/**
 * YUI Compressor nem használható latin2-es karakterkódolás miatt.
 */

webma.equilor = {};

/**
 * Change active document image on mouse over.
 *
 * @param {String} name File name
 */
webma.equilor.change_image = function(name) {
    document.getElementById("havisztori").src = "http://dokumentum.equilor.hu/havi/" + name + ".png";
};


/**
 * Fetch and render document list in the proper place on webpage.
 *
 * @param {String} type Document type
 * @param {Number} limit Number of documents to display
 */
webma.equilor.get_recent_documents = function(type, limit) {
    var q,
        xhr;
    try {
        xhr = new XMLHttpRequest();
    } catch (error) {
        try {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (error) {
        }
    } try {
        q = location.protocol + '//' + location.host + '/images/php/jsapi.php?method=dokumentum&type=' + type + '&limit=' + limit;
        xhr.open("GET", q);
        xhr.onreadystatechange =  function () {
            var match,
                res;
            if (xhr.readyState == 4) {
                if ((xhr.status == 200) || (xhr.status == 0)) {
                    if (document.getElementById("documentlist_" + type))  {
                        res = xhr.responseText;
                        document.getElementById("documentlist_" + type).innerHTML = res;
                        if (type === "havi") {
                            match = res.match(/<!--(.+)-->/);
                            if (match) {
                                webma.equilor.change_image(match[1]);
                            }
                        }
                    }
                }
            }
        };
        xhr.send(null);
    } catch (error) {
    }
};


webma.equilor.TocWidget = function(controller, container) {
    var nodes,
        i,
        chapters = [];

    // Collect and initially hide all chapters
    nodes = container.getElementsByTagName('div');
    for (i = 0; i < nodes.length; i++) {
        if (nodes[i].className.match(/\bchapter\b/)) {
            nodes[i].style.display = 'none';
            chapters.push(nodes[i]);
        }
    }

    /**
     * When clicking on the links of TOC, automatically toggle
     * appropriate chapters.
     */
    var _enableAutoLinking = function() {
        var i,
            nodes = controller.getElementsByTagName('a');
        for (i = 0; i < nodes.length; i++) {
            nodes[i].onclick = (function(i) {
                return function(e) {
                    _toggle(i);
                };
            })(i);
        }
    };

    /**
     * Show specified chapter, hide others.
     *
     * @param {Number} n Chapter index
     */
    var _toggle = function(n) {
        var i;
        for (i = 0; i < chapters.length; i++) {
            if (n === i) {
                chapters[i].style.display = 'block';
            } else {
                chapters[i].style.display = 'none';
            }
        }
    };

    return {
        enableAutoLinking: _enableAutoLinking,
        toggle: _toggle
    };

};

/**
 * @requires dojox.data.CsvStore
 * @param    {Object}            args
 */
webma.equilor.sajtoszobaWidget = function(args) {

    if (!args.container)  {
        return;
    }

    var container = args.container,
        sheetURL = '/images/php/jsapi.php?method=sajtoszoba', // proxy
        store = new dojox.data.CsvStore({
            url: sheetURL,
            label: "cim",
            urlPreventCache: true
        }),
        sortAttributes = [{
            attribute: "datum",
            descending: true
        }],

        /**
         * Generate HTML markup
         */
        parseItems = function(items, request) {
            var secs = [], // sections markup
                ctrls = [], // controllers markup
                attrs, // template variables
                i,
                len,
                item,
                nodes,
                toc;

            for (i = 0, len = items.length; i < len; i++) {
                item = items[i];
                attrs = {
                    html_id: '',
                    datum: store.getValue(item, 'datum'),
                    cim: store.getValue(item, 'cim'),
                    prezentacio: store.getValue(item, 'prezentacio'),
                    kozlemeny: store.getValue(item, 'kozlemeny'),
                    kapcsolodo_tartalmak: store.getValue(item, 'kapcsolodo_tartalmak'),
                    url: 'http://dokumentum.equilor.hu/sajtoszoba/'
                };
                attrs.html_id = 'toc_' + attrs.cim.replace(/\W/g, "").toLowerCase();
                ctrls[ctrls.length] = '<li><a href="#' + attrs.html_id + '">' + attrs.datum + ' &ndash; ' + attrs.cim + '</a></li>';
                secs[secs.length] = '<div class="section chapter"><h2 id="' + attrs.html_id + '">' + attrs.datum + ' &ndash; ' + attrs.cim + '</h2>' +
                    '<ul><li><a href="' + attrs.url + attrs.kozlemeny + '">Közlemény</a></li>';
                if (typeof attrs.prezentacio !== 'undefined') {
                    secs[secs.length] = '<li><a href="' + attrs.url + attrs.prezentacio + '">Prezentáció</a></li>';
                }
                if (typeof attrs.kapcsolodo_tartalmak !== 'undefined') {
                    secs[secs.length] = '<li><a target="_blank" href="' + attrs.url + 'egyeb/' + attrs.kapcsolodo_tartalmak + '">Kapcsolódó tartalmak</a></li>';
                }
                secs[secs.length] = '</ul><p><a class="history-back" href="#">&larr; vissza</a></p></div>';
            }
            container.innerHTML = '<ul id="webma-chapter-widget">' + ctrls.join("") + '</ul>' + secs.join('');

            // Enable TOC widget
            toc = new webma.widgets.TocWidget(document.getElementById('webma-chapter-widget'),
                                              document.getElementById('article'));
            // Back links
            nodes = document.getElementById('webma_widget_sajtoszoba').getElementsByTagName('a');
            for (i = 0, len = nodes.length; i < len; i++) {
                item = nodes[i];
                if (item.className === 'history-back') {
                    webma.util.addEvent(item, 'click', function() {
                        toc.toggleChapter();
                    });
                }
            }

        };

    this.storeData = store.fetch({
        onComplete: parseItems,
        sort: sortAttributes
    });

};

/**
 * @requires dojox.data.CsvStore
 */
webma.equilor.devizaWidget = function() {
    dojo.require("dojox.data.CsvStore");
    dojo.addOnLoad(function() {
    var container = document.getElementById('eqr_widget_deviza'),
        sheetURL = '/images/php/jsapi.php?method=deviza', // proxy
        store = new dojox.data.CsvStore({
            url: sheetURL,
            urlPreventCache: true
        }),

        /**
         * Generate HTML markup
         */
        parseItems = function(items, request) {
            var attrs,
                cls,
                date,
                elDate = document.getElementById('eqr_widget_deviza_day'),
                i,
                isEnglish = /\ben\b/.test(document.getElementsByTagName('body')[0].className),
                len,
                item,
                tbody = container.getElementsByTagName('tbody')[0],
                td,
                tr;

            for (i = 0, len = items.length; i < len; i++) {
                item = items[i];
                attrs = {
                    deviza: store.getValue(item, 'deviza'),
                    deviza_en: store.getValue(item, 'deviza_en'),
                    vetel: store.getValue(item, 'vetel'),
                    eladas: store.getValue(item, 'eladas')
                };

                if (i % 2 === 0) {
                    cls = 'odd';
                } else {
                    cls = '';
                }
                tr = document.createElement('TR');
                tr.className = cls;

                td = document.createElement('TD');
                td.className = 'futamido';
                if (isEnglish) {
                    td.innerHTML = attrs.deviza_en;
                } else {
                    td.innerHTML = attrs.deviza;
                }
                tr.appendChild(td);

                td = document.createElement('TD');
                td.className = 'intval';
                td.innerHTML = attrs.vetel;
                tr.appendChild(td);

                td = document.createElement('TD');
                td.className = 'intval';
                td.innerHTML = attrs.eladas;
                tr.appendChild(td);

                tbody.appendChild(tr);
            }


            // a táblázatba felveszünk egy dátum mezőt, aminek ha
            // van értéke (tehát manuálisan valaki megadott egy
            // dátumot), akkor az jelenik meg, ha a mező üres,
            // akkor pedig a rendszer automatikusan a megfelelő
            // dátumot jeleníti meg (15.00 előtt a tegnapit, 15.00
            // után a mait).
            date = store.getValue(items[0], 'datum');
            if (typeof date == 'undefined') {
                date = (function() {
                    var today = new Date(),
                        year = today.getFullYear(),
                        month = today.getMonth(),
                        day = today.getDate();
                    if (today.getHours() < 15) { // yesterday
                        today = new Date();
                        today.setTime(today.getTime() - (1000 * 60 * 60 * 24));
                        year = today.getFullYear();
                        month = today.getMonth();
                        day = today.getDate();
                    }
                    month++;
                    if (month < 10) {
                        month = '0' + month;
                    }
                    if (day < 10) {
                        day = '0' + day;
                    }
                    return year + '.' + month + '.' + day + '.';
                }());
            }
            elDate.innerHTML = date;

        };

        store.fetch({
            onComplete: parseItems
        });

    });
};

webma.util.addEvent(window, 'load', function() {

    if (/befektetesi_alapok/i.test(window.location.href)) {
        var li = document.getElementById('befektetesi_alapok'),
            ul = li.getElementsByTagName('ul')[0];
        ul.style.display = 'block';
    }

    if (/Investment_Funds/i.test(window.location.href)) {
        var li = document.getElementById('investment_funds'),
            ul = li.getElementsByTagName('ul')[0];
        ul.style.display = 'block';
    }

    // Elemzések widget
    if (document.getElementById('documentlist_havi')) {
        webma.equilor.get_recent_documents('havi', 7);
        webma.equilor.get_recent_documents('heti', 7);
        webma.equilor.get_recent_documents('napi', 5);
    }

    // Sajtószoba widget
    if (document.getElementById('webma_widget_sajtoszoba')){
        dojo.require("dojox.data.CsvStore");
        dojo.addOnLoad(function() {
            webma.equilor.sajtoszobaWidget({
                container: document.getElementById('webma_widget_sajtoszoba')
            });
        });
    }

    // TOC widget
    if (document.getElementById('webma-chapter-widget')) {
        if (typeof window.toc !== 'undefined' && !window.toc.enableAutoLinking) {
            window.toc = webma.equilor.TocWidget(document.getElementById('webma-chapter-widget'), document.getElementById('article'));
        } else {
            var toc = webma.equilor.TocWidget(document.getElementById('webma-chapter-widget'), document.getElementById('article'));
            toc.enableAutoLinking();
        }
    }





    // Deviza widget
    if (document.getElementById('eqr_widget_deviza')) {
        dojo.addOnLoad(function() {
            // Erre az onload wrapper-re nem tudom miért van szükség, de IE-ben
            // csak így jó.
            webma.equilor.devizaWidget();
        });
    }

    // Főoldali banner
    if (document.getElementById('intro_tozsdeforum_button')) {
        var hideIntro = function() {
            document.getElementById('intro_tozsdeforum').style.display = 'none';      };
        webma.util.addEvent(
            document.getElementById('intro_tozsdeforum_button'),
            'click',
            hideIntro);
        setTimeout(hideIntro, 8000);
    }

});
