/* ************************** */
/*                            */
/*   duotive Slideshow v1.0   */
/*                            */
/*       2010 © duotive       */
/*                            */
/* ************************** */

// scroller from MooTools-1.3-RC1
var dScroller = new Class({
    Implements: [Events, Options],
    options: {
        area: 20,
        velocity: 1,
        onChange: function(x, y){
            this.element.scrollTo(x, y);
        },
        fps: 50
    },
    initialize: function(element, options){
        this.setOptions(options);
        this.element = document.id(element);
        this.docBody = document.id(this.element.getDocument().body);
        //  N.B. in More-1.3-RC1, this uses typeOf, changed to $type for BC
        this.listener = ($type(this.element) != 'element') ? this.docBody : this.element;
        this.timer = null;
        this.bound = {
            attach: this.attach.bind(this),
            detach: this.detach.bind(this),
            getCoords: this.getCoords.bind(this)
        };
    },
    start: function(){
        this.listener.addEvents({
            mouseenter: this.bound.attach,
            mouseleave: this.bound.detach
        });
        return this;
    },
    stop: function(){
        this.listener.removeEvents({
            mouseenter: this.bound.attach,
            mouseleave: this.bound.detach
        });
        this.detach();
        this.timer = clearInterval(this.timer);
        return this;
    },
    attach: function(){
        this.listener.addEvent('mousemove', this.bound.getCoords);
    },
    detach: function(){
        this.listener.removeEvent('mousemove', this.bound.getCoords);
        this.timer = clearInterval(this.timer);
    },
    getCoords: function(event){
        this.page = (this.listener.get('tag') == 'body') ? event.client : event.page;
        if (!this.timer) this.timer = this.scroll.periodical(Math.round(1000 / this.options.fps), this);
    },
    scroll: function(){
        var size = this.element.getSize(),
            scroll = this.element.getScroll(),
            pos = this.element != this.docBody ? this.element.getOffsets() : {x: 0, y:0},
            scrollSize = this.element.getScrollSize(),
            change = {x: 0, y: 0},
            top = this.options.area.top || this.options.area,
            bottom = this.options.area.bottom || this.options.area;
        for (var z in this.page){
            if (this.page[z] < (top + pos[z]) && scroll[z] != 0){
                change[z] = (this.page[z] - top - pos[z]) * this.options.velocity;
            } else if (this.page[z] + bottom > (size[z] + pos[z]) && scroll[z] + size[z] != scrollSize[z]){
                change[z] = (this.page[z] - size[z] + bottom - pos[z]) * this.options.velocity;
            }
            change[z] = change[z].round();
        }
        if (change.y || change.x) this.fireEvent('change', [scroll.x + change.x, scroll.y + change.y]);
    }
});

