Event.observe(document, 'dom:loaded', function() {
	MirrorCamera.init()
	if ($('looks')) Looks.init()
	
	$$("form.look, form.new_look, form.image_item, form.store_image, form.new_kaleidoscope, form.kaleidoscope, form.year_image").each(function(element) {
		new NiceForm(element)	
	})
	
	$$(".manageLooks ul li, .manageBackstage ul li").each(function(element) {
		new DraggableElement(element)
	})
	
	if ($('collectionNav')) CollectionNav.init()
	if ($('video') && $('videoLink')) Video.init()
	$$(".popupControl").each(function(e) { new PopupControl(e) })
	
	$$('.yearsList li').each(function(e) { 
		if (e.down('img')) new CursorImage(e)
	})
})

Event.observe(window, 'load', function() {
	Mirror.init()
	if ($('looks')) {
		var lastLook = $('looks').select('li').last()
		$('looks').setStyle({width: (lastLook.cumulativeOffset().leftOffset + lastLook.getWidth() + 20)+'px' })
	}
	
	if ($('storyPage')) StoryPage.init()
	if ($('slidingContainer')) {
		BodyWidth.init()
		NiceScroll.init()
	}
	SwitchLanguages.init()
})

CursorImage = Class.create({
	initialize: function(element) {
		this.element = element
		this.image = this.element.down('img')

		this.element.observe("mouseover", this.initImageMove.bind(this))
		this.element.observe("mouseout", this.finishImageMove.bind(this))
	},
	
	initImageMove: function() {
		this.image.show()
		$$('body')[0].observe('mousemove', this.trackMousePosition.bind(this))
	},
	
	finishImageMove: function() {
		this.image.hide()
		$$('body')[0].stopObserving('mousemove')
	},
	
	trackMousePosition: function(event) {
		this.image.show()
		var left = event.pointerX() - 200

		this.image.setStyle({
			left: left + 'px'
		})
	}
})

var NiceScroll = {
	init: function() {
		if (window.addEventListener) window.addEventListener('DOMMouseScroll', this.processScroll, false)
		window.onmousewheel = document.onmousewheel = this.processScroll;
	},
	
	processScroll: function(event) {
		if (event.wheelDelta) {
			delta = event.wheelDelta / 3
		} else if (event.detail) {
			delta = - event.detail * 30
		}
		
		this.html = $$('html')[0]
		if (this.html.hasClassName("ie") || this.html.hasClassName("webkit")) {
			el = document.body
		} else {
			el = this.html
		}
		
		delta = - (delta / Math.abs(delta)) * 30
		el.scrollLeft += delta
	}
}

var PopupControl = Class.create({
	initialize: function(element) {
		this.link = element
		this.elementToShow = $(element.readAttribute("shows"))
		if ($(element.readAttribute("hides"))) this.elementToHide = $(element.readAttribute("hides"))
		if ($(element.readAttribute("additional_control"))) {
			this.additionalContol = $(element.readAttribute("additional_control"))
			this.additionalContol.observe("click", this.toggleElements.bind(this))
		}
		
		$('topOverlay').observe("click", this.toggleElements.bind(this))
		this.link.observe("click", this.toggleElements.bind(this))
		this.duration = 0.5
	},
	
	toggleElements: function() {
		if (this.elementToShow.style.display != "none") {
			this.hideElement()
			this.showBody()
		} else { 
			this.showElement()
			this.hideBody()
		}
	},
	
	hideElement: function() {
		if (this.elementToHide) {
			this.elementToShow.hide()
			this.elementToHide.appear({ duration: this.duration })
		} else {
			this.elementToShow.fade({ duration: this.duration })
		}

		$('topOverlay').hide()
	},
	
	showElement: function() {
		if (this.elementToHide) this.elementToHide.hide()
		this.elementToShow.appear({ duration: this.duration })

		$('topOverlay').show()
	},
	
	hideBody: function() {
		["slidingContainer", "topNavigation", "startpage"].each(function(part) {
			if ($(part)) $(part).fade({ duration: 0.5, from: 1, to: 0.2 })
		})
	},
	
	showBody: function() {
		["slidingContainer", "topNavigation", "startpage"].each(function(part) {
			if ($(part)) $(part).fade({ duration: 0.5, from: 0.2, to: 1 })
		})
	}
})

var MirrorCamera = {
	init: function() {
		if ($('mirror') && $('camera')) {
			$('camera').observe('click', function(){
				this.toggle()
			}.bind(this))
		}
	}, 
	
	toggle: function() {
		mirror = $('camera').up('div.mirror')
		if (mirror.hasClassName("visibleCamera")) {
			mirror.removeClassName("visibleCamera")
		} else {
			mirror.addClassName("visibleCamera")
		}
	}
}

