$(document).ready(function() {
    var load_image_data = function(carousel, data_container, image_container) {
        var total = $('.total', data_container).text();
        carousel.size(total);
        data_container.children('.photo').each(function(each_idx) {
            var idx = parseInt($("span.idx", this).text());
            var photo = $("img", this);
            if (carousel.has(idx)) return true;
            if ((idx < carousel.first) || (idx > carousel.last)) return true;
            var cropp = $('.cropped', this).text();
            var cropp_th = $('.croppedthumbnail', this).text();
            var full_img = $('.big', this).text();
            var item = $('<img src="'+cropp_th+'" />');
            var full_item = $('<a href="'+ full_img +' "><img src="'+cropp+'"/></a>');
            var tthis = this;
            item.click(function() {
                image_container.unbind('click');
                image_container.html(full_item);
                image_container.click(function(event) {
                    event.preventDefault();
                    var link = $('a', tthis);
                    var t = link.attr('title') || null;
		    var a = link.get(0).href;
                    var g = 'gallery';
                    tb_show(t,a,g);
                    tthis.blur();
                    return false;
                });
            });
            if (idx == 1) item.click();
            carousel.add(idx, item);
        });
    };
    $('.activateCarousel').each(function() {
        var $thisActivator = $(this);
        var $imageContainer = $('.bigPhoto', this);
        var $carouselContainer = $('.carouselContainer', this);
        var load_cbk = function(carousel, state) {
            if (carousel.has(carousel.first, carousel.last)) return;
            var temp_car = $('.temporaryCar', $thisActivator);
            load_image_data(carousel, temp_car, $imageContainer);
            /* I commented it out to prevent from infinitive photos loading */
        };
        var carousel_options = {
            //'size': 5, // The number of total items.
            'scroll': 2, // The number of items to scroll by.
            /*
            'visible': 3, // If passed, the width/height of the items will be calculated and set depending on the width/height of the clipping, so that exactly that number of items will be visible.
            */
            'itemLoadCallback': load_cbk
        };
        $carouselContainer.jcarousel(carousel_options);
    });
});

