/**
 * @copyright  Copyright (c) 2009 Leukeleu B.V. (http://www.leukeleu.nl/)
 * @license    ...
 *
 * @todo       Add comments
 * @todo       Cleanup (options, namespaces, css)
 */
var ProjectViewer = new Class({

	Implements: Options,
	options: {
		wrapper: {
			container:   $('wpr-banner'),
			startValue:  260,
			endValue:    435
		},
		image: {
			container:   $('image-container')
		},
		title: {
			container:   $('title-wrapper'),
			startValue:  -30,
			endValue:    0
		},
		thumbs: {
			container:   $('thumb-wrapper'),
			startValue:  -80,
			endValue:    0,
			width:       80,
			height:      60,
			scale:       1.1
		},
		info: {
			container:   $('info-container'),
			startValue:  0,
			endValue:    1
		},
		slideOut: false
	},

	initialize: function(options) {
		this.setOptions(options);

		this.fx           = {};
		this.currentImage = this.options.image.container.getElement('img');
		this.thumbLinks   = this.options.thumbs.container.getElements('li a');
		this.thumbImages  = this.options.thumbs.container.getElements('li a img');
		this.busy        = false;
		this.show        = false;

		if (this.currentImage) this.initCurrentImage();
		this.initElements();
	},

	initElements: function() {

		// create project details button
		this.btnProjectDetails = $('btn-project-details');
		this.btnProjectDetails.addEvent('click', function(e) {
			e.stop();
			this.toggleInfo();
		}.bind(this));

		// set specific styling on all elements
		this.options.wrapper.container.setStyle('height', this.options.wrapper.startValue);
		this.options.title.container.setStyle('top', this.options.title.startValue);
		this.options.info.container.setStyle('opacity', this.options.info.startValue);
		this.options.thumbs.container.setStyle('bottom', this.options.thumbs.startValue);
		this.currentImage.setStyle('margin-top', this.currentImage.marginTop);

		this.addThumbLinks();
		this.addProjectFx();
		this.addProjectEvents();
	},

	initCurrentImage: function() {
		this.currentImage.fx = {};

		var matches = this.currentImage.getProperty('src').match(/y(\d+)\.[a-zA-Z]{3,}$/i);

		if (matches != null && matches.length == 2) {
			this.currentImage.marginTop = -1 * matches[1].toInt();
		} else {
			this.currentImage.marginTop = -90;
		}

		this.currentImage.fx.animate = new Fx.Tween(this.currentImage, { duration: 'short', transition: Fx.Transitions.Quad.easeOut });
	},

	addProjectFx: function() {

		this.fx.banner       = new Fx.Tween(this.options.wrapper.container, { duration: 'short', transition: Fx.Transitions.Quad.easeOut });
		this.fx.title        = new Fx.Tween(this.options.title.container,   { duration: 'short', transition: Fx.Transitions.Quad.easeOut });
		this.fx.info         = new Fx.Tween(this.options.info.container);
		this.fx.thumbs       = new Fx.Tween(this.options.thumbs.container,  { duration: 'short', transition: Fx.Transitions.Quad.easeOut });

		this.thumbImages.each(function(image) {
			image.fx = new Fx.Morph(image, { duration: 'short' });
		});
	},

	addProjectEvents: function() {

		this.options.wrapper.container.addEvents({
			'click':  function(e) {
				e.stop();
				if (this.show) {
					this.hideProject();
				} else {
					this.showProject();
				}
			}.bind(this)
		});

		this.thumbImages.each(function(image) {

			image.setStyles({
				'width':  this.options.thumbs.width,
				'height': this.options.thumbs.height
			});

			image.addEvents({
				'mouseover':  function(e) {
					e.stop();
					this.thumbFocus(e.target);
				}.bind(this),
				'mouseleave': function(e) {
					e.stop();
					this.thumbBlur(e.target);
				}.bind(this)
			});
		}.bind(this));

		// stop mouseover events children
		this.options.title.container.addEvents({
			'mouseover':  function(e) { e.stop(); }.bind(this)
		});
		this.options.thumbs.container.addEvents({
			'mouseover':  function(e) { e.stop(); }.bind(this)
		});
	},

	showProject: function() {
		this.pauseAllAnimations();
		this.fx.banner.start('height', this.options.wrapper.endValue);
		this.fx.title.start('top', this.options.title.endValue);
		this.fx.thumbs.start('bottom', this.options.thumbs.endValue);
		this.currentImage.fx.animate.start('margin-top', 0);
		this.show = true;
	},

	hideProject: function() {
		this.pauseAllAnimations();
		this.fx.banner.start('height', this.options.wrapper.startValue);
		this.fx.title.start('top', this.options.title.startValue);
		this.fx.thumbs.start('bottom', this.options.thumbs.startValue);
		this.currentImage.fx.animate.start('margin-top', this.currentImage.marginTop);
		this.hideInfo();
		this.show = false;
	},

	toggleInfo: function() {
		this.fx.info.pause();
		this.fx.info.show ? this.hideInfo() : this.showInfo();
	},

	showInfo: function() {
		this.fx.info.start('opacity', this.options.info.endValue);
		this.fx.info.show = true;
	},

	hideInfo: function() {
		this.fx.info.start('opacity', this.options.info.startValue);
		this.fx.info.show = false;
	},

	thumbFocus: function(thumb) {
		var width  = this.options.thumbs.width * this.options.thumbs.scale;
		var height = this.options.thumbs.height * this.options.thumbs.scale;
		var marginTop = (this.options.thumbs.width - width) / 2;

		thumb.fx.pause();
		thumb.fx.start({
			'margin-top': marginTop,
			'width': width,
			'height': height
		});
	},

	thumbBlur: function(thumb) {
		thumb.fx.pause();
		thumb.fx.start({
			'margin-top': 0,
			'width': 80,
			'height': 60
		});
	},

	pauseAllAnimations: function() {
		this.fx.banner.pause();
		this.fx.title.pause();
		this.fx.thumbs.pause();
		this.currentImage.fx.animate.pause();
	},

	addThumbLinks: function() {
		this.thumbLinks.each(function(link) {
			var imagePath = link.getProperty('href');

			link.addEvent('click', function(e) {
				e.stop();
				this.loadImage(imagePath);
			}.bind(this));
		}.bind(this));
	},

	loadImage: function(path) {
		if (!this.busy && path != this.currentImage.getProperty('src')) {
			this.busy = true;

			// show preloader
			this.preloader = new Asset.image('/layouts/vijverborgh/images/preloader.gif', {
				'class': 'preloader'
			});
			this.preloader.inject(this.options.image.container, 'bottom');

			this.newImage = new Asset.image(path, {
				'class': 'project-image',
				onload: function() {
					this.preloader.destroy();
					this.replaceImage();
				}.bind(this)
			});
		}
	},

	replaceImage: function() {
		this.newImage.inject(this.options.image.container, 'top');

		this.currentImage.fx.opacity = new Fx.Tween(this.currentImage, {
			onComplete: function() {
				this.currentImage.destroy();
				this.currentImage = this.newImage;
				this.initCurrentImage();
				this.newImage = null;
				this.busy = false;
			}.bind(this)
		});
		this.currentImage.fx.opacity.start('opacity', 0);
	}
});

