
var ignoreHashChange = false;

function EntriesCarousel(element, fetchParams, offset, count)
{
    _initializing = true;

    /**
     * jCarousel initialisieren
     */
    element = $(element);

    var serverSideOffset = offset ? true : false;

    var tmp = window.location.hash.match('offset\=([0-9]+)')
    if(tmp && tmp[1])
        offset = parseInt(tmp[1]);

    element.jcarousel({
        scroll: 1,
        size: count,
        start: offset+1,
        initCallback: function(carousel) {
            if(serverSideOffset) {
                /**
                 * Wenn ein Offset vorgegeben ist, müssen die schon mit PHP 
                 * eingetragenen <li>s entfernt werden, da jcarousel diese als
                 * Elemente 1 bis x und nicht als Elemente offset bis offset+x
                 * behandelt.
                 */
                for(var i = 0; i < carousel.options.scroll; i++)
                    carousel.remove(i);
            }

            _initMouseoverAnimation();
        },
        itemLoadCallback: { onBeforeAnimation: _load, onAfterAnimation: _initMouseoverAnimation },
        itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }}
    });

    /**
     * Evtl. Detail-Ansicht eines Beitrags initialisieren
     */
    var tmp = window.location.hash.match('view\=([0-9]+)')
    if(tmp && tmp[1])
        _view(tmp[1]);

    /**
     * Navigation (mit Ankern) und Browser-History initialisieren
     */
    ignoreHashChange = true;
    $(window).hashchange(function(hash) {

        if(ignoreHashChange) {
            ignoreHashChange = false;
            return;
        }

        /* Detail-Ansicht eines Beitrags */
        var tmp = window.location.hash.match('view\=([0-9]+)')
        if(tmp && tmp[1])
            _view(tmp[1]);
        else
            _view(null);

        /* Scroll-Status des jCarousels */
        var tmp = window.location.hash.match('offset\=([0-9]+)')
        var offset = 0;
        if(tmp && tmp[1])
            offset = parseInt(tmp[1]);
    
        var carousel = element.data('jcarousel');
        if(carousel.first != offset+1) {
            element.jcarousel('scroll', offset+1);
            _ensureVisible(element);
        }
    });

    _initializing = false;

    function _hashParamSet(key, value)
    {
        var values = {};

        if(window.location.hash) {
            var pairs = window.location.hash.substr(1).split('&');
            for(var i = 0; i < pairs.length; i++) {
                var tmp = pairs[i].split('=');
                values[tmp[0]] = tmp[1];
            }
        }

        if(null === value)
            delete values[key];
        else
            values[key] = value;

        var hash = "";

        $.each(values, function(key, value) {

            /**
             * Wenn der 'offset'-Paramter '0' ist, soll er gar nicht angezeigt
             * werden (z.B., damit dieser nicht in der Browser-History 
             * auftaucht).
             */
            if(key == 'offset' && value == 0)
                return;

            if(hash)
                hash += "&";
            hash += encodeURIComponent(key)+"="+encodeURIComponent(value);
        });

        if(hash || window.location.hash) {

            if("#"+hash == window.location.hash)
                return;

            ignoreHashChange = true;
            window.location.hash = hash;
        }
    }

    function _ensureVisible(element)
    {
        var scrollTop = $(window).scrollTop();
        var scrollBottom = scrollTop + $(window).height();

        var positionTop = element.offset().top;
        var positionBottom = positionTop + element.height();

        if(scrollTop > positionTop)
            $.scrollTo(element, { 'duration': 200 });
        else if(scrollBottom < positionBottom)
            $.scrollTo('+='+(positionBottom-scrollBottom+5)+'px', { 'duration': 200 });
    }

    function _load(carousel, state)
    {
        var offset = carousel.first-1;
        var limit = carousel.last-carousel.first+1;

        _hashParamSet('offset', offset);

        for(var i = carousel.first; i <= carousel.last; i++) {
            if(carousel.has(i)) {
                if(i == offset+1) {
                    offset++;
                    limit--;
                }
            } else
                carousel.add(i, '<div><img src="img/loading.gif" alt="Lade..." /></div>');
        }

        if(!limit)
            return;

        fetchParams.offset = offset;
        fetchParams.limit = limit;

        $.ajax({
            url: 'ajax/get-entries',
            data: fetchParams,
            success: function(data, textStatus, jqXHR) {
                for(var i = 0; i < data.length; i++)
                    carousel.add(offset+i+1, '<div>'+data[i].previewHtml+'</div>');
                
                $('.seoLink').remove();
            }
        });
    }

    function _initMouseoverAnimation()
    {
        element.children('li')
            .unbind('click')
            .click(function() {
                var tmp = $(this).find('.carousel-entry').attr('class').match(/carousel-entry-id-([0-9]+)/);
                _view(tmp[1]);
            })
            .unbind('mouseenter')
            .mouseenter(function(){

                $(this).addClass('__carouselMouseOver');

                $(this).addClass("carousel_over");
                $(this).animate(
                    {
                        'width': '310px',
                        'height': '335px',
                        'margin-left': '0px',
                        'margin-top': '0px',
                        'margin-right': '0px'
                    },
                    75,
                    function() {

                        if($(this).hasClass('__carouselMouseOver')) {

                            $(this).find('.btn_hoeren_container').show();

                            var __this = $(this);
                            $(this).find('.btn_hoeren').fadeIn(175, function() {
                                if(!__this.hasClass('__carouselMouseOver'))
                                    __this.find('.btn_hoeren').hide();
                            });
                        }

                        /**
                         * Wenn während der Animation mouseleave() die 
                         * Klasse wieder zurückgesetzt hat...
                         */
                        $(this).addClass("carousel_over");

                    }
                );
            })
            .unbind('mouseleave')
            .mouseleave(function(){

                $(this).removeClass('__carouselMouseOver');
                $(this).find('.btn_hoeren_container').hide();

                $(this).find('.btn_hoeren').hide();

                $(this).animate(
                    {
                        'width': '290px',
                        'height': '295px',
                        'margin-left': '10px',
                        'margin-top': '20px',
                        'margin-right': '10px'
                    },
                    75,
                    function() {
                        $(this).removeClass("carousel_over");
                    }
                );
            });
    }

    var currentEntry = null;

    function _setViewLocation(id)
    {
        _hashParamSet('view', id);
    }

    function _view(id)
    {
        if(currentEntry && currentEntry.id == id)
            return;

        _setViewLocation(id);

        var container = $('#entryDetailView');

        /**
         * Wenn keine Id gegeben ist (wenn von History zurückgesetzt),
         * heißt das, dass jetzt keine Detail-Ansicht (mehr) angezeigt werden
         * soll.
         */
        if(!id) {
            if(!container.is(':hidden'))
                container.slideUp();

            currentEntry = null;
            return;
        }

        var replace = null;
        if(container.is(':hidden')) {
            replace = false;
            container.slideDown();
        } else {
            replace = true;
        } 

        container.empty();
        container.append('<div class="_carouselLoading" style="position: absolute;"><img src="img/loading.gif" alt="Lade..." /></div>');

        var scroll = !_initializing;

        $.ajax({
            url: 'ajax/get-entry',
            data: { 'id': id },
            success: function(entry, textStatus, jqXHR) {
                currentEntry = entry;
                currentEntry.id = id;

                container.append('<div class="_carouselCurrentContent" style="display: none;">'+entry.detailsHtml+'</div>');

                container.children('._carouselLoading').remove();
                container.children('._carouselCurrentContent').fadeIn(function() { });

                if(scroll)
                    _ensureVisible($('#entryDetailView'))
            }
        });
    }

    this.view = _view;

    function _scrollToLast()
    {
        var carousel = element.data('jcarousel');
        carousel.scroll(carousel.options.size, true);
    }

    this.scrollToLast = _scrollToLast;

    function _scrollToFirst()
    {
        var carousel = element.data('jcarousel');
        carousel.scroll(1, true);
    }

    this.scrollToFirst = _scrollToFirst;
}