var SwitchLanguages = {
	init: function() {
		this.update = this.update.bind(this)
		this.update()
	},
	update: function(){
		$$('.switchLanguages').each(function(langSwitch) {
			if (!langSwitch.links) {
				langSwitch.links = langSwitch.select('p.switch a')
				langSwitch.links.each(function(link){
					link.container = langSwitch
					link.field = langSwitch.down('li.' + link.lang) || langSwitch.down('div.' + link.lang)

					link.selectLang = function() {
						this.container.links.invoke('unselectLang')
						this.field.show()
						this.addClassName('current')
					}
					
					link.unselectLang = function() {
						this.field.hide()
						this.removeClassName('current')
					}
					link.observe('click', link.selectLang.bindAsEventListener(link))
				})
				langSwitch.links[0].selectLang()
			}
		})
	}
}

var BodyWidth = {
	init: function() {
		this.html = $$('html')[0]
		this.body = $$('body')[0]
		
		this.body.setStyle({width: "auto"})
		
		if (this.html.hasClassName("ie") || this.html.hasClassName("webkit")) {
			width = document.body.scrollWidth
		} else {
			width = this.html.scrollWidth
		}
		
		this.body.setStyle({ width: width + 'px' })	
	}
}

var StoryPage = {
	init: function() {
		this.container = $('storyPage')
		width = 0
		
		this.container.select(".storyItem").each(function(e) {
			width += e.getWidth()
			width += parseInt(e.getStyle("margin-left"))
			width += parseInt(e.getStyle("margin-right"))
			width += parseInt(e.getStyle("padding-left"))
			width += parseInt(e.getStyle("padding-right"))
		})
		
		if ($$('html')[0].hasClassName("ie6")) width += 100
		this.container.setStyle({
			width: width + 'px'
		})
	}
}


var CollectionNav = {
	init: function() {
		this.container = $('collectionNav')
		this.elements = this.container.select("a.updateable")
		this.links = this.container.select('a')
		
		this.current = this.elements.first()
		this.elements.each(function(element){
			element.observe("click", function() { this.updateContainer(element) }.bind(this))
		}.bind(this))
	},
	
	updateContainer: function(element) {
		if (element != this.current) {
			new Ajax.Request(element.readAttribute("rel"), { method: "get" })
			this.current = element
			this.updateLinksClassNames()
			Video.close()
			Looks.switchLook()
		}
	},
	
	updateCurrentLink: function(element) {
		this.links.invoke("removeClassName", 'active')
		element.addClassName('active')
	},
	
	updateLinksClassNames: function() {
		this.updateCurrentLink(this.current)
	}
}

var Video = {
	init: function() {
		this.container = $("video")
		this.body = $$('body')[0]
		
		if (this.container.style.display != "none") {
			this.body.addClassName("dark")
			CollectionNav.updateCurrentLink($('videoLink'))
		}
		
		$('videoLink').observe("click", this.toggleContainer.bind(this))
		$$('div.shade')[0].observe("click", this.toggleContainer.bind(this))
	},
	
	toggleContainer: function() {
		!this.body.hasClassName("dark") ? this.open() : this.close()
	},
	
	open: function() {
		this.body.addClassName("dark")
		this.container.show()
		CollectionNav.updateCurrentLink($('videoLink'))
	},
	
	close: function() {
		this.body.removeClassName("dark")
		this.container.hide()
		this.body.stopObserving("click")
		CollectionNav.updateLinksClassNames()
	}
}

var DraggableElement = Class.create({
	initialize: function(element) {
		this.container = element.up('ul')
		
		new Draggable(element, { 
			onDrag: function(draggable) {
				if (this.container)
					this.handleDraggable(element, draggable)
			}.bind(this),
			onEnd: function(draggable) {
				this.sendBlockData(element, draggable)
			}.bind(this)
		})
	},
	
	handleDraggable: function(element, draggable) {
		this.containerElements = this.container.select("li")
		
		var width = 0
		this.containerElements.each(function(element) {
			element.leftOffset = parseInt(element.getStyle("left")) + element.getWidth()
			if (element.leftOffset > width) width = element.leftOffset
		})
		
		scroll = element.leftOffset == width
		this.setContainerWidth(width, scroll)
	},
	
	setContainerWidth: function(width, scroll) {
		width += 600
		this.container.setStyle({width: width + 'px'})
	},
	
	sendBlockData: function(element, draggable) {
		url = element.readAttribute("url")
		className = element.readAttribute("class_name")
		if (this.container) this.sendContainerData()
 		new Ajax.Request(
			element.readAttribute("url"), {
			method: 'put',
			parameters: [
				className+'[offset_left]=' + parseInt(draggable.element.getStyle('left')),
				className+'[offset_top]=' + parseInt(draggable.element.getStyle('top')),
				'authenticity_token=' + encodeURIComponent(window._authenticity_token)
			].join('&')
		})
	},
	
	sendContainerData: function() {
		new Ajax.Request(
			this.container.readAttribute("url"), {
			method: 'put',
			parameters: [
				'collection[container_width]=' + this.container.getWidth(),
				'authenticity_token=' + encodeURIComponent(window._authenticity_token)
			].join('&')
		})
	}
})