window.addEvent('domready', function() {

	if ($('banner')) {

		var options = {
			wrapper: {
				container:  $('wpr-banner'),
				startValue: 260,
				endValue:   435
			},
			image: {
				container: $('image-container')
			},
			title: {
				container:  $('title-wrapper'),
				startValue: -30,
				endValue:   0
			},
			thumbs: {
				container:  $('thumb-wrapper'),
				startValue: -80,
				endValue:   0
			},
			info: {
				container: $('info-container')
			},
			slideOut: false
		};

		var projectViewer = new ProjectViewer(options);
	}

	// newsmodule
	if ($('news')) {
		var newsItems = $('news').getElements('.news');

		newsItems.each(function(newsItem) {
			var newsHead        = newsItem.getElement('h3');
			var newsDescription = newsItem.getElement('.description');

			newsDescription.fx = new Fx.Slide(newsDescription).hide();

			newsHead.addEvent('click', function() {
				newsDescription.fx.toggle();
			});

			newsItem.getElement('div').setStyle('margin-bottom', 5);
		});
	}

	// project strip module
	if ($('project-strip-overview')) {
		var projects = $$('#project-strip-overview .project');

		projects.each(function(project) {

			var info           = project.getElement('div.info-container');
			var titleContainer = project.getElement('div.title-container');

			info.fx = new Fx.Slide(info).hide();

			titleContainer.addEvent('click', function() {
				info.fx.toggle();
			});

		});
	}

	// Knowlegde banner
	if ($('knowledge-banner')) {
		var knowledgeBanner = $('knowledge-banner');
		var kbBlur          = $('kb-blur');
		var kbContent       = $('kb-content');

		// add events on links in image
		var kbLinks = $('kb-links').getElements('a');

		kbBlur.fx = new Fx.Tween(kbBlur, {
			duration: 200
		});

		kbLinks.each(function(link) {

			var linkName   = link.getAttribute('id');

			link.addEvent('mouseover', function() {

				kbBlur.fx.onComplete = function() {
					knowledgeBanner.setProperty('class', linkName);
				};

				kbBlur.setStyle('opacity', 0);
				kbBlur.setProperty('class', linkName);
				kbBlur.fx.start('opacity', 0, 1);

			});

			link.addEvent('mouseout', function() {

				kbBlur.fx.onComplete = function() {
					knowledgeBanner.setProperty('class', '');
				};

				kbBlur.setStyle('opacity', 0);
				kbBlur.setProperty('class', '');
				kbBlur.fx.start('opacity', 0,1);

			});

			link.addEvent('click', function(e) {
				kbContent.setStyle('display', 'block');
				kbContent.getElements('div').setStyle('display', 'none');
				kbContent.getElement('div.' + 'ctt-' + linkName).setStyle('display', 'block');
				new Event(e).stop();
			});
		});

		// close link
		var closeLink = $('kb-closebutton');
		closeLink.addEvent('click', function(e) {
			kbContent.setStyle('display', 'none');
			kbContent.getElements('div').setStyle('display', 'none');
			new Event(e).stop();
		});
	}

	// testimonial behaviour
	var testimonials = $('content').getElements('div.testimonial');

	testimonials.each(function(testimonial, index) {

		var firstParagraph = testimonial.getElement('p');

		if (firstParagraph.getElement('img')) {

			firstParagraph.addClass('images');
			firstParagraph.getElements('br').destroy();

			var allNext = firstParagraph.getAllNext();

			var testimonialContentElement = new Element('div', {
				'class': 'testimonial-content'
			}).inject(testimonial);

			allNext.inject(testimonialContentElement);

			var h3 = testimonialContentElement.getElement('h3');
			allNext = h3.getAllNext();

			var testimonialMoreContentElement = new Element('div', {
				'class': 'testimonial-more-content'
			}).inject(testimonialContentElement);

			allNext.inject(testimonialMoreContentElement);

			var testimonialSlide = new Fx.Slide(testimonialMoreContentElement);

			testimonialSlide.hide();

			testimonial.addEvent('click', function() {
				testimonialSlide.toggle();
				testimonial.toggleClass('slideout');
			});

			new Element('a', {
				'class': 'close',
				'html': 'sluiten'
			}).inject(testimonial, 'top');
		}
	});

	// client login form
	if ($('form_login')) {

		function submitForm(e) {

			var errors = [];

			// check form values
			if (loginForm.username.value == '' || loginForm.username.value == usernameValue) errors.push('username');
			if (loginForm.password.value == '' || loginForm.password.value == passwordValue) errors.push('password');

			if (errors.length > 0) {

				// show errors to user
				var error_text = 'De volgende informatie is niet (juist) ingevuld:' + "\n\n";

				for (var i = 0, error_count = errors.length; i < error_count; i++) {
					error_text += '- ' + errors[i] + "\n";
				}

				error_text += "\n" + 'Probeer het alsjeblieft opnieuw.';
				alert(error_text);

				// stop form submit
				var formEvent = new Event(e);
				formEvent.stop();

			} else {

				loginForm.submit();
			}
		}

		var usernameValue = 'gebruikersnaam';
		var passwordValue = 'wachtwoord';
		var loginForm     = $('form_login');
		var username      = $('username');
		var password      = $('password');
		var submitButton  = $('btn_submit');

		// password.setProperty('type', 'text');

		// replace submit button
		if (submitButton) {
			var submitImage = new Element('div', {
				'class': 'submitImage'
			});
			submitImage.replaces(submitButton);
			submitImage.addEvent('click', submitForm);
		}

		username.addEvents({
			'focus': function(e){
				if (this.value == usernameValue) {
				    this.value = '';
				}
			},
			'blur': function(){
				if (this.value == '') {
				    this.value = usernameValue;
				}
			}
		});

		password.addEvents({
			'focus': function(e){
				if (this.value == passwordValue) {
				    this.value = '';
				}
			},
			'blur': function(){
				if (this.value == '') {
				    this.value = passwordValue;
				}
			}
		});
	}

	// known extensions for shadowbox files
	var shadowbox_exts = ['jpg', 'jpeg', 'png', 'gif'];
	var contents       = $$('#main .content');

	if (projects && projects.length > 0) {
		contents = projects;
	}

	contents.each(function(content, index) {
		var links = content.getElements('a');

		links.each(function(link) {

			// find extension
			var split_slash = link.href.split('/');
			var split_ext   = split_slash.getLast().split('.');
			var ext         = split_ext.getLast();

			// check if extension indicates a shadowbox file
			if (split_ext.length > 1) {
				if (shadowbox_exts.contains(ext)) {
					if (!link.rel) {
						link.rel = 'shadowbox[' + index + ']';
					}
				}
			}
		});
	});
});

// initialize shadowbox
var options = {
	adapter: 'mootools',
	language: 'nl',
	animSequence: 'sync'
};

Shadowbox.init(options);