(function($) {
    $.fn.imagegallary = function() {
        this.each(function() {
            /* клонируем картинки */
            var thmb = $('#imagegallary_images').clone();
            var imagenum = thmb.find('img').length;

            /* если одна картинка, то нисего не делаем */
            if (imagenum <= 1)
                return false;
            
            /* меняем картинки на тумбы */
            thmb.find('img').each(function(){
                $(this)
                    .attr('src', $(this).attr('src').replace('type/1','type/2'))
                    .bind('click', function (){
                        return clickThumb(this);
                    });
            })

            /* прячем картинки */
            $('#imagegallary_images img').hide();
            $('#imagegallary_images img').first().show();
			
			/* панель для просмотра тумбов */
            $(this).append(
                $('<div>').attr('id','imagegallary_thumbs')
                .append(
                    $('<div>').attr('id','imagegallary_thumbs_inner')
                    .append(
                        $(thmb).attr('id','imagegallary_thumbs_inner_scroll')
                    )
                )
            );
			$('#imagegallary_thumbs_inner_scroll img').first().click();
        });
        return this;
    };

    function clickThumb(obj) {
		$('#imagegallary_thumbs_inner_scroll .select').removeClass('select');
		$(obj).parent().addClass('select');
        $('#imagegallary_images img[src$=type/1]:visible').hide();
        $('img[src="'+$(obj).attr('src').replace('type/2','type/1')+'"]').show();
        return false;
    }

    function scroll(obj, str){
        if ($(obj).hasClass('disabled'))
            return false;
        var top;
        top = parseInt($('#imagegallary_thumbs_inner_scroll').css('top'));
        if (str == 'down'){
            top -= 67;
            $('#imagegallary_thumbs_inner_scroll').css('top',top);
            $('#imagegallary_thumbs_up').removeClass('disabled');
            if (-top/67+3 == $('#imagegallary_thumbs_inner_scroll img').length){
                $('#imagegallary_thumbs_down').addClass('disabled');
            }
        }
        else if (str == 'up'){
            top += 67;
            $('#imagegallary_thumbs_inner_scroll').css('top',top);
            $('#imagegallary_thumbs_down').removeClass('disabled');
            if (top == 0){
                $('#imagegallary_thumbs_up').addClass('disabled');
            }
        }
        return false
    }
})(jQuery);
