Event.observe(window, 'load', function() {
	EditWindow.init()
	ContentSlider.init()
	NicePopup.init()
	Preloader.init()
	ImageRotator.init()
	styleSheets.init()
	PageScroller.init()
	ContentsScroller.initAll($$(".rubric"))
	MuteButton.init()


	if ($('page')) {
		Block.init()
		BlockForm.init()
		BlockFormsShowing.init()
	}

})

Event.observe(document, "dom:loaded", function() {
//	Age.init()
})


var MuteButton = {
	init: function() {
		if ($('muteButton')) {
			this.button = $('muteButton')
			this.button.soundOn = function() {
				this.removeClassName('soundOff')
				MuteButton.soundOn()
				Cookie.erase('mute')
			}
			this.button.soundOff = function() {
				this.addClassName('soundOff')
				MuteButton.soundOff()
				Cookie.set('mute', 1)
			}
			this.button.switchSound = function() {
				this.hasClassName('soundOff') ? this.soundOn() : this.soundOff();
			}
			this.button.observe('click', this.button.switchSound.bindAsEventListener(this.button))
			if (Cookie.get('mute')) this.button.soundOff()
		}
	},
	getFlashIDs: function() {
		var iDs = {}
		$$('object').each(function(obj) {
			iDs[obj.getAttribute('id')] = obj.getAttribute('id')
		}.bind(this))
		$$('embed').each(function(obj) {
			iDs[obj.getAttribute('name')] = obj.getAttribute('name')
		}.bind(this))
		return $H(iDs).values()
	},
	getFlashMovies: function() {
		var movies = []
		this.getFlashIDs().each(function(movieId){
			movies.push(window[movieId] || document[movieId])
		}.bind(this))
		return movies
	},
	soundOff: function() {
		this.getFlashMovies().each(function(movie){
			if (movie.setMute) movie.setMute(true)
		}.bind(this))
	},
	soundOn: function() {
		this.getFlashMovies().each(function(movie){
			if (movie.setMute) movie.setMute(false)
		}.bind(this))
	}
//  function getFlashMovie(movieName) {
//   var isIE = navigator.appName.indexOf("Microsoft") != -1;
//   return (isIE) ? window[movieName] : document[movieName];
//  }
//  function formSend() {
//   var text = document.htmlForm.sendField.value;
//   getFlashMovie("ExternalInterfaceExample").sendTextToFlash(text);
//  }
//  function getTextFromFlash(str) {
//   document.htmlForm.receivedField.value = "From Flash: " + str;
//   return str + " received";
//  }
}

var Age = {
	init: function() {
		if ($('age') && !Cookie.get('age')) {
			this.container = $('age')
			this.frame = $('age').down('.frame')
			$('age').down('.older').observe('click', Age.older.bind(this))
		} else if ($('age')) {
			$('age').hide();
		}
	},
	older: function() {
		Cookie.set('age', 1)
		$('age').hide()
	}
	//,
	// resize: function() {
	// 	windowSize = getPageSizeWithScroll()
	// 	this.container.setStyle({
	// 		width: windowSize[0] +'px',
	// 		height: windowSize[1] +'px'
	// 	})
//		window.status = $(document.getElementsByTagName('body')[0]).scrollHeight + ' 123'
//	}
}

var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
	},
	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');
	}
}



function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	return arrayPageSizeWithScroll;
}

var Tools = {
	fadeIn: function(element, timeout) {
		tt = setTimeout(function() {
			new Effect.Appear($(element), { duration: 0.5 }, afterFinish = function() {
				clearTimeout(tt)
			});
		}, timeout)

	}
}

