var archiveBox;

document.loaded(function() {
		
	archiveBox = new ArchiveBox('collage-archive-filter-options', 'collage-archive-link', {
					navigation_menu: 'collage-navigation',
					content_area: 'collage-main-content'
	});	
}.bind(archiveBox));

Event.observe(window, 'load', function() {
		
	if($('collage-send-to-a-friend')) {
		
		new SendToAFriend('collage-send-to-a-friend', 'collage-send-to-a-friend-link');
	}
	
	new ToggleBoxes('collage-archive-filter-options-checkboxes');
	
	var imageRotators = document.getElementsByClassName('collage-image-inner');
	for(var i = 0; i < imageRotators.length; i++) {
		
		new ImageRotator(imageRotators[i], {
						left_button: '.collage-image-navigation-left', 
						right_button: '.collage-image-navigation-right',
						overlay: '.collage-image-navigation',
						image_meta: '.collage-image-navigation-meta'
		});
	}
	
	/* Fix IE6 lack of :hover support */
	var rolloverButtons = ['collage-search-button', 'collage-search-submit'];
	rolloverButtons.each(function(element) {
		
		var button = $(element);
		if(button) {
			
			Event.observe(button, 'mouseover', function() { this.addClassName('button-hover'); }.bindAsEventListener(button));
			Event.observe(button, 'mouseout', function() { this.removeClassName('button-hover'); }.bindAsEventListener(button));
		}
	});
	
	var clicker = new Clicker('collage-navigation-inner', {
			topelement: 'primary-nav', 
			bottomelement: 'collage-main-content',
			padding: 10,
			snap_to: 'top'
	});
	archiveBox.setClicker(clicker);	
	
	// Needed to make IE6/IE7 behave properly
	clicker.windowResized();
}.bind(archiveBox));


var SendToAFriend = Class.create();
SendToAFriend.prototype = {
	
	initialize: function(container, linkClassName) {

		this.container = $(container);
		this.inner_container = this.container.firstDescendant().firstDescendant();
		this.inner_container.height = $(this.inner_container).getHeight();

		this.container.hide();
		
		Event.observe(this.container, 'submit', this.submitForm.bindAsEventListener(this));

		var sendToAFriendLinks = document.getElementsByClassName(linkClassName, 'a');
		for(var i = 0; i < sendToAFriendLinks.length; i++) {

			Event.observe(sendToAFriendLinks[i], 'click', this.showSendToAFriendForm.bindAsEventListener(this));
		}

		var cancelLink = document.getElementsByClassName('cancel-link', 'a');
		if(cancelLink.length > 0) {

			Event.observe(cancelLink[0], 'click', this.hideSendToAFriendForm.bindAsEventListener(this));
		}
	},
	
	showSendToAFriendForm: function(e) {

		this.caller = Event.element(e);
		this.caller.addClassName('disabled');
		
		if(this.container.style.display == 'none') {

			new Effect.ScrollTo('collage-navigation-footer', {
						queue: {
							position: 'front',
							scope: 'sendtoafriendscope',
							limit: 2
						}
			});

			new Effect.SlideDown(this.container, {
						duration: 1.2,
						queue: {
							position: 'end',
							scope: 'sendtoafriendscope',
							limit: 2
						}
			});
		}

		Event.stop(e);
	},

	hideSendToAFriendForm: function(e) {

		this.caller.removeClassName('disabled');

		Effect.SlideUp(this.container, {
					duration: 1.2,
					queue: {
						position: 'end',
						scope: 'sendtoafriendscope',
						limit: 1
					},
					afterFinish: function() {
						
						this.hideErrorFields();
						
						$A(this.inner_container.getElementsByTagName('input')).each(function(e) {

							e.value = '';
						});

						this.inner_container.childElements().each(function(e) {

							e.show();
						});
						
						new Effect.ScrollTo('container');
					}.bind(this)
		});
		
		Event.stop(e);
	},
	
	hideSentForm: function(e) {

		$('collage-article-sent').remove();
		this.hideSendToAFriendForm(e);
	},

	submitForm: function(e) {

		this.container.request({

			onComplete: function(response) {

				this.hideErrorFields();

				var jsonResponse = new String(response.responseText).evalJSON();
				if(jsonResponse.sent) {

					this.sentMail(jsonResponse).bind(this);
				} else {

					this.displayErrors(jsonResponse);
				}
			}.bind(this)
		});

		Event.stop(e);
	},

	sentMail: function(response) {

		this.inner_container.setStyle({'height': this.inner_container.height + 'px'});

		this.inner_container.childElements().each(function(e) {

			e.hide();
		});

		new Effect.Morph(this.inner_container, {
			style: 'height: 32px;',
			duration: 1.2,
			afterFinish: function()  {

				this.inner_container.appendChild(
						Builder.node('div', {id: 'collage-article-sent'}, [
							Builder.node('p', {id: 'collage-response-message'}, response.message),
							Builder.node('p', {id: 'collage-close-confirmation-container'}, [
								Builder.node('a', {href: '#close', id: 'collage-close-confirmation'}, response.close)
							])
						])
				);
				Event.observe('collage-close-confirmation', 'click', this.hideSentForm.bindAsEventListener(this));
			}.bind(this)
		});
	},

	displayErrors: function(response) {

		for(var i = 0; i < response.errors.length; i++) {

			new Insertion.After(
					$(response.errors[i].field),
					Builder.node('div', [Builder.node('p', {className: 'error'}, response.errors[i].message)]).innerHTML
			);
		}

	},

	hideErrorFields: function() {

		this.container.getElementsByClassName('error', 'p').each(function(e) {

			e.remove();
		});
	}
}


