Event.observe(document, 'dom:loaded', function() {
	$$(".thumbnailsBackupView").each(function(element) {
		new BackupsScroller(element)
	})
	
	$$(".backupsListSmall").each(function(element) {
		new SmallBackupsList(element)
	})
	
	$$('.niceButton').each(function(element) {
		new niceButton(element)
	})
	
	$$("ul").each(function(element) {
		element.select("li").each(function(element, index) {
			if (index % 2 != 0) element.addClassName("even")
		})
	})
	
	$$(".postToTwitterForm").each(function(element) { new TwitterForm(element) })
	
	if ($('fileBrowser')) {
		FileBrowser.init()
	}
	
	$$("div.activity").each(function(element) {
		new Activity(element)
	})
	
	if ($$("div.addApplicationButton")[0]) Tools.initAddApplicationPopup()
	
	if ($$(".toggleGroupsDiv")[0]) ToggleTabs.init()
	if ($('niceDialog')) NiceDialog.init()
	
	$$('.fullHeightDiv').each(function(div) { 
		new FullHeightDiv(div) 
	})
	
	if ($$('.backupsTable')[0]) BackupsTable.init()
	$$('.toggleElements').each(function(element) { 
		new ToggleElementsForm(element)
	})
	
	if ($$(".clock")[0]) Clock.init()
	$$('.multipleItemsList').each(function(element) {
		new MultipleItemsList(element)
	})
	
	$$('.screenshotsList').each(function(element) { new ScreenScroll(element) })
	if ($$('body.startPage')[0]) Tools.initStartPageBodyHeight()
	Tools.preload("/images/internal/small-popup-bg-top.png")
	Tools.preload("/images/internal/small-popup-bg-bottom.png")
	setupZoom()
	
	$$('.toggleSubmitForm').each(function(element) { new ToggleSubmitForm(element) })
	Tools.initTextPopups()
	TimeZoneDetector.detect()
	
	$$('input[placeholder]').each(function(element) {
		new Placeholder(element)
	})
	
	$$('div.help div.pages ul.articles').each(function(list){
		list.childElements().each(function(element) {
			new HelpToggle(element)
		})
	})
	
	$$('div.help div.categories').each(function(element) {
		new HelpTabs(element)
	})
	
	if ($('restoringBackupsToggle')) RestoringBackups.init()
	if ($$('.profileForm')[0]) ProfileForm.init()
	if ($('tariffsSelector')) TariffsSelector.init()
})



var ProfileForm = {
	init: function() {
		this.form = $$('.profileForm')[0]
		this.form.observe("submit", function(event) {
			event.stop()
			Tools.showFormPopup('confirmPasswordPopup')
		})
	}
}

var RestoringBackups = {
	init: function() {
		this.link = $('restoringBackupsToggle')
		this.popup = $('restoringApps')
		
		this.link.observe("click", function() {
			this.togglePopup()
		}.bind(this))
	},
	
	togglePopup: function() {
		if (this.link.hasClassName('active'))  {
			this.link.removeClassName('active')
			Effect.Fade(this.popup, { duration: 0.3 })
		} else {
			this.link.addClassName('active')
			Effect.Appear(this.popup, { duration: 0.3 })
		}
	}
}

var	HelpTabs = Class.create({
	initialize: function(element) {
		this.container = element.down('ul')
		this.children = this.container.childElements()
		
		this.groups = element.up("div.help").down('.pages').select('div.group')
		
		this.children.each(function(child) {
			child.observe("click", function() { this.toggle(child) }.bind(this))
		}.bind(this))
	},
	
	toggle: function(child) {
		this.children.invoke('removeClassName', 'active')
		child.addClassName('active')
		
		if ($(child.readAttribute("rel"))) {
			this.groups.invoke('hide')
			$(child.readAttribute("rel")).show()
		} else {
			this.groups.invoke('show')
		}
	}
})

var HelpToggle = Class.create({
	initialize: function(element) {
		this.element = element
		this.text = this.element.down('div.content')
		this.header = this.element.down('h3')
		this.duration = 0.3
		
		this.header.observe("click", function() {
			this.element.hasClassName("closed") ? this.open() : this.close()
		}.bind(this))
	},
	
	open: function() {
		this.element.removeClassName("closed")
		this.slideDown()
	},
	
	close: function() {
		this.element.addClassName("closed")
		Effect.SlideUp(this.text, { duration: this.duration })
	},
	
	slideDown: function() {
		this.text.show()
		var targetHeight = this.text.getHeight()
		this.text.setStyle({ height: '0px', overflow: "hidden" })

		new Effect.Morph(this.text, {
			style: { height: targetHeight + 'px' },
			duration: this.duration
		})
	}
})