var PageScroller = {
	init: function() {
		this.container = $$("div.pages-navigation")[0]
		if (this.container) {
			this.scrollableContainer = this.container.down("ul")

			this.containerWidth = this.container.getWidth()
			this.maxLeft = this.containerWidth - 42 * this.scrollableContainer.childElements().length
			this.container.observe("mouseover", PageScroller.handleMouseOver.bindAsEventListener(PageScroller))
			this.container.observe("mousemove", PageScroller.handleMouseOver.bindAsEventListener(PageScroller))
			this.container.observe("mouseout", PageScroller.handleMouseOut.bindAsEventListener(PageScroller))
			
			var active = this.scrollableContainer.down(".active")
			if (active) {
				var active_i = this.scrollableContainer.childElements().indexOf(active)
				this.left = active_i == null ? 0 : this.containerWidth / 2 - (active_i + 0.5) * 42
			}
			this.speed = 0
			this.doScroll()
		}
	},
	handleMouseOver: function(event){
		var offset = this.container.viewportOffset()
		var x = event.pointerX() - offset[0], sign
		if (x < this.containerWidth / 2) {
			sign = -1
		} else {
			sign = +1
			x = this.containerWidth - x
		}
		this.speed = x <= 200 ? sign * (200 - x) * (200 - x) : 0
		if (this.speed != 0) {
			if (!this.tid) {
				this.tid = setInterval(PageScroller.doScroll.bind(PageScroller), 10)
			}
		} else {
			clearInterval(this.tid)
			this.tid = null
		}
	},
	handleMouseOut: function(){
		this.speed = 0
		clearInterval(this.tid)
		this.tid = null
	},
	doScroll: function(){
		this.left -= this.speed / 3000
		if (this.left > 0) {
			this.left = 0
		}
		if (this.left < this.maxLeft) {
			this.left = this.maxLeft
		}
		this.scrollableContainer.setStyle({left: this.left + "px"})
	}
}


var ContentsScroller = {
	initAll: function(containers) {
		containers.each(function(c){
			ContentsScroller.init(c);
		})
	},
	init: function(container) {
		if (container) {
			container.scrollableContainer = container.down("ul")


			container.doScroll = function() {
				this.left -= this.speed / 3000
				if (this.left > 0 || this.scrollerWidth <= this.containerWidth) {
					this.left = 0
				} else if (this.left < this.maxLeft) {
					this.left = this.maxLeft
				}
				this.scrollableContainer.setStyle({left: this.left + "px"})
			}

			container.handleMouseOver = function(event){
				if (!this.containerWidth) {
					this.containerWidth = this.getWidth()
				}
				if (!this.scrollerWidth) {
					this.scrollerWidth = (this.scrollableContainer.down('li').getWidth() + parseInt(this.scrollableContainer.down('li').getStyle('margin-right')) + parseInt(this.scrollableContainer.down('li').getStyle('margin-left'))) * this.scrollableContainer.childElements().length;
				}
				if (!this.maxLeft) {
					this.maxLeft = this.containerWidth - parseInt(this.getStyle('padding-left')) - this.scrollerWidth
				}
				var offset = this.viewportOffset()
				var x = event.pointerX() - offset[0], sign
				if (x < this.containerWidth / 2) {
					sign = -1
				} else {
					sign = +1
					x = this.containerWidth - x
				}
				this.speed = x <= 200 ? sign * (200 - x) * (200 - x) : 0
				if (this.speed != 0) {
					if (!this.tid) {
						this.tid = setInterval(this.doScroll.bind(this), 10)
					}
				} else {
					clearInterval(this.tid)
					this.tid = null
				}
			}

			container.handleMouseOut = function(){
				this.speed = 0
				clearInterval(this.tid)
				this.tid = null
			}

			container.observe("mouseover", container.handleMouseOver.bindAsEventListener(container))
			container.observe("mousemove", container.handleMouseOver.bindAsEventListener(container))
			container.observe("mouseout", container.handleMouseOut.bindAsEventListener(container))

			container.left = 0
			container.speed = 0
			container.doScroll()
		}
	}
}


var Preloader = {
	init: function() {
		this.preloads = new Array()

		this.preloads[0] = "/images/nicepopup-bg-right.gif"
		this.preloads[1] = "/images/nicepopup-bg-left.gif"

		this.preloads.each(function(element) {
			Preloader.preload(element)
		});
	},

	preload: function(url) {
		var img = new Image()
		img.src = url
	}
}

