(function (){
	jQuery.fn.galleryStandardController = function(){
		function repeat(str,n){
			return new Array(n+1).join(str);
		}
		return this.each(function(){
			var $wrapper = jQuery('> ul', this),
				$items = $wrapper.find('> li'),
				imagediv = jQuery('#galleryImage'),
				gallerybuttons = jQuery('#galleryButtons'),
				title = jQuery('#galleryImageTitle');
				//viewprojectbttn = jQuery('> #galleryImage a', this);
				slidePos = 0;
				initialise();
			//TASKS
			function initialise(){
				numimages = $items.length;
				animateIn(slidePos);
				initTimer();
				initControls();
			};
			function animateIn(which){
				resetbuttonstates(which);
				theitem = jQuery($items).get(which);
				imagealt = jQuery(theitem).find('> img').attr('alt');
				jQuery(title).html(imagealt);
				jQuery(theitem).fadeIn(500,function(){
					image = jQuery(theitem).find('> img').attr('src');
					
					//link = jQuery(theitem).find('> a').attr('href');
					imagediv.css('background-image','url(\''+image+'\')');
					//alert(imgtitle);
					jQuery(theitem).hide();
					
					//jQuery(viewprojectbttn).attr('href', link);
				});
			};
			function buttonMove(num){
				if(!isanimating()){
					//reset timers
					jQuery(document).stopTime();
					initTimer();
					slidePos = num;
					animateIn(num);
				}
			};
			//Function to check if there is any animation going on already
			function isanimating(){
				jQuery($items).each(function(index){
					checkitem = jQuery($items).get(index);
					animatingFlag = !(jQuery(checkitem).not(':animated').length);
					if(animatingFlag) return false;
				});
				if(animatingFlag){
					return true;
				}else{;
					return false;
				}
			};
			function initTimer(){
				jQuery(document).everyTime(6000, function(i) {
					if(!isanimating()){
						if(slidePos + 1 >= numimages){
							slidePos = 0;
						}else{
							slidePos += 1;
						}
						animateIn(slidePos);
					}
				});
			};
			function initControls(){
				jQuery($items).each(function(index){
					if(index==slidePos){
						jQuery('<li class="current"><a href="#"><!--  --></a></li>').appendTo(gallerybuttons);
					}else{
						jQuery('<li><a href="#"><!--  --></a></li>').appendTo(gallerybuttons);
					}
				});
				controls = jQuery(gallerybuttons).find('> li');
				jQuery(controls).each(function(index){
					anchor = jQuery(controls).find('> a').get(index);
					jQuery(anchor).click(function(){
						buttonMove(index);
						return false;
					});
				});
			};
			function resetbuttonstates(){
				$buttons = jQuery(gallerybuttons).find('> li');
				jQuery($buttons).each(function(index){
					button = jQuery($buttons).get(index);
					if(index == slidePos){
						jQuery(button).addClass('current');
					}else{
						jQuery(button).removeClass('current');
					}
				});
			};
			window.animateIn = buttonMove;
		});
		
	};
})(jQuery)