var TimeZoneDetector = {
	detect: function() {
		current_time = new Date()
		Cookie.set('timezone', current_time.getTimezoneOffset(), 1000)
	}
}

var Placeholder = Class.create({
	initialize: function(element) {
		if (this.detect()) return;
		
		this.element = element
		this.t = element.readAttribute("placeholder")
		this.element.removeAttribute("placeholder")
		this.element.originalType = this.element.readAttribute('type')
		
		if (this.element.value == '') this.setDefaultValues()

		this.element.observe("blur", this.blur.bind(this))
		this.element.observe("focus", this.focus.bind(this))
		this.element.observe("change", this.focus.bind(this))
		this.blur()
	},
	
	detect: function() {
		var i = document.createElement('input');
		return 'placeholder' in i;
	},
	
	setDefaultValues: function() {
		this.disable()
	},
	
	blur: function() {
		if (this.element.value == '') this.disable()
	},
	
	focus: function() {
		if (this.element.value == this.t) this.enable()
	},
	
	enable: function() {
		this.element.value = '' 
		this.element.removeClassName('hint')
		this.element.writeAttribute("type", this.element.originalType)
	},
	
	disable: function() {
		this.element.value = this.t
		this.element.addClassName("hint")
		this.element.writeAttribute("type", "text")
	}
})

var ToggleSubmitForm = Class.create({
	initialize: function(element) {
		this.container = element
		this.baseValue = Form.serialize(this.container)
		this.button = this.container.down("input[type=submit]")
		this.disableButton()
		
		setInterval(function() {
			this.checkCurrentFormValue()
		}.bind(this), 10)
	},
	
	checkCurrentFormValue: function() {
		this.baseValue != Form.serialize(this.container) ? this.enableButton() : this.disableButton()
	},
	
	enableButton: function() {
		this.button.writeAttribute("type", "submit")
		this.button.up("div.niceButton").removeClassName("disabled")
	},
	
	disableButton: function() {
		this.button.writeAttribute("type", "button")
		this.button.up("div.niceButton").addClassName("disabled")
	}
})

var ScreenScroll = Class.create({
	initialize: function(element) {
		this.container = element
		this.children = this.container.childElements()
		
		this.zindex = 10000
		this.defaultWidth = this.children.first().getWidth()
		this.outWidth = parseInt(this.container.getWidth() / 3)
		this.animationDuration = 0.3
		
		this.children.each(function(child, index) {
			this.children[index].leftPosition = child.positionedOffset().left
			this.children[index].defaultWidth = child.getWidth()
		}.bind(this))

		this.children.each(function(element) {
			element.observe("mouseover", function() { this.showScreenshot(element) }.bind(this))
		}.bind(this))
	},
	
	showScreenshot: function(element) {
		this.hidePreviousElements(element)
	},
	
	hidePreviousElements: function(element) {
		this.children.each(function(child, index) {
			if (index < this.children.indexOf(element)) {
				child.morph("width:" + this.outWidth + 'px', {duration: this.animationDuration})
			} else if (index == this.children.indexOf(element)) {
				child.morph("width:" + this.defaultWidth + 'px', {duration: this.animationDuration})
			}
		}.bind(this))
	}
})

var MultipleItemsList = Class.create({
	initialize: function(element) {
		this.container = element
		this.children = this.container.select("li")
		
		this.formElement = $(this.container.readAttribute('rel'))
		
		this.children.each(function(element) {
			if (!element.hasClassName("inactive")) element.observe("click", function() { this.toggleElement(element) }.bind(this))
		}.bind(this))
	},
	
	toggleElement: function(element) {
		element.hasClassName("active") ? element.removeClassName("active") : element.addClassName("active")
		this.updateForm()
	},
	
	updateForm: function() {
		arr = []
		this.container.select("li.active").each(function(element) {
			arr.push(element.readAttribute('rel'))
		})
		
		this.formElement.value = arr.join(" ")
	}
})