var NiceForm = Class.create({
	initialize: function(element) {
		this.form = element
		this.inputs = this.form.select("input")
		this.inputs = this.inputs.concat(this.form.select("textarea"))
		
		this.submitButton = this.form.down("input[type=submit]")
		this.inputs = this.inputs.without(this.submitButton)
		this.inputs = this.inputs.select(function(input) { return input.up("li") && input.up("li").hasClassName('required') })
		
		this.inputs.each(function(input) {
			input.observe("change", this.checkButtons.bind(this))
		}.bind(this))
	},
	
	checkButtons: function() {
		flag = true // all submits are completed
		this.inputs.each(function(input) {
			if (!input.value) flag = false
		})
		
		if (flag) {
			this.submitButton.removeAttribute("disabled")
		} else { 
			this.submitButton.writeAttribute("disabled", "disabled")
		}
	}
})

var Audio = {
	attach: function() {
		if ($('soundTrack')) this.init()
	},
	
	init: function() {
		this.player = window["audio"] || document["audio"]
		this.playing = false
		
		this.link = $('soundTrack')
		this.control = this.link.down("span.border")
		
		this.link.observe("click", function() {
			this.togglePlayer()
		}.bind(this))
		
		this.player.embed()
	},
	
	togglePlayer: function() {
		if (!this.playing) {
			this.link.down(".status").innerHTML = "Pause"
			this.player.playMusic()
			this.playing = true
		} else {
			this.link.down(".status").innerHTML = "Play"
			this.player.stopMusic()
			this.playing = false
		}
	},
	
	updateControl: function(position, length) {
		var completePercent = parseInt(position) / parseInt(length)
		
		this.control.setStyle({
			width: (100 - completePercent * 100) + "%"
		})
	}
}

var Looks = {
	init: function() {
		if ($('looks')) {
			this.container = $('looks')
			this.looks = this.container.select('li')

			this.looks.each(function(look){
				if (look.down('a')) {
					look.bigLook = look.down('a').href
					if (look.down('span.index')) look.number = look.down('span.index').innerHTML
					look.observe('click', this.showLook.bindAsEventListener(this))
				}
			}.bind(this))
			
			if (this.container.down('li.default')) {
				this.doShowLook(this.container.down('li.default'))
			}
		}
	},
	
	showLook: function(event) {
		event.stop()
		this.doShowLook(event.element().up('li'))
	},
	
	doShowLook: function(look) {
		if (this.currentLook && look == this.currentLook) {
			this.switchLook()
		} else {
			this.switchLook(look)
		}
	},
	
	hideCurrentLook: function() {
		this.switchLook()
	},
	
	insertBigLook: function(src) {
		if (this.bigLook) this.bigLook.remove()
		
		
		if (this.currentLook.number) {
			content = '<div class="bigLook" id="bigLook"><span class="index">'+ this.currentLook.number + '</span>\
			<img src="' + this.currentLook.bigLook + '" alt="" /></div>'	
		} else {
			content = '<div class="bigLook" id="bigLook"><img src="'+this.currentLook.bigLook+'" alt="" /></div>'
		}
		
		$$('body')[0].insert({top: content})
		this.bigLook = $('bigLook')
		this.bigLook.observe('click', this.hideCurrentLook.bind(this))
	},
	
	showNewLook: function(look) {
		this.currentLook = look
		new Effect.Opacity(this.currentLook, {to: 0.1, duration: 0.2})
		this.insertBigLook()
		this.bigLook.setStyle({display: 'block', opacity: 0})
		new Effect.Opacity(this.bigLook, {to: 1, duration: 0.2})
	},
	
	switchLook: function(newLook) {
		if (this.currentLook) {
			new Effect.Opacity(this.currentLook, {to: 1, duration: 0.2})
		}

		if (newLook) {
			var afterFinish = function(){
				this.showNewLook(newLook)
			}.bind(this)
		} else {
			var afterFinish = function() {
				this.bigLook.setStyle({display: 'none'})
				this.currentLook = null
			}.bind(this)
		}

		if (this.bigLook && this.bigLook.getStyle('opacity')) {
			new Effect.Opacity(this.bigLook, {to: 0, afterFinish: afterFinish, duration: 0.1})
		} else {
			afterFinish()
		}
	}
}

var Mirror = {
	init: function() {
		if ($$('.forest').size()) {
			this.forest = $$('.forest')
			this.forest.invoke("setStyle", {"left": 0 })
			
			Event.observe(document, "mousemove", this.moveForest.bindAsEventListener(this))
		}
	},
	moveForest: function(event) {
		this.forest.invoke('setStyle', {"backgroundPosition":  this.getBackgroundX(event) + "% 50%"})
	},
	getBackgroundX: function(event) {
		return (event.pointerX() / document.viewport.getWidth())*100
	}
}

