Ext.namespace('ArchivFinder');

ArchivFinder.app = function ()
{
    var wrapper, fieldSet, resultBox, resultBox2, selectBox, loadingBox, errorBox, selectIssuesBox, issueBox, loadedIssues;
    var url = '/archiv/archiv-finder.php';
    var isPreselect = false;
    var initApp = function()
    {
        fieldSet = wrapper.createChild({
            tag: 'fieldset'
        });
        selectBox = fieldSet.createChild({
            tag: 'select'
        });
        if (Ext.isIE) {
            selectBox.dom.add(new Option('--- Publikation auswählen ---', ''));
        } else {
            selectBox.createChild({
                tag: 'option',
                value: '',
                html: '--- Publikation auswählen ---',
                style: 'font-weight: bold;'
            });
        }
        
        loadingBox = fieldSet.createChild({
            tag: 'div',
            cls: 'finder-loading finder-hidden',
            html: 'Lade Ausgaben...'
        });
        
        resultBox = fieldSet.createChild({
            tag: 'div',
            cls: 'finder-hidden',
            html: ''
        });
        titleBox = resultBox.createChild({
            tag: 'h3',
            cls: 'finder-product-title',
            html: ''
        });
        errorBox = wrapper.createChild({
            tag: 'div',
            cls: 'finder-error finder-hidden',
            html: ''
        });
        selectIssuesBox = resultBox.createChild({
            tag: 'select'
        });
        resultBox2 = wrapper.createChild({
            tag: 'div',
            cls: 'finder-results finder-hidden',
            html: ''
        });
        issueBox = resultBox2.createChild({
            tag: 'div',
            cls: 'finder-issue finder-hidden'
        });
        for(i = 0; i < ArchivFinder.products.length; i++)
        {
            var x = i;
            if (ArchivFinder.products[i])
            {
                if (Ext.isIE) {
                    selectBox.dom.add(new Option(ArchivFinder.products[i][1], ArchivFinder.products[i][0]))
                } else {
                    selectBox.createChild({
                        tag: 'option',
                        value: ArchivFinder.products[i][0],
                        html: ArchivFinder.products[i][1]
                    });
                }
            }
        }
        selectBox.on('change', changedSelectBox, this);
        selectIssuesBox.on('change', function() {
            var value = selectIssuesBox.getValue();
            if (value && value.length > 0 && loadedIssues[value])
            {
                showIssue(value);
            }
        },this);
    };
    
    var changedSelectBox = function() {
        var value = selectBox.getValue();
        if (value && value.length > 0)
        {
            loadingBox.removeClass('finder-hidden');
            resultBox.addClass('finder-hidden');
            resultBox2.addClass('finder-hidden');
            errorBox.addClass('finder-hidden');
            issueBox.addClass('finder-hidden');
            Ext.Ajax.request({
                method: 'GET',
                url: url,
                success: productLoadSuccess,
                failure: function() {
                    // showError('Server nicht erreichbar');
                },
                params: {method: 'getIssuesByProduct', product: value}
            });
        }
    };
    
    var productLoadSuccess = function(response, opts)
    {
        loadingBox.addClass('finder-hidden');
        var o;
        try{
            o = Ext.util.JSON.decode(response.responseText);
        } catch(e) {
            showError('Server nicht erreichbar');
        }
        if (o && o.data && o.data.issue)
        {
            if (typeof o.data.issue.length != 'number') {
                o.data.issue = [o.data.issue];
            }
            if (o.data.issue.length > 0) {
                loadedIssues = o.data.issue;
                var title = selectBox.dom.options[selectBox.dom.selectedIndex].text;
                updateResultBox(title);
                resultBox.removeClass('finder-hidden');
                resultBox2.removeClass('finder-hidden');
            }
        } else {
            // showError('Keine Ausgaben gefunden');
        }
    };
    
    var showError = function(msg)
    {
        loadingBox.addClass('finder-hidden');
        resultBox.addClass('finder-hidden');
        errorBox.removeClass('finder-hidden');
        errorBox.dom.innerHTML = msg;
    }
    
    var updateResultBox = function(title)
    {
        titleBox.dom.innerHTML = title;
        var newContent = '';
        var year = '';
        while (selectIssuesBox.dom.hasChildNodes()) {
            selectIssuesBox.dom.removeChild(selectIssuesBox.dom.firstChild);
        }

        for (i = 0; i < loadedIssues.length; i++)
        {
            if (year != loadedIssues[i]['@attributes'].year) {
                if (year.length > 0) selectIssuesBox.dom.appendChild(group);
                var group = document.createElement("optgroup");
                group.label = loadedIssues[i]['@attributes'].year;
                year = loadedIssues[i]['@attributes'].year;
            }
            var option = document.createElement("option");
            option.value = i;
            option.appendChild(document.createTextNode(loadedIssues[i].title+'/'+year));

            group.appendChild(option);
            if (i + 1 == loadedIssues.length) {
                selectIssuesBox.dom.appendChild(group);
            }

            /*if (year != loadedIssues[i]['@attributes'].year) {
                if (year.length > 0) newContent += '</optgroup>';
                newContent += '<optgroup label="'+loadedIssues[i]['@attributes'].year+'">';
                year = loadedIssues[i]['@attributes'].year;
            }
            newContent += '<option value="'+i+'">'+loadedIssues[i].title+'/'+year+'</option>';
            if (i + 1 == loadedIssues.length) {
                newContent += '</optgroup>';
            }*/
            
        }
        //selectIssuesBox.dom.innerHTML = newContent;
        if (isPreselect)
        {
            if (loadedIssues[1]) var n = 1;
            else n = 0;
            selectIssuesBox.dom.selectedIndex = n;
            showIssue(n);
            isPreselect = false;
        } else {
            showIssue(0);
        }
    };
    
    var showIssue = function(num)
    {
        if (loadedIssues[num])
        {
            issueBox.removeClass('finder-hidden');
            var title = selectBox.dom.options[selectBox.dom.selectedIndex].text;
            if (selectIssuesBox.dom.selectedIndex < 0) return;
            var ausgabe = selectIssuesBox.dom.options[selectIssuesBox.dom.selectedIndex].text;
            var pfad = loadedIssues[num]['@attributes'].path;
            var url_pdf = '/de/archiv/pop-archiv.php?issue='+pfad+'&name='+title+'&year='+ausgabe;
            issueBox.removeClass('finder-hidden');
            var newContent = '';
            if (loadedIssues[num].image) {
                newContent += '<div class="trenner"></div><div class="archivFinderCover">';
                if (loadedIssues[num].epaper) {
                    newContent += '<a title="als ePaper lesen" href="'+loadedIssues[num].epaper['@attributes'].url+'" target="_blank" onclick="return tgdEPaperArchivFinder(\''+loadedIssues[num].epaper['@attributes'].url+'\',\''+title+' '+ausgabe+'\');">';
                }
                newContent += '<img src="'+loadedIssues[num].image['@attributes'].url+'&amp;width=110" class="finder-issue-image" alt="'+title+'"/>';
                if (loadedIssues[num].epaper) {
                    newContent += '</a>';
                }
                newContent += '</div>';
            }
            newContent += '<div class="archivFinderLinks">';
            newContent += '<h4>'+title+'</h4>';
            newContent += '<p>Ausgabe: '+ausgabe+'</p>';               
            if (loadedIssues[num].epaper)
                newContent += '<a title="als ePaper lesen" href="'+loadedIssues[num].epaper['@attributes'].url+'" target="_blank" onclick="return tgdEPaperArchivFinder(\''+loadedIssues[num].epaper['@attributes'].url+'\',\''+title+' '+ausgabe+'\');"><img alt="epaper" src="/backstage/images/oemus_common/btn_als_epaper_lesen.jpg"/></a><br />';
            newContent += '</div><div class="clearBlock"></div><div class="spacer12"></div>';
            newContent += '<div class="btn271"><a class="pfeilBlau" href="javascript:;" onclick="Shadowbox.open({content: \''+url_pdf+'\',player:\'iframe\',title:\''+title+'\',height:621,width:620});" title="als PDF lesene" >als PDF lesen</a></div>';
            if (ArchivFinder.productLinks && ArchivFinder.productLinks[loadedIssues[num]['@attributes'].product])
                newContent += '<div class="btn271"><a class="pfeilBlau" title="zur aktuellen Ausgabe" href="'+ArchivFinder.productLinks[loadedIssues[num]['@attributes'].product]+'">zur aktuellen Ausgabe</a></div>';              
            issueBox.dom.innerHTML = newContent; 
        } else {
            showError('Ausgabe konnte nicht geladen werden.');
        }
    }
    
    return {
        init: function(config)
        {
            if (!config) {
                config = {
                    wrapper: 'archivFinder'
                };
            }
            if (!config.wrapper) config.wrapper = 'archivFinder';
            wrapper = Ext.get(config.wrapper);
            if (wrapper && ArchivFinder.products)
            {
                initApp();
                if (config.preSelect) ArchivFinder.app.preSelect(config.preSelect);
            }
        },
        wrapper: function() {
            return wrapper;
        },
        resultBox: function() {
            return resultBox;
        },
        preSelect: function(value) {
            for (i = 0; i < selectBox.dom.options.length; i++)
            {
                if (selectBox.dom.options[i].value == value) {
                    selectBox.dom.selectedIndex = i;
                    isPreselect = true;
                    changedSelectBox();
                    break;
                }
            }
        }
    }
}();