var Clock = {
	init: function() {
		this.container = $$('.clock')[0]
		this.hours = this.container.down('.time')
		this.date = this.container.down(".date")
		this.halfTimeContainer = this.container.down('span.half')
		
		setInterval(function() {
			this.updateTime()
		}.bind(this), 500)
	},
	
	
	halfTime: function() {
		return this.halfTimeContainer.hasClassName("active")
	},
	
	updateTime: function() {
		t = new Date() 
		delimiter = this.hours.innerHTML.match(/\:/) ? " " : ":"
		delimiter = "<span class='timeDelimiter'>"+delimiter+"</span>"
		
		this.hours.innerHTML = this.halfTime() ? t.strftime("%I" + delimiter + "%M %p") : t.strftime("%H" + delimiter + "%M")
		this.date.innerHTML = t.strftime("%d %B")
	}
}

var ToggleElementsForm = Class.create({
	initialize: function(element) {
		this.container = element
		this.currentElement = this.container.down('.active')
		
		this.changeField = $(this.container.readAttribute('rel'))
		this.elements = this.container.select(this.currentElement.tagName)
		
		this.elements.each(function(element) {
			element.observe("click", function() { if (!element.hasClassName("active")) this.toggleElements(element) }.bind(this))
		}.bind(this))
	},
	
	toggleElements: function(element) {
		this.elements.invoke('removeClassName', "active")
		element.addClassName('active')
		
		this.changeField.value = element.readAttribute("rel")
		if (this.container.hasClassName("upgradeTariffsList")) Tools.updateNewTariffData(this.changeField.value)
	}
})

var BackupsTable = {
	init: function() {
		this.container = $$('.backupsTable')[1]
		this.wrapper = this.container.up(".backupsTableContainer")
		
		this.row = this.container.select("tr").last()
		
		while (this.container.getHeight() < this.wrapper.getHeight()) {
			this.createColumns()
		}
		
		this.container.select("tr").last().remove()
	},
	
	createColumns: function() {
		this.container.down('tbody').insert("<tr>" + this.row.innerHTML + "</tr>")
		this.updateOddEven()
	},
	
	updateOddEven: function() {
		this.container.down('tbody').select("tr").each(function(element, index) {
			element.removeClassName("even")
			element.removeClassName("odd")
			index % 2 != 0 ? element.addClassName("even") : element.addClassName("odd")
		})
	}
}

var FullHeightDiv = Class.create({
	initialize: function(element) {
		this.container = element
		this.marginBottomSize = parseInt(this.container.getStyle("marginBottom"))
		this.resize()
		Event.observe(document.onresize ? document : window, "resize", function() {
			this.resize()
		}.bind(this))
	},
	
	resize: function() {
		height = document.viewport.getHeight() - this.container.positionedOffset().top
		height = height - this.marginBottomSize
		this.container.setStyle({ height: height + 'px', "margin-bottom": "0" })
	}
})

var SmartOrderCalc = {
	init: function() {
		this.container = $('smartOrderCalc')
		this.field = this.container.down("input.text")
		this.subTotal = $('subTotalSum').down('.value')
		
		this.price = parseFloat(this.container.down('span.tariffPrice').innerHTML)

		if (this.container.down(".currentBalance")) {
			this.balance = parseFloat(this.container.down(".currentBalance").down(".value").innerHTML)
			this.total = this.container.down(".total").down(".value")
		}
		
		this.hiddenField = $('priceHiddenField')
		this.field.observe("keyup", function() { 
			this.updateSubTotal() 
		}.bind(this))
	},
	
	updateSubTotal: function() {
		if (this.field.value.match(/[0-9]+/)) {
			this.parsedValue = parseFloat(this.field.value.match(/[0-9]+/)[0])
			this.subTotal.innerHTML = this.price * this.parsedValue
			this.field.value = this.parsedValue
			if (this.balance) this.updateTotal(this.parsedValue * this.price)
		} else {
			this.field.value = ""
		}
		this.hiddenField.value = this.balance ? this.total.innerHTML : this.subTotal.innerHTML
	},
	
	updateTotal: function(value) {
		this.total.innerHTML = (value - this.balance)
	}
}

var NiceDialog = {
	init: function() {
		this.popup = $('niceDialog')
		this.closeButton = $('closeNiceDialog')
		this.popupWrap = this.popup.down("div.wrap")
		
		this.closeButton.observe("click", function() { this.hide() }.bind(this))
	},
	
	hide: function() {
		new Effect.Morph(this.popup, {
			style: 'height: 0px',
			duration: 0.4,
			afterFinish: function() {
				this.popup.setStyle({display: "none"})
			}.bind(this)
		})
	},
	
	show: function(container) {
		this.popup.show()
		if (container) this.popupWrap.innerHTML = $(container).innerHTML
		
		this.popupHeight = document.viewport.getHeight() - 50
		this.wrapHeight = this.popupHeight - parseInt(this.popupWrap.getStyle("padding-top")) - parseInt(this.popupWrap.getStyle("padding-bottom"))
		
		this.popupWrap.setStyle({"height" : this.wrapHeight + 'px'})
		new Effect.Morph(this.popup, {
			style: 'height: '+ this.popupHeight +'px',
			duration: 0.4,
			afterFinish: function() {
				if ($('smartOrderCalc')) SmartOrderCalc.init()
			}.bind(this)
		})
	}
}

