Cufon('.gothic')

Event.observe(document, 'dom:loaded', function(){
	BeveledImageBorder.init()
	Cufon.now()
	AdjustText.init()

	TextAreaButtons.init()
	MaskChoices.init()
	NoYandexCheckBox.init()
	CalendarControls.init()
	CalendarMonths.init()
	Comments.init()
})

var Growl = {
	growler: function(){
		if (this._growler == undefined) {
			this._growler = new k.Growler()
		}
		return this._growler
	}
	,growl: function(msg, options) {
		return this.growler().growl(msg, options)
	}
	,info: function(msg, options){
		return this.growler().info(msg, options)
	}
	,warn: function(msg, options){
		return this.growler().warn(msg, options)
	}
	,error: function(msg, options){
		return this.growler().error(msg, options)
	}
	,ungrowl: function(n, o){
		return this.growler().ungrowl(n, o)
	}
}

var AdjustText = {
	init: function(){
		$$('div.text').each(function(div){
			if (div.getStyle('overflow') == 'hidden') {
				var height = div.getHeight()
				div.setStyle({overflow: 'visible', height: 'auto'})
				if (height < div.getHeight()) {
					var children = div.childElements()
					children.invoke('setStyle', {display: 'none'})
					var lastChild
					children.each(function(child){
						child.show()
						lastChild = child
						if (height < div.getHeight()) {
							throw $break
						}
					})
					if (lastChild.down()) {
						lastChild = lastChild.down()
					}

					var useInnerText = !!lastChild.innerText
					var words = (useInnerText ? lastChild.innerText : lastChild.textContent).split(' ')
					do {
						if (!words.pop()) {
							break
						}
						var text = words.join(' ') + '…'
						if (useInnerText) {
							lastChild.innerText = text
						} else {
							lastChild.textContent = text
						}
					} while(height < div.getHeight())
				}
				div.setStyle({height: height + 'px'})
			}
		}.bind(this))
	}
}

var TextAreaButtons = {
	init: function(){
		$$('textarea').each(function(textarea){
			if (textarea.up('div.control').hasClassName('formatted')) {
				var textareaControl = new Control.TextArea(textarea)
				var toolbar = new Control.TextArea.ToolBar(textareaControl)
				textarea.textareaControl = textareaControl
				toolbar.container.className = 'markdown_toolbar'

				toolbar.addButton('Italics', function(){
					this.wrapSelection('*', '*')
				}, {
					className: 'italics'
				})

				toolbar.addButton('Bold', function(){
					this.wrapSelection('__', '__')
				}, {
					className: 'bold'
				})

				toolbar.addButton('Link', function(){
					var selection = this.getSelection()
					var response = prompt('Введите ссылку', '')
					if (response == null) {
						return
					}
					this.replaceSelection('[' + (selection == '' ? 'Текст ссылки' : selection) + '](' + (response == '' ? 'http://link_url/' : response).replace(/^(?!(f|ht)tps?:\/\/)/, 'http://') + ')')
				}, {
					className: 'link'
				})

				toolbar.addButton('Heading', function(){
					var selection = this.getSelection()
					if (selection == '') {
						selection = 'Заголовок'
					}
					this.replaceSelection("\n" + selection + "\n" + '-'.times(Math.max(5, selection.length)) + "\n")
				}, {
					className: 'heading'
				})

				var listRegexp          = /^\s*(?:\*+|\d+\.)(?:\s|$)/
				var unorderedListRegexp = /^\s*(?:\*+)(?:\s|$)/
				var orderedListRegexp   = /^\s*(?:\d+\.)(?:\s|$)/
				toolbar.addButton('Unordered List', function(event){
					var addList
					this.collectFromEachSelectedLine(function(line){
						var listRegexp = /^\s*(?:\*+|\d+\.)(?:\s|$)/
						if (addList == undefined) {
							addList = line.match(unorderedListRegexp) ? false : true
						}
						return (addList ? '* ' : '') + line.replace(listRegexp, '')
					})
				}, {
					className: 'unordered_list'
				})

				toolbar.addButton('Ordered List', function(event){
					var addList, i = 1
					this.collectFromEachSelectedLine(function(line){
						if (addList == undefined) {
							addList = line.match(orderedListRegexp) ? false : true
						}
						return (addList ? i++ + '. ' : '') + line.replace(listRegexp, '')
					})
				}, {
					className: 'ordered_list'
				})
			}
		})
	},
	addImage: function(button, image_code){
		var textareaControl = button.up('div.control').down('textarea').textareaControl
		textareaControl.replaceSelection(image_code)
	}
}

