Event.observe(window, 'load', function() {
	if ($$("ul.pageList")[0]) Slider.init()
	Persons.init()
	
	$$(".navigationMenu").each(function(element) {
		element.handler = Object.clone(DoubleColumns)
		element.handler.init(element.select('a'))
	})
	
	$$('a[internal]').each(function(element) {
 		new InternalLinks(element)
	})
	
	Preloader.init()
	pressList.init()
	url.init()
});

var InternalLinks = Class.create({
	initialize: function(element) {
		element.observe("click", function(event) {
			event.stop()
			this.openUrl(element.readAttribute("internal"))
		}.bind(this))
	},
	
	openUrl: function(route) {
		url.set(route)
		window.fromInternal = true
		url.init()
	}
})

var Preloader = {
	init: function() {
		this.images = [
			"leftarr.gif",
			"leftmenu-arr-inactive.gif",
			"leftmenu-arr.gif",
			"products_menu_bg_active.gif",
			"products_menu_bg.gif",
			"rightarr.gif"
		]
		
		this.doPreload()
	},
	
	doPreload: function() {
		this.images.each(function(url) {
			this.heavyImage = new Image(); 
			this.heavyImage.src = "/images/"+url;
		})
	}
}

var pressList = {
	init: function() {
		this.openedSheet = null

		$$('ul.pressList').each(function(pressListContainer){

			pressListContainer.childElements().each(function(element) {
				if (element.down('div.content')) {

					element.observe("click", function(event) {
						if (event.element().nodeName != 'A') pressList.initSlide(element)
					}.bind(this))
					element.down('div.content').observe("click", function(event) {
	//					event.stop()
					})

				}
			}.bind(this))
		}.bind(this))
	},
	
	initSlide: function(element) {
		if (this.openedSheet) { 
			if (this.openedSheet == element) {
				this.doSheetHide(element.down('div.content'))
				this.openedSheet = null
			} else {
				this.doSheetChange(element.down('div.content'))
				this.openedSheet = element
			}
		} else {
			this.openedSheet = element
			this.doSheetShow(element.down('div.content'))
		}
	},

	doSheetChange: function(open) {
		new Effect.SlideDown(open, { duration: 0.9})
		new Effect.SlideUp(this.openedSheet.down('div.content'), { duration: 0.9 });
	},

	doSheetShow: function(element) {
		new Effect.SlideDown(element, { duration: 0.9})
	},
	
	doSheetHide: function(element) {
		new Effect.SlideUp(element, { duration: 0.9})
	}
}

