jQuery.fn.slideShow = function(options) {
    var options = jQuery.extend({
        speed: 1000,
        interval: 1000,
        block_width : 958,
        containerIdPagination: 'SlideShowPagination',
        containerClassPaginationItemDummy: 'slideShowPaginationItemDummy',
        containerClassPaginationItemActive: 'slideShowPaginationItemActive',
        containerClassPaginationItemDeactive: 'slideShowPaginationItemDeactive',
        containerIdPaginationImg: 'slideShowPaginationImg',
        containerIdBtnNext: 'BtnSlideShowNext',
        containerIdBtnPrev: 'BtnSlideShowPrev'
    }, options);


    return this.each(function() {
        var timeoutKeeper = false;
        /**
        * Vasylchenko Oleksii
        * 12.08.2011
        * Move images with given direction
        */
        var slideMove = function($active, $next, direction_prev, animateMode) {
            in_work = 2;

            if (direction_prev) {
                $width = options.block_width;
            }
            else {
                $width = -options.block_width;
            }
            if (animateMode) {
                var time_animate = options.speed;
            } else {
                var time_animate = 0;
            }
            $active.animate({left: $width}, time_animate, function() {
                $active.addClass('last-active').css({zIndex: 9});
                in_work -= 1;
                if (!in_work) {
                    if (timeoutKeeper) {
                        clearTimeout(timeoutKeeper);
                    }
                    timeoutKeeper = setTimeout(slideSwitch, options.interval);
                }
            });

            $next
                .addClass('active')
                .css({zIndex: 10})
                .css({left: -$width})
                .css({opacity: 1.0})
                .animate({left: 0}, time_animate, function() {
                    $active.removeClass('active last-active').css({zIndex: 8, opacity: 0});
                    in_work -= 1;
                    if (!in_work) {
                        if (timeoutKeeper) {
                            clearTimeout(timeoutKeeper);
                        }
                        timeoutKeeper = setTimeout(slideSwitch, options.interval);
                    }
                });

        }

        /**
        * Vasylchenko Oleksii
        * 12.08.2011 
        * Preparing images for pagination
        */
        var prepare_pagination_img = function () {
            $.each($('#' + options.containerIdPaginationImg).find('img'), function(i){
                pagination_img[i + 1] = $(this).attr('src');
            });
        }

        var pagination_img = Array();
        var in_work = false;
        var $slideShow = $(this);

        prepare_pagination_img();

        $slideShow.css({
            position: 'relative'
        });

        var $images = $slideShow.find('.img');

        // if there are no images
        if (!$images.size()) {
            return;
        }

        // if there are not enough images - we clone it
        var posInImages = 0;
        
        if ($images.size() <= 1) {
            $images.css('display', 'block');
            $('#' + options.containerIdPagination).hide();
            return;
        } else {
            while ($images.size() < 2) {
                $slideShow.append($images.eq(posInImages).clone());
                posInImages++;
                $images = $slideShow.find('.img');
            }
            
            $images.css({
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 8,
                opacity: 0,
                display: 'block'
            });

            var totalImages = $images.size();
            var loadedImages = 0;
            var started = false;
            // [2011.06.23 Art] 
            var $pagCont = $('#'+options.containerIdPagination);
            var $pagItemDummy = $('.'+options.containerClassPaginationItemDummy);
            var countInc = 0;

            $('<table cellpadding="0" cellspacing="0" style="margin: 0 auto;"><tr></tr></table>').appendTo($pagCont);
            $insidePagCont = $pagCont.find('tr');
            $slideShow.find('.img').each(function(){
                countInc++;
                $(this).attr('count', countInc);
                $pagItemDummy.clone().css('display', 'block').attr({'id':'Pagination'+countInc, 'countPag': countInc}).
                    css('background-image', 'url(' + pagination_img[countInc] + ')').
                    addClass(options.containerClassPaginationItemDeactive).
                    click(function(){
                        slideSwitch(false, $(this).attr('countPag'), $('.' + options.containerClassPaginationItemActive + ':first').attr('countPag') > $(this).attr('countPag'));
                    }).appendTo($insidePagCont).wrap('<td></td>');
            })

            // slideshow
            var slideSwitch = function(tmp, toNumber, direction) { //fromNumber) {
                if (!in_work) {
                    var animateMode = true;
                    var $active = $slideShow.find('.img.active');
                    
                    if ($active.length == 0) {
                        animateMode = false;
                        $active = $slideShow.find('.img:last');
                    }
                    // use this to pull the images in the order they appear in the markup
                    //var $next =  $active.next().length ? $active.next() : $slideShow.find('img:first');

                    if (typeof(toNumber) != 'undefined') {
                        if ($slideShow.find('.img[count='+toNumber+']').length) {
                            var $next =  $slideShow.find('.img[count='+toNumber+']');
                            // если тыцнули на текущую картинку, то ничего не делаем
                            if ($active.attr('count') == toNumber) {
                                return;
                            }
                        } else {
                            if ($active.next().length) {
                                var $next =  $active.next();
                            } else {
                                var $next =  $slideShow.find('.img:first');
                            }
                        }
                    } else {
                        var $next =  $active.next().length ? $active.next() : $slideShow.find('.img:first');
                    }
                    slideMove($active, $next, direction, animateMode);
                    // может делать неактивные сразу все пункты пагинации, для особо нетерпеливых, 
                    //    чтобы избежать залипание активного пункта меню
                    $('#'+options.containerIdPagination).find('[id^=Pagination]').removeClass(options.containerClassPaginationItemActive).
                        addClass(options.containerClassPaginationItemDeactive);
                    // -----
                    $('#Pagination'+$next.attr('count')).removeClass(options.containerClassPaginationItemDeactive).
                            addClass(options.containerClassPaginationItemActive);
                   
                }
            }

            // preloader
            $(this).find('img').load(function() {
                loadedImages++;
                if (loadedImages == totalImages && !started) {
                    started = true;
                    slideSwitch();
                }
            }).each(function() {
                if (this.complete) {
                    $(this).trigger("load");
                }
            });

            // [2011.09.01 Art] Добавил функционал двух кнопок PREV NEXT
            if ($('#'+options.containerIdBtnNext).length) {
                $('#'+options.containerIdBtnNext).click(function(){
                    slideSwitch();
                })
            }
            if ($('#'+options.containerIdBtnPrev).length) {
                $('#'+options.containerIdBtnPrev).click(function(){
                    var $active = $slideShow.find('.img.active');
                    if ($active.length == 0) {
                        $active = $slideShow.find('.img:last');
                    }
                    var count = $active.attr('count');
                    if (count == 1) {
                        // slideSwitch(false, totalImages, count);
                        slideSwitch(false, totalImages, true);
                    } else {
                        // slideSwitch(false, count-1, count);
                        slideSwitch(false, count-1, true);
                    }
                })
            }
            // end PREV NEXT

        }
    });
}



