/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
var openXGroupId = null;
var slides = new Array();
var isPaused = false;
var currentSlide = null;
var isSlideAnimating = false;
var carousel = null;

$(function() {
	if (openXGroupId != null) {
		loadBanners(openXGroupId);
	}
  }
);

function loadBanners(groupid, car) {	
	$.ajax({
		type: 'POST',
		url: '/default/carousel',
		dataType: 'json',
		data: {'openx_group_id': groupid},
		complete: function(req, textStatus) {
			if (textStatus == 'success') {				
				for( var idx=0; idx < slides.length; idx++) {
					var progressBarSelector = '#progressBar_'+slides[idx].position;					
					$(progressBarSelector).progressBar(
							0,
						{
							steps: 100,
							stepDuration: (slides[idx].timer * 10),
							max: 100,
							height: 3, 
							width: (slides[idx].position == slides.length ? slides[idx].tabWidth+6 : slides[idx].tabWidth),
							boxImage: '/images/spacer.gif',
							barImage: '/images/homepage/herocarousel/progressbg_orange_'+slides.length+'.gif', 
							showText: false,
							callback: function(data) {								
								var idparts = data.id.split('_');
								var slideidx = idparts[1]-1;
								if (!slides[slideidx].progressBarData) {
									
									//Initialize the slide with the appropriate
									//data instance.
									slides[slideidx].progressBarData = data;
									slides[slideidx].progressBarData.stopped = true;
									
									data.slide = slides[slideidx];
									if (slideidx == (slides.length-1)) {
										//We've initialized the last progressbar
										//so now initialize and show the carousel
										$("#mycarousel").jcarousel({
											auto:0, 
											start: 1, 
											animation:"slow",
											scroll:1,
											rtl:false,
											wrap:'both',
											itemVisibleInCallback: function(car, item, tidx, state) {
												isSlideAnimating = false;
											},
											initCallback: function(car) {
												carousel = car;
											},
											itemLoadCallback: function(car, state) {
												if (state != 'init') return;
												
												//Load the slides into the carousel
												for (var idx=0; idx<slides.length; idx++) {
													car.add(slides[idx].position, htmlSlide( slides[idx] ));
												}
												car.size( slides.length );
												
												//Raise the tab and start the timer of the first slide
												showSlide(slides[0], 'noop');
											}
										});
										
									}
								}
								
								if (data.running_value == data.value && !data.stopped) {
									if (!isPaused) {
										nextSlide();																			
									}									
								}
							}
						}		
					);
					
				}
				
				

				$('.previous-inactive').click(function(event) {
					event.preventDefault();
					previousSlide();
				});
				
				$('.next-inactive').click(function(event) {					
					event.preventDefault();
					nextSlide();
				}); 
					
			    $('.jcarousel-control a').click(function(event) {			    	
			    	event.preventDefault();
			    	if (!isSlideAnimating) { 
				    	hideSlide(currentSlide);
						var slideIdx = ((this.id).split('_'))[1];
						showSlide(slides[slideIdx-1]);
			    	}
				});

			}
			
		},
		success: function(jsonobj) {
			//load the html container for the carousel
			$('#home-hero').html( jsonobj.carouselContent );
			
			//Set the total width of the tabPanel so we can calculate
			//tab widths based on the number of slides.
			tabPanelWidth = jsonobj.tabPanelWidth;
			
			//Loop through the banners and create a linked list
			var myBanners = jsonobj.banners;
			for (var idx = 0; idx < myBanners.length; idx++) {
				var banner = myBanners[idx];
				if (idx == 0) {
					myBanners[idx].slidePrevious = myBanners[myBanners.length-1];
				} else {
					myBanners[idx].slidePrevious = myBanners[idx-1];
				}
				
				if (idx == myBanners.length-1) {
					myBanners[idx].slideNext = myBanners[0];
				} else {
					myBanners[idx].slideNext = myBanners[idx+1];
				}
				
				slides[idx] = myBanners[idx];
			}
			
		}});
	
}

function htmlSlide( slide ) {
	var assetType = (slide.asset.substring(slide.asset.lastIndexOf('.')+1)).toLowerCase();
	switch (assetType) {
		//TODO: support for swf and movie files
		case 'jpg':
		case 'gif':
		case 'png':
		default:
			var imgTag =  '<a href="'+slide.url+'"><img src="'+slide.asset+'" width="'+slide.width+'" height="'+slide.height+'" alt="'+slide.title+'" /></a>';
			//console.log('Loading img: '+imgTag);
			return imgTag;
	}
}


/*
 * Display the next slide in the carousel.
 */
function nextSlide() {
	if (!isSlideAnimating) { 
		if (currentSlide) {
			hideSlide(currentSlide);	
			//Display the nextslide	
			showSlide(currentSlide.slideNext, 'next');
		} else {
			currentSlide = slides[0];
			showSlide(currentSlide);
		}
	}
}

function previousSlide() {
	if (!isSlideAnimating) {
		if (currentSlide) {
			hideSlide(currentSlide);
			//Display the previuous
			showSlide(currentSlide.slidePrevious, 'prev');
		} else {
			currentSlide = slides[0];
			showSlide(currentSlide);
		}
	}
}

/*
 * Display the given slide
 */
function showSlide(slide, scrollto) {
	if (!isSlideAnimating) {
		currentSlide = slide;	
		
		//Raise the slide tab
		$('#banner_'+(slide.position)+' + .inner-bar').show();
		
		if (scrollto == 'noop') {
		} else if (scrollto == 'next') {
			isSlideAnimating = true;
			carousel.next();
		} else if (scrollto == 'prev') {
			isSlideAnimating = true;
			carousel.prev();
		} else {
			carousel.scroll(slide.position);
		}
		
		if (!isPaused) {
			//Set the current sldie to not stopped
			slide.progressBarData.stopped = false;
			//Start autoSlide timer
			var progressBarSelector = '#progressBar_'+slide.position;		
			slide.progressBarData.running_value = 0;
			$(progressBarSelector).progressBar(100);//when reloading the progressBar it calls back the nextSlide function.		
		}
	}
}

/*
 * Hide the given slide
 */
function hideSlide(slide) {
	//Set the progressBarData state to stopped
	slide.progressBarData.stopped = true;
	//stop the current slide's timer
	slide.progressBarData.value = slide.progressBarData.running_value;
	//Hide the slide tab
	$('#banner_'+(slide.position)+' + .inner-bar').hide();
}

/*
 * Stop auto slide timers
 */
function pauseAutoSlide() {
	isPaused = true;
	stopAll();
}

function stopAll() {
	for (var idx=0; idx < slides.length; idx++) {
		slides[idx].progressBarData.value = slides[idx].progressBarData.running_value;
	}
	isSlideAnimating = false;
}


/*
 * Play auto slide starting at the currentSlide
 */
function playAutoslide() {
	isPaused = false;
	if (currentSlide) { 
		showSlide(currentSlide);
	} else {
		showSlide(slides[0]);
	}
}

function togglePausePlay() {
	var clsname = $('#pause-play').attr('class');

	$('#pause-play').removeClass(clsname);
	if (clsname == 'pause-inactive') {
		$('#pause-play').addClass('play-inactive');
		pauseAutoSlide();
	} else {
		$('#pause-play').addClass('pause-inactive');
		$('#pause-play').css();
		playAutoslide();
	}
	
}