var BlockForm = {
	init: function() {
		BlockForm.cacheElements()
	},

	show: function(int_id) {
		$(BlockForm.idPrefixed(int_id)).appear({ duration: 0.1 })
	},

	cacheElements: function() {
		this.block_forms = $$('div.blockForm')
	},

	idPrefixed: function(int_id) {
		return 'block_form_'+int_id
	}
}

var BlockFormsShowing = {
	init: function() {
		$$('a.addBlock').each(function(link) {
			link.observe('click', BlockFormsShowing.clickAddLink)
		})
	},
	clickAddLink: function(event) {
		EditWindow.show()
		var link = event.element()
		var type = link.id.toString().match(/.*Block/)
		if (type) {
			$$('div.' + type + 'Form.new').first().show()
		}
	}
}

var Block = {
	init: function() {
		if ($('css_editform')) {
			Block.cacheElements()
			this.blocks.each(function(block) {
				block.absolutize()
				Block.makeDraggable(block)
				if (block.down('div.edit')) {
					block.down('div.edit').observe('click', Block.editClick)
				}
				block.observe('mouseover', Block.handleMouseOver);
				block.observe('mouseout', Block.handleMouseOut);
			})
			$('page').insert('<div class="grid" style="display: none;"></div>');
		}
	},

	handleMouseOver: function(event) {
		clearTimeout(this.handle_timeout)
		
		
		event.findElement('div.block').down('div.handle').appear({duration: 0.1});
		
		
		event.findElement('div.block').down('div.edit').appear({duration: 0.1});
	},

	handleMouseOut: function(event) {
		this.handle_timeout = setTimeout(function() {
			
			event.findElement('div.block').down('div.handle').fade()
			
			event.findElement('div.block').down('div.edit').fade()
		}, 1000)
	},

	makeDraggable: function(block) {
		new Draggable(block, {
			handle: 'handle',
			onStart: function(draggable) {
				$('page').down('div.grid').appear({duration: 0.2})
			},
			onEnd: function(draggable) {
				$('page').down('div.grid').fade({duration: 0.1})
				new Ajax.Request(
					window._blocks_path + '/' + getId(draggable.element.getAttribute('id')),
					{
						asynchronous: true,
						evalScripts: true,
						method: 'put',
						parameters: [
							'block[offset_x]=' + parseInt(draggable.element.getStyle('left')),
							'block[offset_y]=' + parseInt(draggable.element.getStyle('top')),
							'authenticity_token=' + encodeURIComponent(window._authenticity_token)
						].join('&')
					}
				)
			}
		})
	},

	editClick: function(event) {
		EditWindow.show()
		BlockForm.show(getId(event.findElement('div.block').id))
		event.stop()
	},

	cacheElements: function() {
		this.blocks = $('page').select('div').findAll(function(div) {
			return div.hasClassName('block')
		})
	}
}

// later do this
var Rubrics = {
	init: function() {
		this.page_elements = $$("li.page_element")
		this.page_elements.each(function(element) {
			element.observe("click", function() {
				Rubrics.selectionInit()
			})
		})
	},

	selectionInit: function() {
		this.page_elements.each(function(element) {
			element.observe("mouseover", function() {
				Rubrics.addSelection(element)
			})
		})
	},

	addSelection: function(element) {
		element.addClassName("selection")
	}
}

var Screenshot = {
	init: function() {

	},

	refresh: function(issue_id, page_id) {
		$('screenshotArea').innerHTML = '<img src="/images/loading-screenshot.gif" />'

		new Ajax.Request('/pages/get_screenshot/'+issue_id+"/"+page_id, {
			method:'get',
				onSuccess: function(transport){
					Screenshot.append(transport.responseText.evalJSON(), transport.responseText )
				},
				onFailure: function(transport){ alert(transport.responseText) }
		});
	},

	append: function(json, response) {
		$('screenshotArea').innerHTML = '<img src="'+json+'" />'
	}
}

