Ext.namespace("WCS");

WCS.Carousel = function(allImages, callback, config) {
	carouselScope = this;
    for (var i = 0; i < allImages.length; i++) {
        allImages[i].id = "carouselSeat" + i;
    }
	
    function getItemHTML(seat) {
    	var width = seat.width ? seat.width : 200;
    	var height = seat.height ? seat.height : 250;
    	if (config.textscroller == true) {
            return seat.text;
    	} else {
    		return '<img id="' + seat.id + '" src="' + seat.image + '" width="' + width + '" height="' + height + '" />';
    	}
    }
    
    function carousel_itemVisibleInCallback(carousel, item, i, state, evt)
    {
        // The index() method calculates the index from a
        // given index who is out of the actual item range.
        var idx = carousel.index(i, allImages.length);
        carousel.add(i, getItemHTML(allImages[idx - 1]));
        
		var seat = Ext.get(item.firstChild.id);
		if (seat) {
			seat.removeAllListeners();
			Ext.EventManager.on(seat, 'click', function(evt, obj) {
				var seatNum = parseInt(obj.id.replace("carouselSeat",""));
				carouselScope.getSeat(seatNum).onClick();
			});
		}
    };

    function carousel_itemVisibleOutCallback(carousel, item, i, state, evt)
    {
        carousel.remove(i);
    };

    this.createSeats = function(configSeats, callback) {

        var s = [];

        if (configSeats) {
            for (var i = 0; i < configSeats.length; i++) {
                var image = configSeats[i];
                s.push(new WCS.Carousel.Seat(image, callback));
            }
        }

        return s;
    };

    this.getSeat = function(i) {
        return seats[i];
    };
    
    this.getSeats = function() {
        return seats;
    };
    
    seats = this.createSeats(allImages, callback);
    jcarousel = jQuery('#mycarousel').jcarousel({
        vertical: config.vertical,
        auto: config.auto,
        wrap: config.wrap,
        animation: config.animation,
        easing: config.easing,
        scroll: config.scroll,
        visible: config.visible,
        itemVisibleInCallback: {onBeforeAnimation: carousel_itemVisibleInCallback},
        itemVisibleOutCallback: {onAfterAnimation: carousel_itemVisibleOutCallback}
    });
};

WCS.Carousel.Seat = function(image, callback) {
    this.image = image;
    this.callback = callback;
};

WCS.Carousel.Seat.prototype = {
    onClick: function() {
		// This creates the window in the same window manager as the shortcuts.
    	this.callback(this.image);
    }
};