var ArchiveBox = Class.create();
ArchiveBox.prototype = {

	initialize: function(archiveBox, archiveLink) {
			
		this.container = $(archiveBox);
		this.archive_link = $(archiveLink);
		this.orginal_height = 0;
		
		this.options = Object.extend({}, arguments[2] || {});	
		
		if(this.options.navigation_menu) {
		
			this.original_height = Element.getHeight(this.options.navigation_menu);
		}
				
		if(this.container && typeof(ARCHIVE_EXPANDED) == 'undefined') {
				
			this.container.hide();
		}
		
		if(this.archive_link) {
		
			Event.observe(this.archive_link, 'click', this.toggleArchiveBox.bindAsEventListener(this));
		}
	},

	toggleArchiveBox: function(e) {
						
		if(this.container.getStyle('display') == 'none') {
		
			if($(this.options.content_area) && Element.getHeight(this.options.content_area) < this.original_height) {
			
				this.original_bottom_padding = parseInt($(this.options.content_area).getStyle('paddingBottom').toString().replace('px', ''));			
				$(this.options.content_area).setStyle({
							paddingBottom: (this.original_height - Element.getHeight(this.options.content_area)) + 'px'
				});
			}
		}
					
		new Effect.toggle(this.container, 'blind', { 
				queue: { 
					position: 'end', 
					scope: 'archive_box_scope',
					limit: 1
				},
				afterFinish: function() {
								
					if(this.container.getStyle('display') == 'none') {
					
						$(this.options.content_area).setStyle({
							paddingBottom: this.original_bottom_padding + 'px'
						});		
					}
					
					this.clicker.windowResized();
				}.bind(this)
		});
		
		Event.stop(e);
	},
	
	setClicker: function(c) {
	
		this.clicker = c;
	}
}



var ToggleBoxes = Class.create();
ToggleBoxes.prototype = {

	initialize: function(identifier) {

		this.identifier = $(identifier);

		if(this.identifier) {
	
			var checkBoxes = this.identifier.getElementsByTagName('input');
			for(var i = 0; i < checkBoxes.length; i++) {
	
				if(checkBoxes[i].value == 'all') {
	
					Event.observe(checkBoxes[i], 'click', this.toggleCheckBoxes.bindAsEventListener(this));
				} else {
	
					Event.observe(checkBoxes[i], 'click', this.toggleAllBox.bindAsEventListener(this));
				}
			}
		}	
	},
	
	toggleCheckBoxes: function(e) {
	
		var allBox = Event.element(e);
	
		var checkBoxes = this.identifier.getElementsByTagName('input');
		for(var i = 0; i < checkBoxes.length; i++) {
	
			if(checkBoxes[i].type == 'checkbox') {
	
				if(allBox.checked) {
	
					checkBoxes[i].checked = true;
				} else {
	
					checkBoxes[i].checked = false;
				}
			}
		}	
	},
	
	toggleAllBox: function(e)
	{
		var currentBox = Event.element(e);
	
		var checkBoxes = this.identifier.getElementsByTagName('input');
		var notChecked = false;
		for(var i = 0; i < checkBoxes.length; i++) {
	
			if(checkBoxes[i].value == 'all') {
	
				if(!currentBox.checked) {
	
					checkBoxes[i].checked = false;
				}
				allBox = checkBoxes[i];
			} else {
	
				if(!checkBoxes[i].checked) {
	
					notChecked = true;
				}
			}
		}
	
		if(!notChecked) {
	
			allBox.checked = true;
		}
	}	
}