var Tools = {
	initAddApplicationPopup: function() {
		this.addAppButton = $$("div.addApplicationButton")[0]
		
		this.addAppPopup = $('addAppPopup')
		this.closePopupButton = this.addAppPopup.down('.closePopup').down("input")
		
		this.addAppButton.observe("click", function() { this.showAddAppPopup() }.bind(this))
		this.closePopupButton.observe("click", function() { this.closeAddAppPopup() }.bind(this))
	},
	
	showAddAppPopup: function() {
		this.addAppButton.hide()
		this.addAppPopup.setStyle({
			display: "block",
			overflow: "hidden",
			height: 0 + 'px'
		})
		
		new Effect.Morph(this.addAppPopup, {
		  style: 'height: 100px',
		  duration: 0.8
		})
		
		new Effect.Morph('domainsList', {
			style: 'height: '+ ($('domainsList').getHeight() - 100) + 'px',
			duration: 0.8
		})
	},

	closeAddAppPopup: function() {
		new Effect.Morph(this.addAppPopup, {
			style: 'height: 0px',
			duration: 0.8, 
			afterFinish: function() {
				this.addAppButton.show()
				this.addAppPopup.hide()
			}.bind(this)
		})
		
		new Effect.Morph('domainsList', {
			style: 'height: '+ ($('domainsList').getHeight() + 100) + 'px',
			duration: 0.8
		})
	},
	
	showFormPopup: function(id) {
		realId = id || 'smallPopup'
		new Effect.Appear('fade', { duration: 0.6, to: parseFloat($('fade').getStyle('opacity')) })
		new Effect.Appear(realId, { duration: 0.6 })
		
		$(realId).stopObserving("click")
		$(realId).down(".close").observe("click", function(event) {
			event.stop()
			this.hideFormPopup(realId)
		}.bind(this))
	},
	
	hideFormPopup: function(id) {
		new Effect.Fade('fade', { duration: 0.6 })
		new Effect.Fade(id, { duration: 0.6 })
	},
	
	updateNewTariffData: function(id) {
		new Ajax.Request('/tariffs/'+id, { method:'get' })
	},
	
	preload: function(file) {
		var tmp = new Image()
		tmp.src = file
	},
	
	initStartPageBodyHeight: function() {
		this.startpageBody = $$('body.startPage')[0]
		this.setStartpageBodyHeight()
		Event.observe(document.onresize ? document : window, "resize", function() {
			this.setStartpageBodyHeight()
		}.bind(this))
	},
	
	setStartpageBodyHeight: function() {
		this.startpageBody.setStyle({
			height: document.viewport.getHeight() + 'px'
		})
	},
	
	initTextPopups: function() {
		if ($('tosLink')) { 
			$('tosLink').observe("click", function(event) {
				event.stop()
				this.textPopup($('tosLink').readAttribute("href"))
			}.bind(this))
		}
	},
	
	textPopup: function(url) {
		window.open(url + "?small=true", 'title', "menubar=no,width=950,height=630,toolbar=no")
	},
	
	include: function(url) {
		new Ajax.Request("/javascripts/" + url + '.js', { method: "get" })
	}
}

