// create namespace
Ext.namespace('NT');

NT.preloadStart = 1;
NT.preloadSize = 3;
NT.loadcontent = false;
NT.app = function() {
    var resizeEvent, resizeTask;
    var D = Ext.lib.Dom;var E = Ext.lib.Event;
    var themes = {}, selThemes= [], aboutTheme = false, isVista = false;
    var container, articles, max, currentIdx = 0, animation, anim =false, down = false, scroll = false, lastScrollPos = 0;
    var contentWidth, activeBgImg = 0, bgImgs = [], defaultImg;
    var mMenuHandle, mMenu, tMenu, subMenuHandle, about, archiv, impressum;
    var currentVisible = container;
    var galery, contentHeight, keyNav;
    var themenContainer, inField;

    var navigate = function(direction, isClick)
    {
        var newIdx = currentIdx + direction;
        while(direction !=0 && !(Ext.fly(articles[newIdx]) && Ext.fly(articles[newIdx]).isVisible()) && newIdx < max)
        {
            if(direction > 0)
                newIdx++;
            else
                newIdx--;
            if(newIdx <= 0 || newIdx >= max)
                break;
        }
        //console.log(newIdx)
        if(!isClick && newIdx > -1 && Ext.fly(articles[currentIdx]).first())
        {
            var checkIdx = newIdx;
            var currentHeight = Ext.fly(articles[currentIdx]).first().getHeight() - 39;
            var currentY = Ext.fly(articles[currentIdx]).first().getY();
            if(currentHeight > contentHeight)
            {
                if(direction == 0)
                {
                    anim = false;
                    return;
                }
                else if(direction == 1 && currentY + currentHeight + 263 > contentHeight)
                {
                    anim = false;
                    return;
                }
                else if(direction == -1 && currentY + currentHeight > 39 && currentY < 39)
                {
                    anim = false;
                    return;
                }
            }
        }
       // Ext.get('head').dom.innerHTML += direction;
        if(/*!galery.isOpen &&*/ newIdx >= 0 && newIdx < max && !anim)
        {
            //container.anim().stop();
            //Ext.get('head').dom.innerHTML += 'oho';
            anim = true;
            var to = !newIdx ? 0 : Ext.fly(articles[newIdx]).getY() + container.getScroll().top - 39;
            if(direction != 0){
                Ext.fly('bg1').stopFx();
                Ext.fly('bg2').stopFx();
            }
            //if(animation)
               // animation.stop();
            if(!to && !container.getScroll().top)
            {
                 if(direction)
                    afterNavigate(direction);
                anim = false;
            }
            else
            {
                animation = container.anim({scroll: { to: [0, to] }}, {duration: 0.5, callback: function(){
                    if(direction)
                        afterNavigate(direction);
                    anim = false;
                }.createDelegate(this), easing: 'easeOut'}, 'scroll');
            }
            currentIdx = newIdx;
            lastScrollPos = to;
            if(direction == 0)
                setThemeBg();
        }
    };

    var afterNavigate = function(direction)
    {
        if(!Ext.fly(articles[currentIdx]).first())
            loadArticles(currentIdx);
        else
        {
            var lMin = currentIdx - NT.preloadSize < 0 ? 0 : currentIdx - NT.preloadSize;
            var lMax = currentIdx + NT.preloadSize >= max ? max-1 : currentIdx + NT.preloadSize;
            var check = direction > 0 ? lMax : lMin;
            if(!Ext.fly(articles[check]).first())
                loadArticles(check);
        }
        if(!anim)
            return;
        setThemeBg();
    };

    var setThemeBg = function(no_anim)
    {
        galOpen = false;
        var themeId = articles[currentIdx].className.match(/theme_(\d+)/)[1];
        fadeImg(themes[themeId], no_anim);
    };

    var fadeImg = function(img, no_anim, duration)
    {
        duration = duration || 1;
        var nextBgIdx = activeBgImg ? 0 : 1;
        //console.trace();
        var nextBg = Ext.get(bgImgs[nextBgIdx]);
        nextBg.hide();
        nextBg.dom.src = "";
        nextBg.dom.src = img;
        //nextBg.show().hide();
        var bg = Ext.get(bgImgs[activeBgImg]);
        if(nextBg.dom.src == bg.dom.src)
            return;
        activeBgImg = nextBgIdx;
        var fn = function(){
           /* if(/*(isVista && Ext.isIE) || no_anim)
            {
                //bg.setDisplayed(false);
                bg.hide();
                //nextBg.setDisplayed(true);
                if(Ext.isIE)
                    ;//nextBg.dom.style['filter'] = '';
                nextBg.show();
            }
            else{*/
                bg.fadeOut({duration:duration});
                nextBg.fadeIn({duration:duration});
            //}
        }
        fn.defer(400);
    }

    var loadArticles = function(idx)
    {
        var el = Ext.get(articles[idx]);

        el.insertHtml('afterBegin', '<div class="post"><div class="articleMask"></div></div>');
        el.child('div.articleMask').mask('');
        Ext.Ajax.request({
            method: 'GET',
            url: 'index.php',
            success: loadSuccess.createDelegate(this),
            params: {idart: 7, idcontent: articles[idx].id.match(/\d+$/)[0], idx: idx}
         });

        /*el.load({
            method: 'GET',
            indicatorText : '',
            url: 'index.php',
            params: {idart: 7, idcontent: articles[idx].id.match(/\d+$/)[0]}
        }, null, function(params){Ext.fly(params.el).child('div.article').unmask()}.createDelegate(this));*/
    }

    var loadSuccess = function(response, opts)
    {
        var idx = opts.params.idx;
        if(container.child('div.articleMask'))
            container.child('div.articleMask').unmask();
        var data = Ext.decode(response.responseText);
        if(data.success)
        {
            var arts = data.list;
            forEach(arts, function(item, idx){
                if(!Ext.fly('art_' + idx).child('.article'))
                {
                    Ext.fly('art_' + idx).update(item);
                    Ext.fly('art_' + idx).select('.input-field').on('focus', preFocus, this);
                    Ext.fly('art_' + idx).select('.input-field').on('blur', postBlur, this);
                    //Ext.fly('art_' + idx).select('textarea.input-field').on('keydown', updateCounter, this);
                    Ext.fly('art_' + idx).select('textarea.input-field').on('keyup', updateCounter, this);
                    Ext.fly('art_' + idx).select('.vote_button').on('click', submitVote, this);
                }
            }, this);
            setupHover();
            setupImageHover();
        }
       //console.log(arguments)
    };

    var loadComments = function(artId)
    {
        var art = Ext.fly(articles[currentIdx]);
        var comments = art.child('.comments');
        if(!comments)
        {
            anim = true;
            Ext.Ajax.request({
               method: 'GET',
               url: 'index.php',
               success: loadCommentSuccess.createDelegate(this),
               params: {idart: 32, id: artId}
            });
        }
        else
        {
            art.child('div.comments_button').setDisplayed(false);
            comments.setDisplayed(true);
        }
    };

    var loadCommentSuccess = function(response, opts)
    {
        anim = false;
        var data = Ext.decode(response.responseText);
        if(data.success)
        {
            var art = Ext.fly(articles[currentIdx]);

            art.select('.input-field').un('focus', preFocus, this);
            art.select('.input-field').un('blur', postBlur, this);
            art.child('div.comments_button').setDisplayed(false);
            if(!data.first)
            {
                if(art.child('.comments')){
                    art.child('.comments').remove();
                }
            }
            else
            {
                var ctBoxes = art.select('.contentBox > div:not(.t)').remove();
                art.child('div.contentBox').insertHtml('beforeEnd', data.first);
            }
            art.child('div.dynContent').insertHtml('afterBegin', data.content);
            art.select('.input-field').on('focus', preFocus, this);
            art.select('.input-field').on('blur', postBlur, this);
            //art.select('textarea.input-field').on('keydown', updateCounter, this);
            art.select('textarea.input-field').on('keyup', updateCounter, this);
            art.select('.new-comment-form').on('click', function(ev, el){
                var form = Ext.fly(Ext.id(this));
                form.select('.comments-form').setHeight(260, true);
            });
        }
        else if(data.errors)
        {
            var error = data.errors.errorDesc;
            var art = Ext.fly(articles[currentIdx]);
            if(art.child('.jam-form'))
            {
                var errorDiv = art.child('.jam-first-item');
                error =  '<div class="headline">Fehler</div><div class="text"><p class="comment-error">' + error + '</p></div>'
            }
            else
                var errorDiv = art.child('.comment-error') || art.child('.headlineInner').insertHtml('afterEnd', '<p class="comment-error"></p>', true);
            errorDiv.update(error);
        }
    };

    var hideComments = function()
    {
        var art = Ext.fly(articles[currentIdx]);
        art.child('.comments').setDisplayed(false);
        art.child('div.comments_button').setDisplayed(true);
        navigate(0, true)
    };

    var submitComment = function(artId)
    {
        var params = {idart: 32, id: artId, action: 'create'};
        var art = Ext.fly(articles[currentIdx]);
        var inputs = art.select('.input-field');
        inputs.each(function(input){
            params[input.dom.name] = input.dom.value == input.dom.defaultValue ? '' : input.dom.value;
        }, this);
        Ext.Ajax.request({
            method: 'POST',
            url: 'index.php',
            success: loadCommentSuccess.createDelegate(this),
            params: params
         });
    };

    var submitVote = function(artId)
    {
        var answer;
        var params = {idart: 42, id: artId, action: 'vote'};
        var art = Ext.fly(articles[currentIdx]);
        var inputs = art.select('input[name=answer]');
        inputs.each(function(input){
            if(input.dom.checked)
                answer = input.dom.value;
        }, this);
        if(answer)
        {
            params['answer'] = answer;
            Ext.Ajax.request({
                method: 'POST',
                url: 'index.php',
                success: voteSuccess.createDelegate(this),
                params: params
             });
        }
    };
    var submitVote = function(event,el)
    {
        submitImgVote(articles[currentIdx].id.match(/art_(\d+)/)[1], event.getTarget('.vote_button'));
    };
    
    var submitImgVote = function(artId, answer)
    {
        var hasAnswer;
        var params = {idart: 42, id: artId, action: 'vote'};
        var art = Ext.fly(articles[currentIdx]);
        var inputs = art.select('.vote_button');
        inputs.each(function(input, els, idx){
            if(input.dom == answer){
                answer = idx + 1;
                hasAnswer = true;
            }
        }, this);
        if(hasAnswer)
        {
            params['answer'] = answer;
            Ext.Ajax.request({
                method: 'POST',
                url: 'index.php',
                success: voteSuccess.createDelegate(this),
                params: params
             });
        }
    };

    var voteSuccess = function(response, opts)
    {
        var data = Ext.decode(response.responseText);
        if(data.success)
        {
            var art = Ext.fly(articles[currentIdx]);
            art.select('.vote').remove();
            art.child('.contentBox').insertHtml('beforeEnd', data.content);
        }
    };

    var preFocus = function(ev, el)
    {
        inField = true;
        if(el.value == el.defaultValue)
            el.value = '';
    };

    var postBlur = function(ev, el)
    {
        inField = false;
        if(el.value == '')
            el.value = el.defaultValue;
    }
    
    var updateCounter = function(ev, el)
    {
        if (el.parentNode)
        {
            var ml = parseInt(el.getAttribute('maxlength'));
            if (el.value.length > ml) el.value = el.value.substring(0,ml);
            //Ext.get(Ext.id(el.parentNode)).select('div.text-counter').elements[0].innerHTML = el.value.length + '/500';
            el.nextSibling.nextSibling.innerHTML = el.value.length +'/'+ ml;
        }
    }

    var getScrollDirection = function(is_anim)
    {
        var newIdx = currentIdx, art, divisor;
        var div = container.getScroll().top - lastScrollPos;
        if(div != 0)
        {
            divisor = div > 0 ? 3 : 1.5;
            for(var i = 0; i < max; i++)
            {
                art = Ext.fly(articles[i]);
                if((art.getY() + (art.getHeight() / divisor)) > 0)
                {
                    newIdx = i;
                    break;
                }
            }
            //if(is_anim && newIdx == currentIdx)
               // newIdx = div > 0 ? currentIdx + 1 : currentIdx - 1;
        }
        return newIdx - currentIdx;
    };

    var getScrollOffset = function(articleId)
    {
        for(var i = 0; i < max; i++)
            if(articles[i].id == 'art_' + articleId)
                break;
        return i -currentIdx;
    };

    var initNavigation = function()
    {

        container.on({
            'click':  {
                fn: function(event, el){
                    scroll = false;
                    event.stopEvent();
                    galery.open(Ext.get(articles[currentIdx]));
                    galery.play();
                    currentVisible = galery;
                },
                delegate: 'div.media_play'
            },
            scope: this
        });

        container.on({
            'click':  {
                fn: function(event, el){
                    scroll = false;
                    event.stopEvent();
                    var idart = articles[currentIdx].id.match(/art_(\d+)/)[1];
                    NT.Video.open('video_'+idart);
                    currentVisible = NT.Video;
                },
                delegate: 'div.video_play'
            },
            scope: this
        });

        container.on({
            'click':  {
                fn: function(event, el){
                    if(event.getTarget('div.prevArticle'))
                        navigate(-1, true);
                    else if(event.getTarget('div.nextArticle'))
                        navigate(1, true);
                    else
                    {
                        var el;
                        if(el = event.getTarget('div.links'))
                        {
                            var articleId = event.getTarget('a').href.match(/\d+$/)[0];
                            var tIds = [];
                            forEach(themes, function(i, tId){
                                tIds.push(tId)
                            }, this);
                            Ext.select('.sub-nav-element').addClass('subSel');
                            filterThemes(tIds, true);
                            navigate(getScrollOffset(articleId), true);
                            event.stopEvent();
                        }
                        else if(event.getTarget('div.comments_button'))
                        {
                            loadComments(articles[currentIdx].id.match(/art_(\d+)/)[1]);
                            event.stopEvent();
                        }
                        else if(event.getTarget('.close_comments'))
                        {
                            hideComments();
                            event.stopEvent();
                        }
                        else if(event.getTarget('.submit-form'))
                        {
                            submitComment(articles[currentIdx].id.match(/art_(\d+)/)[1]);
                            event.stopEvent();
                        }
                    }
                },
                delegate: 'div.post-wrap'
            },
            'mousewheel':  {
                fn: function(event){
                    var delta = event.getWheelDelta() > 0 ? 1 : -1;
                    navigate(-delta);
                }//,
                //stopEvent: true
            },
            //für Scrollbar
            'mousedown' : function(event){
                //console.log(event)
                if(contentWidth < event.xy[0])// || !Ext.isIE)
                    down = true;
            },
            'mouseup' : {
                fn: function(event){
                    //alert(event.xy[0])
                    if(scroll && down)
                    {
                        navigate(getScrollDirection());
                        down = false;
                        scroll = false;
                    }
                },
                delay: 10
            },
            'scroll': {
                fn: function(){
                    if(!anim)
                    {
                        if(!Ext.isIE)
                            scroll = true;
                            //container.focus();
                        else if(down){
                            navigate(getScrollDirection(true));
                            //anim = true;
                        }
                    }
                },
                buffer: Ext.isIE ? 500 : 0

            },
            scope: this
        });

        container.on({
            'click':  {
                fn: function(event, el){
                    //console.log(arguments)
                    var page = el.className.match(/b(\d)/);
                    pageText(page[1]);
                },
                delegate: 'div.pagenav'
            },
            scope: this
        });

        container.on({
            'click':  {
                fn: function(event, el){
                    var themeId = articles[currentIdx].className.match(/theme_(\d+)/)[1];
                    showTheme(themeId);
                },
                delegate: 'div.themeLink'
            },
            scope: this
        });

        Ext.fly(document).on({
            'keydown': function(ev)
            {
                var key = ev.getKey();

                if((key == 34 || key == 40) && !inField)
                    navigate(1, key == 34);
                if((key == 33 || key == 38) && !inField)
                    navigate(-1);
                if(key == 34 || key == 33 || (key == 9 && !inField) || (ev.getTarget().name == 'text' && !ev.shiftKey && key == 9) || (ev.getTarget().name == 'name' && ev.shiftKey&& key == 9))
                    ev.stopEvent();
                //if(!ev.altKey && !ev.ctrlKey)

            }
        });
    };

    var pageText = function(page)
    {
        var pages = Ext.fly(articles[currentIdx]).select('.text div[class*=content_]');
        pages.setDisplayed(false);
        Ext.fly(articles[currentIdx]).select('.textPage').removeClass('active');
        Ext.fly(articles[currentIdx]).select('div.content_' + page).setDisplayed(true);
        Ext.fly(articles[currentIdx]).child('.b' + page).parent().addClass('active')
    };

    var showTheme = function(themeId, is_about)
    {
        aboutTheme = is_about;
        currentVisible.setDisplayed(false);
        themenContainer.select('.theme').setDisplayed(false)
        var th =  Ext.get('theme_' + themeId);
        if (!th.hasClass('hidden'))
        {
            if(!Ext.isIE)
            {
                th.setStyle('overflow', 'hidden');
                th.slideIn('l', {
                    callback: function(){
                        th.setStyle('overflow', 'auto');
                        fadeImg(themes[themeId]);
                        setTopWidth();
                    },
                    scope:this
                });
            }
            else{
                th.setDisplayed(true);
                fadeImg(themes[themeId]);
            }
            currentVisible = th;
            setTopWidth();
        } else {
            handleMClick(null, 'about', 'index.php?idcat=9');
        }
    };

    var archivToArticle = function(ev)
    {
        var el;
        if(el = ev.getTarget('div.archivArticle'))
        {
            ev.stopEvent();
            var id = el.className.match(/art_(\d+)/)[1];
            archiv.setDisplayed(false);
            //archiv.first().hide();
            container.setDisplayed(true);
            currentVisible = container;
            navigate(getScrollOffset(id), true);
        }
    };

    var correctArchivHeadlines = function(params)
    {
        if(params.el.id == 'archiv')
        {
            if(Ext.isIE6)
                Ext.select('div.archivMonth').each(function(el){el.dom.innerHTML = el.dom.innerHTML})
            var heads = Ext.select('.bg p.text', true, params.el);
            heads.each(splitHeadlines, this);
        }
        Ext.fly(params.el).on('click', archivToArticle, this, {delegate: 'div.archivArticle'});
    };

    var filterArchiv = function(themeId)
    {
        var archivDivs = archiv.select('div.archivArticle');
        var monthDivs = archiv.select('div.archivMonth');
        archivDivs.setDisplayed(true);
        monthDivs.setDisplayed(true);
        if(themeId)
        {
            archivDivs.each(function(archivDiv){
                var tid = parseInt(archivDiv.dom.className.match(/archiv-theme-(\d+)/)[1]);
                archivDiv.setDisplayed(tid == themeId);
            }, this);
            var check = false;
            monthDivs.each(function(monthDiv){
                var nx = monthDiv.next();
                check = false;
                while(nx.first() && !nx.first().isVisible())
                {
                    //if(nx.next())
                        nx = nx.next();

                }
                if(nx && (nx.hasClass('archivMonth') || !nx.first() || !nx.first().hasClass('archivArticle')))
                {
                    monthDiv.setDisplayed(false);
                }
            }, this);
        }
        setTopWidth();
    };

    var setupImageHover = function(all)
    {
        var opts = all ? Ext.select('.hover-image') : currentVisible.select('.hover-image');
        opts.each(function(item){
            if(!item.hasClass('hi'))
            {
                item.hover(
                    function(){
                        Ext.fly(this, '_internal').child('.image-normal').setDisplayed(false);
                        Ext.fly(this, '_internal').child('.image-hovered').setDisplayed(true);
                    },
                    function(){
                        Ext.fly(this, '_internal').child('.image-normal').setDisplayed(true);
                        Ext.fly(this, '_internal').child('.image-hovered').setDisplayed(false);
                    }
                );
                item.addClass('hi');
            }
        }, this);
    }

    var splitHeadlines = function(head)
    {
        var height = head.getHeight();
        var rows = height/22;
        if(rows > 1)
        {
            var words = head.first().dom.innerHTML.split(/\s/);
            var spanWords = [words[0]];
            var spans = [];
            for(var i = 1, len =words.length; i < len; i++)
            {
                spanWords.push(words[i]);
                head.dom.innerHTML = '<span>' + spanWords.join(' ') + '</span>';
                if(head.first().getHeight() > 22)
                {
                    spanWords.pop();
                    spans.push('<span>' + spanWords.join(' ') + '</span>');
                    spanWords = [words[i]];
                }
            }
            if(spanWords.length)
                spans.push('<span>' + spanWords.join(' ') + '</span>');
            head.dom.innerHTML = spans.join(' ');
        }

    }

    var handleMClick = function(ev, showDirect, loadUrl)
    {
        var isDirect = typeof showDirect;
        if(isDirect == 'string' || !ev.getTarget('li[id^=theme-]'))
        {
            var el;
            if(isDirect == 'string' || (el = ev.getTarget('li[id^=nav-]')))
            {
                var ctId, target;
                if (isDirect == 'string')
                {
                    ctId = showDirect;
                } else {
                    ev.stopEvent();
                    ctId = el.id.replace(/^nav-/, '');
                    target = Ext.fly(el).child('a', true) ? Ext.fly(el).child('a', true).target : '';
                }
                if(target == '_blank')
                {
                    window.open(Ext.fly(el).child('a', true).href, "_blank");
                    return;
                }
                else if(ctId == 'home')
                {
                    if(currentVisible != container)
                    {
                        currentVisible.setDisplayed(false);
                        container.setDisplayed(true);
                    }
                    navigate(getScrollOffset(NT.preloadId), true);
                    currentVisible = container;
                    setTopWidth();
                    return;
                }
                else if(ctId != 'filter')
                {
                    var ct = Ext.get(ctId);
                    currentVisible.setDisplayed(false);
                    //if(currentVisible.first() && currentVisible != container)
                        //currentVisible.first().hide();
                    ct.setDisplayed(true);
                    //fadeImg(defaultImg);
                    currentVisible = ct;
                    if(!ct.first())
                    {
                        if (isDirect != 'string')
                            loadUrl = Ext.fly(el).child('a', true).href;
                        ct.insertHtml('afterBegin', '<div class="articleMask"></div>');
                        ct.child('div.articleMask').mask('');
                        ct.load({
                            method: 'GET',
                            indicatorText : '',
                            url: loadUrl

                        }, null, function(params){
                            if(ct.child('div.articleMask'))
                                ct.child('div.articleMask').unmask()
                            if(ctId == 'archiv')
                            {
                                correctArchivHeadlines(params);
                            }

                            setupImageHover();
                            setupHover();

                            if(ct.first()){
                                ct.first().setDisplayed(true);

                            };
                            fadeImg(defaultImg);
                            setTopWidth();
                            }.createDelegate(this));
                    }
                    else
                    {
                        if(ct.first())
                        {
                            if(!Ext.isIE)
                                ct.first().slideIn('l', {
                                        callback: function(){
                                            fadeImg(defaultImg);
                                        },
                                        scope:this
                                    });
                            else
                            {
                                ct.first().setDisplayed(true);
                                fadeImg(defaultImg);
                            }
                        }
                            //ct.first().setDisplayed(true);
                        setTopWidth();
                    }
                }
                else
                {
                    Ext.fly(el).child('ul').toggle();
                }
            }
        }
    };

    var handleSubMClick = function(ev)
    {
        var fn = function()
        {
            var selIds = [];
            var sels = subMenuHandle.select('.subSel');
            sels.each(function(sel){
                var id = sel.dom.id.match(/theme-(\d+)/)[1];
                selIds.push(id);
            }, this);
            selIds.push('12');
            return selIds;
        }
        ev.stopEvent();
        var el;
        if(el = ev.getTarget('li[id^=theme-]'))
        {
            Ext.fly(el).toggleClass('subSel');
            var selIds = fn();
            filterThemes(selIds);
        }
        else if(el = ev.getTarget('#do-filter'))
        {
            subMenuHandle.select('li[class*=nummer-]').addClass('subSel');
            var selIds = fn(true);
            //subMenuHandle.setDisplayed(false);
            filterThemes(selIds);
        }
    }

    var filterThemes = function(themeIds, silent)
    {
        if(!themeIds)
            return;
        if(!Ext.isArray(themeIds))
            themeIds = [themeIds];
        container.select('.post-wrap').setDisplayed(false);

        currentVisible.setDisplayed(false);
        container.setDisplayed(true);
        currentVisible = container;
        for(var i = 0, len = themeIds.length; i < len; i++)
        {
            container.select('.theme_' + themeIds[i]).setDisplayed(true);
        }
        selThemes = themeIds;
        if(!silent)
            goToFirstThemeArticle(themeIds);
        setTopWidth();
        //goToFirstFilled(true);
    }

    goToFirstThemeArticle = function(themeIds)
    {
        var tId;
        tId = articles[currentIdx].className.match(/theme_(\d+)/)[1];
        if(themeIds.indexOf(tId) > -1){
            navigate(0, true);
            return;
        }
        if(themeIds.length > 1)
            themeIds.pop();
        var match = false;
        for(var i = 0; i < max; i++)
        {
            tId = articles[i].className.match(/theme_(\d+)/)[1];
            if(themeIds.indexOf(tId) > -1)
            {
                match = true;
                break;
            }
        }
        if(!match)
        {
            for(var i = 0; i < max; i++)
            {
                if(articles[i].className.match(/theme_12/))
                    break;
            }
        }
        var dis = i - currentIdx;
        navigate(dis, true);
    };

    var initMainMenu = function()
    {
        mMenuHandle.on('mouseover', function(){
            //if(!Ext.isIE8)
                mMenu.moveTo(0,69, true);
            /*else
                mMenu.moveTo(2,71, true);*/
        }, this);
        mMenu.on({
            'mouseout': {
                fn :function(e){
                    if(!e.within(mMenu,  true))
                    {
                        subMenuHandle.setDisplayed(false);
                        //if(!Ext.isIE8)
                            mMenu.moveTo(0,0, true);
                        /*else
                            mMenu.moveTo(2,2, true);*/
                    }
                }
                //,delay: 1000
            },
            'click': handleMClick
        }, this);
        tMenu.on({
            'click': function(ev, el)
            {
               if (el.href)
               {
                  ev.stopEvent();
                  var divname = el.id.match(/^topnav-(.+)$/);
                  if (divname) handleMClick(null, divname[1], el.href);
               }
            }
        }, this);
    };

    var initSubMenu = function()
    {
        subMenuHandle = Ext.get('theme-filter');
        subMenuHandle.on('click', handleSubMClick, this);
    };

    var closeInfo = function(ev)
    {
        currentVisible.setDisplayed(false);
        if(!ev.getTarget('.theme'))
        {
            container.setDisplayed(true);
            //if(Ext.isIE )
                container.dom.scrollTop = Ext.fly(articles[currentIdx]).getY() + container.getScroll().top - 39;
            setThemeBg();
            currentVisible = container;
        }
        else
        {
            if(aboutTheme)
            {
                about.setDisplayed(true);
                if(!Ext.isIE)
                {
                    about.first().slideIn('l', {
                        callback: function(){
                            fadeImg(defaultImg);
                        },
                        scope:this
                    });
                }else
                {
                    fadeImg(defaultImg);
                }
                currentVisible = about;
            }
            else{
                container.setDisplayed(true);
                //if(Ext.isIE)
                    container.dom.scrollTop = Ext.fly(articles[currentIdx]).getY() + container.getScroll().top - 39;
                currentVisible = container;
            }
        }
        setTopWidth();
    }

    var getEls = function()
    {
        isVista = /windows nt 6.0/.test(navigator.userAgent.toLowerCase());
        themenContainer = Ext.get('themenContainer');
        currentVisible = container = Ext.get('articles');
        contentWidth = container.getWidth() - 15;
        articles = Ext.query('.post-wrap');
        max = articles.length;
        bgImgs = Ext.query('.bgImg');
        var themeCont = Ext.query('.theme');
        for(var i = 0, len = themeCont.length; i < len; i++)
        {
            var theme = Ext.fly(themeCont[i]);
            var tId = themeCont[i].id.replace(/theme_/, '');
            var img = theme.child('img').setDisplayed(false);
            var imgSrc = img.dom.src;
            themes[tId] = imgSrc;
            if(theme.hasClass('hidden'))
                defaultImg = imgSrc;
        }
        mMenuHandle = Ext.get('nav-handle');
        mMenu = Ext.get('main-nav');
        tMenu = Ext.get('nav-top');
        var bd = Ext.getBody();
        about = bd.insertHtml('beforeEnd', '<div id="about" style="display:none;"></div>', true);
        archiv = bd.insertHtml('beforeEnd', '<div id="archiv" style="display:none;"></div>', true);
        impressum = bd.insertHtml('beforeEnd', '<div id="impressum" class="page-content-text" style="display:none;"></div>', true);
        datenschutz = bd.insertHtml('beforeEnd', '<div id="datenschutz" class="page-content-text" style="display:none;"></div>', true);
        haftungsausschluss = bd.insertHtml('beforeEnd', '<div id="haftungsausschluss" class="page-content-text" style="display:none;"></div>', true);
        nutzungsbedingungen = bd.insertHtml('beforeEnd', '<div id="nutzungsbedingungen" class="page-content-text" style="display:none;"></div>', true);
        bd.insertHtml('beforeEnd', '<div id="galerieContainer" style="display:none;"><div class="contentText"></div></div>');
        Ext.getBody().on('click', closeInfo, this, {delegate: 'div.close_content'});
        about.on('click', function(ev, el){
            var themeId = el.className.match(/theme_(\d+)/)[1];
            showTheme(themeId, true);
        }, this, {delegate: 'div.themeTeaser'});
        archiv.on('click', function(ev){
            var target;
            if(ev.getTarget('#archiv-filter-selected'))
                Ext.fly('archiv-filter-select').toggle();
            else if(target = ev.getTarget('li'))
            {
                var tid = parseInt(target.id.match(/archiv-theme-(\d+)/)[1]);
                filterArchiv(tid);
                //var imgSrc = Ext.fly(target).first().getAttribute('rel');
                Ext.fly('archiv-filter-selected').first().dom.src = Ext.fly(target).last().dom.src;
                Ext.fly('archiv-filter-select').setDisplayed(false);
            }
           //if(ev.getTarget('#archiv-filter'))
                //filterArchiv(5);
        }, this);
    };

    var hoverOn = function()
    {
        Ext.fly(this, '_internal').addClass('hovered');
    }

    var hoverOff = function()
    {
        Ext.fly(this, '_internal').removeClass('hovered');
    }

    var setupHover = function(el)
    {
        var hovers = el ? el.select('.hover') : Ext.select('.hover');
        hovers.each(function(item){
            if(!item.parent('.hover-wrap'))
            {
                var hoverEl = item.wrap({tag: 'div', cls:'hover-wrap'});
                hoverEl.hover(hoverOn, hoverOff);
            }
        }, this);
    };

    var setTopWidth = function()
    {
        contentHeight = D.getViewHeight() - 69;
        var fn = function()
        {

            if(container.isVisible() && (currentVisible == NT.Video || currentVisible == galery))
                currentVisible = container;
            var newWidth = (currentVisible == NT.Video || currentVisible == galery) ? '100%' : currentVisible.dom.scrollWidth;
            Ext.fly('top').setWidth(newWidth);
        }
        fn.defer(500);
    };

    goToFirstFilled = function()
    {
       for(var i = 0; i < max; i++)
       {
            var art = Ext.fly(articles[i]);
            if(art.dom.id == 'art_' + NT.preloadId)
            {
                navigate(i, true);
                break;
            }
       }
    };

    return {
        init: function() {
            getEls();
            galery = new NT.Gallery();
            setTopWidth();
            Ext.EventManager.on(window, 'resize', setTopWidth);
            initNavigation();
            goToFirstFilled();
            initMainMenu();
            initSubMenu();
            NT.Video.init();
            setupHover();
            setupImageHover(true);
            container.select('.input-field').on('focus', preFocus, this);
            container.select('.input-field').on('blur', postBlur, this);
            //container.select('textarea.input-field').on('keydown', updateCounter, this);
            container.select('textarea.input-field').on('keyup', updateCounter, this);
            container.select('.vote_button').on('click', submitVote, this);
            if (typeof NT.loadcontent == 'object')
            {
               handleMClick(null, NT.loadcontent[0], 'index.php?idcat='+NT.loadcontent[1]);
            }
            if (NT.loadthema && NT.loadthema > 0)
            {
              if (Ext.get("theme_"+NT.loadthema)){
                showTheme(NT.loadthema);
              }
            }
        },

        fadeImg: fadeImg,
        setTopWidth: setTopWidth,
        setThemeBg: setThemeBg,
        setupHover: setupHover,
        hoverOn: hoverOn,
        hoverOff: hoverOff,
        setActiveImage: function()
        {
            activeBgImg = Ext.fly('bg1').isVisible() ? 0 : 1;
        },
        setArticleScroll: function()
        {
            container.dom.scrollTop = Ext.fly(articles[currentIdx]).getY() + container.getScroll().top - 39;
        }
    }
}();

Ext.onReady(NT.app.init);