document.observe('dom:loaded', function() {
	if ($$('.main_menu').length > 0 ) {
		menu.initialize();
	}
	if ($('slideshow')) {
		slideshow.initialize();
	}
	if ($('gallery')) {
		gallery.initialize(assets_jsarray);
	}
});

function random(min, max) {
	return Math.floor(min + (max-min) * Math.random());
}

var menu = {
	initialize: function() {
		var start_state = [];
		var a_menu = $('menu');
		if (!$$('.main_menu')[0].hasClassName('hold')) {
			var items = $$('.secondary_menu li, .activities_menu li');
			for (var i=0, len=items.length; i<len; i++) {
				(function(i) {
					var li = items[i];
					if (li.innerHTML.length > 10) {
						start_state.push({
							element: li,
							className: li.className
						});
						li.observe('mouseover', function() {
							menu.filter(li.className.split(' '), li);
						});
						li.observe('mouseout', function() {
							items.invoke('removeClassName', 'inactive');
							menu.reset_states();
						});
					}
				})(i);
			}
		}
		Event.observe(window, 'scroll', function() {
			var top = a_menu.cumulativeScrollOffset()[1];
			a_menu.style.top = 13 + top + 'px';
		});
		this.start_state = start_state;
		this.items = items;
		
		if ($$('.activities_menu_holder').length > 0) {
			var sec = $$('.secondary_menu_holder')[0];
			var act = $$('.activities_menu_holder')[0];
			Effect.SlideDown(sec);
			Effect.SlideDown(act);
		}
	},
	reset_states: function() {
		this.start_state.each(function(state) {
			state.element.className = state.className;
		});
	},
	filter: function(input, item) {
		var output = item.up('ul').hasClassName('secondary_menu') ?
			$$('.activities_menu')[0] : $$('.secondary_menu')[0];
		
		output.childElements().invoke('addClassName', 'inactive');
		
		for (var i=0, len=input.length; i<len; i++) {
			var value = input[i];
			if (!value.include('active') && value.length > 1) {
				output.select('.' + value).invoke('removeClassName', 'inactive');
			}
		}
	}
}

var slideshow = {
	initialize: function() {
		this.slides = $('slideshow').select('.slide');
		this.current = 0;
		this.resize();
		
		var images = this.slides.collect(function(i) {
			var image = i.select('img')[0];
			return {
				element: image,
				src: image.alt
			}
		});
		
		this.preload(images, function() {
			slideshow.change();
			setInterval(function() {
				slideshow.change();
			}, 2000);
			Event.observe(window, 'resize', function() {
				slideshow.resize();
			});
		});
	},
	preload: function(images, callback) {
		if (images.length > 0) {
			var image = new Image();
			var onload = function() {
				images[0].element.src = images[0].src;
				images = images.without(images[0]);
				setTimeout(function() {
					slideshow.preload(images, callback)
				}, 30);
			};
			if (Prototype.Browser.IE) {
				image.onload = onload;
			} else {
				image.observe('load', onload);
			}
			image.src = images[0].src;
		} else {
			callback();
		}
	},
	resize: function() {
		var first_column_width = $('content').hasClassName('home') ? 220 : 360;
		$('content').style.width = document.viewport.getWidth() - first_column_width + 'px';
		$('content').style.height = document.viewport.getHeight() - 40 + 'px';
	},
	change: function() {
		var prev = this.current;
		var prev_slide = this.slides[prev];
		this.current = this.current + 1 >= this.slides.length ? 0 : this.current + 1;
		this.slides.invoke('setStyle', {'zIndex': 1});
		this.slides[this.current].style.zIndex = 100;
		this.slides[this.current].appear({duration: 0.5, afterFinish: function() {
			prev_slide.fade({duration: 0.25});
		}});
	}
}