var Activity = Class.create({
	initialize: function(element) {
		this.container = element
		
		this.groupsContainer = this.container.down("div.toggleGroups")
		this.filesContainer = this.container.down("div.files")
		this.fileInfo = this.container.down("div.fileInfo")
		
		this.setHeight()
		
		this.groupsContainer.select("li").each(function(element) {
			if (!element.hasClassName("disabled"))	element.observe("click", function() { this.toggleMenuGroup(element) }.bind(this))
		}.bind(this))
		
		this.filesContainer.select("h6").each(function(element) {
			element.observe("click", function() { this.toggleGroup(element.up("div")) }.bind(this))
		}.bind(this))
		
		this.filesContainer.select("li").each(function(element) {
			if (element.up(".filesGroup").id != "deletedFiles") {
				element.observe("click", function() {
					this.selectElement(element)
					this.getFileData(element)
				}.bind(this))
			}
		}.bind(this))
	},
	
	selectElement: function(element) {
		this.filesContainer.select("li").invoke('removeClassName', "active")
		element.addClassName("active")
	},
	
	getFileData: function(element) {
		new Ajax.Request("/files/show", { 
			method: 'post',
			parameters: [
				'id=' + this.container.readAttribute("backup_id"),
				'folder=' + element.readAttribute("folder"),
				'authenticity_token=' + encodeURIComponent(window._authenticity_token)
			].join('&'),
			onComplete: function(transport) {
				this.fileInfo.innerHTML = transport.responseText
			}.bind(this)
		})
	},
	
	toggleMenuGroup: function(element) {
		this.showFilesGroupByRel(element.readAttribute("rel"))
		this.toggleClassNames(element)
	},
	
	closeElement: function(element) {
		element.down('h6').addClassName("closed")
		element.down('ul').hide()
	},
	
	openElement: function(element) {
		element.down('h6').removeClassName("closed")
		element.down('ul').show()
	},
	
	showFilesGroupByRel: function(rel) {
		elements = this.container.select('div.filesGroup')
		
		if (rel) {
			elements.each(function(e) { this.closeElement(e) }.bind(this))
			this.openElement($(rel))
		} else {
			elements.each(function(e) { this.openElement(e) }.bind(this))
		}
	},
	
	toggleGroup: function(element) {
		element.down('h6').hasClassName("closed") ? this.openElement(element) : this.closeElement(element)
	},
	
	toggleClassNames: function(element) {
		this.groupsContainer.select("li").invoke('removeClassName', "active")
		element.addClassName("active")
	},
	
	setHeight: function() {
		height = document.viewport.getHeight() - this.container.positionedOffset().top
		
		this.groupsContainer.setStyle({ height: height + 'px' })
		this.filesContainer.setStyle({ height: height + 'px' })
		this.fileInfo.setStyle({ height: height + 'px' })
	}
})

var ToggleTabs = {
	init: function() {
		this.container = $$(".toggleGroupsDiv")[0]
		this.tabsContainer = this.container.down(".toggleGroups")
		this.dataContainer = this.container.down(".toggleContent")
		
		this.tabs = this.tabsContainer.select("li")
		this.groups = this.dataContainer.select(".group")
		
		this.tabs.each(function(tab) {
			tab.observe('click', function() { this.showGroupByRel(tab) }.bind(this))
		}.bind(this))
		
		this.setHeight()
	},
	
	toggleClassNames: function(element) {
		this.tabs.invoke('removeClassName', "active")
		element.addClassName("active")
	},
	
	setHeight: function() {
		height = document.viewport.getHeight() - this.container.positionedOffset().top
		height = height - parseInt(this.container.getStyle("marginBottom"))
		this.container.setStyle({ height: height + 'px' })
		this.tabsContainer.setStyle({ height: height + 'px' })
		this.dataContainer.setStyle({ height: height + 'px' })
		this.tabsContainer.down('ul').setStyle({ height: height + 'px' })
	},
	
	showGroupByRel: function(tab) {
		this.groups.invoke('hide')
		$(tab.readAttribute("rel")).show()
		
		this.toggleClassNames(tab)
	},
}