var MaskChoices = {
	init: function(){
		$$('div.mask_choices').each(function(mask_choices){
			var lis = mask_choices.select('li')
			mask_choices.total = lis.length
			lis.each(function(li, i){
				if (li.down('input').checked) {
					mask_choices.selected = i
				}
			}.bind(this))
			if (mask_choices.selected == undefined) {
				mask_choices.selected = Math.floor(Math.random() * mask_choices.total)
			}

			this.update(mask_choices)

			mask_choices.down('a.prev').observe('mousedown', function(e){ e.stop() })
			mask_choices.down('a.next').observe('mousedown', function(e){ e.stop() })
			mask_choices.down('a.prev').observe('click', function(e){
				var mask_choices = e.element().up('div.mask_choices')
				mask_choices.selected = (mask_choices.selected + mask_choices.total - 1) % mask_choices.total
				this.update(mask_choices)
			}.bindAsEventListener(this))
			mask_choices.down('a.next').observe('click', function(e){
				var mask_choices = e.element().up('div.mask_choices')
				mask_choices.selected = (mask_choices.selected + 1) % mask_choices.total
				this.update(mask_choices)
			}.bindAsEventListener(this))
		}.bind(this))
	}
	, update: function(mask_choices){
		mask_choices.select('li')[mask_choices.selected].down('input').checked = true
		mask_choices.down('ul').setStyle({marginTop:-500 * mask_choices.selected + 'px'})
		if (mask_choices.total > 1) {
			mask_choices.down('a.prev').show()
			mask_choices.down('a.next').show()
		} else {
			mask_choices.down('a.prev').hide()
			mask_choices.down('a.next').hide()
		}
	}
}

var BeveledImageBorder = {
	init: function(){
		$$('div.formatted_text div.image, div.formatted_text div.gallery, div.formatted_text div.video, div.formatted_text div.big_video').each(function(container){
			var canvas = container.down('canvas')
			if (canvas) {
				var container_type = container.className
				var size = container_type == 'video' || container_type == 'big_video' ? 30 : 15
				
				if (container.down('img') == undefined) {
					dim = container.down().getDimensions()
				} else {
					dim = container.down('img').getDimensions()
				}
				
				var dsize = size * 2
				var cwidth = dim.width + dsize, cheight = dim.height + dsize
				var width = dim.width, height = dim.height
				canvas.width = cwidth
				canvas.height = cheight

				if (!canvas.getContext) {
					window.G_vmlCanvasManager.initElement(canvas);
				}
				if (canvas.getContext) {
					var img = container.down('img'), img_dup
					if (img) {
						img_dup = img.cloneNode(true)
						img_dup.addClassName('transparent_overlay')
						container.insert(img_dup)
					}

					if (container_type == 'gallery') {
						var galleryPrev = container.down('div.control div.prev')
						var galleryNext = container.down('div.control div.next')
						galleryPrev.observe('mousedown', function(e){ e.stop() })
						galleryNext.observe('mousedown', function(e){ e.stop() })
						galleryPrev.observe('click', this.toggleGalleryImage.bindAsEventListener(this, -1))
						galleryNext.observe('click', this.toggleGalleryImage.bindAsEventListener(this, 1))
						img_dup.observe('click', this.toggleGalleryImage.bindAsEventListener(this, 1))
					}

					var ctx = canvas.getContext('2d')

					ctx.beginPath()
					p = this.points(size)
					ctx.moveTo(         p[0][0],           p[0][1])
					ctx.lineTo(         p[1][0], cheight - p[1][1])
					ctx.lineTo(cwidth - p[2][0], cheight - p[2][1])
					if (container_type == 'gallery') {
						ctx.lineTo(cwidth - p[3][0] / 2, size / 2)
					} else {
						ctx.lineTo(cwidth - p[3][0], p[3][1])
					}

					if (container_type == 'image' || container_type == 'gallery') {
						p = this.points(size)
						ctx.moveTo(dsize - p[0][0], dsize  - p[0][1])
						if (container_type == 'gallery') {
							ctx.lineTo(width + p[1][0], dsize + 10 + p[1][1] / 2)
						} else {
							ctx.lineTo(width + p[1][0], dsize - p[1][1])
						}
						ctx.lineTo(width + p[2][0], height + p[2][1])
						ctx.lineTo(dsize - p[3][0], height + p[3][1])
					}

					ctx.closePath()
					ctx.fillStyle = "#" + main_color
					ctx.fill()
				}
			}
		}.bind(this))
	}
	,points: function(size){
		var points = [0, 1, 0, 1].map((Math.random() < 0.5 ? this.pointA : this.pointB).bind(this, size))
		return Math.random() < 0.5 ? points : points.reverse()
	}
	,pointA: function(size, n){
		return [(Math.random() + n) * 0.5 * size, (Math.random() + 1 - n) * 0.5 * size]
	}
	,pointB: function(size, n){
		return [(Math.random() + n) * 0.5 * size, (Math.random() + n) * 0.5 * size]
	}

	,toggleGalleryImage: function(e, delta){
		var container = e.element().up('div.gallery')
		var control = container.down('div.control')
		var lis = control.up('div.gallery').down('ul').select('li')
		var currentContainer = control.down('div.count span.current')
		var current = parseInt(currentContainer.innerHTML)
		var total = parseInt(control.down('div.count span.total').innerHTML)
		var transparentOverlay = container.down('img.transparent_overlay')
		var new_current = [[current + delta, 1].max(), total].min()
		if (current != new_current) {
			current = new_current
			currentContainer.update(current)
			if (current <= 1) {
				control.addClassName('first')
			} else {
				control.removeClassName('first')
			}
			if (current >= total) {
				control.addClassName('last')
			} else {
				control.removeClassName('last')
			}
			lis.each(function(li, i){
				if (i < current - 1) {
					li.hide()
				} else if (i == current - 1) {
					li.show()
					transparentOverlay.src = li.down('img').src
				}
			})
		}
	}
}

