Event.observe(window, 'load', function() {	
	$$('.textGallery').each(function(tg) {
		new TextGallery(tg)
	})
	
	$$(".spaceGallery").each(function(sg) {
		new SpaceGallery(sg)
	})
	
	// $$('.niceHover').each(function(nh) {
	// 	new NiceHover(nh)
	// })
	// 
	$$("a img").each(function(image) {
		new ImageHover(image)
	})
	
	$$('.setRelativeHeight').each(function(el) {
		new ColumnHeight(el)
	})
	
	Logo.init()

	
	if ($("gallery_event_id")) Tools.observeGalleryForm()
	if ($('map')) Tools.embedMap()
	if ($('photosList')) Photos.init()
})

Event.observe(document, 'dom:loaded', function() {
	SlidingTabs.init()
	if ($$('html')[0].hasClassName("ie7")) {
		$$('body')[0].descendants().each(function(d) {
			if (d.getStyle("display") == "inline-block") {
				d.setStyle({display: "inline"})
			}
		})
	}
})

var ColumnHeight = Class.create({
	initialize: function(element) {
		if (element.getHeight() < element.previous().getHeight()) {
			element.setStyle({
				height: ($('slidingTabs').down('.opened').getHeight() - 166) + 'px'
			})
		}
	}
})

var ImageHover = Class.create({
	initialize: function(element) {
		this.element = element
		this.wrap = this.element.wrap("div", {"class": "imageWrap"})
		this.wrap.insert("<div class='overlay'></div>")
		this.wrap.down('div.overlay').setStyle({
			width: this.element.getWidth() + 'px',
			height: this.element.getHeight() + 'px'
		})
		
		this.wrap.observe("mouseenter", function() {
			this.addHover()
		}.bind(this))
		
		this.wrap.observe("mouseleave", function() {
			this.removeHover()
		}.bind(this))
	},	
	
	addHover: function() {
		this.wrap.addClassName("mouseOver")
	},
	
	removeHover: function() {
		this.wrap.removeClassName("mouseOver")
	}
})

// var NiceHover = Class.create({
// 	initialize: function(element) {
// 		this.element = element
// 		this.wrap = this.element.down('.wrap')
// 		this.originalPosition = this.element.getStyle("position")
// 		
// 		this.element.observe("mouseenter", function() {
// 			this.addNiceHover()
// 		}.bind(this))
// 		
// 		this.element.observe("mouseleave", function() {
// 			this.removeNiceHover()
// 		}.bind(this))
// 	},
// 	
// 	addNiceHover: function() {
// 		this.element.setStyle({ height: this.element.getHeight() + 'px'})
// 		this.wrap.setStyle({ position: "absolute" })
// 		
// 		this.element.addClassName("niceHoverOn")
// 	},
// 	
// 	removeNiceHover: function() {
// 		this.element.setStyle({ 
// 			position: "relative"
// 		})
// 		
// 		this.element.removeClassName("niceHoverOn")
// 	}
// })

var Photos = {
	init: function() {
		this.container = $('photosList')
		this.elements = this.container.select("li")
		
		this.largeImage = $('largeImageView')
		
		this.blockWidth = this.elements.first().getWidth() + parseInt(this.elements.first().getStyle("marginRight"))
		this.center = 3
		this.duration = 0.5
		
		this.ul = this.container.down('ul')
		this.setUlWidth()
		
		this.elements.each(function(element) {
			element.observe("click", function() {
				this.scrollToElement(element, true)
			}.bind(this))
		}.bind(this))
		
		this.currentElement = this.container.down("li.current") 
		this.scrollToElement(this.currentElement)
		
		$('moveLeftLink').observe("click", function() {
			if (this.currentElement.previous()) this.scrollToElement(this.currentElement.previous(), true)
		}.bind(this))
		
		$('moveRightLink').observe("click", function() {
			if (this.currentElement.next()) this.scrollToElement(this.currentElement.next(), true)
		}.bind(this))
	},
	
	setUlWidth: function() {
		width = this.elements.length * this.blockWidth
		width += 30
		this.ul.setStyle({"width" : width + 'px'})
	},
	
	scrollToElement: function(element, animate) {
		this.currentElement = element
		
		this.elements.invoke("removeClassName", "current")
		this.currentElement.addClassName("current")
		
		index = this.elements.indexOf(element)
		position = (this.center - index) * this.blockWidth
		if (animate) {
			new Effect.Morph(this.ul, {
				style: { left: position + 'px' },
				duration: this.duration
			})
			
			this.largeImage.up('div.photo').setStyle({ height: this.largeImage.up('div.photo').getHeight() + 'px' })
			new Effect.Fade(this.largeImage, {
				afterFinish: function() {
					el = this.currentElement.down('img')
					this.largeImage.writeAttribute({
						src: el.readAttribute("rel"),
						width: el.readAttribute("new_size").split("x")[0],
						height: el.readAttribute("new_size").split("x")[1]
					})
					
					new Effect.Appear(this.largeImage, { duration: this.duration })
					this.largeImage.up('div.photo').setStyle({ height: "auto" })
				}.bind(this), duration: this.duration
			})
		} else {
			this.ul.setStyle({
				left: position + 'px'
			})
		}
	}
}

