var GTimeout = 2000;
$(document).ready(function() {
	$('.fadeboxgallery').each( function() {
		new FadeBoxGallery($(this).attr('id'));
		})});

function FadeBoxGallery(ID){
	this.Opacity = 1;
	this.images = [];
	this.iCache = [];
	this.paused = false;
	this.bannerID = 0;
	this.container = ID;
	this.Timeout = 0;
	this.countdown = 4000;
	this.fadetime = 1000;
	var _me=this;
	var cache = [];
	
	this.rotate = function(){
		var _me=this;
		
		if(this.images.length < 2){
			return false;
			}
		if(this.bannerID >= this.images.length){
			this.bannerID = 0;
			}
		
		this.swap();
		this.bannerID++;
		this.Opacity = (this.Opacity) ? 0:1;
		var _me=this;
		this.Timeout = setTimeout(function() { _me.rotate() },this.countdown);
		}
	
	this.gotoID = function(BannerID){
		var _me=this;
		this.bannerID = BannerID;
		clearTimeout(this.Timeout);
		this.swap();
		this.Timeout = setTimeout(function() { _me.rotate() },this.countdown + 6000);
		this.Opacity = (this.Opacity) ? 0:1;
		return false;
		}
		
	this.swap = function(){
		var _me=this;
		this.highlightNav();
		i = this.bannerID;
		Opacity = this.Opacity;
		$('#'+this.container+' .imagebox div img').each( function() {
			var $$ = $(this);
			if(Opacity){ // Switch foreground image
				$$.attr('src',_me.iCache[i].src);
			}else{ // Switch background image
				$$.parent().css('backgroundImage','url("'+_me.iCache[i].src+'")');
				}
			$$.fadeTo(_me.fadetime,Opacity);
			});
		}
	
	this.highlightNav = function(){
		_me = this;
		
		$('#'+this.container+' .fadeboxnav a').each( function(i) {
			var $$ = $(this);
			if(i == _me.bannerID){
				$$.addClass( 'active' );
			}else{
				$$.removeClass( 'active' );
				}
			});
		}
	
	this.preload = function(){
		if(this.images.length < 1){
			return false;
			}
		for(i = this.images.length;i--;){
			this.iCache[i] = document.createElement('img');
			this.iCache[i].src = this.images[i];
			}
		}
	
	$('#'+this.container+' .fadeboxnav a').each( function(i) {
		var $$ = $(this);
		_me.images[i] = $$.attr('href');
		$$.click(function () { $$.blur(); return _me.gotoID(i); });
		});
	
	this.highlightNav();
	this.preload();
	this.Timeout = setTimeout(function() { _me.rotate() },GTimeout);
	
	GTimeout += 2000;
	}