var Engine = {
	
	doStuff: function() {
		this.beSexy();
		this.audioLoad();
		this.twitterLoad();
		this.audioAnim();
		this.bookAnim();
		(!window.ie ? this.resizeCover() : '');
		this.clearFields();
		this.expandField();
		this.postResponse();
		this.attachLinkAction();
		this.firefoxAntialising();
		this.manageSearchField();
	},
	
	// add the additional stylesheet
	beSexy: function() {
		new Element('link', {
			'rel': 'stylesheet',
			'type': 'text/css',
			'href': baseUrl+'template/css/advanced.css',
			'charset': 'utf-8'
		}).injectAfter('primary-style');
	},
	
	manageSearchField: function() {
		var sField = $('simple-field');
		var initialText = 'search for ...';
		
		try {
			if(sField.value == '') {
				sField.addClass('default');
				sField.value = initialText;
			}
			
			sField.addEvents({
				focus: function(e) {
					if(this.value == initialText) {
						this.value = '';
						this.removeClass('default');
					}
				},
				blur: function(e) {
					if(this.value == '') {
						this.value = initialText;
						this.addClass('default');
					}
				}
			});
		} catch(e) {
			
		}
	},
	
	// fix firefoxes crappy antialising by replacing to a bitmap font
	firefoxAntialising: function() {
		if(window.gecko) $$('#main .details').setStyle('font-family', 'Lucida Grande');
	},
	
	// oldschool urlencode... using Mootools anyhows
	urlEncode: function() {
		return this.replace(/\s/g, "+").replace(/&/, "&amp;").replace(/"/, "&quot;");
	},	
	
	// using delay(MS) instead
	sleep: function(msec) {
		var then = new Date().getTime()+msec;
	    while (then >= new Date().getTime()) {
	    }
	},
	
	// make the whole container clickable
	addLinkAction: function(obj) {
	    obj.each(function(item) {
			var link = item.getProperty('href');
			var newItem = item.getParent();
			
			newItem.addEvent('click', function() {
				window.location.href = link;
			});
		});
	},
	
	// add link actions here
	attachLinkAction: function() {
		this.addLinkAction($$('#audio li a'));
		this.addLinkAction($$('#books li a'));
	},
		
	// clear all comment fields
	clearFields: function() {
		var commentFields = $$('#add-comment p input');

		commentFields.each(function(commentField) {
			commentField.setAttribute('value', '');
		});
	},

	// change height on more than 280 chars
	expandField: function() {
		var text = $('content');
		var fx = new Fx.Style(text, 'height', {			
			duration: 300,
			wait: false,
			transition: Fx.Transitions.Quad.easeOut
		});
				
		if($defined(text)) text.addEvents({
			keyup: function() {
				var theLength = this.value.length;
				
				(theLength > 280) ? fx.start(150) : fx.start(80);
			}
		});
	},
	
	prepeareSegments: function() {
		
		// loading container
		var sWait = new Element('div', {'id': 'wait'}).injectInside($('re-int-cont'));
		new Element('span').setText('Ok, now wait while the magic is happening.').injectInside(sWait);
		
		// sucess container
		var sYay = new Element('div', {'id': 'yay'}).injectInside($('re-int-cont'));
		new Element('span').setText('Sweet! Response was added.').injectInside(sYay);
	},
	
	// compose a dynamically injected comment
	injectResponse: function(option) {
		var isSetComment = $('response-container')
		
		if(!isSetComment) {
			$$('.commentInfo').setStyle('display', 'none');
			var responses = new Element('ul', {
				'id': 'response-container'
			}).injectInside('responses');
		}

		var rCont = new Element('li', {
			'class': 'response',
			'styles': {
				'opacity': 0
			}
		}).injectInside('response-container');
		
		var title = new Element('h3').setText((option.url.value ? '' : option.name.value)).injectInside(rCont);
		
		if(option.url.value) {
			var link = new Element('a', {
				'href': option.url.value,
				'title': option.name.value
			}).setText(option.name.value).injectInside(title);
		}

		var dCont = new Element('ul').injectInside(rCont);
		
		var userpicCont = new Element('li', {'class': 'userpic'}).injectInside(dCont);
		var userpic = new Element('img', {
			'src': '',
			'alt': ''
		}).injectInside(userpicCont);
		
		var bodyCont = new Element('li', {'class': 'content'}).injectInside(dCont);
		var body = new Element('p').setHTML(option.comment.value).injectInside(bodyCont);
		
		var fx = new Fx.Styles(rCont, {
			duration: 1000, 
			transition: Fx.Transitions.Quad.easeOut
		});
		
		fx.start({
			'opacity': 1
		})
	},
	
	// switch classes on errors
	checkFields: function(options) {
		var missingClass 	= 'missing';
		var comment 		= options.comment;
		var name 			= options.name;
		var mail 			= options.mail;
		
		((comment.value == '') ? comment.addClass(missingClass) : comment.removeClass(missingClass));
		((name.value == '') ? name.addClass(missingClass) : name.removeClass(missingClass));
		((mail.value == '') ? mail.addClass(missingClass) : mail.removeClass(missingClass));
	},	
	
	// go back to the first segment on errors
	firstSegment: function() {
		this.start(0);
	},
	
	// post a response and add all the magic and stuff
	postResponse: function() {
		var obj 		= this;
		var respForm 	= $('response-form');
		var segment 	= ($defined(respForm) ? respForm.getSize().size.x : false);
		var submit 		= $('add-resp');
		var rContent 	= $('content');
		var rName 		= $('name');
		var rMail 		= $('mail');
		var rUrl 		= $('url');
		var reCont		= $('re-int-cont');
		var options 	= {
			'name': 	rName,
			'comment': 	rContent,
			'url': 		rUrl,
			'mail': 	rMail
		};
		
		try {
			var fx = reCont.effect('left', {
				duration: 500, 
				transition: Fx.Transitions.Back.easeOut
			});
			
			// add new segments
			this.prepeareSegments();
			
			// switch to ajax mode - makes the form unobtrusive
			respForm.setProperty('action', (respForm.getProperty('action')+'?mode=ajax'));
			
			submit.addEvent('click', function(e) {
				respForm.send({
					onRequest: function() {
						
						// make a chain as I don't want the fields to change color instantly
						fx.start(-segment).chain(function() {
							
							// check and (un)highlight fields
							obj.checkFields(options);
						});
					},
					onComplete: function() {
						fx.start(-segment*2);
					
						// inject comment
						obj.injectResponse(options);
						
						// return to the first segment
						obj.firstSegment.bind(fx).delay(6000);
						
						// clear comment textarea
						rContent.value = '';
					},
					onFailure: function() {
						fx.start(0);
						
						// check and (un)highlight fields
						obj.checkFields(options);
					}
				})
				new Event(e).stop();
			});
		} catch(e) {

		}
	},
	
	
	//
	// MAKE MORE GENERIC !!!!!!!!!!!!!!!!
	//
	
	twitterLoad: function() {
		var url 	= baseUrl + 'twitter.php';
		var twitterEl = $('twitter');
		var modeEl 	= $('add-more-twitts');
		
		var loadEl = new Element('li', {
			'class': 'loaderTicker'
		}).injectInside(modeEl.getParent().getParent());
		
		twitterEl.setStyle('opacity', 0);
		modeEl.setStyle('opacity', 0);
		
		var twitterBox = new Fx.Styles('twitter', {
			duration: 500, 
			transition: Fx.Transitions.Quart.easeOut
		});
		
		var loader = new Fx.Style(loadEl, 'opacity', {
			duration: 800,
			transition: Fx.Transitions.Quad.easeOut
		});
		
		var mode = new Fx.Style(modeEl, 'opacity', {
			duration: 800,
			transition: Fx.Transitions.Quad.easeOut
		});

		new Ajax(url, {
			method: 'get',
			update: twitterEl,
			onRequest: function() {
			},
			onComplete: function(t) {
				if(t == 'noworky') {					
					twitterBox.start({
						'height': 25
					}).chain(function() {
						this.start({
							'opacity': 1
						});	
					});
					mode.start(0);
					twitterEl.empty();
					var errorMessage = new Element('li', {
						'class': 'errorMessage'
					}).injectInside(twitterEl).setText("Couldn't fetch Twitter stuff. Bummer dude.");
				} else {
					twitterBox.start({
						'height': 230
					}).chain(function() {
						this.start({
							'opacity': 1
						});	
					});
					mode.start(1);
				}
				loader.start(0);
			},
			onFailure: function() {
				$$('#fetching-stuff span').setText('No worky');
			}
		}).request();
	},
	
	audioLoad: function() {
		var url 	= baseUrl + 'lastfm.php';
		var audioEl = $('audio');
		var modeEl 	= $('audio-mode');
		
		var loadEl = new Element('li', {
			'class': 'loaderTicker'
		}).injectInside(modeEl.getParent().getParent());
		
		audioEl.setStyle('opacity', 0);
		modeEl.setStyle('opacity', 0);
		
		var audioBox = new Fx.Styles('audio', {
			duration: 500, 
			transition: Fx.Transitions.Quart.easeOut
		});
		
		var loader = new Fx.Style(loadEl, 'opacity', {
			duration: 800,
			transition: Fx.Transitions.Quad.easeOut
		});
		
		var mode = new Fx.Style(modeEl, 'opacity', {
			duration: 800,
			transition: Fx.Transitions.Quad.easeOut
		});

		new Ajax(url, {
			method: 'get',
			update: audioEl,
			onRequest: function() {
			},
			onComplete: function(t) {
				if(t == 'noworky') {					
					audioBox.start({
						'height': 20
					}).chain(function() {
						this.start({
							'opacity': 1
						});	
					});
					mode.start(0);
					audioEl.empty();
					var errorMessage = new Element('li', {
						'class': 'errorMessage'
					}).injectInside(audioEl).setHTML("Bummer, no love from <strong>Last.fm</strong> today.");				
				} else {
					audioBox.start({
						'height': 210
					}).chain(function() {
						this.start({
							'opacity': 1
						});	
						audioEl.setStyle('overflow', 'visible');
					});
					mode.start(1);
				}
				loader.start(0);
			},
			onFailure: function() {
				$$('#fetching-stuff span').setText('No worky');
			}
		}).request();
	},
	
	audioAnim: function() {
		var audioEl = $('audio');
		var audioFx = new Fx.Styles('audio', {duration: 500, transition: Fx.Transitions.Quart.easeOut});

		$('audio-mode').addEvent('click', function(e) {
			if(audioEl.hasClass('simple')) {
				this.setText('(simple view)');
			} else if(audioEl.hasClass('detailed')) {
				this.setText('(detailed view)');
			}

			audioFx.start({
				'opacity': 0
			}).chain(function() {
				audioEl.setStyle('overflow', 'hidden');
				if(audioEl.hasClass('simple')) {
					this.start({
						'height': 650
					});
					audioEl.setProperty('class', 'detailed');
				} else if(audioEl.hasClass('detailed')) {
					this.start({
						'height': 210
					});
					audioEl.setProperty('class', 'simple');
				}	
			}).chain(function() {
				this.start({
					'opacity': 1
				});
				audioEl.setStyle('overflow', 'visible');
			});

			new Event(e).stop();
		});
	},
	
	bookAnim: function() {
		var bookEl = $('book');
		var bookFx = bookEl.effects({duration: 500, transition: Fx.Transitions.Quart.easeOut});

		$('book-mode').addEvent('click', function(e) {
			if(bookEl.hasClass('simple')) {
				this.setText('(simple view)');
			} else if(bookEl.hasClass('detailed')) {
				this.setText('(detailed view)');
			}

			bookFx.start({
				'opacity': 0
			}).chain(function() {
				if(bookEl.hasClass('simple')) {
					this.start({
						'height': 650
					});
					//bookEl.setStyle('padding', '0'); // WTF?!
					bookEl.className = 'detailed';
				} else if(bookEl.hasClass('detailed')) {
					this.start({
						'height': 225
					});

					bookEl.className = 'simple';
				}	
			}).chain(function() {
				this.start({
					'opacity': 1
				});
			});

			new Event(e).stop();
		});
	},
	
	resizeCover: function() {
	    $$('#book li a img').each(function(book) {
			var fx = new Fx.Styles(book, {
				duration: 150, 
				wait: false
			});
	
			book.addEvents({
				mouseenter: function() {
					fx.start({
						'left': -40,
						'height': 167,
						'width': 120,
						'top': -30
					});
				},
				mouseleave: function() {
					fx.start({
						'left': 4,
						'height': 134,
						'width': 93,
						'top': 4
					});
				}
			});
		});
	}
}

// make all happen on domready
window.addEvent('domready', function() {
	Engine.doStuff();
});