var Tools = {
	startpage: function() {
		return location.pathname == '/'
	},
	
	observeGalleryForm: function() {
		this.selector = $("gallery_event_id")
		this.selector.observe("change", function() {
			this.updateGalleryForm()
		}.bind(this))
	},
	
	updateGalleryForm: function() {
		this.selector.value == "" ? $('gallery_title_control').show() : $('gallery_title_control').hide()
	},
	
	embedMap: function() {
		if (GBrowserIsCompatible()) {
			var map = new GMap2($('map'));
			map.setCenter(new GLatLng(55.804971, -37.586095), 16)
			map.setUIToDefault()
		}
	}
}

var Logo = {
	init: function() {
		this.container = $('logo')
		
		this.bottom = this.container.down(".bottom")
		this.bottom.handler = new LogoPart(this.bottom)
		
		this.middle = this.container.down(".middle")
		this.middle.handler = new LogoPart(this.middle)
		
		this.top = this.container.down(".top")
		this.top.handler = new LogoPart(this.top)
		
		if (Tools.startpage()) {
			this.showAll()
			
			this.container.observe("mouseenter", function() { this.hideAll() }.bind(this))
			this.container.observe("mouseleave", function() { this.showAll() }.bind(this))
		}
	},
	
	showAll: function() {
		this.middle.handler.goToColumn()
		this.top.handler.goToColumn()
	},
	
	hideAll: function() {
		this.middle.handler.goToBase()
		this.top.handler.goToBase()
	},
	
	animatePart: function(part) {
		parts = {
			"events": "top",
			"community": "bottom", 
			"space": "middle"
		}
		
		logoPart = parts[part]
		eval("this." + logoPart + ".handler.animateWidth()")
	}
}

var LogoPart = Class.create({
	initialize: function(element) {
		this.element = element
		this.defaultPosition = parseInt(element.getStyle("left"))
		
		this.image = this.element.down('img')
		
		this.defaultWidth = this.image.getWidth()
		this.minWidth = 1
		
		this.leftLimit = -306
		this.rightLimit = 335
		
		this.duration = 1
		this.rotateDuration = 0.2
	},
	
	goToColumn: function() {
		position = this.element.hasClassName("middle") ? this.rightLimit : this.leftLimit
			
		new Effect.Morph(this.element, {
			style: { left: position + 'px' }, duration: this.duration, 
			transition: Effect.Transitions.sinoidal
		})
	},
	
	goToBase: function() {
		new Effect.Morph(this.element, {
			style: { left: this.defaultPosition + 'px' }, duration: this.duration, 
			transition: Effect.Transitions.sinoidal
		})
	},
	
	animateWidth: function() {
		new Effect.Morph(this.image, {
			style: { width: this.minWidth + 'px' },
			duration: this.rotateDuration,
			afterFinish: function() { this.finishAnimateWidth() }.bind(this)
		})
	},
	
	finishAnimateWidth: function() {
		new Effect.Morph(this.image, {
			style: { width: this.defaultWidth + 'px' },
			duration: this.rotateDuration
		})
	}
})

