dojo.provide("Z2h.Slideshow");

dojo.require("dojo.fx");
dojo.require('dojo.fx.easing');
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.require("Z2h.Slide");

dojo.declare("Z2h.Slideshow", [dijit._Widget, dijit._Templated], {
	templateString: null,
	templatePath: dojo.moduleUrl("Z2h","templates/Slideshow.html"),
	widgetsInTemplate : true,

	/**
	 * Private variables
	 */
	_slides: null,/*all the slides loaded from the data store */
	_controls: null,
	_current_slide: 0, /*currently showing slide */
	_slide_dataStore: null, /*data store containing the slides */
	_timeout_to_next: null, /*timeout that is set when slideshow is created,
							//is canceled as soon as the user interacts with a slide or
							//chooses their own slide */
	
	/**
	 * Public variables
	 */
	slideType: '', /*type of slides being displayed ( currently can only display one type of slide at a type*/
	dataStoreUrl: '', /*url for the data store*/
	timeout: 10, /*timeout between slides switching*/
	itemCount: 0,
	cssClass: '',
	
	/**
	 * Methods
	 */
	
	postCreate: function(){
		this.inherited("postCreate",arguments);
		
		var loadingDivCoords = dojo.contentBox(this.loadingSlides);
		var slideContainer = dojo.contentBox(this.slideListElement);
		var loadingImgCoords = dojo.contentBox(this.loadingImage);
		
		dojo.style(this.loadingImage,{
			'left': (loadingDivCoords.w/2)-(loadingImgCoords.w/2)+"px",
			'top':  (loadingDivCoords.h/2)-(loadingImgCoords.h/2)+"px"
		});
		
		this._slide_dataStore = new dojo.data.ItemFileReadStore({
			url: this.dataStoreUrl
		});
		this._slide_dataStore.fetch({ onComplete: dojo.hitch(this,'populateSlides'), onError: dojo.hitch(this,'slideLoadError')});
	},
	
	populateSlides: function(items,request){		
		var slideshowDivCoords = dojo.contentBox(this.slideShowContainer);
		dojo.style(this.slideListElement, 'width', slideshowDivCoords.w * ( items.length + 1)+"px" );

		this._slides = [];
		
		if ( items.length > 0 ){
			for ( var i in items ){
				var slide = null;
				try {
					slide = this.getSlide( items[i] );
					slide._slideshow = this;
					this._slides[i] = slide;
					dojo.style(slide.slideListItem,'width', slideshowDivCoords.w+"px");
					dojo.style(slide.slideListItem,'height', slideshowDivCoords.h+"px");
					dojo.place(slide.slideListItem,this.slideListElement,'last');
				} catch ( e ){
					console.log("Unable to load slide #"+i+": ",e);
				}
			}
			this.setup();
			dojo.destroy(this.loadingSlides);
		} else {
			//error if no slides found
			this.slideLoadError('','');
		}
	},
	
	getSlide: function(args){
		args.cssClass = this.cssClass;
		if ( this.slideType == "video" ){
			dojo.require("Z2h.Slide.Video");
			return new Z2h.Slide.Video(args);
		} else if ( this.slideType == "image" ){
			dojo.require("Z2h.Slide.Image");
			return new Z2h.Slide.Image(args);
		} else if ( this.slideType == "contest" ){
			dojo.require("Z2h.Slide.Contest");
			return new Z2h.Slide.Contest(args);
		}
		return null;
	},
	
	setup: function(){
		this.setupControl();
		this.setIntervalToNext();
		this.slideTo(0);
	},
	
	setupControl: function(){
		if ( this._slides.length > 0 ){
			this._controls = [];
			for ( var i=0; i< this._slides.length; i++ ) {
				var listEl = dojo.create('li');
				var anchorEl = dojo.create('a');
				dojo.attr(anchorEl,'href','#');
				dojo.attr(anchorEl,'title','Item #'+(i+1));
				var spanEl = dojo.create('span');
				dojo.attr(spanEl,'innerHTML','Item '+(i+1));
				dojo.place(spanEl,anchorEl);
				dojo.place(anchorEl,listEl);
				dojo.place(listEl,this.rotatorControl);
				dojo.addClass(anchorEl,'img_replace');
				dojo.attr(anchorEl,'id',this.slideShowContainer.id+"_Control_"+i)
				dojo.connect(anchorEl,'onclick',dojo.hitch(this,'controlClick'));
				this._controls[i] = anchorEl;
			}
		}
		
	},
	
	slideLoadError: function(error,request){
//		Z2h.tooltip.popupError("Unable to find any slides for the slideshow");

		dojo.style(this.slideError,'display','block');
		
		var errorDivCoords = dojo.coords(this.slideError);
		var slideContainer = dojo.coords(this.slideListElement);
		var errorTextCoords = dojo.coords(this.slideErrorText);
		
		dojo.style(this.slideErrorText,{
			'left': (errorDivCoords.w/2)-(errorTextCoords.w/2)+"px",
			'top':  (slideContainer.h/2)-(errorTextCoords.h/2)+"px"
		});

		dojo.destroy(this.loadingSlides);
		
	},
	
	controlClick: function(evt){
		this.clearIntervalToNext();
		evt.preventDefault();
		var slideTo = evt.target.id.replace(this.slideShowContainer.id+"_Control_","");
		this.slideTo(slideTo);
		this._current_slide = parseInt(slideTo);
		this.setIntervalToNext();
	},
	
	slideTo: function(next){
		this.hideCurrentSlide();
		if ( next >= 0 && next <= this._slides.length ){
			for ( var i in this._controls ){
				if ( i == next ){
					dojo.addClass(this._controls[i],'selected_rotator_item');
				} else {
					dojo.removeClass(this._controls[i],'selected_rotator_item');
				}
			}

            var currentMarginLeft = dojo.style(this.slideListElement,'marginLeft');
            var firstSlide = this._slides[0].slideListItem;
            var slideWidth = dojo.style(firstSlide,'width') + dojo.style(firstSlide,'marginRight') + dojo.style(firstSlide,'marginLeft');

            var newMarginLeft = -1 * slideWidth * next;
			
			var slideAnimation = dojo.animateProperty({
					node: this.slideListElement,
					widget: this,
					properties: { marginLeft: { start: currentMarginLeft, end: newMarginLeft, units:"px"} },
					easing: dojo.fx.easing.quadInOut,
					duration: 2000,
					onEnd: function(){
						this.widget.showCurrentSlide();
					}
				});
			slideAnimation.play();

		}
	},
	
	showCurrentSlide: function(){
		if ( this._slides && this._slides[this._current_slide] ){
			this._slides[this._current_slide].show(this);
		}
	},
	
	hideCurrentSlide: function(){
		if ( this._slides && this._slides[this._current_slide] ){
			this._slides[this._current_slide].hide();
		}
	},
	
	slideToNext: function(){
		if ( this._slides && this._slides[this._current_slide].okayToSlide() ){
		    this.hideCurrentSlide();
			this._current_slide += 1;
			if ( this._current_slide == this._slides.length ) {
				this._current_slide = 0;
			}
			this.slideTo(this._current_slide);
		}
	},
	
	setIntervalToNext: function(){
		//we want the timeout to be in seconds, but setInterval expects milliseconds
		if ( this._slides.length > 1 && this.timeout > 0 ){
			speed = this.timeout * 1000;
			this._interval = setInterval(dojo.hitch(this,'slideToNext'),speed);
		}
	},
	
	clearIntervalToNext: function(){
		if ( this._interval ){
			clearInterval(this._interval);
		}
		this._interval = false;
	}
	
});