$(function() {
    $('.post > .post-body').each(function() {
        var ii = 0;
		
        $('img', this).each(function() {
            if (this.offsetWidth > 100 && $(this).attr('src')) {
                ii++;
            }
			var $t = $(this);
			title = $t.closest('.post').find('img').attr('title');
			$t.closest('.post').find('.description').html('<p>'+title+'</p>');		
        });

        if (ii > 2) {
            var ul = $('<ul class="galleria"></ul>').prependTo(this);
            var im = null;
            $('img', this).each(function() {

                if (this.offsetWidth > 100 && $(this).attr('src') && $(this).attr('class') !== 'single') {
                    var li = $('<li></li>').appendTo(ul);
                    var i = $('<img title="' + $(this).attr('title') + '" src="' + $(this).attr('src') + '">').appendTo(li).
                        click(function() {
                            $(im).attr('src', i.attr('src'));
							var $t = $(this);
							title = $t.attr('title');
							$t.closest('.post').find('.description').html('<p>'+title+'</p>');
                        });
                    if (!im) {
                        im = $('<img src="' + $(this).attr('src') + '" class="main">').insertBefore(ul);
                    }
                    $(this).remove();
                }  
            });
            $('<div class="clear"></div>').insertAfter(ul);
        }
    });
});