var EditWindow = {
	init: function() {
		this.edit_window = $$('div.editWindow').first()
		if (this.edit_window) {
			this.edit_window.down('div.closeButton').observe('click', EditWindow.dblclick)
			EditWindow.makeDraggable()
		}
		//windowHead
	},

	makeDraggable: function() {
		new Draggable(this.edit_window, {
			handle: 'handle',
			onStart: function(draggable) {
				;
			},
			onEnd: function(draggable) {
				;
			}
		})
	},

	dblclick: function(event) {
		EditWindow.hide()
	},

	clearContents: function() {
		this.edit_window.select('div.windowBody').first().childElements().each(function(div) {
			div.hide()
		})
	},

	show: function() {
		EditWindow.clearContents()
		this.edit_window.appear({duration: 0.1})
	},

	hide: function() {
		this.edit_window.fade({duration: 0.1})
	}
}

function getId(string_id) {
	return string_id.replace(/[a-zA-Z_]/g, '')
}

var ContentSlider = {
	init: function() {
		if ($$("div.issue-content")[0]) {
			$A(['logo', 'logo-white']).each(function(objectId){
				$(objectId)._visible = !($(objectId).getStyle('display') == 'none')
				$(objectId).observe("click", function(event) {
					event.stop()
					ContentSlider.toggleArea()
				})
			}.bind(this))

			this.content_popup = $$("div.issue-content")[0]
			this.content_popup.setStyle({display:"none"})

			this.rubrics = $$("div.issue-content li.rubric")
			this.rubrics.each(function(element) {
				element.observe("click", ContentSlider.toggleRubric.bindAsEventListener(ContentSlider))
			})

			this.openedRubric = null
		}
	},

	toggleArea: function() {
		if (this.content_popup.getStyle("display")=="none") {
			$('logo').setStyle({display: 'block'})
			$('logo-white').setStyle({display: 'none'})
			Effect.Appear(this.content_popup, { duration: 0.4 });
		} else {
			$('logo').setStyle({display: ($('logo')._visible ? 'block' : 'none')})
			$('logo-white').setStyle({display: ($('logo-white')._visible ? 'block' : 'none')})
			this.content_popup.setStyle({display:"none"})
		}
	},

	toggleRubric: function(event) {
		var rubric = event.element().up('.rubric')
		if (ContentSlider.currentRubric == rubric) {
			ContentSlider.closeRubric(rubric)
			ContentSlider.currentRubric = null
		} else {
			ContentSlider.currentRubric = rubric
			this.rubrics.each(function(r){
				rubric == r ? ContentSlider.openRubric(r) : ContentSlider.closeRubric(r)
			}.bind(this))
		}
	},

	openRubric: function(rubric) {
		if (rubric.showRubricEffect) rubric.showRubricEffect.cancel()
		rubric.showRubricEffect = new Effect.Morph(rubric.down('ul'), {
			style: {
				height:"130px",
				paddingTop: "20px"
			},
			duration: 0.3
		});
	},

	closeRubric: function(rubric) {
		if (rubric.showRubricEffect) rubric.showRubricEffect.cancel()
		rubric.showRubricEffect = new Effect.Morph(rubric.down('ul'), {
			style: {
				height: "0px",
				paddingTop: "0px"
			},
			duration: 0.3
		});
	}
}