var SmallBackupsList = Class.create({
	initialize: function(element) {
		this.element = element
		this.wrap = this.element.down('div.wrap')
		this.list = this.element.down('ul')
		this.blocks = this.list.childElements()
		this.blockWidth = 48
		
		Event.observe(document.onresize ? document : window, "resize", function() {
			this.setWidth()
			this.setCurrentBlock()
			this.checkArrows()
		}.bind(this))
		
		this.setWidth()
		this.setCurrentBlock()
		this.element.down("a.back").observe("click", this.scrollLeft.bind(this))
		this.element.down("a.forward").observe("click", this.scrollRight.bind(this))
		this.checkArrows()
	},
	
	setWidth: function() {
		this.list.setStyle({
			width: (this.blocks.size() * this.blockWidth) + 'px',
			left: 0
		})
		
		this.wrap.setStyle({width: 'auto'})
		var wrapWidth = this.wrap.getWidth() - this.wrap.getWidth() % this.blockWidth
		this.wrap.setStyle({width: wrapWidth + 'px'})
	},
	
	setCurrentBlock: function() {
		var halfWidth = this.wrap.getWidth() / 2
		this.halfIndex = Math.floor(halfWidth / this.blockWidth) - 1
		var currentBlock = this.element.down('li.current')
		var currentBlockIndex = this.blocks.indexOf(currentBlock)

		if (currentBlockIndex < this.halfIndex) {
			this.setWrapperPosition(this.halfIndex)
		} else if (currentBlockIndex > this.blocks.length - 1 - this.halfIndex) {
			this.setWrapperPosition(this.blocks.length - this.halfIndex - 3)
		} else {
			this.setWrapperPosition(currentBlockIndex)
		}
	},
	
	setWrapperPosition: function(index) {
		this.scrollPosition = index - this.halfIndex
		var size = this.scrollPosition * this.blockWidth
		this.list.setStyle({ left: "-" + size + 'px' })
	},
	
	scrollLeft: function() {
		var newPosition = this.scrollPosition - this.halfIndex
		if (newPosition > this.halfIndex) {
			this.morph(newPosition * this.blockWidth * -1)
			this.scrollPosition = newPosition
		} else {
			this.morph(0)
			this.scrollPosition = 0
		}
	},
	
	scrollRight: function() {
		var maxRight = this.maxRight()
		newPosition = this.scrollPosition + this.halfIndex
		if (newPosition < this.maxRight()) {
			this.morph(newPosition * this.blockWidth * -1)
		} else {
			newPosition = maxRight
			this.morph(newPosition * this.blockWidth * -1)
		}
		this.scrollPosition = newPosition
	},
	
	morph: function(to) {
		new Effect.Morph(this.list, {
			style: { left: to + 'px' }, 
			duration: 0.8, 
			afterFinish: this.checkArrows.bind(this)
		})
	},
	
	maxRight: function() {
		return this.blocks.length - this.halfIndex * 2 - 3
	},
	
	checkArrows: function() {
		if (this.blocks.length < this.halfIndex * 2) {
			this.element.down("a.back").hide()
			this.element.down("a.forward").hide()
		} else if (this.scrollPosition == 0) {
			this.element.down("a.back").hide()
			this.element.down("a.forward").show()
		} else if (this.scrollPosition == this.maxRight()) {
			this.element.down("a.back").show()
			this.element.down("a.forward").hide()
		} else {
			this.element.down("a.back").show()
			this.element.down("a.forward").show()
		}
	}
})

var BackupsScroller = Class.create({
	initialize: function(container) {
		this.container = container
		
		this.wrapper = this.container.down("ul")
		this.wrapper.relativize()
		
		this.elements = this.wrapper.childElements()

		this.forwardButton = this.container.down("a.forward")
		this.backButton = this.container.down("a.back")
		
		if (this.container.hasClassName("thumbnailsBackupView")) {
			this.blockWidth = 84
		} else {
			this.blockWidth = 50
		}
		
		this.containerWidth = this.container.getWidth()
				
		this.blocksToScroll = Math.floor(this.containerWidth / this.blockWidth)
		this.sizeToScroll = this.blocksToScroll * this.blockWidth
				
		this.container.down("div.wrap").setStyle({ width: this.sizeToScroll + 'px'})
		this.forwardButton.observe("click", function() { this.doScroll('forward') }.bind(this))
		this.backButton.observe("click", function() { this.doScroll('back') }.bind(this))
		this.setWrapperWidth()
		
		this.maxLeft = parseInt(this.wrapper.getStyle('width')) - this.sizeToScroll
		
		this.forwardButton.hide()
		this.backButton.hide()
		
		if (this.container.hasClassName("thumbnailsBackupView")) {
			this.wrapper.setStyle({ left: "-" + this.maxLeft + "px" })
			this.updateArrows()
		} else {
			currentItem = this.wrapper.down("li.current")
			index = this.elements.indexOf(currentItem)
			this.wrapper.setStyle({
				left: "-" + (index * this.blockWidth) + 'px'
			})
			this.updateArrows()
		}
	},
	
	setWrapperWidth: function() {
		firstElement = this.elements.first()
		width = 84 * this.elements.length
		this.wrapper.setStyle({"width": width + "px"})
	},
	
	doScroll: function(direction) {
		currentLeft = parseInt(this.wrapper.getStyle("left"))
		if (direction == 'forward') {
			newLeft = currentLeft - this.sizeToScroll
		} else {
			newLeft = currentLeft + this.sizeToScroll
		}
		
		if (newLeft < 1 && newLeft >= -this.maxLeft) {
			new Effect.Morph(this.wrapper, {
				style: { left: newLeft + 'px', }, duration: 1.2, transition: Effect.Transitions.sinoidal,
				afterFinish: function() {
					this.updateArrows()
				}.bind(this)
			})
		}
	},
	
	updateArrows: function() {
		left = parseInt(this.wrapper.getStyle('left'))

		this.backButton.show()
		this.forwardButton.show()
		
		if (left == -this.maxLeft) this.forwardButton.hide()
		if (left + this.sizeToScroll > 0) this.backButton.hide()
		
		/* check if blocks count is too small for arrows show */
		if (this.blockWidth * this.elements.length < this.sizeToScroll) {
			this.forwardButton.hide()
			this.backButton.hide()
		}
	}
})