var gallery = {
	initialize: function(images) {
		this.element = $('gallery');
		this.thumbnails_element = $('thumbnails');
		this.thumbnails_container = $('thumbnails').select('.wrapper')[0];
		this.image = $$('#image img')[0];
		this.image_container = $('viewer');
		this.path = '/assets';
		this.small = 'thumb';
		this.big = 'preview';
		this.images = images;
		this.thumbnails = [];
		
		for (var i=0, len=images.length; i<len; i++) {
			var image = images[i];
			var thumbnail = new Thumbnail(image, i);
			this.thumbnails.push(thumbnail);
			if (Object.isArray(this.images[i])) {
				this.images[i] = this.images[i][0];
			}
		}
		
		Sortable.create('sortable', {
			overlap: 'horizontal', constraint: false,
			tag: 'div', handle: 'handle', onUpdate: function() {
			new Ajax.Request('/assets/sort?list=sortable', {
				asynchronous: true, evalScripts: true,
				parameters: Sortable.serialize("sortable") + '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)
			})
		}});
				
		$$('#viewer .show_all')[0].observe('click', function() {
			gallery.show_all();
		});
		$$('.total')[0].innerHTML = images.length;
		
		if (images.length > 1) {
			$$('.next')[0].observe('click', function() {
				gallery.next();
			});
			this.image.observe('click', function() {
				gallery.next();
			});
			$$('.prev')[0].observe('click', function() {
				gallery.prev();
			});
		} else {
			$$('.next, .prev').invoke('hide');
		}
	},
	path_for: function(type, image) {
		return [this.path, image.split('.').first(), this[type], image].join('/');
	},
	show: function(image, in_array) {
		if (image.in_roll) {
			$$('.current')[0].innerHTML = image.in_roll + 1;
		} else {
			var current = this.images.indexOf(in_array) + 1;
			$$('.current')[0].innerHTML = image.roll ? 1 : current;
			$$('.total')[0].innerHTML = image.roll ? image.roll.length : this.images.length;
			this.current = current - 1;
		}
		
		gallery.check();
		
		if (this.fade != null) {
			this.fade.cancel();
		}
		this.fade = new Effect.Fade(this.image, {duration: 0.5});
		this.image.style.display = 'inline';
		this.image.removeAttribute('width');
		
		this.preload(image.big_path, function(i) {
			gallery.image.src = image.big_path;
			if (gallery.appear != null) {
				gallery.appear.cancel();
			}
			gallery.appear = new Effect.Appear(gallery.image, {duration: 0.5});
		});
	},
	check: function() {
		var self = this.thumbnails[this.current];
		var c = self.roll ? self.current : this.current;
		var s = self.roll ? self.roll.length : this.images.length;
		
		if (c + 1 >= s && !self.roll) {
			$$('.next')[0].addClassName('inactive');
		} else if (c - 1 < 0) {
			$$('.prev')[0].addClassName('inactive');
		} else {
			$$('.next')[0].removeClassName('inactive');
			$$('.prev')[0].removeClassName('inactive');
		}
	},
	next: function() {
		var self = this.thumbnails[this.current];
		if (self.roll) {
			if (self.current + 1 < self.roll.length) {
				self.current++;
				var img = {
					big_path: this.path_for('big', self.roll[self.current]),
					in_roll: self.current
				};
			} else {
				self.current = 0;
				var img = self;	
			}
			this.show(img, self.roll[self.current]);
		} else {
			if (this.current + 1 < this.images.length) {
				this.current++;
				this.show(this.thumbnails[this.current], this.images[this.current]);
			}
		}
	},
	prev: function() {
		var self = this.thumbnails[this.current];
		if (self.roll) {
			if (self.current - 1 >= 0) {
				self.current--;
				if (self.id+'.jpeg' == self.roll[self.current]) {
					var img = self;
				} else {
					var img = {
						big_path: this.path_for('big', self.roll[self.current]),
						in_roll: self.current
					};
				}
				this.show(img, self.roll[self.current]);
			}
		} else {
			if (this.current - 1 >= 0) {
				this.current--;
				this.show(this.thumbnails[this.current], this.images[this.current]);
			}
		}
	},
	show_all: function() {
		this.image_container.fade({duration: 0.5, afterFinish: function() {
			gallery.thumbnails_element.appear({duration: 0.5});
		}});		
	},
	preload: function(image_src, callback) {
		var image = new Image();
		var onload = function() {
			setTimeout(function() {
				callback(image);
			}, 1000);
		};
		if (Prototype.Browser.IE) {
			image.onload = onload;
		} else {
			image.observe('load', onload);
		}
		image.src = image_src;
	}
}

var Thumbnail = Class.create({
	initialize: function(image, id) {
		this.roll = Object.isArray(image) ? image : false;
		if (this.roll) {
			image = image[0];
			this.current = 0;
		}
		
		this.small_path = gallery.path_for('small', image);
		this.big_path = gallery.path_for('big', image);
		this.id = image.replace('.jpeg', '');
		this.element = new Element('div', {'id': 'item_' + this.id, 'class': 'thumbnail' + (this.roll ? ' roll' : '')});
		
		var img = new Element('img', {'style': 'display: none'});
		if (!Prototype.Browser.Webkit) {
			Event.observe(img, 'load', this.show.bind(this));
		}
		img.src = this.small_path;
		this.element.insert({top: img});
		this.img = img;
		if (Prototype.Browser.Webkit) {
			Event.observe(img, 'load', this.show.bind(this));
		}
		
		var t = this;
		img.observe('click', function() {
			gallery.image.src = '/images/blank.gif';
			gallery.thumbnails_element.fade({duration: 0.5, afterFinish: function() {
				gallery.show(t, image);
				gallery.image_container.appear({duration: 0.5});
			}});
		});
		
		gallery.thumbnails_container.insert({bottom: this.element});
		if (draggable) {
			this.element.insert({bottom: '<div class="handle" style="cursor:move">MOVE</div>'});
		}
	},
	show: function() {
		this.img.appear({duration: 0.5});
	}
});