;(function($) {
	/**
	 * Image Rotator plugin
	 * @param {Object} options
	 */
	$.fn.bannerRotator = function(options) {
		return this.each(function(){
			var $this = $(this);
			var banners = options.banners; // array
			var loaded = [];
			var total = banners.length; // total images length
			var duration = options.interval ? options.interval : 7000; // interval millisecond
			var cycleAnimId = 0;
			var currentIndex = 0; // current index
			var nextIndex = 0;
			var $loading = null;
			var autoRotate = true;
			var isLoading = false;
			
			$this.css({
				'position': 'relative'
			});
			
			function rotateItems() {
				clearInterval(cycleAnimId);
				
				if (loaded[nextIndex]) {
					animate();
				} else {
					if ($loading) {
						$loading.show();
					}
					$('<img />').load(function(event){
						isLoading = false;
						if ($loading) {
							$loading.hide();
						}
						loaded[nextIndex] = $(this);
						animate();
					}).attr('src', banners[nextIndex].image);
					isLoading = true;
				}
			}
			
			function animate() {
				// Create next banner item and prepend
				$nextBannerItem = createBannerItem(nextIndex);
				$this.prepend($nextBannerItem.hide());
				
				currentIndex = nextIndex;
				nextIndex++;
				if(nextIndex > (total - 1)) nextIndex = 0;
				
				// Clear last banner
				if ($this.find('.banner-item').length > 1) {
					$this.find('.banner-item:last').fadeOut('normal', function(event){
						$(this).remove();
					});
				}
					
				$nextBannerItem.fadeIn('normal', function(){
					if (total == 1) return;
					if (!autoRotate) return;
					cycleAnimId = setInterval(function(){
						rotateItems();
					}, duration);
				});
			}
			
			function createBannerItem(index) {
				var data = banners[index];
				
				// Setting up title
				var $title = '';
				if (data.strap_line != '') {
					$title = $('<div />').css({
						'position': 'absolute'
					}).addClass('banner-title')
					.append($('<h3 />').html(data.strap_line));
				}
				
				return $('<div />').css({
					'position': 'absolute',
					'cursor': 'pointer'
				}).addClass('banner-item').append($title).append(loaded[index]).hover(function(){
					$(this).addClass('over');
				}, function(){
					$(this).removeClass('over');
				}).click(function(event){
					if (data['target'] == '_blank') {
						window.open(data.link);
					} else {
						window.location = data.link;
					}
					return event.preventDefault();
				});
			}
			
			// Start rotating banners
			rotateItems();
		});
	}
})(jQuery);
