/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var homepage = {
	
	
	totalImages: 0,
	currentImg: 0,
	waitingImg: null,
	galleryInterval: 5000,
	galleryFade: 500,
	galleryTimeout: null,
		
	start: function() {
		
		// get a count of the images
		homepage.totalImages = $('#galleryImages li').length;
		
		// kick off the image rotation
		homepage.galleryTimeout = setTimeout( 'homepage.galleryRotate()', homepage.galleryInterval );
		
		// bind the gallery nav
		$('#galleryNav a').bind( 'click', function() {
			var selectedNav = $(this).parent().attr('id').substr(5);
			
			if ( homepage.waitingImg == null ) {
				
				clearTimeout( homepage.galleryTimeout );
				homepage.waitingImg = selectedNav;
				homepage.gallerySwitch();
								
			}
		});
		
		homepage.startCarousel();
		
	},
	
	startCarousel:function() {
		
		var liFbWidth = ( common.confirmPageSize() ? 200 : 184 ) ;
		
		if ( $('#carouselNext').length ) {
			
			// remove carousel lite before applying it
			$("#carouselContainer div").jCarouselLite = null;
			$('#carouselNext').unbind('click');
			$('#carouselPrev').unbind('click');
			
			$("#carouselContainer div").jCarouselLite({
					initCallback: 'reset',
					btnNext: "#carouselNext",
					btnPrev: "#carouselPrev",
					speed: 700,
					visible: 5,
					liWidth: liFbWidth,
					liHeight: 117
				});
		}
		
	},
	

	/**
	 * Selects the next image on the stack and kicks off the fade
	 */
	galleryRotate: function() {
		
		homepage.waitingImg = homepage.currentImg + 1;
		if ( homepage.waitingImg >= homepage.totalImages ) homepage.waitingImg = 0;
		
		homepage.gallerySwitch();
				
	},
	
	/**
	 * Switch the previous and next images and resets the waitingImg variables
	 * and resets all the classes
	 */
	gallerySwitch: function() {
		
		$('#galleryImages .selected').addClass('previous').removeClass('selected');
		
		// hide the waiting image 
		$('#gimg_' + homepage.waitingImg)
			.css({ 
				opacity:	0 
			})
			.addClass('selected')
			.animate({
					opacity: 1
				}, 
				homepage.galleryFade,
				function() {
					
					homepage.currentImg = homepage.waitingImg;
					
					$('#galleryNav .selected').removeAttr('class');
					$('#gnav_' + homepage.currentImg).addClass('selected');
					
					homepage.waitingImg = null;
					
					$('#galleryImages .previous').removeAttr('class');
					
					homepage.galleryTimeout = setTimeout(
						'homepage.galleryRotate()', 
						homepage.galleryInterval 
					);

				});

		
	}
	
	
	
	
	
};



$(homepage.start);
$(window).resize(homepage.startCarousel);