var TwitterForm = Class.create({
	initialize: function(element) {
		this.maxSymbolsCount = 140
		this.textarea = element.down('textarea')
		this.counter = new Element('div', { 'class' : "symbolsCounter" })
		
		this.counter.innerHTML = this.maxSymbolsCount - this.textarea.value.length
		this.textarea.observe("keyup", function(e) {
			this.updateCounter(e)
		}.bind(this))
		
		element.insert(this.counter)
	},
	
	updateCounter: function(event) {
		symbolsCount = this.maxSymbolsCount - this.textarea.value.length
		this.counter.innerHTML = symbolsCount
		
		if (symbolsCount < 0) this.textarea.value = this.textarea.value.substr(0, this.maxSymbolsCount)
	}
})

var niceButton = Class.create({
	initialize: function(element) {
		if (element.hasClassName("sticky")) {
			element.observe("mousedown", function() {
				element.hasClassName("mouseDown") ? element.removeClassName("mouseDown") : element.addClassName("mouseDown") 
			})
		} else {
			element.observe("mousedown", function() {
				element.addClassName("mouseDown")
			})

			element.observe("mouseup", function() {
				element.removeClassName("mouseDown")
			})

			element.observe("mouseout", function() {
				element.removeClassName("mouseDown")
				element.removeClassName("mouseOver")
			})
			
			element.observe("mouseover", function() {
				element.addClassName("mouseOver")
			})
		}
	}
})

var FileBrowser = {
	init: function() {
		this.container = $('fileBrowser')
		this.foldersContainer = this.container.down(".folders").down("div.wrap")
		
		this.addClickEvents()
		this.setContainerHeight()
			
		Event.observe(document.onresize ? document : window, "resize", function() {
			this.setContainerHeight()
		}.bind(this))
	},
	
	setContainerHeight: function() {
		height = document.viewport.getHeight() - this.container.positionedOffset().top
		this.container.down("div.folders").setStyle({
			height: height + 'px'
		})
		
		this.container.select("div.folders div.col").each(function(element) {
			element.setStyle({ height: height + 'px' })
		})
		
		wrapWidth = 0
		this.container.select("div.col").each(function(el) {
			wrapWidth += el.getWidth()
		}.bind(this))
		
		this.container.down('div.wrap').setStyle({
			width: wrapWidth + 'px'
		})
		this.container.down("div.folders").scrollLeft = 1000000
	},
	
	removeUnnecessaryColumns: function(element) {
		cols = this.container.select("div.col")
		currentCol = element.up("div.col")
		cols.each(function(col, index) {
			if (index > cols.indexOf(currentCol)) col.remove()
		})
	},
	
	addClickEvents: function() {
		this.container.select("li span").invoke('stopObserving', 'click')

		this.container.select("li span").each(function(element) {
			element.observe("click", function(event) { 
				this.setClassNames(element.up("li"))
				this.getContents(element.up("li"))
			}.bind(this))
		}.bind(this))
	},
	
	setClassNames: function(element) {
		element.up("div.col").select("li").invoke("removeClassName", "active")
		element.addClassName('active')
	},
	
	getContents: function(element) {	
		type = element.hasClassName("directory") ? "list" : "show"
		
		this.sendRequest(type, element, function(transport) {
			this.removeUnnecessaryColumns(element)
			this.foldersContainer.insert(new Element("div", {"class" : "col"}).update(transport.responseText))	
			this.addClickEvents()
			this.setContainerHeight()
		}.bind(this))
	},
	
	sendRequest: function(action, element, success) {
		new Ajax.Request("/files/" + action, { 
			method: 'post',
			parameters: [
				'id=' + this.container.readAttribute("backup_id"),
				'folder=' + element.readAttribute("folder"),
				'authenticity_token=' + encodeURIComponent(window._authenticity_token)
			].join('&'),
			onComplete: success
		})
	}
}

