var carousel = function(){
  return {
		MODE_IDLE: 0,
		MODE_SLIDESHOW: 1,
		MODE_COURSE_SELECT: 2,
		MODE_MAP: 3,
		MODE_COURSE_DETAIL: 4,
		mode: 0,
		initialised: false,
		locked: false,
		slideLocked: false,
		coursesImgFade: true,
		safeTop: 500,
		launchTop: 0,
		items: [],
		slidePos: 0,
		slideDelay: 9000,
		categoryTemplate: new Ext.Template(
      '<div style="left:{left}px;top:{top}px" class="carousel">',
			  '<img src="{src}" />',
				//'<div class="carousel-info"><div class="bg-carousel-info"></div><div class="carousel-info-text">{info}</div></div>',
				'<div class="carousel-block">',
					//'<a href="/'+LANG+'/portfolio/browse/{url}/" class="jump">VIEW</a>',
			    '<div class="carousel-name">{name}</div>',
					'<div class="carousel-strapline">{strapline}</div>',
				'</div>',
			'</div>'
    ),
		
		imgPreloadTpl: new Ext.Template(
      '<img class="hide" src="{src}" />'
    ),		
		
		carouselNavItem: new Ext.Template(
      '<div class="carousel-nav-item pos-{pos}">{name}</div>'
    ),
		
		locationNavItem: new Ext.Template(
      '<div class="carousel-nav-item location pos-{pos}">{name}</div>'
    ),
		
		mapRegionTemplate: new Ext.Template(
      '<div class="map-region" style="top:{top}px;left:{left}px;width:{width}px;height:{height}px">',
			  '<div class="map-region-bg"></div>',
			'</div>'
    ),
		
		mapLocationTemplate: new Ext.Template(
      '<div class="map-location" style="top:{top}px;left:{left}px;width:{width}px;height:{height}px"></div>'
    ),
		
		mapInfoTemplate: new Ext.Template(
      '<div class="region-name map-info-element">{translation_text}</div>'
    ),
		
		locationListItemTemplate: new Ext.Template(
      '<div class="location map-info-element">',
			  '<div class="onclick-toggle map-info-location">{name}</div>',
				'<div class="toggle-content-wrapper">',
				'<div class="location-course-list toggle-content"></div>',
				'</div>',
			'</div>'
    ),
		
		courseListElementTemplate: new Ext.Template(
      '<a href="{href}" class="course map-list-element dark link-small">{name}</a>'
    ),
		
		coursesWrapperTemplate: new Ext.Template(
      '<div class="courses-wrapper"></div>'
    ),
		
		courseTemplate: new Ext.Template(
      '<a href="/'+LANG+'/courses/{url}" class="carousel-course">{name}</a>'
    ),
		
		slideImageTemplate: new Ext.Template(
      '<img class="slide-image" src="{src}" />'
    ),
		
		slideNavTemplate: new Ext.Template(
      '<div class="slide-nav-item"></div>'
    ),
		
		heights: {
		  slideshowMode: 385,
			courseSelectMode: 247,
			mapMode: 495,
			courseDetailMode: 385
		},
		
		positions: [
		  {top: 6, left: 6},
			{top: 6, left: 335},
			{top: 6, left: 665},
			{top: 110, left: 6},
			{top: 110, left: 335},
			{top: 110, left: 665},
			{top: 211, left: 6},
			{top: 211, left: 335},
			{top: 211, left: 665}
		],
		
		setMode: function(mode){
			if(this.locked == true) return;
		  this.mode = mode;
			if(this.initialised == true){
				Ext.select('.carousel-nav-item').removeClass('selected');
				switch(mode){
			    case this.MODE_COURSE_DETAIL:
				    this.initCourseDetailMode(); break;
					case this.MODE_COURSE_SELECT:
				    if(this.courseSelectModeInitialised != true){
						  this.setSport(this.sports[0]);
						} else {
						  this.initCourseSelectMode();
						}
						
						break;
					case this.MODE_MAP:
				    this.initMapMode(); break;
				  case this.MODE_SLIDESHOW:
			    default:	
				    this.initSlideshowMode(); break;				
				}
			}
		},
		
		setItems: function(items){
		  this.items = items;
			this.initMainNav();
		},
		
		setSlides: function(slides){
		  this.slides = slides;
			this.slideWrapper = Ext.get('slide-wrapper');
		},
		
		setRegions: function(regions){
		  this.regions = regions;
			//this.locationsWrapper = Ext.get('locations-wrapper');
		},
		
		initMainNav: function(){
		  this.sports = [];
			for(var i=0;i<this.items.length;i++){
				this.sports[i] = this.carouselNavItem.append(Ext.get('carousel-nav'), {pos: i, name: this.items[i].name}, true);
				this.sports[i].data = this.items[i];
				this.sports[i].on('click', function(){carousel.setSport(this);});
			}
			this.locationNavEl = this.locationNavItem.append(Ext.get('carousel-nav'), {pos: i+1, name: 'location'}, true);
			this.locationNavEl.on('click', function(){carousel.setMode(carousel.MODE_MAP)});
			this.slideNavEl = this.locationNavItem.append(Ext.get('carousel-nav'), {pos: i+2, name: 'photos'}, true);
			this.slideNavEl.on('click', function(){carousel.setMode(carousel.MODE_SLIDESHOW)});
			this.mainNavItems = Ext.select('.carousel-nav-item');
		},
		
		lock: function(){
		  this.locked = true;
		},
		
		unlock: function(){
		  this.locked = false;
		},
		
		showLockedAlert: function(){
		  //this.wrapper.highlight();
		},
		
		init: function(){
			// get all the relevant elements
			this.carouselWrapper = Ext.get('carousel');
			
			this.contentsWrapper = Ext.get('carousel-contents-wrapper');
			this.mapWrapper = Ext.get('map-wrapper');
			this.slideshowWrapper = Ext.get('slide-wrapper');
			this.modeWrappers = Ext.select('.carousel-mode-wrapper');
			// to cover up the carousel if they mouseover the main navigation
			//this.setNavHandler();
			this.imgPreload.defer(4000, this);
			// this here?
			//Ext.get('revert-to-sport').on('click', this.revertToSport, this);
			
			this.initialised = true;
			this.setMode(this.mode);
		},
		
		imgPreload: function(){
		  for(var i=1;i<this.slides.length;i++){
			  this.imgPreloadTpl.append(Ext.getBody(), {src: this.slides[i].src});
			}
		},
		
		setNavHandler: function(){
			this.coverEl = Ext.get('carousel-cover');
			this.coverEl.setVisibilityMode(Ext.Element.DISPLAY);
		  Ext.get('main-nav').hover(this.showCover, this.hideCover, this);
		},
		
		showCover: function(){
		  Ext.fly('carousel-cover').fadeIn({duration: .3, endOpacity: .65, stopFx: true});
		},
		
		hideCover: function(){
		  Ext.fly('carousel-cover').fadeOut({duration: .2, stopFx: true});
		},
		
		resetPositions: function(el){
			
			if((this.mode != this.MODE_SLIDESHOW) && (this.slides.length > 1)){
				this.stopSlideshow();
			}
			this.modeWrappers.setTop(this.safeTop);
			el.setTop(this.launchTop);
		},
		
		setDisplayBase: function(el, height){
			this.modeWrappers.fadeOut({duration: .2});				
		  this.carouselWrapper.setHeight(height, {duration: 1, easing: "easeBothStrong"});
		  (function(el){this.resetPositions(el);el.fadeIn({duration: .5, stopFx: true});}).defer(1000, this, [el]);
		},
		
	
	
	
	
	
	
		
		
		// slideshow mode
		
		initSlideshowMode: function(){
		  this.setDisplayBase(this.slideshowWrapper, this.heights.slideshowMode);
			this.mainNavItems.removeClass('selected');
			this.slideNavEl.addClass('selected');
			
			if(this.slideshowInitialised != true){
				this.slideCaptionWrapper = Ext.get('slide-caption-wrapper');
				this.slideCaptionElement = Ext.get('slide-caption');
				
				Ext.get('slide-info').hover(this.stopSlideshow, function(){this.slideshowFirstRun = true;this.runSlideshow();}, this);
				this.slideInfoContentEl = Ext.get('slide-info-help-content');
			  this.mainSlide = this.slideImageTemplate.insertFirst(this.slideshowWrapper, this.slides[0], true);
				this.setSlideCaption(this.slides[0]);
				this.slideInfoContentEl.update(this.slides[0].image_note);
				
				if(this.slides.length > 1){
					this.backSlide = this.slideImageTemplate.insertFirst(this.slideshowWrapper, this.slides[1], true);
				  this.hasMultipleSlides = true;
					// show the navigation
					this.slideNav = [];
					for(var i=0;i<this.slides.length;i++){
						this.slideCaptionWrapper.hover(this.stopSlideshow, function(){this.slideshowFirstRun = true;this.runSlideshow();}, this);
						this.slideNav[i] = this.slideNavTemplate.append(Ext.get('slide-nav'), {}, true);
						this.slideNav[i].data = this.slides[i];
						this.slideNav[i].pos = i;
						this.slideNav[i].on('click', function(){carousel.userSetSlide(this);});
					}
					Ext.select('.slide-nav-item').removeClass('selected');
			    this.slideNav[this.slidePos].addClass('selected');
				  this.slidePos = 1;
				  this.slideshowInitialised = true;	
				  this.currentSlide = this.mainSlide;
				  this.hiddenSlide = this.backSlide;
				}
				
			}
			this.slideshowFirstRun = true;
			if(this.slides.length > 1){
				//alert(this.slides.length);
				this.runSlideshow();
			}
		},
		
		stopSlideshow: function(){
			if(!this.slideshowAuto) return;
		  Ext.TaskMgr.stop(this.slideshowAuto);
			this.slideshowRunning = false;
		},
		
		setSlideCaption: function(slide){
			if(slide.caption){
			  (function(slide){
			    this.slideCaptionElement.update(slide.caption);
					this.slideCaptionWrapper.dom.href = slide.href;
					this.slideCaptionWrapper.fadeIn({duration:.5});
					
			  }).defer(1, this, [slide]);
			}
		},
		
		runSlideshow: function(){
			if(this.slideshowRunning == true || this.slideshowLocked == true || this.slides.length < 2) return;
			this.slideshowAuto = Ext.TaskMgr.start({
        run: this.nextSlide,
				scope: this,
        interval: this.slideDelay
      });
		  this.slideshowRunning = true;
		},
		
		
		nextSlide: function(){
			if(this.slideshowFirstRun == true){
			  this.slideshowFirstRun = false;
				return;
			}
			if(this.slideshowLocked == true || this.slides.length < 2) return;
			if(this.slideNav){
				Ext.select('.slide-nav-item').removeClass('selected');
			  this.slideNav[this.slidePos].addClass('selected');
			}
			this.slideCaptionWrapper.fadeOut({duration:.25});
			this.slideshowLocked = true;
			if(this.currentSlide == this.mainSlide){
			  this.mainSlide.fadeOut({duration: 1});
				this.hiddenSlide = this.mainSlide;
				this.currentSlide = this.backSlide;
			} else {
			  this.mainSlide.fadeIn({duration: 1});
				this.hiddenSlide = this.backSlide;
				this.currentSlide = this.mainSlide;
			}
			(function(){
				this.setSlideCaption.defer(100, this, [this.slides[this.slidePos]]);
				this.slideInfoContentEl.update(this.slides[this.slidePos].image_note);
				Ext.get('slide-info-help-content').update(this.slides[this.slidePos].image_note);
				this.slidePos++;
				if(this.slidePos >= this.slides.length){
				  this.slidePos = 0;
				}
			  this.hiddenSlide.dom.src = this.slides[this.slidePos].src;
				
				this.slideshowLocked = false;
			}).defer(1100, this);
		},
		
		userSetSlide: function(slide){
		  if(this.slideshowLocked == true) return;
			// pos is stored as slide.pos
			//alert(slide.pos);
			this.slidePos = slide.pos;
			// ref is stored as slide.data
			slide = slide.data;
			this.hiddenSlide.dom.src = slide.src;
			this.stopSlideshow();
			this.runSlideshow.defer(300, this);
			
			
		},
		
		
		
		
		
	
		
		// course select mode
		
		initCourseSelectMode: function(boolDoNotSetDisplayBase){
			if(this.courseSelectModeInitialised != true){
			  this.coursesWrapper = Ext.get('courses-wrapper');
				this.categoriesWrapper = Ext.get('categories-wrapper');
				this.categoriesWrapper.setVisibilityMode(Ext.Element.DISPLAY);
			  this.courselistWrapper = Ext.get('courselist-wrapper');
				this.courselistContainer = Ext.get('courselist-container');
				Ext.get('revert-to-sport').on('click', this.revertToSport, this);
				this.courseSelectModeInitialised = true;
			}
			if(boolDoNotSetDisplayBase) return;
			this.setDisplayBase(this.coursesWrapper, this.heights.courseSelectMode);
		},
		
		setSport: function(sport){
			if(this.courseSelectModeInitialised != true){
				this.initCourseSelectMode(true);
			}
			if(this.mode != this.MODE_COURSE_SELECT){
			  this.setMode(this.MODE_COURSE_SELECT);
				this.setSport.defer(400, this, [sport]);
				return;
			}
			if(!sport){
				this.categoriesShowing = false;
				this.resetPositions();
			  this.setSport(this.sports[0]);
				return;
			}
			if(this.mode == this.MODE_SLIDESHOW){
			  this.stopSlideshow();
			}
			
			if(this.currentSport == sport && this.categoriesShowing == true) return;
			if(this.locked == true){
				this.showLockedAlert();
				return;
			}
			
			this.locked = true;
			// change the highlighted sport
			
		
			this.currentSport = sport;
			var deferTime = 1;
			// hide the wrapper
			if(this.categoriesShowing == true){
			  this.coursesWrapper.fadeOut({duration: .5, easing: 'easeBoth'});
				deferTime = 500;
			} else {
				this.hideCourses();
			}
		  // change them when the wrapper is hidden			
			(function(){
				this.categoriesWrapper.update('');
				var cats = this.currentSport.data.items;
				this.cats = [];
				for(var i=0;i<cats.length;i++){
					var src = '/img/carousel/no-teaser-image.png';
					if(cats[i].teaser_image){
					  src = SITE_ROOT + cats[i].teaser_image;
					}
					this.cats[i] = this.categoryTemplate.append(this.categoriesWrapper, {
																		top: this.positions[i].top,
																		left: this.positions[i].left,
																		name: cats[i].name,
																		url: cats[i].url,
																		strapline: cats[i].description,
																		src: src
																	}, true);
					this.cats[i].data = cats[i];
					this.cats[i].on('click', function(){carousel.setCategory(this);});
				}
				//Ext.select('.carousel').fadeIn({duration: .6, easing: 'easeOutStrong'});
			}).defer(deferTime, this);
			// bring the new display back in the same way we hid it
			if(this.categoriesShowing == true){
			  (function(){
				  this.coursesWrapper.fadeIn({duration: .5, easing: 'easeBoth', stopFx: true});
				}).defer(deferTime, this);
			} else {
				(function(){
					if(this.courseSelectPositioned != true){
					  var y = 0; //Ext.get('carousel').getTop();
						y += window.pageYOffset	|| document.body.scrollTop || document.documentElement.scrollTop;
						this.courseSelectPositioned = true;
					} else {
						var y = Ext.get('carousel').getTop()+Ext.get('carousel-nav').getHeight()-4;
						//y += window.pageYOffset	|| document.body.scrollTop || document.documentElement.scrollTop;
					}
					//var y = Ext.get('carousel').getTop()+Ext.get('carousel-nav').getHeight()+3;
					this.categoriesWrapper.setY(y, {duration: 1, easing: 'easeBoth'});
				}).defer(deferTime, this);
			}			
			this.categoriesShowing = true;
			
			// unlock when the new display is settled
			var unlockTime = deferTime + 1000;
			this.unlock.defer(unlockTime, this);
			
			this.mainNavItems.removeClass('selected');
			sport.addClass('selected');
			
			
			
		},
		
		setCategory: function(category){
			if(this.locked == true){
				this.showLockedAlert();
				return;
			}
			this.locked = true;
			this.hideCategoriesUp();
			this.currentCategory = category;
			//Ext.select('.carousel').fadeOut({duration:.2, remove: true});
			(function(){
				Ext.get('courses-title').update(this.currentCategory.data.name);
				var courses = this.currentCategory.data.courses;
				this.courses = [];
				for(var i=0;i<courses.length;i++){
					this.courses[i] = this.courseTemplate.append(this.courselistContainer, {
																	  name: courses[i].name,
																		url: this.currentSport.data.url+'/'+courses[i].url+'/'
																	}, true);
					this.courses[i].data = courses[i];
					//this.courses[i].on('click', function(){carousel.setCourse(this);});
				}
				var y = Ext.get('carousel').getTop()+Ext.get('carousel-nav').getHeight()-4;
				this.courselistWrapper.setY(y, {duration:1, easing: 'easeBoth'});
				this.unlock.defer(100, this);
			}).defer(1, this);
		},
		
		
		hideCourses: function(){
		  this.courselistWrapper.setY(530, {duration:1, easing: 'easeBoth', stopFx: true});
			(function(){
        this.courselistContainer.update('');
				Ext.get('courses-title').update('');
			}).defer(1000, this);
		},
		
		hideCategoriesUp: function(){
		  this.categoriesWrapper.setY(-230, {duration: 1, easing: 'easeBoth', stopFx: true});
			this.categoriesShowing = false;
		},
		
		revertToSport: function(){
		  this.hideCourses();
			this.setSport(this.currentSport);
		},
		
		
		
		
		// map mode
		initMapMode: function(){
		  this.setDisplayBase(this.mapWrapper, this.heights.mapMode);
			if(this.mapInitialised != true){
				this.mapInfoWrapper = Ext.get('map-info-wrapper');
			  this.mapInfoEl = Ext.get('map-info');
				this.locationInfoBox = Ext.get('location-info-box');
				//Ext.get('map-info-close').on('click', this.hideRegionDisplay, this);
				this.launchMapDisplay(); 
			  this.mapInitialised = true;
			}
			this.mainNavItems.removeClass('selected');
			this.locationNavEl.addClass('selected');
			this.mapShowing = true;
			
		},
		
		launchMapDisplay: function(){
      this.regionEls = [];
		  for(var i=0;i<this.regions.length;i++){
			  this.regionEls[i] = this.mapRegionTemplate.append(this.mapWrapper, this.regions[i], true);
				this.regionEls[i].data = this.regions[i];
				// this.regionEls[i].hover(function(){carousel.showRegion(this);}, function(){}, this.regionEls[i]);
				
				this.regionEls[i].locations = [];
				for(var j=0;j<this.regions[i].locations.length;j++){
					this.regionEls[i].locations[j] = this.mapLocationTemplate.append(this.regionEls[i], this.regions[i].locations[j], true);
					this.regionEls[i].locations[j].data = this.regions[i].locations[j];					
				}
				this.regionEls[i].on('click', function(){carousel.showRegionInfo(this);});
			}
		},
		
		showRegion: function(region){
			//Ext.select('.map-region').removeClass('selected');
			//region.addClass('selected');
			//this.mapInfoEl.fadeOut({duration:.1, stopFx: true});
			//this.showRegionInfo.defer(110, this, [region]);
		},
		
		showRegionInfo: function(region){
			Ext.select('.map-region').removeClass('selected');
			region.addClass('selected');
			var locs = region.locations;
			for(var i=0;i<locs.length;i++){
				//alert(locs[i].data.name);
			  locs[i].hover(function(e, t){carousel.showLocationHover(e, t, this);}, function(){carousel.hideLocationHover(this);}, locs[i]);
			}
			this.mapInfoEl.fadeOut({duration:.1, stopFx: true});
			(function(){
 		    this.mapInfoEl.update('');
			  this.mapInfoTemplate.append(this.mapInfoEl, region.data);
			  this.mapInfoEl.fadeIn({duration: .1, stopFx: true});
				this.showLocationList(region);
			}).defer(110, this, [region]);
		},
		
		showLocationHover: function(e, t, location){
			/*var pos = e.getXY();
			this.locationInfoBox.setXY([pos[0]-20, pos[1]-30], false);
		  this.locationInfoBox.update(location.data.name);
			this.locationInfoBox.fadeIn({duration: .25, stopFx: true});*/
		},
		
		hideLocationHover: function(){
		  //this.locationInfoBox.fadeOut({duration: .25, stopFx: true});
		},
		
		showLocationList: function(region){
			var locs = region.locations;
			var els = [];
		  for(var i=0;i<locs.length;i++){
			  els[i] = this.locationListItemTemplate.append(this.mapInfoEl, locs[i].data, true);
				els[i].courses = locs[i].data.courses;
				els[i].mapElement = locs[i];
				els[i].hover(function(){carousel.locationListMouseover(this);}, function(){carousel.locationListMouseout(this);}, els[i]);
				els[i].on('click', function(e, t){carousel.toggleMapLocationCourseList(e, t, this);});
			}
		},
		
		locationListMouseover: function(element){
		  element.mapElement.addClass('selected');
		},
		
		locationListMouseout: function(element){
		  element.mapElement.removeClass('selected');
		},
		
		toggleMapLocationCourseList: function(e, t, location){
			var el = e.getTarget('.map-info-element', null, true).child('.location-course-list');
		  var courses = location.courses;
			core.contentToggle({
        element: el,
				template: this.courseListElementTemplate
			}, courses);
		},
		
		
		
		
		
		
		
		
		
		// course detail mode
		initCourseDetailMode: function(){
		  this.setMode(this.MODE_SLIDESHOW);
		}
		
		
	}
}();

Ext.onReady(function(){ carousel.init.defer(1000, carousel); });


