Event.observe(window, 'load', function(){
//	SlideDown.init();
	ImageRotator.init();
	PageScroller.init();
	IllustrationControls.init()
});


var IllustrationControls = {
	init: function() {
		if ($('switchToVideo') && $('switchToPhoto')) {
			this.photo = $$('div.illustration div.images')[0]
			this.video = $$('div.illustration div.movie')[0]
			this.showVideo = $('switchToVideo')
			this.showPhoto = $('switchToPhoto')

			this.showVideo.observe('click', function() {
				this.photo.setStyle({display: 'none'})
				this.showPhoto.removeClassName('current')
				this.video.setStyle({display: 'block'})
				this.showVideo.addClassName('current')
			}.bind(IllustrationControls))

			this.showPhoto.observe('click', function() {
				this.photo.setStyle({display: 'block'})
				this.showPhoto.addClassName('current')
				this.video.setStyle({display: 'none'})
				this.showVideo.removeClassName('current')
			}.bind(IllustrationControls))
		}
	}
}

var SlideDown = {
	init: function() {
		$$('ul.slideDown li').each(function(teaser){
			teaser.header = teaser.down('h3')
			teaser.description = teaser.down('p')

			teaser.description.hide()

			teaser.showDescription = function(event) {
				this.description.show()
				this.siblings().invoke('hideDescription')
			}
			teaser.hideDescription = function(event) {
				this.description.hide()
			}

			teaser.observe('mouseover', teaser.showDescription.bindAsEventListener(teaser))
		}.bind(this))
	}
}

var Scroll = {
	init: function() {
		if ($('galleryImages') && $('toleft') && $('toright')) {
			this.galleryLeft = $('toleft');
			this.galleryRight = $('toright');
			this.scroll = $('galleryImages').down('ul');
		}
	}
}


var ImageRotator = {
	imageLoaded: function(img) {
	    // During the onload event, IE correctly identifies any images
	    // that weren't downloaded as not complete. Others should too.
	    // Gecko-based browsers act like NS4 in that they report this
	    // incorrectly: they always return true.
	    if (!img.complete) {
	        return false;
	    }
	    // 
	    // // However, they do have two very useful properties: naturalWidth
	    // // and naturalHeight. These give the true size of the image. If
	    // // it failed to load, either of these should be zero.
	    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
	        return false;
	    }

	    // No other way of checking: assume it's ok.
	    return false;
	},
	init: function() {
		$$("div.imageRotator").each(function(element) {

			if (element.childElements().length > 1) {
				element.currentImage = 1
				element.timeOut = null
				element.images = element.childElements()
				element.images.each(function(img){
					img.loaded = false
					img.checkLoaded = $(new Image())
					img.checkLoaded.setStyle({'position': 'absolute', 'top': '0', 'left': '-10000px'})
					document.getElementsByTagName('body')[0].appendChild(img.checkLoaded)
					img.checkLoaded.src = img.src
					img.checkLoaded.observe('load', function(e){
						this.loaded = true
					}.bindAsEventListener(img))
				}.bind(this))
				
				if (element.up().down('img.goForward')) {
					element.up().down('img.goForward').observe("click", function(event){
						ImageRotator.showNext(element)
					}.bind(this))
				}
				if (element.up().down('img.goBackward')) {
					element.up().down('img.goBackward').observe("click", function(event) {
						ImageRotator.showPrevious(element)
					}.bind(this))
				}
				ImageRotator.startSlideshow(element)
			} else {
				element.up().down('.navigator').hide()
			}
			$$('.navigator img').each(function(obj){
				obj.observe('mouseover', function(event){this.src = this.src.replace('.gif', '-s.gif')})
				obj.observe('mouseout',  function(event){this.src = this.src.replace('-s.gif', '.gif')})
				var tmp = new Image(); tmp.src = obj.src.replace('.gif', '-s.gif');
			})
		}.bind(this))
	},
	startSlideshow: function(rotator) {
		rotator.timeOut = setTimeout(function() { ImageRotator.doShowNext(rotator, 1, 'slideshow') }, 3500)
	},
	showNext: function(obj) {
		ImageRotator.doShowNext(obj, 1)
	},
	showPrevious: function(obj) {
		ImageRotator.doShowNext(obj, -1)
	},

	doShowNext: function(rotator, offset, slideshow) {
		newCurrentImage = (rotator.currentImage + offset + rotator.images.length) % rotator.images.length
		if (true || this.imageLoaded(rotator.images[newCurrentImage].checkLoaded) || rotator.images[newCurrentImage].loaded) {
			rotator.images.each(function(obj){
				(obj != rotator.images[newCurrentImage]) ? ImageRotator.hide(obj) : ImageRotator.show(obj)
			})
			rotator.currentImage = newCurrentImage
			if (rotator.timeOut) clearTimeout(rotator.timeOut);
			if (slideshow) ImageRotator.startSlideshow(rotator)
		}
  },
	hide: function(object) {
		if (object.fadeEffect) object.fadeEffect.cancel()
		object.fadeEffect = Effect.Fade(object, { duration: 0.8 })
	},

	show: function(object) {
		if (object.fadeEffect) object.fadeEffect.cancel()
		object.fadeEffect = Effect.Appear(object, { duration: 0.8 })
	}

}

