// JavaScript Document


// the speed of the logo scroller, number of miliseconds per pixel of logo..
// bigger numbers = slower scrolling.
LOGO_SCROLL_SPEED = 22;

// the type of animation fot the scroll - either 'swing' or 'linear'
LOGO_SCROLL_TYPE = "swing";

// miliseconds taken to fade each stage of the quote
QUOTE_FADE_SPEED = 2800;


// miliseconds taken to fade each stage of the quote
PRODUCT_FADE_SPEED = 2800;
// the time that each product image is shown for before it starts to fade out again
PRODUCT_FADE_DELAY = 5000;



jQuery( function($) {		// wrap it all in JQuery in case we called this function before the page is ready...
		
		var debug = false;
		var logosContainer = $("#homeClientLogos");
		var logosScrollingContainer = $('<div id="scrollingContainer"></div>');
		
		logosContainer.bind("allImagesLoaded", fillScroller);
		logosContainer.bind("scrollFinished", scrollLogos);
		
		$(window).bind("quoteStart", fadeQuote);
		$(window).trigger("quoteStart");
		

		var logosLoadingCount=0;
		
		$.ajax({
			url:		"/cgi-bin/home.pl",		
			data:		{
							com			:	"getHomeInfo"
						},
			dataType:	'json',
			success:	function (data, textStatus) {
								
								var logos =data.logos;
								
								$(logos).each(function() {
								   logosLoadingCount++;
									var img = $('<img src="' + this.src + '">').one("load", logoLoaded);
									var imgLink = $('<a href="' + this.link + '" class="imageLink"></a>');
									
								 	var logoContainer = $('<div class="scrollingLogo"></div>').append(imgLink.append(img));
									logosScrollingContainer.append(logoContainer);
								});
								
								
								logosContainer.append(logosScrollingContainer);
						
							
								startProductImages(data.productImages);
								
								
						},
			error:		function (request) {if (debug) {alert("error fetching logos list" + request.responseText )}},
			complete:	function () {}
		});
		
	
		
		function fillScroller() {
			//console.log("filling scroller...");
			// make sure that there are enough logos to fill the scroller
			var containerWidth = logosContainer.outerWidth();
			var overlapRequired = 200;
			var logosWidth = logosScrollingContainer.outerWidth();	// figure out how wide our current logos are...
			
			if (logosContainer.children().length < 1) {				// stop now if we don't actually have any logos
				return false;	
			}
			
			indexToCopy=0;
			while ((logosWidth - overlapRequired) < containerWidth) { // duplicate the start of the list until we have a wide enough set of logos to fill the space + overlap
				//console.log(logosWidth);
				var toClone = logosScrollingContainer.children().eq(indexToCopy);
				logosWidth += toClone.outerWidth();
				logosScrollingContainer.css("width", parseInt(logosScrollingContainer.css("width")) + toClone.outerWidth() + "px");
				logosScrollingContainer.append(toClone.clone());
				indexToCopy ++;
			}

			logosContainer.trigger("scrollFinished");
		}
		
		
		function logoLoaded() {
			// we have to keep track of logo images loading, as they are loaded ofter the DOM is ready
			// if we try to scroll before the images have loaded we don't know how wide they are.
			logosLoadingCount--;	// reduce the count of logos that re loading...
			
			// increase the width of the logos container by the width of the container for this logo - prevents wrapping
			logosScrollingContainer.css("width", parseInt(logosScrollingContainer.css("width")) + $(this).parents(".scrollingLogo").outerWidth() + "px");
			
			if (logosLoadingCount ==0) {	// they are all here!
				logosContainer.trigger("allImagesLoaded");	// trigger the event to start the scrolling
			}
			
			
		}
		
		
		function scrollLogos() {
			var leftLogo = logosScrollingContainer.children("div:first");
			var distance = leftLogo.outerWidth();
		
			var time = parseInt(distance * LOGO_SCROLL_SPEED);
			
			logosScrollingContainer.animate(
							{left:"-=" + distance + "px"},
							time,
							LOGO_SCROLL_TYPE,
							function() {
								var leftLogo = logosScrollingContainer.children("div:first");	// the logo we just scrolled off the screen
								logosScrollingContainer.append(leftLogo.clone());				// add a copy of the removed logo to the right of the list
								
								logosScrollingContainer.css("left", "0px");						 // move the scrolling box back to the original position
								leftLogo.remove();
								logosContainer.trigger("scrollFinished");	// trigger the event to scroll some more
								
							}
			);
		}
		
		
		
		function fadeQuote() {
			
			var quote = $("#quote");
			var quoteName = $("#quoteName");
			quote.css("background-position", "0px 0px")	// move to part 1
			quote.fadeIn(QUOTE_FADE_SPEED,function() {				// fade in part one
				quote.fadeOut(QUOTE_FADE_SPEED, function(){			// fade out part one
					quote.css("background-position", "-240px 0px")	// move to part 2
					quote.fadeIn(QUOTE_FADE_SPEED,function() {			// fade in part 2
						quote.fadeOut(QUOTE_FADE_SPEED, function(){		// fade out part 2
							quote.css("background-position", "-480px 0px")	// move to part 3
							quote.fadeIn(QUOTE_FADE_SPEED,function() {			// fade in part 3
								quoteName.fadeIn(QUOTE_FADE_SPEED, function(){		// fade in Oscar Wilde
										quote.fadeOut(QUOTE_FADE_SPEED);			// fade out part 3
										quoteName.fadeOut(QUOTE_FADE_SPEED, function(){	// fade out Oscar
											$(window).trigger("quoteStart"); 			//start over
										});										 
								});
							})	
						});
					})
				})
			});
		}
		
		
		
		
		/* ========================================
		Relating to fading product images
		 ========================================*/
		
		var p1 = $('<div class="featuredProductImage" id="featuredProduct1"><img src=""></div>').fadeOut(1);
		var p2 = $('<div class="featuredProductImage" id="featuredProduct2"><img src=""></div>').fadeOut(1);
		$("#productImages").append(p1).append(p2);
		
		
		function startProductImages(productImages) {
			//[{src:imgSource}, {src:imgSource}, {src:imgSource}]
	
			if (productImages.length <=0) {
				return false;
			}
			
			var nextImageIndex = 0;
			populateProduct1();
			populateProduct2();
			fadeProduct2(1000)
		
			function getNextImageSrc() {
				var toReturn = productImages[nextImageIndex].src;
				nextImageIndex++;
				if (nextImageIndex > (productImages.length-1)) {
					nextImageIndex=0;
				}
				return toReturn;
			}
			
			function populateProduct1 () {
				$("#featuredProduct1 img").attr("src", getNextImageSrc());
			}
						
			function populateProduct2 () {
				$("#featuredProduct2 img").attr("src", getNextImageSrc());
			}
			
			function fadeProduct1() {
				setTimeout(
					function() {
						
						$("#featuredProduct1").fadeOut(PRODUCT_FADE_SPEED, function (){ populateProduct1(); fadeProduct2() } );
						$("#featuredProduct2").fadeIn(PRODUCT_FADE_SPEED);
					},
					PRODUCT_FADE_DELAY
				);
			}
			
			function fadeProduct2(newDelay) {
				setTimeout(
					function() {
						$("#featuredProduct2").fadeOut(PRODUCT_FADE_SPEED, function (){ populateProduct2(); fadeProduct1() } );
						$("#featuredProduct1").fadeIn(PRODUCT_FADE_SPEED);
					},
					newDelay || PRODUCT_FADE_DELAY
				);
			}
			
		
		}
		 
	
		
});	// end of jquery ready