var SpaceGallery = Class.create({
	initialize: function(element) {
		this.container = element
		this.imageContainer = element.down('div.wrap')
		this.images = this.imageContainer.select("img.image")
		
		this.images.invoke("setStyle", "left: 100%")
		this.images.first().setStyle("left: 0")
		
		this.zoomLinks = this.container.select('a.zoomLink')
		
		this.counter = this.container.down('div.text').down('span.current')

		this.currentImage = 0 
		this.animationDuration = 0.6
		
		this.imageContainer.down('img.left').observe("click", function() {
			this.goPrevious()
		}.bind(this))
		
		this.images.each(function(image) {
			image.setStyle({"cursor": "pointer"})
			image.observe("click", function() { this.goNext() }.bind(this))
		}.bind(this))
		
		this.imageContainer.down('img.right').observe("click", function() {
			this.goNext()
		}.bind(this))
	},
	
	goNext: function() {
		newIndex = this.currentImage == (this.images.length - 1)  ? 0 : this.currentImage + 1
		this.showImage(this.currentImage, newIndex, "right")
	},
	
	goPrevious: function() {
		newIndex = this.currentImage == 0 ? (this.images.length - 1) : this.currentImage - 1
		this.showImage(this.currentImage, newIndex, "left")
	},
	
	showImage: function(previous, next, direction) {
		this.currentImage = next
		this.counter.innerHTML = this.currentImage + 1
		
		if (direction == "left") {
			this.images[next].setStyle({left: "-100%"})
			
			new Effect.Morph(this.images[next], {
				style: { left: "0%" }, duration: this.animationDuration
			})
			
			new Effect.Morph(this.images[previous], {
				style: { left: "100%"}, duration: this.animationDuration
			})
		} else {
			this.images[next].setStyle({left: "100%"})
			this.images[previous].setStyle({left: "0"})
			
			new Effect.Morph(this.images[next], {
				style: { left: "0%" }, duration: this.animationDuration
			})
			
			new Effect.Morph(this.images[previous], {
				style: { left: "-100%" }, duration: this.animationDuration
			})
		}
		
		this.setZoomLinkUrl()
	},
	
	setZoomLinkUrl: function() {
		largeImage = this.images[this.currentImage].up('span').readAttribute("rel")
		this.zoomLinks.each(function(link) {
			link.readAttribute("href") == largeImage ? link.show() : link.hide()
		})
	}
})

var TextGallery = Class.create({
	initialize: function(element) {
		this.container = element
		this.imageContainer = element.down('div.images')
		this.images = this.imageContainer.select("img")
		this.images.invoke("hide")
		this.images.first().show()
		
		this.counter = this.container.down('div.title').down('span.text').down('span.current')
		this.updateImageContainerSize(this.images.first())
		
		this.images.each(function(image) {
			image.observe("click", function() {
				this.goNext()
			}.bind(this))
		}.bind(this))
		
		this.currentImage = 0
		
		this.container.down('img.goPrevious').observe("click", function() {
			this.goPrevious()
		}.bind(this))
		
		this.container.down('img.goNext').observe("click", function() {
			this.goNext()
		}.bind(this))
	},
	
	goNext: function() {
		newIndex = this.currentImage == (this.images.length - 1)  ? 0 : this.currentImage + 1
		this.showImage(this.currentImage, newIndex)
	},
	
	goPrevious: function() {
		newIndex = this.currentImage == 0 ? (this.images.length - 1) : this.currentImage - 1
		this.showImage(this.currentImage, newIndex)
	},
	
	showImage: function(previous, next) {
		this.currentImage = next
		this.counter.innerHTML = this.currentImage + 1
		this.updateImageContainerSize(this.images[next])
		new Effect.Fade(this.images[previous], { duration: 0.4 })
		new Effect.Appear(this.images[next], { duration: 0.4 })
	},
	
	updateImageContainerSize: function(image) {
		this.imageContainer.setStyle({
			width: image.getWidth() + 'px',
			height: image.getHeight() + 'px'
		})
	}
})