var PageScroller = {
	init: function() {
		this.container = $$("div.projectScroll")[0]

		if (this.container) {
			this.scrollableContainer = this.container.down("ul")
			this.left = 0
			this.containerWidth = this.container.getWidth()

			this.computedWidth = 0
			$A(this.scrollableContainer.getElementsByTagName('li')).each(function(element) {
				this.computedWidth += $(element).getWidth()
				if (element.hasClassName('current')) {
					this.currentElement = element
				}
			}.bind(this))
			this.scrollableContainer.setStyle({width: this.computedWidth+'px'})
			this.maxLeft = this.containerWidth - this.computedWidth

			if (this.currentElement) {
				this.left = -(this.currentElement.positionedOffset()['left'] - this.containerWidth/2 + this.currentElement.getWidth()/2)
				this.left = Math.max(Math.min(this.left, 0), this.maxLeft)
				this.scrollableContainer.setStyle({marginLeft: this.left + "px"})
			}

			this.container.observe("mouseover", this.handleMouseOver.bindAsEventListener(this))
			this.container.observe("mousemove", this.calculateSpeed.bindAsEventListener(this))
			this.container.observe("mouseout", this.handleMouseOut.bindAsEventListener(this))

		}
	},
	calculateSpeed: function(event){
		var offset = this.container.viewportOffset()

		var x = event.pointerX() - offset[0], sign
		if (x < this.containerWidth / 2) {
			sign = -1
		} else {
			sign = +1
			x = this.containerWidth - x
		}

		this.speed = (x <= 400 ? sign * (400 - x) * (400 - x) : 0) / 10000
	},
	handleMouseOver: function(event){
		this.calculateSpeed(event)
		if ((this.left < 0 && this.speed < 0) || (this.left > this.maxLeft && this.speed > 0)) {
			this.stopFade()
			this.startScroll()
		}
	},
	handleMouseOut: function(event) {
		if (!Position.within(this.container, event.pointerX(), event.pointerY())) {
			this.startFade()
			this.stopScroll()
		}
	},

	startFade: function() {
		if (!this.fadeInterval && !this.borderFadeInterval) {
			this.fadeInterval = setInterval(this.doFade.bind(this), 20)
		}
	},
	doFade: function() {
		if (Math.abs(this.speed) >= 0.1 && (this.left < 0 && this.left > this.maxLeft)) {
			this.speed = this.speed * 0.9
			this.doScroll(true)
		} else {
			this.stopFade()
		}
	},
	stopFade: function() {
		clearInterval(this.fadeInterval)
		this.fadeInterval = null
	},

	startBorderFade: function() {
		if (!this.borderFadeInterval) {
			this.borderFadeIteration = 0
			this.borderFadeInterval = setInterval(this.doBorderFade.bind(this), 20)
		}
	},
	doBorderFade: function() {
		if (this.borderFadeIteration >= 2 && (this.left < 1 && this.left > this.maxLeft-1)) {
			this.stopBorderFade()
		} else {
			this.left -= this.borderFadeOffset()
			this.scrollableContainer.setStyle({marginLeft: this.left + "px"})
			this.borderFadeIteration++
		}
	},
	borderFadeOffset: function() {
		if (this.borderFadeIteration <= 5) {
			return this.speed * Math.cos(this.borderFadeIteration/10*Math.PI) / 2
		} else {
			if (this.speed < 0) {
				return this.left * 0.1
			} else {
				return (-this.maxLeft+this.left) * 0.1
			}
		}
	},
	stopBorderFade: function() {
		this.speed = 0
		clearInterval(this.borderFadeInterval)
		this.borderFadeInterval = null
	},

	startScroll: function() {
		if (this.speed != 0 && !this.scrollInterval) {
			this.scrollInterval = setInterval(PageScroller.doScroll.bind(PageScroller), 50)
		}
	},
	doScroll: function(border){
		this.left -= this.speed
		if (!border) {
			if (this.left >= 0) {
				this.stopScroll()
				this.startBorderFade()
			} else if (this.left <= this.maxLeft) {
				this.stopScroll()
				this.startBorderFade()
			}
		}
		this.scrollableContainer.setStyle({marginLeft: this.left + "px"})
	},
	stopScroll: function() {
		clearInterval(this.scrollInterval)
		this.scrollInterval = null
	}
}
