var chapterCarousel;
var chaptersIndex = {};

Ext.onReady(function() {

	// index chapters
	var i = 0;
	Ext.select('.chapter').each(function(chapterEl) {
		chaptersIndex[chapterEl.dom.title] = i++;
	});

	// create carousel
	chapterCarousel = new Ext.ux.Carousel('chaptersWrapper', {
		itemSelector: '.chapter'
		,hideNavigation: true
	});
	
	// wire chapters menu
	Ext.fly('chaptersMenu').select('a').on('click', function(e, target) {
		
		// cancel link
		e.stopEvent();
		
		// switch slide
		chapterCarousel.setSlide(chaptersIndex[target.title]);
	});
	
	// setup indicating selected chapter
	chapterCarousel.on('change', function(slide, index) {
		
		markChapterSelected(slide.select('.chapter').item(0));
		
	});
	
	// indicate initial chapter
	markChapterSelected(Ext.fly('chaptersWrapper').select('.chapter').item(0));

});



function markChapterSelected(chapter) {
	
	if(!chapter)
	{
		return false;
	}
	
	
	var chapterTitle = chapter.dom.title;
	var chapterLink = Ext.fly('chaptersMenu').select('a[title='+chapterTitle+']').item(0);
	
	if(chapterLink)
	{
		chapterLink.parent('li').radioClass('selected');
	}
	else
	{
		Ext.fly('chaptersMenu').select('li').removeClass('selected');
	}	
}