var NoYandexCheckBox = {
	init: function(){
		this.toggleNoYandex = this.toggleNoYandex.bindAsEventListener(this)
		if (this.noYandexCheckBox = $('festival_article_no_yandex')) {
			this.sourceFields = [$('festival_article_source_title'), $('festival_article_source_href')].compact()
			this.sourceFields.each(function(sourceField){
				['change', 'keyup', 'keydown'].each(function(event){
					sourceField.observe(event, this.toggleNoYandex)
				}.bind(this))
			}.bind(this))
		}
	}
	, toggleNoYandex: function(e){
		this.noYandexCheckBox.checked = !this.sourceFields.all(function(sourceField){ return sourceField.value.blank() })
	}
}

var CalendarControls = {
	init: function(){
		this.showInCalendar = $('article_show_in_calendar')
		this.calendarControls = $('calendar_controls')
		if (this.showInCalendar && this.calendarControls) {
			this.showInCalendar.observe('change', function(e){
				this.toggleCalendarControls()
			}.bindAsEventListener(this))
			this.toggleCalendarControls()
		}
	}
	, toggleCalendarControls: function(){
		if (this.showInCalendar.checked) {
			this.calendarControls.show()
		} else {
			this.calendarControls.hide()
		}
	}
}

var CalendarMonths = {
	init: function(){
		this.monthsSelectorSwitcher = $('months_selector_switcher')
		if (this.monthsSelectorSwitcher) {
			this.monthsSelector = $('months_selector')
			this.monthsSelectorSwitcher.observe('click', function(){
				this.monthsSelector.toggle()
			}.bindAsEventListener(this))
			this.prevMonth = this.monthsSelector.down('div.prev_month')
			this.nextMonth = this.monthsSelector.down('div.next_month')
			this.months = this.monthsSelector.select('div.month')
			this.shownMonth = this.months.indexOf(this.months.find(function(month){ return month.visible() })) || 0
			this.maxShownMonth = this.months.length - 1
			this.prevMonth.observe('mousedown', function(e){ e.stop() })
			this.nextMonth.observe('mousedown', function(e){ e.stop() })
			this.prevMonth.observe('click', this.switchMonth.bindAsEventListener(this, -1))
			this.nextMonth.observe('click', this.switchMonth.bindAsEventListener(this, 1))
			this.switchMonth(null, 0)
		}
	}
	, switchMonth: function(e, delta){
		var newShownMonth = [[this.shownMonth + delta, 0].max(), this.maxShownMonth].min()
		if (newShownMonth != this.shownMonth) {
			this.shownMonth = newShownMonth
			this.months.each(function(month, i){
				if (i == this.shownMonth) {
					month.show()
				} else {
					month.hide()
				}
			}.bind(this))
		}
		if (this.shownMonth > 0) {
			this.prevMonth.show()
		} else {
			this.prevMonth.hide()
		}
		if (this.shownMonth < this.maxShownMonth) {
			this.nextMonth.show()
		} else {
			this.nextMonth.hide()
		}
	}
}

var Comments = {
	init: function(){
		this.writeComment = $('write_comment')
		this.newCommentForm = $('new_comment')
		if (this.writeComment && this.newCommentForm) {
			this.toggleSubmit = this.toggleSubmit.bind(this)
			this.submit = this.newCommentForm.down('input[type=submit]')
			this.fields = this.newCommentForm.select('input[type=text], textarea')
			this.submit.disable()
			this.fields.each(function(field){
				'focus,blur,change,cut,copy,paste,keyup'.split(',').each(function(eventType){
					field.observe(eventType, this.toggleSubmit)
				}.bind(this), true)
			}.bind(this))

			if (window.location.hash != '#comments') {
				this.writeComment.show()
				this.newCommentForm.hide()
			}
			this.writeComment.observe('click', function(e){
				e.stop()
				this.writeComment.hide()
				this.newCommentForm.show()
				this.newCommentForm.down('input[type=text]').focus()
			}.bind(this))
		}
	}
	, toggleSubmit: function(e){
		var allow = this.fields.all(function(field){
			var value = field.value
			if (value.strip().length < 3) {
				return false
			}
			if (field.id == 'comment_name' && !value.strip().match(/^[a-z0-9._%+-]+@[a-z0-9\-]+\.+[a-z]{2,4}$/i)) {
				return false
			}
			return true
		})
		if (allow) {
			this.submit.enable()
		} else {
			this.submit.disable()
		}
	}
}