var NicePopup = {
	init: function() {
		if ($$("div.pictureBlock")[0]) {
			this.nicePopups = $$("div.pictureBlock")
			this.tt = new Hash
			
			this.nicePopups.each(function(element) {
				if (element.down('img').readAttribute("alt")!="") {
					element.observe("mouseover", function(e) {
						var el = e.element()
						if (!el.hasClassName('pictureBlock')) {el = el.up('.pictureBlock')}
						NicePopup.showPopup(el)
					})
					
					element.observe("mouseout", function(e) {
						var el = e.element()
						if (!el.hasClassName('pictureBlock')) {el = el.up('.pictureBlock')}
						NicePopup.hidePopup(el)
					})
				}
			})

		}
	},

	showPopup: function(element) {
// 		this.tt.each(function(pair) {
//			clearTimeout(pair.value)
// 		})
		if (!element.down('div.popup')) {
			if (parseInt(element.getStyle("left")) > 600) {
				var template = new Template('<div class="imagepopup-left popup"><div class="top">#{alt}</div><div class="bottom"></div></div>');
			} else {
				var template = new Template('<div class="imagepopup-right popup"><div class="top">#{alt}</div><div class="bottom"></div></div>');
			}
			
			var show = {alt: element.down('img').readAttribute("alt")};
			element.insert(template.evaluate(show));
		}
	},

	hidePopup: function(element, event) {
		this.tt.set(element.readAttribute("id"), setTimeout(function() {
			element.down('div.popup').remove()
		}, 10))
		
	}
}

var ImageRotator = {
	init: function() {
		if ($$("div.pictureBlock")[0]) {
			this.rotators = new Hash()
			this.imageBlocks = $$("div.pictureBlock")
			this.timeOut = null
			this.imageBlocks.each(function(element) {


				this.leftCoordinate = element.getStyle("left")
				this.topCoordinate = element.getStyle("top")
				if (this.topCoordinate && this.leftCoordinate) {

					if (!ImageRotator.rotators.get(this.leftCoordinate+";"+this.topCoordinate)) {
						ImageRotator.rotators.set(this.leftCoordinate+";"+this.topCoordinate, new Array())
						this.array = ImageRotator.rotators.get([this.leftCoordinate+";"+this.topCoordinate])
						this.array.push(element)
					} else {
						this.array = ImageRotator.rotators.get([this.leftCoordinate+";"+this.topCoordinate])
						this.array.push(element)
					}
				}
			})
			
			this.rotators.values().each(function(array) {
				if (array.length>1) {
					ImageRotator.initSwitching(array)
				}
			})
		}
	},

	initSwitching: function(array) {
		array.each(function(element) {
			element.observe("click", function() {
				element.setStyle({"cursor":"pointer"})
				ImageRotator.showNext(array, array.indexOf(element))
			})
		})
		ImageRotator.showNext(array, 1)
	},

	showNext: function(array, index, previous) {
		if (index < array.length -1) {
			newindex = index + 1
		} else {
			newindex = 0
		}
		array.each(function(obj){
			if (obj != array[newindex]) ImageRotator.hide(obj);
		}.bind(this));

		if (array[newindex].fadeEffect) array[newindex].fadeEffect.cancel();
		array[newindex].fadeEffect = Effect.Appear(array[newindex], { duration: 0.8 });
		if (this.timeOut) {
			clearTimeout(this.timeOut)
		}
		this.timeOut = setTimeout(function() {
			ImageRotator.showNext(array, newindex, index)
		}, 2500)

	},
	hide: function(object) {
		if (object.fadeEffect) object.fadeEffect.cancel();
		object.fadeEffect = Effect.Fade(object, { duration: 0.8 });
	}
}

var styleSheets = {
	init: function() {
	if ($("css_editform")) {
			this.textarea = $("css_editform").down('textarea')
			this.stylesheet = $('stylesheet')

			this.textarea.observe("keydown", function() {
				styleSheets.updateStyle()
			})
			$('submit-button').observe("click", function() {
				styleSheets.sendData()
			})
		}
	},

	updateStyle: function() {
		this.stylesheet.innerHTML = ""
		this.stylesheet.innerHTML = this.textarea.value
	},

	sendData: function() {
		new Ajax.Request('/pages/update_style',
			{
				method:'post',
			parameters: {authenticity_token: window._authenticity_token, page_id: window._page_id, style_text: this.textarea.value},
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
				},
				onFailure: function(){ alert('Something went wrong...') }
			});
	}
}


