var CarouselWrapper_clickHandler = null;
var CarouselWrapper_carouselList = {};

function CarouselWrapper(params)
{
    this.list = [];
    this.callback = null;

    for (var p in params) {
      this[p] = params[p];
    }

    // We remove statically added items, to have unified behavior
    $("#"+this.id+" li").remove();
}

CarouselWrapper.prototype.AddItem = function(item) {

    this.list.push(item);

}

CarouselWrapper.prototype.ItemLoadCallback = function(carousel, state) { 

    for (var i = carousel.first; i <= carousel.last; i++) {

        if (carousel.has(i)) {
            continue;
        }

        if (i > this.list.length) {
            break;
        }

        var listIndex = i-1;

        // Funny way how to create DOM objects using jQuery
        var htmlObj = $('<img src="' + this.list[listIndex].url + 
              '" mf:index="' + listIndex +
              '" alt="' + this.list[listIndex].title + '" />').get(0);

        var oThis = this;
        $(htmlObj).click( function() { 
            oThis.callback(oThis.list, $(this).attr('mf:index'));
        });

        carousel.add(i, htmlObj);
    }

}

CarouselWrapper.prototype.Init = function(callback) {

    var oThis = this;
    this.callback = (callback?callback:CarouselWrapper_clickHandler);

    $(function() {
        var id = oThis.id;
        $('#'+id).jcarousel({
            scroll: oThis.scroll,
            size: oThis.size,
            initCallback: function(carousel) {
                CarouselWrapper_carouselList[id] = carousel;
            },
            itemLoadCallback: {
                onBeforeAnimation: function(carousel, state) { 
                    oThis.ItemLoadCallback(carousel, state) 
                }
            }
        });
    });
}

CarouselWrapper.getById = function(id) {
    return CarouselWrapper_carouselList[id];
}

CarouselWrapper.click = function(callback) {
    CarouselWrapper_clickHandler = callback;
}