var animationItemWidth = 0;

$.fn.homepopup = function () {
    var popup = this.eq(0);
    //overlay
    var overlay = $('<div id="homepopupOverlay"></div>');
    var bodyW = $(document).width();
    var bodyH = $(document).height();
    overlay.width(bodyW);
    overlay.height(bodyH);
    popup.before(overlay);
    //animacia na popup
    var desiredHeight = popup.height();
    popup.find('.homepopup, .close').hide();
    popup.height(1).show();
    popup.css({
        top: (($(window).height() - desiredHeight) / 2 + $(document).scrollTop()) + 'px',
        left: (($(window).width() - popup.width()) / 2 + $(document).scrollLeft()) + 'px'
    });
    popup.animate({
        height: desiredHeight + 'px'
    },{
        duration: 500,
        complete: function () {
            $(this).find('.homepopup, .close').show();
        }
    });
    popup.find('.close').click(function () {
        popup.hide();
        overlay.remove();
    });
    return this;
};

$(function () {
    //hlavne menu kategorii
    //klik na cely element LI
    $('#topcategorymenu li').css('cursor','pointer').click(function () {
        location.href = $(this).find('a').attr('href');
    });
    //animacia
    //nastavime sirku elementu animationData
    animationItemWidth = $('#animationData div.item:eq(0)').width();
    $('#animationData').width($('#animationData div.item').length * animationItemWidth);
    //hover na elementy LI (sipky a animacia obrazkov)
    $('#topcategorymenu li').hover(function () {
        $(this).addClass('hover');
        //animacia
        mainAnimationRun(this);
    },function () {
        $(this).removeClass('hover');
        var activeCategory = $('#topcategorymenu li.active:eq(0)');
        if (activeCategory.length) {
            mainAnimationRun(activeCategory);
        }
    });
    //zoskrolovanie animacie na prave aktivnu kategoriu
    var activeCategory = $('#topcategorymenu li.active:eq(0)');
    if (activeCategory.length) {
        mainAnimationRun(activeCategory, true);
    }
    
    //homepopup
    $('#homepopup').homepopup();
});

function mainAnimationRun(starter, noanim) {
    var regex = /([a-zA-Z]+)_([0-9]+)/;
    var match = regex.exec($(starter).attr('id'));
    if (match) {
        var index = $('#animationData div.item').index($('#topanimationItem_' + match[2]));
        var leftpos = -(index * animationItemWidth);
        if (noanim) {
            $('#animationData').stop().css('left', leftpos + 'px');
        } else {
            $('#animationData').stop().animate({
                left: leftpos + 'px'
            },{
                duration: 600,
                queue: false
            });
        }
    }
}