'use strict';

oml.ui.appPanel = function() {

    var ui = oml.user.ui,

        that = Ox.SplitPanel({
            elements: [
                {
                    element: oml.$ui.mainMenu = oml.ui.mainMenu(),
                    size: 20
                },
                {
                    element: oml.$ui.mainPanel = oml.ui.mainPanel()
                }
            ],
            orientation: 'vertical'
        })
        .bindEvent({
            oml_page: function(data) {
                setPage(data.value, data.previousValue);
            }
        });

    setPage(ui.page);

    function setPage(page, previousPage) {
        var dialogs = {
            welcomeDialog: ['welcome'],
            appDialog: ['about', 'faq', 'terms', 'development', 'contact'],
            updateDialog: ['update'],
            userDialog: ['preferences', 'peers', 'transfers'],
            importExportDialog: ['import', 'export'],
            helpDialog: ['help', 'documentation']
        };
        // close dialogs
        if (Ox.every(dialogs, function(pages) {
            return !Ox.contains(pages, page);
        }) && Ox.some(dialogs, function(pages) {
            return Ox.contains(pages, previousPage)
        })) {
            $('.OxDialog:visible').each(function() {
                Ox.$elements[$(this).data('oxid')].close();
            });
        }
        // open dialogs
        Ox.forEach(dialogs, function(pages, dialog) {
            if (Ox.contains(pages, page) && !Ox.contains(pages, previousPage)) {
                $('.OxDialog:visible').each(function() {
                    Ox.$elements[$(this).data('oxid')].close();
                });
                oml.$ui[dialog] = oml.ui[dialog]().open();
            }
        });
    }

    oml.bindEvent({
        transfer: Ox.throttle(function(data) {
            var mediastate = data.progress == -1
                    ? 'unavailable'
                    : data.progress < 1
                        ? 'transferring'
                        : 'available';
            oml.$ui.list.value(data.id, {
                mediastate: mediastate
            });
            oml.$ui.browser.value(data.id, {
                mediastate: mediastate
            });
            if ((data.progress == 1 || data.progress == -1) && data.id == ui.item) {
                Ox.Request.clearCache();
                oml.$ui.infoView.updateElement(ui.item);
            }
        }, 250)
    });

    that.reload = function() {
        Ox.Request.cancel();
        Ox.Request.clearCache();
        oml.unbindEvent();
        oml.$ui.appPanel.remove();
        oml.$ui.appPanel = oml.ui.appPanel().appendTo(Ox.$body);
        return that;
    };

    return that;

};