var SlidingTabs = {
	init: function() {
		this.container = $("slidingTabs")
		this.tabs = this.container.select("div.tab")
		this.fadeDuration = 0.5
		this.morphDuration = 1.2
		this.bgDuration = 0.2
		this.title = $$('title')[0]
		this.defaultTitle = this.container.readAttribute("defaultTitle")
		
		this.tabs.each(function(tab) {
			tab.bar = tab.down('div.bar')
			tab.bar_link = tab.down('a.j-tab-bar_link')
			tab.short = tab.down('div.short')
			tab.large = tab.down('div.large')
			tab.defaultBg = tab.getStyle("backgroundColor")
			
			tab.bar_link.observe("click", function(event) {
				Event.stop(event);
				if (!tab.hasClassName("opened")) this.showTab(tab, Event.element(event).up('a').readAttribute('href'))
				return false;
			}.bind(this))
			
			tab.observe("mouseenter", function() {  this.highlightTab(tab) }.bind(this))
			tab.observe("mouseleave", function() { this.removeTabHighLight(tab) }.bind(this))
		}.bind(this))
		
		// if (this.container.down("div.opened")) this.setCurrentTab(this.container.down("div.opened"))
		this.setTabsHeight()
		
		$('logo').observe("click", function() {
			this.closeAllTabs()
		}.bind(this))
	},
	
	setTabsHeight: function(tab) {
		this.tabs.invoke("setStyle", {height: 'auto'})
		if (tab) {
			maxHeight = tab.getHeight()
		} else {
			maxHeight = this.tabs.max(function(t) { return t.getHeight() })
		}
		this.tabs.invoke("setStyle", {height: maxHeight + 'px'})
	},
	
	setCurrentTab: function(tab) {
		tab.setStyle({width: this.openedTabWidth() + 'px'})
		// tab.down('div.short').hide()
		// tab.down('div.large').show()
		this.otherTabs(tab).each(function(t) {
			t.setStyle({width: t.bar.getWidth() + 'px'})
			t.down('div.inner').hide()
		}.bind(this))
	},
	
	openedTabWidth: function() {
		barWidth = this.tabs.first().bar.getWidth()
		margin = parseInt(this.tabs.first().getStyle("marginRight"))
		usedWidth = (this.tabs.length - 1) * (margin + barWidth)
		width = this.container.getWidth() - usedWidth - 46
		return width
	},
	
	showTab: function(tab, content_url) {
		var self = this
		var i = 0;
		this.tabs.each(function(t) {
			if ( t !== tab){
				this.fadeContent(t.down('div.inner'), function(){
					self.closeTab(t); 
					if (i == 1){ self.openTab(tab, content_url); console.log(tab)}
					i++
				})
			}
			if (t.hasClassName('b-tab-index')){
				t.removeClassName('b-tab-index')
			}
		}.bind(this))
	},
	
	highlightTab: function(tab) {
		tabName = $w(tab.className)[1].gsub("Tab", "")
		Logo.animatePart(tabName)
		this.backgroundIn(tab)
	},
	
	removeTabHighLight: function(tab) {
		this.backgroundOut(tab)
	},
	
	fadeContent: function(block, callback) {
		if (block) {
			new Effect.Fade(block, {
				duration: this.fadeDuration,
				afterFinish: callback
			})			
		}
	},
	
	backgroundIn: function(tab) {
		tab.addClassName("hover")
	},
	
	backgroundOut: function(tab) {
		tab.removeClassName("hover")
	},
	
	openTab: function(tab, content_url) {
		var self = this;
		tab.addClassName("opened b-sliding-tab-opened")
		this.setTitle(tab.readAttribute("title"))
				
		new Effect.Morph(tab, {
			duration: this.morphDuration,
			style: { width: this.openedTabWidth() + 'px' },
			afterFinish: function() {
				
				new Ajax.Request(content_url + '.js',
					{ method:'get',
						onSuccess: function(response){
							window.location.hash = 'redirect-' + content_url
							var text = response.responseText
							tab.down('div.inner').replace('<div class="inner"><div class="large">' + text + '</div></div>')
							self.tabs.invoke("setStyle", {height: tab.down('div.inner').getHeight() + 140 + 'px'})
						}
					}
				)
				
				new Effect.Appear(
					tab.down('div.inner'),
					{ duration: this.fadeDuration,
						afterFinish: function() { 
							// window.location = content_url
							this.setTabsHeight(tab.down('div.inner')) 
						}.bind(this)
					}
				)
			}.bind(this)
		})
	},
	
	closeAllTabs: function() {
		maxHeight = 0
		this.setTitle()
		this.tabs.each(function(tab) {
		// 	tab.down('div.large').hide()
			this.fadeContent(tab.down('div.large'));
			tab.removeClassName('opened')
			tab.removeClassName('b-sliding-tab-opened')
			new Effect.Morph(tab, {
				style: { width: "326px" },
				duration: this.morphDuration,
				afterFinish: function() {
					tab.addClassName('b-tab-index');
					this.setTabsHeight();
					var self = this 
					tab.down('div.inner').show();
					new Ajax.Request( tab.down('a.j-tab-bar_link') + '_short.js',
						{ method:'get',
							onSuccess: function(response){
								var text = response.responseText
								// console.log(this.container)
								tab.down('div.inner').replace('<div class="inner">' + text + '</div>')
								self.setTabsHeight();
								window.location.hash = 'redirect-/'
							}
						}
					)
				}.bind(this)})
		}.bind(this))
		
		// todo: refactor
	},
	
	closeTab: function(tab) {
		new Effect.Morph(tab, {
			duration: this.morphDuration,
			style: { width: tab.bar.getWidth() + 'px' },
			afterFinish: function() { tab.removeClassName("opened"); tab.removeClassName("b-sliding-tab-opened") }
		})
	},
	
	otherTabs: function(tab) {
		return this.tabs.without(tab)
	},
	
	setTitle: function(title) {
		
		this.title.remove()
		if (title) {
			$$('head')[0].insert("<title>" + title + " — " + this.defaultTitle + "</title>")
		} else {
			$$('head')[0].insert("<title>" + this.defaultTitle + "</title>")
		}

		this.title = $$('title')[0]
	}
}