TariffsSelector = {
	init: function() {
		this.container = $('tariffsSelector')
		this.slider = this.container.down('div.bar')
		this.control = this.slider.down('div.control')
		this.tariffContainer = this.container.down('div.tariff')
		this.greenBar = this.slider.down('div.green')
		
		this.tariffs = eval(this.container.down('span.tariffIds').innerHTML)
		this.tariffsData = this.container.down("span.tariffsData").innerHTML.evalJSON()
		this.parseData(this.tariffsData)
		
		// hash which converts selected value to tariff ID.
		this.values = new Hash
		current = 1
		this.tariffs.each(function(tariff_id) {
			this.values.set(current, tariff_id)
			current += 1
		}.bind(this))
		
		this.sliderControl = new Control.Slider(this.control, this.slider, {
			values: this.getTariffsValues(),
			sliderValue: this.getDefaultValue(),
			range: $R(0, this.tariffs.length),
			alignX: -30,
			onChange: this.change.bind(this),
			onSlide: this.slide.bind(this)
		})
		
		if ($('freeTariff')) $('freeTariff').observe("click", this.setFreeTariff.bind(this))
		this.setBackground()
	},
	
	setFreeTariff: function() {
		this.sliderControl.setValue(0)
		this.setControlPrice(this.tariffsData[this.tariffs.first()]["space"])
		this.setBackground()
		this.setTariffData(this.tariffs.first())
	},
	
	getDefaultValue: function() {
		if (this.container.down(".currentTariffSpace")) {
			this.getCurrentTariff()
			return this.currentTariffIndex
		} else {
			return 0
		}
	},
	
	getTariffsValues: function() {
		if (this.container.down("span.usedSpace")) {
			this.usedSpace = parseInt(this.container.down("span.usedSpace").innerHTML)
			this.minimumTariffIndex = 0
			hash = new Hash(this.tariffsData)
			hash.each(function(k, v) {
				if (k[1]["space"] <= this.usedSpace) {
					this.minimumTariffIndex = v + 1
				}
			}.bind(this))
			this.minimumTariffIndex ++
			this.setMinimumSpaceBar()
		} else {
			this.minimumTariffIndex = 1
		}
		
		return $R(this.minimumTariffIndex, this.tariffs.length)
	},
	
	setMinimumSpaceBar: function() {
		if (this.container.down("div.used")) {
			this.bar = this.container.down("div.used")
			var width = (this.minimumTariffIndex / this.tariffs.length) * this.slider.getWidth()
			this.bar.setStyle({ width: parseInt(width) + 'px'})
		}
	},
	
	getCurrentTariff: function() {
		this.currentTariffSpace = parseInt(this.container.down(".currentTariffSpace").innerHTML)
		this.currentTariffId = parseInt(this.container.down(".currentTariffId").innerHTML) // id can be not in list of our ids.
		
		var dataHash = new Hash(this.tariffsData).sortBy(function(td) {
			return td[1].space
		})
		
		dataHash.each(function(k, v) {
			if (k[1]["space"] <= this.currentTariffSpace) {
				this.currentTariffId = k[0]
				this.currentTariffIndex = v
			}
		}.bind(this))
		this.currentTariffIndex ++
	},
	
	currentTariff: function() {
		return this.tariffsData[this.currentTariffId]
	},
	
	slide: function(value) {
		var tariff_id = this.getTariffId(value)
		this.setControlPrice(this.tariffsData[tariff_id]['space'])
		this.setBackground()
		this.setTariffData(tariff_id)
	},

	change: function(value) {
		var tariff_id = this.getTariffId(value)
	},

	setTariffData: function(id) {
		$('selectedTariff').replace($('tariff_' + id).innerHTML)
	},
	
	getTariffId: function(tariff_id) {
		return this.values.get(tariff_id)
	},
	
	parseData: function() {
		var newData = {}
		this.tariffsData = this.tariffsData.sortBy(function(td) {
			return td.tariff.space
		})
		
		this.tariffsData.each(function(element, index) {
			id = element["tariff"]["id"]
			newData[id] = element["tariff"]
		})
		
		this.tariffsData = newData
	},
	
	setControlPrice: function(value) {
		this.control.down('span').innerHTML = value
	},
	
	setBackground: function() {
		var position = parseInt(this.control.getStyle("left")) + 20
		this.greenBar.setStyle({ width: position + 'px' })
	}
}

var Cookie = {
	set: function(name, value, daysToExpire, path) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		path = '; path=' + encodeURI(path || '/');
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path);
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
}