var url = {
	init: function () {
		this.curHost = this.getHost()
		this.domain = url.getDomain()
		
		this.routes = [
			{name: ':name', action: Slider.openPageFromUrl},
			{name: ':name/:id', action: Slider.openPageFromUrl}
		]
		
		this.currentPath = decodeURI(this.findUrl())
		if (this.currentPath != "false")  {
			this.parseRoutes()
		}
	},
	
	parseRoutes: function() {
		$A(this.routes).each(function(route) {
			this.splittedRoute = route["name"].split("/")
			this.splittedPath = this.currentPath.split("/")
			if (this.splittedRoute.length == this.splittedPath.length) {
				flag = true
				params = new Hash
				
				this.splittedRoute.each(function(block, index) {
					if (block.toLowerCase() != this.splittedPath[index]) {
						if (!block.match("\:.+")) {
							flag = false
						} else {
							params.set(block.substr(1), this.splittedPath[index])
						}
					}
					
				}.bind(this))
				

				if (flag) {
					route["action"](params)
				}
			}
		}.bind(this))
	},
	
	set: function(route) {
		window.location.href = this.domain + "#" + route
	},
	
	drop: function() {
		window.location.href = this.domain + "#"
	},
	
	redirectToHome: function() {
		window.location.href = urlParser.domain
	},
	
	getDomain: function() {
		return "http://"+document.domain
	},
	
	reloadWithHash: function(hash) {
		document.location.href = this.getDomain() + "#" + hash
	},
	
	goToIndex: function() {
		window.location.href = url.curHost
	},
	
	getHost: function() {
		if (window.location.href.match(/.+\#/g)) {
			host = window.location.href.match(/.+\#/g)[0]
			host = host.substr(0, host.length-1)
		} else {
			host = window.location.href
		}
		
		return host
	},
	
	findUrl: function() {
		cururl = window.location.href.match(/\#.+/g)
		if (cururl) {
			return cururl[0].substring(1)
		} else {
			return false
		}
	}
}


// Reviews part 

var Scroll = {
	init: function() {
		//setting defaults
		if ($('toleft')) $('toleft').observe('click', this.scrollLeft.bindAsEventListener(this));
		if ($('toright')) $('toright').observe('click', this.scrollRight.bindAsEventListener(this));

		this.image = $('imageContainer')
		this.scroller = $('blocks');
		this.scrollerWidth = parseInt($('blocks-wrap').getWidth());
		var lastElement = this.scroller.childElements().last();
		this.maxScrollOffset = lastElement.positionedOffset()['left'] + lastElement.getWidth();
		this.scroller.setStyle({'width': -this.maxScrollOffset + 'px'});
		this.maxScrollOffset = this.scrollerWidth - this.maxScrollOffset;

		this.scroller.childElements().each(function(element) {
			element.observe("click", function(event) {
				event.stop()
				Scroll.showImage(element)
			})
			
			element.observe("mouseover", function(event) {
				element.down('.description').show()
			})
			
			element.observe("mouseout", function(event) {
				element.down('.description').hide()
			})
		})
		this.showImage(this.scroller.childElements().first())
		this.checkArrows();
		this.currentOffset = 0
	},

	showImage: function(element) {
		if ($('flash-video')) {
			$('flash-video').remove()
			$('imageContainer').insert("<div id='flashArea'></div>")
		}
		
		if (!element.down('.video')) {
				this.imageSrc = element.down('.picture').innerHTML
				this.image.down('img').writeAttribute("src", this.imageSrc)
				this.image.down('img').setStyle({display:"block"})
		} else {
			this.image.down('img').setStyle({display:"none"})
			this.flashSrc = element.down('.video').innerHTML
			this.imageSrc = element.down('.picture').innerHTML
			swfobject.embedSWF("/swf/player.swf", "flashArea", "462", "290", "8.0.0", "/swf/expressInstall.swf", {video:this.flashSrc, picture:this.imageSrc}, {wmode:'transparent'},  {bgcolor: 'FFFFFF', allowfullscreen: true, allowScriptAccess: 'always', id: 'flash-video'});
		}
	
	},

	limitOffset: function(offset) {
		return Math.max(Math.min(0, offset), this.maxScrollOffset);
	},
	getOffsetByDirection: function(direction) {
		if (direction == 'left') {
			this.currentOffset = this.limitOffset(this.currentOffset + this.scrollerWidth);
		} else {
			this.currentOffset = this.limitOffset(this.currentOffset - this.scrollerWidth);
		}
		
		return this.currentOffset;
	},

	doScroll: function(direction) {
		new Effect.Morph(this.scroller, {
			style: 'left:'+this.getOffsetByDirection(direction)+'px',
			duration: 0.3
		});
		Scroll.checkArrows();
	},

	scrollLeft: function(event) {
		event.stop();
		this.doScroll('left');
	},

	scrollRight: function(event) {
		event.stop();
		this.doScroll('right');
	},

	checkArrows: function() {
		if (this.currentOffset == 0 || !this.currentOffset) {
			$('toleft').hide()
		} else {
			$('toleft').show()
		}
		
		if (this.currentOffset <= this.maxScrollOffset) {
			$('toright').hide()
		} else {
			$('toright').show()
		}
	}
}

DoubleColumns = {
	init: function(links) {
		this.productLinks = links
		if (this.productLinks.length > 0) {
			this.currentProduct = $(this.productLinks[0].readAttribute('rel'))
			
			this.opacityAnimationDuration = 0.2
			
			this.introText = this.productLinks[0].up('li').up('li').down('.intro')
			this.pageLink = this.productLinks[0].up('li').up('li').down('h3.clickable')
			
			this.rightCol = this.productLinks[0].up(".products").down(".productsWrap")
			
			this.productLinks.each(function(element) {
				element.observe("click", function(event) {
					event.stop()
					this.showProduct(event.findElement('a'))
				}.bind(this))
			}.bind(this))
		}
		
	},
	
	setBackButton: function() {
		this.pageLink.stopObserving("click")
		
		this.pageLink.observe("click", function() {
			this.showIntroPage()
		}.bind(this))
	},
	
	showIntroPage: function() {
		this.currentProduct.fade({duration: this.opacityAnimationDuration, afterFinish: function() {
			this.animateProductShow(this.introText)
		}.bind(this)})
		
		this.productLinks.each(function(element) {
			element.up('li').removeClassName("active")
		})
		
		
		this.currentProduct = $(this.productLinks[0].readAttribute('rel'))
		this.setOriginalEvent()
	},
	
	setOriginalEvent: function() {
		this.pageLink.stopObserving("click")
		this.pageLink.observe("click", function(event) {
			event.stop()
			Slider.addPageEvent(this.pageLink)
		}.bind(this))
	},
	
	handlePagesHide: function() {
		this.showIntroPage()
	},
	
	showProduct: function(element) {
		this.introText.hide()
		
		url.set(element.up('li').up('li').down('h3').readAttribute("id")+"/"+element.readAttribute("rel"))
		this.rightCol.setStyle({height: this.currentProduct.getHeight()+ "px"})
		
		this.currentProduct.fade({duration: this.opacityAnimationDuration, afterFinish: function() {
			this.animateProductShow(this.currentProduct)
		}.bind(this)})
		
		this.productLinks.each(function(element) {
			element.up('li').removeClassName("active")
		})
		
		element.up('li').addClassName("active")
		this.currentProduct = $(element.readAttribute('rel'))
		this.setBackButton()
	},
	
	animateProductShow: function(element) {
		element.appear({duration: this.opacityAnimationDuration})
			
		new Effect.Morph(this.rightCol, {
			style: {
				height: this.currentProduct.getHeight() + 'px'
			},
			duration: 0.2
		});
	}
}


Persons = {
	init: function() {
		this.personLinks = $$('#personsmenu a')
		if (this.personLinks.length > 0) {
			this.personLinks[0].up('li').addClassName("active")
			this.currentPerson = $(this.personLinks[0].readAttribute('rel'))

			this.rightCol = $$(".pageTeam .rightcol")[0]
			this.personLinks.each(function(element) {
				element.observe("click", function(event) {
					event.stop()
					Persons.showPerson(event.findElement('a'))
				})
			})

			this.opacityAnimationDuration = 0.2
		}
		
	},
	
	showPerson: function(element) {
		url.set(element.up('li').up('li').down('h3').readAttribute("id")+"/"+element.readAttribute("rel"))
		window.fromInternal = true
		
		this.rightCol.setStyle({height: this.currentPerson.getHeight()+ "px"})
		
		this.currentPerson.fade({duration: this.opacityAnimationDuration, afterFinish: function() {
			this.animatePersonShow()
		}.bind(this)})

		this.personLinks.each(function(element) {
			element.up('li').removeClassName("active")
		})
		
		element.up('li').addClassName("active")
		this.currentPerson = $(element.readAttribute('rel'))

	},
	
	animatePersonShow: function() {
		this.currentPerson.appear({duration: this.opacityAnimationDuration})
		
		new Effect.Morph(this.rightCol, {
			style: {
				height: this.currentPerson.getHeight() + 'px'
			},
			duration: 0.1
		});
	}
}

Slider = {
	init: function() {
		this.wrapper = $$('div.pagesWrap')[0]
		this.firma = $$('span.firma')[0]
		this.heading = $$('div.heading')[0]
		this.openedPage = null
		this.pagesElements = $$("ul.pageList")[0].childElements()
		if ($$('img.ho-we-do-it')[0]) {
			this.startBodyObserving()
		}
		
		$$('h3.clickable').each(function(element) {
			element.observe("click", function(event) {
				event.stop()
				this.addPageEvent(element)
			}.bind(this))
		}.bind(this))
		
		this.openedHeight = (this.pagesElements.length * 56) + 70
		this.normalHeight = this.pagesElements.length * 57 - 1 
	},
	
	addPageEvent: function(element) {
		if (Slider.openedPage !=element.up('li').down('div.container')) {
			Slider.selectActiveElement(element)
		}
		
		Slider.showPage(element.up('li').down('div.container'))
	},
	
	initShowAllPages: function(event) {
		if (!event.element().up('p.anticrisisLink')) {
			event.stop()
			this.stopBodyObserving()
			$$('img.ho-we-do-it')[0].hide()
			$$('body')[0].stopObserving("click")
			Slider.showAllPages()
		}
	},
	
	startBodyObserving: function() {
		$$('body')[0].setStyle({cursor:"pointer"})
		$$('body')[0].observe("click", function(event) {
			if (event.element().getAttribute('href') == null) {
				this.initShowAllPages(event)
			}
		}.bind(this))
		$('logo-top').stopObserving('click')
	},
	
	stopBodyObserving: function() {
		$$('body')[0].setStyle({cursor:"default"})
		$$('body')[0].stopObserving("click")
		$('logo-top').observe("click", function(event) {
			event.stop()
			Slider.hideAllPages()
		})
	},
	
	selectActiveElement: function(element) {
		$$('div.pagesWrap li').each(function(element) {
			element.removeClassName("openedPage")
			if (element.hasClassName('teamOpened')) {
				element.removeClassName("teamOpened")
				element.morph("background-color:#b2d600;", { duration: 0.3 })
			}
		})
		
		element.up('li').addClassName('openedPage')
		if (element.up('li').hasClassName("team")) {
			element.up('li').morph("background-color:#FFFFFF;", { duration: 0.5, delay: 0.3 })
			element.up('li').addClassName("teamOpened")
		}
	},
	
	showAllPages: function() {
		this.duration = 0.6
		this.callBackDuration = 1
		$$('img.ho-we-do-it')[0].hide()
		
		this.scrollToTop()

		new Effect.Morph(this.heading, { style: { opacity:"0", "margin-bottom":"10px"}, duration: this.duration, afterFinish: function() {
				new Effect.Morph(Slider.heading, { style: { opacity:"0", "margin-bottom":"45px"}, duration: this.callBackDuration, afterFinish: function() {
					$$("ul.pageList")[0].show()
					}
				})
		}.bind(this) });

		this.scrollToTop()

		this.wrapper.setStyle({display:"block"})
		this.firma.setStyle({display:"block"})
		new Effect.Morph(this.wrapper, { style: { height: Slider.openedHeight +"px", display: "block"}, duration: this.duration, afterFinish: function() {
				new Effect.Morph(Slider.wrapper, { style: { height: Slider.normalHeight +"px"}, duration: this.callBackDuration, afterFinish: function(){
					Slider.wrapper.setStyle({height:"auto"})
				}})
		}.bind(this) });

		this.scrollToTop()

		new Effect.Morph(this.heading.down('p'), { style: {height: "0px"}, duration: 0.4 });
		new Effect.Morph('car', { style: {"background-position": "160% bottom"}, duration: 0.4,
		afterFinish: function() {
			$('car').hide()
		} });
	},
	
	hideAllPages: function() {
		if (this.openedPage) {
			this.checkPageClosing()
			new Effect.SlideUp(this.openedPage, { duration: 0.9, afterFinish: function() {
					this.openedPage.up('li').removeClassName("openedPage")
					this.openedPage = null
					Slider.doHideAllPages()
					Products.handlePagesHide()
			}.bind(this) });
		} else {
			Slider.doHideAllPages()
		}
	},
	
	doHideAllPages: function() {
		this.animationDuration = 0.8
		new Effect.Morph(this.heading, { style: { "margin-bottom":"147px", "margin-top": "153px"}, duration: this.animationDuration});
		
		new Effect.SlideUp(this.wrapper, { duration: this.animationDuration, afterFinish: function() {
			Slider.startBodyObserving()
			$$('.pageList')[0].setStyle({display:"none"})
		} });
		
		$$('img.ho-we-do-it')[0].show()
		
		this.heading.setStyle({display:"block", height: "auto", opacity: "1"})
		this.heading.down('p').setStyle({height:"auto"})
		this.startBodyObserving()
	},
	
	openPageFromUrl: function(params) {
		if (params.get('name') == 'team') {
			Slider.openPersonFromUrl(params)
		} else {
			if (window.fromInternal) {
				Slider.findPageAndShow(params.get('name'))
				if (params.get('id')) {				
					setTimeout(function() {
						element = $$("a[rel="+params.get('id')+"]")[0]
						element.up(".navigationMenu").handler.showProduct(element)
					}, 1000)
				}
			} else {
				Slider.showAllPages()
				this.timeOut = setTimeout(function() {
					Slider.findPageAndShow(params.get('name'))
					if (params.get('id')) {				
						setTimeout(function() {
							element = $$("a[rel="+params.get('id')+"]")[0]
							element.up(".navigationMenu").handler.showProduct(element)
						}, 1000)
					}
				}, 1000)
			}
		}
	},
	
	openPersonFromUrl: function(params) {
		if (window.fromInternal) {
			Slider.findPageAndShow(params.get('name'))			
			element = $$("a[rel="+params.get('id')+"]")[0]
			
			if (params.get('id')) {				
				setTimeout(function() {
					element = $$("a[rel="+params.get('id')+"]")[0]
					Persons.showPerson(element)
				}, 1000)
			}
		} else {
			Slider.showAllPages()
			this.timeOut = setTimeout(function() {
				Slider.findPageAndShow(params.get('name'))
				if (params.get('id')) {				
					setTimeout(function() {
						element = $$("a[rel="+params.get('id')+"]")[0]
						Persons.showPerson(element)
					}, 1000)
				}
			}, 1000)
		}
	},
	
	findPageAndShow: function(name) {
		$$("li h3.clickable").each(function(element) {
			if (element.getAttribute('id') == name) {
				Slider.selectActiveElement(element)
				Slider.showPage(element.up('li').down('div.container'))
			}
		})
		
		this.stopBodyObserving()
		clearTimeout(this.timeOut)
	},
	
	scrollToTop: function(scrollToElement) {
		window.scrollTo(0,0)
		// if (!scrollToElement) scrollToElement = $$('div.heading')[0]
		// new Effect.ScrollTo(scrollToElement, {duration: 0.3});
	},
	
	showPage: function(element) {
		element.up('li').down('.container').setStyle({height:"auto"})
		this.pageAnimationDuration = 0.8
		this.headingAnimationDuration = 0.8
		if (this.openedPage != element) {
			url.set(element.up('li').down('h3').getAttribute('id'))
			if (this.openedPage) {

				this.scrollToTop()

				new Effect.Morph(this.heading, { style: { opacity:"0", "margin-bottom":"65px"}, duration: this.headingAnimationDuration})
				new Effect.SlideUp(this.openedPage, { duration: 0.8, afterFinish: function() {
					new Effect.Morph(Slider.heading, { style: { opacity:"0", "margin-bottom":"10px"}, duration: 0.4})
					
					new Effect.SlideDown(element, { duration: 0.8, afterFinish: function() {
						if (element.up('li').hasClassName("reviews")) Scroll.init()
					} });
				}.bind(this) });
			} else {
				new Effect.Morph(this.heading, { style: { opacity:"0", "margin-bottom":"0px", "margin-top":"50px"}, duration: this.headingAnimationDuration, afterFinish: function() {
					new Effect.SlideDown(element, { duration: 0.8, afterFinish: function() {
						if (element.up('li').hasClassName("reviews")) Scroll.init()
					} });
				}.bind(this) })
			}
			
			this.openedPage = element
		} else {
			url.drop()
			this.checkPageClosing()
			
			new Effect.SlideUp(element, { duration: 1.5, afterFinish: function() {
					new Effect.Morph(Slider.heading, { style: { opacity:"0", "margin-bottom":"10px", "margin-top":"153px"}, duration: 0.5})
					element.up('li').removeClassName("openedPage")
			} });
			
			this.openedPage = null
		}
	},
	
	checkPageClosing: function() {
		if (this.openedPage.up('li').hasClassName('teamOpened')) {
			this.openedPage.up('li').removeClassName("teamOpened")
			this.openedPage.up('li').morph("background-color:#b2d600;", { duration: 1.3 })
		}
	}
	
}

