$(function() {
    // random preview
    $(document).on('click', '#random > #randomize', function() {
        $('#random').empty().load(this.href);
        return false;
    });
    $('#random > a').trigger('click');
    
    // save/restore scroll position
    if(sessionStorage) {
        var currentPage = location.pathname;
        var scrollpos_pages = {};
        if('scrollpos_pages' in sessionStorage) {
            scrollpos_pages = JSON.parse(sessionStorage.scrollpos_pages);
        }
        if(currentPage in scrollpos_pages) {
            $('#main')[0].scrollTop = scrollpos_pages[currentPage][0];
            $('#reception')[0].scrollTop = scrollpos_pages[currentPage][1];
        } else {
            scrollpos_pages[currentPage] = [0,0];
        }
        
        $('#main').on('scroll', function() {
            scrollpos_pages[currentPage][0] = this.scrollTop;
            sessionStorage.scrollpos_pages = JSON.stringify(scrollpos_pages);
        });
        $('#reception').on('scroll', function() {
            scrollpos_pages[currentPage][1] = this.scrollTop;
            sessionStorage.scrollpos_pages = JSON.stringify(scrollpos_pages);
        });
        
        $('#date a:link').on('click', function() {
            scrollpos_pages[this.pathname]=[0,0];
            sessionStorage.scrollpos_pages = JSON.stringify(scrollpos_pages);
        });
        
    
        $('#nav').on('scroll', function() {
            sessionStorage.scrollpos_nav = this.scrollTop
        });
        $('#date').on('scroll', function() {
            sessionStorage.scrollpos_date = this.scrollTop
        });
        
        
        
        $('#nav')[0].scrollTop = sessionStorage.scrollpos_nav;
        $('#date')[0].scrollTop = sessionStorage.scrollpos_date;
    }

    /* tag wizzardry
     *
     */
    var tags_active = {};       // currently clicked tags
    var documents_active = {};  // currently active documents

    // store active tags in browser's session database
    if(sessionStorage) {
        if ('tags_active' in sessionStorage) {
            tags_active = JSON.parse(sessionStorage.tags_active)
        }
    }

    // mark tags as active, unwrap behind ellipsis if hidden
    function mark_tags() {
        for(var id in tags_active) {
            var element = $('a[data-tag='+id+']');
            if (element.addClass('active').is(':hidden')) {
                element.parent().parent().find('li.expand > a').trigger('click');
            };  
        }
    }

    // show documents that fit the current tag selection
    function mark_documents() {
        if(!$.isEmptyObject(tags_active)) {
            $('#tags-reset').addClass('active');
        } else {
            $('#tags-reset').removeClass('active');
        }
        documents_active = {};
        $('#date a').removeClass('inactive');    
        if ($.isEmptyObject(tags_active)) return;

        for (doc in documents) {
             var all_tags_fit = true;
             for (var tag in tags_active) {
                if (!(tag in documents[doc])) {
                    all_tags_fit = false;
                }
            }
            if (!all_tags_fit) {
                $('#'+doc).addClass('inactive');
            } else {
                documents_active[doc]=0;
            }
        }

    }

    function store_tags() {
        if(sessionStorage) {
            sessionStorage.tags_active = JSON.stringify(tags_active);
        }
    }

    function calculate_tags() {
        if(!$.isEmptyObject(tags_active)) {
            var result = {};
            
            for (tag in all_tag_ids) {
                if(!(tag in tags_active)) {
                    var counter = 0;
                    for (doc in documents_active) {
                         if(tag in documents[doc]) {
                            counter++;
                        }
                    }
                    result[tag] = counter;
                }
            }
            
            for(tag in result) {
                var thistag = $('a[data-tag='+tag+']')
                thistag.children('span').text(result[tag]);
                if(result[tag]==0)
                    thistag.addClass('inactive')
                else
                    thistag.removeClass('inactive')
            }
        } else {
            $('a.tag').each(function(){
                $(this).removeClass('inactive').find('span').text( $(this).data('n') );
            });
        }
    }

    // reset tags if user follows link to document not fitting
    // the current tag selection
    $('#date a').on('click', function() {
        if ($(this).hasClass('inactive')) {
            $('#tags-reset').trigger('click');
        }
    })


    // prepare handmade tags
    $('#main a.tag').not('a.tag[data-tag]').each( function() {
        var element = $(this);
        element.attr('data-tag', all_tags[element.text()]);
        
    });


    $('a.tag').bind('click', function() {
        var id = $(this).data('tag');
        if (id in tags_active) {
            delete tags_active[id]
            $('a[data-tag='+id+']').removeClass('active');
        } else {
            tags_active[id]=0;
            if ($('a[data-tag='+id+']').addClass('active').is(':hidden')) {
                $('a[data-tag='+id+']').parent().parent().find('li.expand > a').trigger('click');
            };
        }
        mark_documents();
        calculate_tags();
        store_tags();
        return false;
    });

    $('#tags-reset').bind('click', function() {
        $('a[data-tag]').removeClass('active');
        tags_active = {};
        mark_documents();
        calculate_tags();
        store_tags();

    });

    // ellipsis
    var expander = $('<li class="expand"><a>...</a></li>')
        .bind('click', function() {
            $(this).hide().siblings().show();
            return false;
        });

    $('#nav ul.tags').each(function() {
        var elements = $(this).find('li');
        if (elements.length > 5) {
            elements.slice(5).hide();
            var exp = expander.clone(true);
            exp.insertAfter( elements.eq(5));
            
        }
    });


    mark_tags();
    mark_documents();
    calculate_tags();
});