var duotiveSlide = new Class({
	Implements: Chain,
	initialize: function(options){
		
		// validation if the slideshow exists on the page
		if ($('slideshow-wrapper') != null) {
		
			// setting up the options
			this.options = options;
			that = this;
			// getting the images ready
			var images = this.options.container.getChildren('img');
			images_src = new Array();
			images.each(function(item, index){
				images_src[index] = item.getProperty('src');
			});
			
			// getting rid off the images
			images.dispose();
			
			// adding the options
			if (this.options.captions == true){
				if ($('slideshow-full-text') == null ){
					this.options.captions = false;
				}
			}		
			if (this.options.gallery == true) {
				if ($('slide_nav') != null) {
					this.addGallery();
				} else {
					this.options.gallery = false;
					if (that.options.captions != false) {
						$('slideshow-full-text').setStyle('top', 248);
					}
				}
			}
			this.start();
		}
	},
	
	addGallery: function(){
		
		// setting up the gallery content
		gallery = $('slide_nav');
		var ul = gallery.getChildren('ul');
		thumbs = ul.getChildren('li');
		var thumb_width = this.options.thumbnailWidth;
		var thumb_margin = this.options.thumbnailMargin;
		ul.setStyle('width', (thumb_width + thumb_margin) * images_src.length);
		
		
		// fading fx for the gallery
		var gallery_fx = new Fx.Tween(gallery, {duration: 300});
		var captions_hover_fx = new Fx.Tween($('slideshow-full-text'), {duration: 300});
		gallery_fx.start('opacity', 1);
		$('header-wrapper').addEvents({
			'mouseenter': function() {
				gallery_fx.cancel();		
				gallery_fx.start('opacity', 1);
				if (that.options.captions != false) {
					captions_hover_fx.cancel();
					captions_hover_fx.start('top', 148);
				}
			},
			'mouseleave': function() {
				gallery_fx.cancel();
				gallery_fx.start('opacity', 0);
				if (that.options.captions != false) {
					captions_hover_fx.cancel();
					captions_hover_fx.start('top', 248);	
				}
			}
		});
		// adding the scrolling effect
		var gallery_scroll = new dScroller(gallery, {area: 90, velocity: 0.15});
	    gallery.addEvent('mouseenter', gallery_scroll.start.bind(gallery_scroll));
		
		
	},
	
	start: function() {
		// adding the basic slideshow elements
		var box_a = new Element('div', {
			'class': 'box',
			'styles':{
				'margin': 'auto',
				'width': '100%',
				'height': 465,
				'position': 'absolute',
				'top': 0,
				'overflow':'hidden'
			}
		}).injectInside(this.options.container);
		var box_b = new Element('div', {
			'class': 'box',
			'styles':{
				'margin': 'auto',
				'width': '100%',
				'height': 465,
				'position': 'absolute',
				'top': 0,
				'left':0,
				'overflow':'hidden',
				'opacity':0
			}		
		}).injectInside(this.options.container);
		
		boxes = [box_a, box_b];
		if (that.options.captions != false) {
			captions = $$('#slideshow-full-text div.slide-text');
			captions.setStyle('opacity', 0);
			captions[0].setStyle('opacity', 1);
		}
		faded = true;
		playing = true;
		inMotion = false;
		oldCaption = 0;
		newCaption = 1;
		counter = 0;
		oldCounter = -1;
		
		// applying backgrounds to the boxes
		boxes.each(function(item, index){
			item.setStyle('background', 'url(' + images_src[counter] + ') no-repeat center');
			counter++;
		});
		
		// adding the slide link
		
		slideAnchors = $$('#slideshow-full-anchors a');
		slideLinks = new Array();
		slideAnchors.each(function(item, index){
			slideLinks[index] = item.getProperty('href');
		});
		slideAnchors.dispose();

		slideLink = new Element('a', {
			'class': 'slide-link',
			'href':slideLinks[oldCaption],
			'styles':{
				'margin': 'auto',
				'width': '100%',
				'height': this.options.sliderHeight,
				'position': 'absolute',
				'top': 0,
				'overflow': 'hidden'
			}
		}).injectInside($('slideshow-full-anchors'));

		
		slide_fx = new Fx.Tween(boxes[1], {duration: (this.options.duration)/2});
		if (this.options.autoPlay == true ) this.autoPlay();
	},
	
	autoPlay: function() {
		// animation settings
		function imageChange(){
			switch(faded){
				case false:
					if (counter >= images_src.length) { counter = 0; }
					faded = true;
					inMotion = true;
					changeCaption();
					if (that.options.gallery != false) activeThumb();					
					slide_fx.start('opacity', 0).chain(function(){
						boxes[1].setStyle('background', 'url(' + images_src[counter] + ') no-repeat center');
						if ( playing == false ) { /*startPeriodical();*/ } 
						else { counter++; }
						this.callChain();
					}).chain(function(){
						inMotion = false;
					});
				break;
				case true:
					if (counter >= images_src.length) { counter = 0; }
					faded = false;
					inMotion = true;
					changeCaption();
					if (that.options.gallery != false)  activeThumb();
					slide_fx.start('opacity', 1).chain(function(){
						boxes[0].setStyle('background', 'url(' + images_src[counter] + ') no-repeat center');
						if ( playing == false ) { /*startPeriodical();*/ } 
						else { counter++; }
						this.callChain();
					}).chain(function(){
						inMotion = false;
					});
				break;
			}
		} // end of imageChange()
		
		function startPeriodical(){
			imageChangePeriod = (function(){
				playing = true;
				if ( inMotion == false )
				imageChange();
			}).periodical(that.options.duration)
		}
		
		startPeriodical();
		
		// function that changes the image captions
		function changeCaption() {
			
			if ( newCaption >= images_src.length ) newCaption = 0;
			
			// if the same thumbnail is pressed more than once, don't change the caption
			if (oldCaption != newCaption) {
				slideLink.setProperty('href', slideLinks[newCaption]);
				if (that.options.captions != false) {
					current_caption_fx = new Fx.Tween(captions[newCaption], {duration: parseInt((that.options.duration) / 4)});
					current_caption_fx.start('opacity', 1);
					old_caption_fx = new Fx.Tween(captions[oldCaption], {duration: (that.options.duration)/2});
					old_caption_fx.start('opacity', 0);	
				}
				oldCaption = newCaption;
				newCaption++;
			}
			
			
		}
		
		// setting up the thumbnails events
		var anchors = $$('#slide_nav ul a');
		
		anchors.each(function(item, index){
			item.setProperty('rel', index);
			item.addEvent('click', function(e){
				e.stop();
				if ( inMotion == false ) {
					playing = false;
					$clear(imageChangePeriod);
					counter = index;
					newCaption = counter;
					function thumbImageChange(){
						switch (faded) {
							case false:
								if (counter >= images_src.length) {
									counter = 0;
								}
								faded = true;
								inMotion = true;
								changeCaption();
								if (that.options.gallery != false) activeThumb();
								var tempChain = new Chain();
								tempChain.chain(function(){
									boxes[0].setStyle('background', 'url(' + images_src[counter] + ') no-repeat center');
								}).chain(function(){
									slide_fx.start('opacity', 0);
								}).wait(that.options.duration/2).chain(function(){
									inMotion = false;
								});
								tempChain.callChain();
								tempChain.callChain();
								tempChain.callChain();
								break;
							case true:
								if (counter >= images_src.length) {
									counter = 0;
								}
								faded = false;
								inMotion = true;
								changeCaption();
								if (that.options.gallery != false) activeThumb();
								var tempChain = new Chain();
								tempChain.chain(function(){
									boxes[1].setStyle('background', 'url(' + images_src[counter] + ') no-repeat center');
								}).chain(function(){
									slide_fx.start('opacity', 1);
								}).wait(that.options.duration/2).chain(function(){
									inMotion = false;
								});
								tempChain.callChain();
								tempChain.callChain();
								tempChain.callChain();
								break;
						} // end of switch
					
					
					} // end of thumbInageChange()
					thumbImageChange();
				} // end if
				
				
			}); // end of Event
		});
		
		function activeThumb(){
			if (newCaption > 0) {
				var thumbnails = $$('#slide_nav ul li');
				thumbnails.each(function(item){
					item.removeClass('active');
				});
				thumbnails[newCaption - 1].setProperty('class', 'active');
			}
		}
	}
		
});



window.addEvent('load', function(){
	var slider = new duotiveSlide({
		container: $('header-wrapper'),
		autoPlay: true,
		captions: true,
		gallery: true,
		thumbnailWidth: 142,
		thumbnailMargin: 16,
		duration: 4000, // in milliseconds ( 1000ms = 1s )
		transition: 'Fx.Transitions.Expo.easeOut'
	});
});