var ImageRotator = Class.create();
ImageRotator.prototype = {

	initialize: function(container) {
		
		this.IMAGE_WIDTH = 599;
		this.container = $(container);
	
		if(this.container) {
		
			this.outer_container = this.container.up();
							
			this.options = Object.extend({
				overlay: 'overlay',
				left_button: 'left-button',
				right_button: 'right-button',
				image_meta: 'image-meta'
			}, arguments[1] || {});
							
			this.options.overlay = $(this.outer_container).down(this.options.overlay);
			
			this.options.left_button = $(this.outer_container).down(this.options.left_button);
			this.options.right_button = $(this.outer_container).down(this.options.right_button);
			this.options.image_meta = $(this.outer_container).down(this.options.image_meta);
			
			$(this.options.overlay).hide();
			
			this.TOTAL_IMAGES = this.container.getElementsBySelector('img').length;
			this.CURRENT_IMAGE = 1;
	
			Event.observe(this.container, 'mouseover', this.showNavigation.bindAsEventListener(this));
			Event.observe(this.container, 'mouseout', this.hideNavigation.bindAsEventListener(this));
			Event.observe(this.options.overlay, 'mouseover', this.mouseoverOverlay.bindAsEventListener(this));
			Event.observe(this.options.overlay, 'mouseout', this.mouseoutOverlay.bindAsEventListener(this));
			Event.observe(this.options.left_button, 'click', this.moveLeft.bindAsEventListener(this));
			Event.observe(this.options.right_button, 'click', this.moveRight.bindAsEventListener(this));
			
			this.updateMeta();
							
			this.container.getElementsBySelector('img').each(function(obj) {
			
				Event.observe(obj, 'mouseover', this.mouseoverImage.bindAsEventListener(this));
				Event.observe(obj, 'mouseout', this.mouseoutImage.bindAsEventListener(this));
				
			}.bind(this));
		}
	},
	
	moveLeft: function(e) {

		Event.stop(e);
		
		if(this._getElementLeft(this.container) >= 0) return;

		new Effect.Move(this.container, {
							x: this.IMAGE_WIDTH,
							y: 0,
							transition: Effect.Transitions.sinoidal,
							duration: 1,
							queue: {
								position: 'end', 
								scope: 'rotator_scope', 
								limit: 1
							},
							afterFinish: this.decreaseMeta.bind(this)
		});
	},
	
	moveRight: function(e) {
	
		Event.stop(e);
		
		var totalWidth = 0;
		this.container.getElementsBySelector('img').each(function(e) {
			
			totalWidth += e.getWidth();
		});
				
		if((totalWidth*-1) >= (this._getElementLeft(this.container) - this.IMAGE_WIDTH)) return false;
		
		new Effect.Move(this.container, {
							x: this.IMAGE_WIDTH * -1,
							y: 0,
							transition: Effect.Transitions.sinoidal,
							duration: 1,
							queue: {
								position: 'end', 
								scope: 'rotator_scope', 
								limit: 1
							},
							afterFinish: this.increaseMeta.bind(this)
		});
		
	},
	
	updateMeta: function() {
		
		$(this.options.image_meta).update(this.CURRENT_IMAGE +" / "+ this.TOTAL_IMAGES);
	},
	
	increaseMeta: function() {
		
		this.CURRENT_IMAGE = this.CURRENT_IMAGE + 1;
		this.updateMeta();
	},
	
	decreaseMeta: function() {
		
		this.CURRENT_IMAGE = this.CURRENT_IMAGE - 1;
		this.updateMeta();
	},
	
	showNavigation: function(e) {
					
		if(this.navigation_opened || this.TOTAL_IMAGES < 1) return;
		
		new Effect.Appear(this.options.overlay, { 
					duration: 0.4,
					from: 0,
					to: 0.5,
					queue: { 
						position: 'end', 
						scope: 'navigation_scope',
						limit: 2
					},
					afterUpdate: this.mouseoverNav.bind(this)
		});
	},
	
	hideNavigation: function(e) {
	
		setTimeout(function() {
							
				if(!this.mouseover_overlay && !this.mouseover_image && $(this.options.overlay)) {
				
					new Effect.Fade(this.options.overlay, { 
							duration: 0.4,
							queue: { 
								position: 'end', 
								scope: 'navigation_scope',
								limit: 2
							},
							afterUpdate: this.mouseoutNav.bind(this)
					});
				}
			}.bind(this),
			50
		);
	},
	
	mouseoverNav: function(e) {
		
		this.navigation_opened = true;
	},
	
	mouseoutNav: function(e) {
		
		this.navigation_opened = false;
	},
	
	mouseoverImage: function(e) {
		
		this.mouseover_image = true;
	},
	
	mouseoutImage: function(e) {
		
		this.mouseover_image = false;
	},
	
	mouseoverOverlay: function(e) {
		
		this.mouseover_overlay = true;
	},
	
	mouseoutOverlay: function(e) {
		
		this.mouseover_overlay = false;
		this.hideNavigation();
	},
	
	_getElementLeft: function(element) {
	
		return parseInt(new String($(element).getStyle('left')).replace('px', ''));
	}	
}