/*
	Simple Jquery Carosuel plugin for siteworx
	Author:Yong Qui Zheng
	
	version 2:
	Auto scrolling, image dimension scaling
	Author:Patrick Armstrong

*/
var photoContainer;// just for temp because we need to use the photo array later
var xPos=0;
var xIndex=0;
var incrementAmount=0;
var swapTimer=-1; //this needs to be initialized to -1
var swapIndex=0;
var swapInterval=0;
var sCarousel = { };

(function($){

	window.sCarousel.preloadImages = function(photoBucket) {
		$.each(photoBucket, function(index) {
			loadImage(photoBucket[index].photoUrl);
		});
	}
	
	window.sCarousel.removePreloadedImages = function() {
		removeLoadedImages();
	}

	$.fn.sCarouselz =  function(photoBucket,options){
			
			if(!photoBucket || photoBucket.length==0)
			{
				return false;
			}
			//here we create the default setting
			
			var defaultSetting={
				useImageScroller:false,
				backArrow:"BACK",
				forwardArrow:"FOWARD",
				hasThumbNailPicture:false,
				swapInterval:5000
			};
			photoContainer=photoBucket; // setting the photo container for later use
			
			//extend the pass in option with the defaultSetting
			var settings=$.extend(false,defaultSetting,options);
			
			swapInterval = settings.swapInterval;
			
			//init the carousel
			$(this).each(function(){
				// the bottom code will generate the html markup for the carousel
				var carouselHtml=generateCarouselMarkUp(settings.useImageScroller,settings);
				$(this).html(carouselHtml);
				$(".forwardArrow").each(function(){
					$(this).click(function(){
						slideRight(false);
					});
				});
				
				$(".backArrow").each(function(){
					$(this).click(function(){
						slideLeft(false);
					}
					);
				});
				
				// the function below will set the wrapper's width
				initWrapperWidth();
				
				$("#tabs_highlights").hover(
					// clear the timer when the pointer is hover over the nav image
					function(){
						clearSwapTimer();
					},
					// start the timer when the pointer is out of the nav image
					function(){
						setSwapTimer();
					}
				);
				
				
			});
	
			if (photoContainer.length>1){
				setSwapTimer();
			}
			
	};
	
	//generating the carousel markup
	function generateCarouselMarkUp(useImageScroller,settings){
		if(!photoContainer)return;
		var j=0;
		var carouselMarkUp="<div class='carousel-highlight' id=>" + getHighlightHtml(0) + "</div>";
		carouselMarkUp += "<div class='carousel-nav-holder'>";
		if(useImageScroller){
			carouselMarkUp+="<div class='left'><a class='backArrow' href='javascript:void(0);'></a></div><div class='right'><a class='forwardArrow' href='javascript:void(0);'></a></div><ol id='scrollController'><div id='nav-wrapper'><ol class='innerList'>"
		}else{
			carouselMarkUp+="<div class='left'><a class='backArrow' href='javascript:void(0);'>"+settings.backArrow
							+"</div><div class='right'><a class='forwardArrow' href='javascript:void(0);'>"
							+settings.forwardArrow+"</a></div><ol id='scrollController'><div id='nav-wrapper'><ol class='innerList'>";
		}
		for(var i = 0;i<photoContainer.length;i++){
			if(!settings.hasThumbNailPicture){	
					if(j<3){
						carouselMarkUp+="<li><div class='contentContainer'><a><div class='imgContainer'><img src='"+photoContainer[i].photoUrl+"' " + getImageStyle(getOffscreenImageDimensions(photoContainer[i].photoUrl), 50, 50) + " class='carousel-thumbnail-image' onclick='swapImage("+i+
										", false)'></img></div></a><div><span><a href='javascript:swapImage("+i+", false)'>"+photoContainer[i].title+"</a></span></div></div></li>";
										j++;
					}
					if(j>=3){
						if(i==photoContainer.length-1){
							carouselMarkUp+="</ol>";
						}
						else{
							carouselMarkUp+="</ol><ol class='innerList'>";
						}
						j=0;	
					}
			}
			else{
				carouselMarkUp+="<li><a><img src='"+photoContainer[i].thumbNail+"' class='carousel-thumbnail-image'></img></a><div><span><a href='javascript:swapImage("+i+", false)'>"+photoContainer[i].title+"</a></span></div></li>";
			}
		}
		if(useImageScroller){
			carouselMarkUp+="</ol></div></div>";
		}else{
			carouselMarkUp+="</ol></div></div>";
		}
		return carouselMarkUp;
	};
	// a function that will set the width of the wrapper
	function initWrapperWidth(){
		if($(".contentContainer")==null)return;// if the content container is null just return
		// get the number of innerList
		var numOfEle=$(".innerList").length;
		// if there are no element than just return
		if(numOfEle==0)return;
		//getting the width of an innerList element
		var eleWidth=$(".innerList").width();
		// set the increment amount
		incrementAmount=eleWidth;
		// getting the total width
		var totalWidth=eleWidth * numOfEle;
		// setting the total width to the wrapper
		$("#nav-wrapper").width(totalWidth);
	};
	
})(jQuery);

	//The bottom function provide the sliding functionality for the carousel
	function slideLeft(autoSlide){
		if(xPos==0){
			xPos=$("#nav-wrapper").width()-incrementAmount;
			xIndex=Math.ceil(photoContainer.length/3)-1;
		}
		else
		{
			xPos-=incrementAmount;
			xIndex--;
		}
		setSwapIndexFromSlider(xIndex, autoSlide);
		$("#scrollController").animate({scrollLeft:xPos},1000);
		
	};
	// The bottom function provide the sliding functionality to the right for the carousel
	function slideRight(autoSlide){
		if(xPos>=$("#nav-wrapper").width()-incrementAmount){
			xPos=0;
			xIndex=0;
		}
		else
		{
			xPos+=incrementAmount;
			xIndex++;
		}
		setSwapIndexFromSlider(xIndex, autoSlide);
		$("#scrollController").animate({scrollLeft:xPos},1000);
		
	};
	//swapping images on click
	function swapImage(index, autoSwap){
		if (typeof autoSwap === "undefined")
		{
			autoSwap = true;
		}
		clearSwapTimer();
		if (swapIndex !== index)
		{
			swapIndex = index;
		}
		$(".carousel-highlight").html(getHighlightHtml(swapIndex));
		if (index % 3 === 0 && !isSliderCorrect())
		{
			slideRight(true);
		}
		if (autoSwap)
		{
			setSwapTimer();
		}
	}
	
	function getHighlightHtml(index)
	{
		index = index || 0;
		var containerWidth = 200;
		var containerHeight = 150;
		var imgUrl = photoContainer[index].photoUrl;
		var imgHtml = '<img src="'+imgUrl+'" ';
		imgHtml += getImageStyle(getOffscreenImageDimensions(imgUrl), containerWidth, containerHeight);
		imgHtml += ' />';
		return "<div class=\"carousel-highglight-img-container\">" + imgHtml + "</div><div class='carousel-rest' id='highlights_content_text'><div class='current-vol' id='highlights_content_text_date'>"+photoContainer[index].date+"</div><div class='title' id='highlights_content_text_heading'><a href='"+photoContainer[index].titleUrl+"'><strong>"
		+photoContainer[index].title+"</strong></a></div><div class='desc' id='highlights_content_text_teaser'>"+photoContainer[index].desc+"</div></div>";
	}
	
	function increaseCountAndSwap() {
		swapIndex++;
		if (swapIndex >= photoContainer.length)
		{
			swapIndex = 0;
		}
		swapImage(swapIndex);
	}
	
	function setSwapTimer() {
		if (swapTimer === -1)
		{
			swapTimer=setTimeout(function() { increaseCountAndSwap(); },swapInterval);
		}
	}
	
	function clearSwapTimer() {
		clearTimeout(swapTimer);
		swapTimer = -1;
	}
	
	function setSwapIndexFromSlider(sliderPos, autoSlide) {
		swapIndex = (sliderPos*3);
		if (!autoSlide)
		{
			swapIndex--;
		}
	}
	
	function isSliderCorrect() {
		var lowerBound = xIndex*3;
		var upperBound = lowerBound+2;
		
		if (swapIndex >= lowerBound && swapIndex <= upperBound)
		{
			return true;
		}
		return false;
	}
	
	function safeLog(msg) {
		if (typeof console === 'object' && typeof console.log === 'function')
		{
			console.log(msg);
		}
	}
	
	function getImageStyle(dimensions, containerWidth, containerHeight)
	{
		var imgStyle = "";
		var containerRatio = containerWidth/containerHeight;
		if (dimensions.width*containerRatio > dimensions.height)
		{
			var ratio = dimensions.width/containerWidth;
			imgStyle += 'style="width:'+containerWidth+'px; margin-top:'+Math.floor((containerHeight-(dimensions.height/ratio))/2)+'px;"';
		}
		else
		{
			var ratio = dimensions.height/containerHeight;
			imgStyle += 'style="height:'+containerHeight+'px; margin-left:'+Math.floor((containerWidth-(dimensions.width/ratio))/2)+'px;"';
		}
		return imgStyle;
	}
