var HomeGallery = {
	imageArr: null,
	current_img: 0,
	total_imgs: null,
	interval: null,
	timeOut: 5000,
	autoplay: true,
	
	init: function() {
		this.imageArr = $("div#home_gallery_wrap > div");
		this.total_imgs = this.imageArr.length - 1;
		this.setIndexes();
		this.showCount();
		var _this = this;
		if(this.autoplay == true){
			this.interval = setInterval(function() { _this.showNext(); }, _this.timeOut);
		}
	},
	
	setIndexes: function() {
		for(var i=0; i < this.imageArr.length; i++) {
			$(this.imageArr[i]).css("z-index", this.imageArr.length - i).css('opacity', 0).filter(":first").css('opacity', 1.0);
		}
	},
	
	showNext: function() {
		if(this.current_img < this.total_imgs) {
			// show next image behind
			$(this.imageArr[this.current_img + 1]).css('opacity', 1.0).css('display', 'block');
			// fade out current image
			$(this.imageArr[this.current_img]).fadeOut(800);
			// increment counter
			this.current_img++;
			this.showCount();
		} else {
			// fade in first image
			var _this = this;
			
			// reset counter
			_this.current_img = 0;
			_this.showCount();
			
			$(this.imageArr[0]).fadeIn(800, function() {
				// hide last image
				$(_this.imageArr[_this.imageArr.length-1]).css('opacity', 0);
			});
		}
	},
	
	showPrev: function() {
		if(this.current_img >= 1) {
			// show next image behind
			var _this = this;
			$(this.imageArr[this.current_img - 1]).fadeIn(800, function(){
			});
			// fade out current image
			$(this.imageArr[this.current_img]).fadeOut(800);
			
			// increment counter
			this.current_img--;
			this.showCount();
		} else {
			// fade in last image
			var _this = this;
			
			// reset counter
			_this.current_img = _this.total_imgs;
			_this.showCount();
			
			$(this.imageArr[this.imageArr.length-1]).css('opacity', 1.0).css('display', 'block');
			$(this.imageArr[0]).fadeOut(800, function() {
				// hide last image
			});
		}
	},
	
	showCount: function() {
		var _counter = $('span#gallery_current');
		var _current = this.current_img + 1;
		var _total = this.total_imgs + 1;
		_counter.text(_current + "/" + _total);
	}
}

// DOM ready Events
$(function() {

	if( $('div#home_gallery_wrap > div').length > 1 ) {
		HomeGallery.timeOut = "5000";
		HomeGallery.init();
		$('span#case_studies_navigator').fadeIn();
	}
	

	$('img#case_studies_next').click(function(){
		
			HomeGallery.showNext();
			//HomeGallery.showCount();
			clearInterval(HomeGallery.interval);
			HomeGallery.init();
		return false;
	});
	
	$('img#case_studies_previous').click(function(){
		
			HomeGallery.showPrev();
			//HomeGallery.showCount();
			clearInterval(HomeGallery.interval);
			HomeGallery.init();
		return false;
	});
	
});