(function($) {
    $.fn.cyclePictures = function() {
        var _matchedObj = this;
        var _container = this.first().parent();

        $('<a id="bannerLink" href=""><img id="soft_shadow_image" src="/images/prozrachnost.png"/></a>').insertBefore(this.first()).css({
            position: 'absolute',
            top: 0,
            left: 0,
			height: '199px',
			width: '817px',
            'z-index': '99999'
        });
        
        function _changeElements(index) {
            var next_index;
            if(index == (_matchedObj.length - 1)) {
                next_index = 0;
            } else {
                next_index = index + 1;
            }
            $(_matchedObj[next_index]).css({opacity: 0, display: 'block'});
            $(_matchedObj[index]).stop().animate({opacity: 0}, 1000, 'linear');
            $(_matchedObj[next_index]).stop().animate({opacity: 1}, 1000, 'linear');

            $("#bannerLink").attr('href', $(_matchedObj[next_index]).attr('href'));
            document.getElementById("bannerLink").title = _matchedObj[next_index].title;

            window.setTimeout(function() { _animateElement(next_index, index); }, 2000);
        }

        function _animateElement(index, previous_index) {
			if(previous_index != 'undefined') {
				$(_matchedObj[previous_index]).css({
												display:'none', 
												top: -$(_matchedObj[previous_index]).find("img").height() + 199 + 'px'
												});
			}
            $(_matchedObj[index]).css({
										display:'block', 
										top: -$(_matchedObj[index]).find("img").height() + 199 + 'px'
										});
            $(_matchedObj[index]).stop().animate({top: 0}, 8000, 'linear');

            setTimeout(function() {_changeElements(index);}, 9000);
        }
        
        function _init() {
			$(window).load(_start);
        }
        
        function _start() {
            _matchedObj.each(function() {
                $(this).css({
                                position: 'absolute',
                                left: 0,
                                top: -$(this).find("img").height() + 199 + 'px',
                                display: 'none'
                            });
            });
            _matchedObj.first().css('display', 'block');
            $("#bannerLink").attr('href', _matchedObj.first().attr('href'));
            setTimeout(function() {_animateElement(0);}, 2000);
        }
        _init();
        return false;
    };
})(jQuery);

