// JavaScript Document
$(document).ready(function() {
	if(mobile_device)
	{	
		//mobiles just get the first image and no text.
		return;
	}
	if($('div#carouselSimple').length)
	{
		simpleCarousel = new WGC_CarouselSimple('div#carouselSimple','simpleCarousel',5000);
		simpleCarousel.loadCarousel();
	}

});


function WGC_CarouselSimple(carouselArea,carouselName,carouselInterval)
{
	this.carouselArea = carouselArea;
	this.carouselName = carouselName;
	this.carouselInterval = carouselInterval;
	this.currentIndex = 'x';
	this.timer;
	this.paused = false;
	this.intransition = false;
	this.navigation = false; // boolean for whether or not to use <> navigation
	this.image_width = false;
	this.image_height = false;
	this.button_width = false;
	this.slides = Array();
	this.images = Array();
	// analyze the div contents for a html li list of elements
	// for each li call the construct function to convert it into a slide
	this.loadCarousel = function()
	{

		this.debug('simple carousel library loaded');
		

		
		this.carouselAreaObj = $(this.carouselArea);	
		this.carouselAreaId = $(this.carouselArea).attr('id');
		
		if(!this.carouselAreaObj.length)
		{
			this.debug('carouselAreaObj can\'t be found');
			// no element? just die.
			return;	
		}	

		lis = $(this.carouselArea +' li');
	
		if(!lis.length)
		{
			this.debug('no list of items in carouselAreaObj');
			// no list of items? jsut die
			return;
		}
		
		$(this.carouselArea +' ul').remove();// remove the list, it ain't needed anymore
		
		// now loop through the list items and construct slides from them
		for(c=0;c<lis.length;c++)
		{
			li = $(lis[c]);
			this.constructSlide(li,c);
		}		
		
		this.constructCarousel();
		
		this.preloadSlide(0); // show the first slide			
	}
	this.constructCarousel = function()
	{
		

		style = '';
		if(this.image_width && this.image_height && this.button_width)
		{
			var width = (this.button_width*2)+this.image_width;
			style = ' style="width:'+width+'px;height:'+this.image_height+'px;"';
			$('#'+this.carouselAreaId).width(width+'px');
			$('#'+this.carouselAreaId).height(this.image_height+'px');
		}		
		
		html = '<div id="'+this.carouselAreaId+'Box" class="simple-carousel-box" onMouseover="'+this.carouselName+'.rotateStop()"  onMouseout="'+this.carouselName+'.rotateContinue()"'+style+'>';

		if(this.navigation)
		{
			style = '';
			if(this.image_width && this.image_height && this.button_width)
			{
				style = ' style="width:'+this.button_width+'px;height:'+this.image_height+'px;"';
			}				
			html += '<div class="nav back"'+style+'><a href="javascript:'+this.carouselName+'.rotateBack()"><span>Back</span></a></div>';
			html += '<div class="nav forward"'+style+'><a href="javascript:'+this.carouselName+'.rotateForward()"><span>Forward</span></a></div>';	
		}

		html += '</div>';
		
		this.carouselAreaObj.prepend($(html));	

		if(this.navigation)
		{
			// turn off the back nav as we are at the start.
			//this.toggleRotateBack(false);			
		}
	}
	this.constructSlide = function(ele,index)
	{
		img = ele.children('a').attr('rel');
		href = ele.children('a').attr('href');
		target = ele.children('a').attr('target');
		title = ele.children('a').text();
		text = ele.children('p').html();
		
		
		this.images[index] = img;

		this.debug('creating slide for '+ img);
		
		wintarget = '';
		
		if(target)
		{
			wintarget = ' target="'+target+'"';	
		}
		
		
		if(!href || href=='#')
		{
			href = false;
		}
		
		readmore = false;
		if(href && ele.children('a').hasClass('read-more'))
		{
			debug(index+ ' has a read more '+title);	
			readmore = true;
		}
		style = '';
		if(this.image_width && this.image_height)
		{
			style += 'width:'+this.image_width+'px;height:'+this.image_height+'px;';
		}
		if(this.button_width)
		{
			style += 'left:'+this.button_width+'px;';	
		}
		if(style.length)
		{
			style = ' style="'+style+'"'; 	
		}
		html = '<div class="slide" id="slide'+index+'"'+style+'>';
		
		if(href) html += '<a href="'+href+'"'+wintarget+' class="slide-image-link">';
		
		html += '<img src="'+img+'" title="'+title+'" class="slide-image" />';
		
		if(href) html += '</a>';
		
		html += '<div class="slide-copy gradient-background border-top-grey">';
		html += '<p>';
		
		html += text;
		
		if(href && readmore) html += '<br /><a href="'+href+'"'+wintarget+' class="read-more">Read more</a>';
		
		
		html += '</p>';
		html += '</div>';
		html += '</div>';
		
		this.slides[index] = html;
	}
	this.preloadSlide = function(index)
	{
		if(index == this.currentIndex)
		{
			this.debug('no point '+index+ ' is the same as '+this.currentIndex);
			return;
		}
		this.debug('preloading slide '+index);
		var _self = this;
		this.preLoadImages(
			 [
			 this.images[index]
			 ],function(){
				 // _self.debug('image preloaded '+_self.images[index]);

				  _self.transitionSlide(index);
				  		
			 }
		);
	}
	

	this.transitionSlide = function(nextIndex)
	{
		
		
		if(typeof carouselTimer == 'object')
		{
			carouselTimer.clearTimer();
		}
		else
		{
			clearTimeout(this.timer);// clear the timeout everytime otherwise we get timers flying off everywhere and it goes mad
		}
		this.debug('adding index '+nextIndex);
		$('div#slide'+this.currentIndex).css('z-index',5); // move current slide down in the z-index order
		$('div#'+this.carouselAreaId+'Box').append(this.slides[nextIndex]);// append the next slide on, it is invisible by default.
		$('div#slide'+this.nextIndex).css('z-index',7); // move the next slide up in the z-index order so we can fade it over the existing one.
		
		removeIndex = this.currentIndex;
		
		// fade the new slide in this.fadeInterval ms, when done remove the old one
		var _self = this;
		this.intransition = true;
		$('div#slide'+nextIndex).fadeIn(this.fadeInterval,function()
		{
			$('div#slide'+removeIndex).hide();
			$('div#slide'+removeIndex).remove();
			_self.intransition = false;
			_self.debug('removing index '+removeIndex);
		});
		
		this.currentIndex = nextIndex;
		this.rotateSlides();
	}	

	this.rotateSlides = function()
	{
		if(this.paused)
		{
			return;	
		}
		if(this.currentIndex == (this.slides.length-1))
		{
			var nextTimedIndex = 0;	
			this.debug('at the end');
		}
		else
		{
			var nextTimedIndex = this.currentIndex + 1;	
		}
		//this next bit should be made a bit more robust... 
		var _self = this;
		
		if(typeof carouselTimer == 'object')
		{
			this.debug('could be using the timer');	
			carouselTimer.addCallback(function(){_self.preloadSlide(nextTimedIndex);});
		}
		else
		{
			this.timer = setTimeout(function(){_self.preloadSlide(nextTimedIndex);}, this.carouselInterval);		
		}
	
		
		
	}
	this.rotateStop = function()
	{
		this.paused = true;

		if(typeof carouselTimer == 'object')
		{
			carouselTimer.clearTimer();
		}
		else
		{
			clearTimeout(this.timer);// clear the timeout everytime otherwise we get timers flying off everywhere and it goes mad
		}
	}
	this.rotateContinue = function()
	{
		this.paused = false;
		this.rotateSlides();
		//this.traceMsg('starting rotation');
	}	
	
	this.rotateBack = function()
	{
		if(this.intransition)
		{
			return;	
		}
		if(this.currentIndex  == 0)
		{
			this.debug('at the start, getting last index');

			this.preloadSlide(this.slides.length-1);
			return;	
		}
		this.preloadSlide(this.currentIndex-1);
	}
	this.rotateForward = function()
	{
		if(this.intransition)
		{
			return;	
		}
		if(this.currentIndex == (this.slides.length-1))
		{
			this.debug('at the end, setting first index');
			this.preloadSlide(0);
			return;	
		}
		this.preloadSlide(this.currentIndex+1);			
	}
	this.debug = function(msg)
	{
		debug(this.carouselName+':: '+msg);
	}
	this.useNavigation = function(bool)
	{
		this.navigation = bool;
	}
	this.setImageHeight = function(val)
	{
		this.image_height = val;
	}
	this.setImageWidth = function(val)
	{
		this.image_width = val;
	}
	this.setButtonWidth = function(val)
	{
		this.button_width = val;	
	}
	this.preLoadImages = function(imageList,callback) {
		var pic = [], i, total, loaded = 0;
		if (typeof imageList != 'undefined') {
			if ($.isArray(imageList)) {
				total = imageList.length; // used later
					for (i=0; i < total; i++) {
						pic[i] = new Image();
						pic[i].onload = function() {
							loaded++; // should never hit a race condition due to JS's non-threaded nature
							if (loaded == total) {
								if ($.isFunction(callback)) {
									callback();
								}
							}
						};
						pic[i].src = imageList[i];
					}
			}
			else {
				pic[0] = new Image();
				pic[0].onload = function() {
					if ($.isFunction(callback)) {
						callback();
					}
				}
				pic[0].src = imageList;
			}
		}
		pic = undefined;
	};	
}
