/* Behaviour v2. (c) Ben Nolan. My stuff is BSD Licensed. Selector class is MIT Licensed. */

function $(expression, scope){
	if (typeof expression != 'string'){
		return expression;
	}
	
	var results = Selector.Find(expression, scope);
	return expression.match(/#\S+$/)?results[0]:results;
}

var Class = {
	create: function(superClass){
		return function() {
			if (superClass){
				for (property in superClass.prototype){
					this[property] = superClass.prototype[property];
				}
			}
			
			if (this.initialize){
				this.initialize.apply(this, arguments);
			}
		}
	}
}

Object.extend = function(destination, source) {
	for (property in source) destination[property] = source[property];
	return destination;
}

Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    return __method.apply(object, arguments);
  }
}

Function.prototype.bindAsEventListener = function(object) {
var __method = this;
	return function(event) {
		__method.call(object, event || window.event);
	}
}

var Selector = Class.create();
Selector.Find = function(expression, scope){
	if (!expression.split){
		return null;
	}
	
	var expr, expressions = expression.split(/\s+/), scopes=[scope || document];
	
	for (var i=0;expr=expressions[i];i++){
		var selector = new Selector(expr), results = [];
		
		for (var j=0;scope=scopes[j];j++){
			selector.findElements(scope || document, results);
		}
		
		scopes = results;
	}
	
	return scopes;
};
Selector.prototype = {
	initialize: function(expression){
		this.params ={classNames: []};
		this.expression = expression;
		this.parseExpression();
		this.compileMatcher();
	},
	parseExpression: function(){
		function abort(message){ throw 'Parse error in selector: ' + message; }
		
		if (this.expression == '') abort('empty expression');
		if (this.expression == '*') return this.params.wildcard = true;
			
		var params = this.params, expr = this.expression, match;
		while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)){
			var modifier = match[1], clause = match[2], rest = match[3];
			switch (modifier){
				case '#':
					params.id = clause; 
					break;
				case '.':
					params.classNames.push(clause); 
					break;
				default:
					params.tagName = clause.toUpperCase(); 
					break;
			}
			expr = rest;
		}
		
		if (expr.length > 0) abort(expr);
	},
	buildMatchExpression: function(){
		var params = this.params, conditions = [], clause;
		
		if (params.wildcard)
			return 'true';
	 
		if (clause = params.id)
			conditions.push('element.id == "' + clause + '"');
		if (clause = params.tagName)
			conditions.push('element.tagName.toUpperCase() == "' + clause + '"');
		if ((clause = params.classNames).length > 0)
			for (var i = 0; i < clause.length; i++)
				conditions.push('element.className.match(/\\b' + clause[i] + '\\b/)');
		
		return conditions.join(' && ');
	},
	compileMatcher: function(){
		eval('this.match = function(element){ if (!element.tagName) return false; return ' + this.buildMatchExpression() + ' }');
	},
	findElements: function(scope, results){
		var element;

		if (element = document.getElementById(this.params.id))
			if (this.match(element))
				return results.push(element);
		
		scope = scope.getElementsByTagName(this.params.tagName || '*');
		
		for (var i = 0; i < scope.length; i++)
			if (this.match(element = scope[i])){
				results.push(element);
			}
	
		return results;
	}
}

$Behaviour = Class.create();
$Behaviour.prototype = {
	initialize : function(){
		this.sheets = new Array;
	},
	register : function(sheet){
		this.sheets.push(sheet);
	},
	apply : function(scope){
		var sheet, selector;
		
		for (var i=0;sheet=this.sheets[i];i++){
			for (selector in sheet){
				this.applyFunctionToSelector(selector, scope, sheet[selector])
			}
		}
	},
	applySelector : function(selector, scope){
		var sheet;
		
		for (var i=0;sheet=this.sheets[i];i++){
			if (sheet[selector]){
				this.applyFunctionToSelector(selector, scope, sheet[selector])
			}
		}
	},
	applyFunctionToSelector : function(selector, scope, func){
		var element, list;
		
		try{
			list = Selector.Find(selector, scope);
		}catch(e){
			throw 'Error applying selector \'' + selector +'\'';
		};
		
		for (var i=0;element=list[i];i++){
			// Bit ugly....
			if (element.behaving_for){
				if (element.behaving_for[selector]){
					continue;
				}
			}else{
				element.behaving_for={};
			}
			element.behaving_for[selector] = true;
			
			//try{
				func(element);
			//}catch(e){
			//	throw 'Error applying function for selector \'' + selector +'\'';
			//}
		}
	}	
}

Behaviour = new $Behaviour;

/* Moo.fx */

/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
Saturday, February 11, 2006
v 1.2.1
*/

var fx = new Object();
//base
fx.Base = function(){};
fx.Base.prototype = {
	setOptions: function(options) {
	this.options = {
		duration: 500,
		onComplete: '',
		transition: fx.sinoidal
	}
	Object.extend(this.options, options || {});
	},

	go: function() {
		this.startTime = (new Date).getTime();
		this.timer = setInterval (this.step.bind(this), 13);
	},

	step: function() {
		var time  = (new Date).getTime();
		if (time >= this.options.duration+this.startTime) {
			this.now = this.to;
			clearInterval (this.timer);
			this.timer = null;
			if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
		}
		else {
			var Tpos = (time - this.startTime) / (this.options.duration);
			this.now = this.options.transition(Tpos) * (this.to-this.from) + this.from;
		}
		this.increase();
	},

	custom: function(from, to) {
		if (this.timer != null) return;
		this.from = from;
		this.to = to;
		this.go();
	},

	hide: function() {
		this.now = 0;
		this.increase();
	},

	clearTimer: function() {
		clearInterval(this.timer);
		this.timer = null;
	}
}

//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.el.style.overflow = "hidden";
		this.el.iniWidth = this.el.offsetWidth;
		this.el.iniHeight = this.el.offsetHeight;
		
		this.setOptions(options);
	}
});

fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {	
	increase: function() {
		this.el.style.height = this.now + "px";
	},

	toggle: function() {
		if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
		else this.custom(0, this.el.scrollHeight);
	}
});

fx.Width = Class.create();
Object.extend(Object.extend(fx.Width.prototype, fx.Layout.prototype), {	
	increase: function() {
		this.el.style.width = this.now + "px";
	},

	toggle: function(){
		if (this.el.offsetWidth > 0) this.custom(this.el.offsetWidth, 0);
		else this.custom(0, this.el.iniWidth);
	}
});

//fader
fx.Opacity = Class.create();
fx.Opacity.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.now = 1;
		this.increase();
		this.setOptions(options);
	},

	increase: function() {
		if (this.now == 1 && (/Firefox/.test(navigator.userAgent))) this.now = 0.9999;
		this.setOpacity(this.now);
	},
	
	setOpacity: function(opacity) {
		if (window.ActiveXObject) this.el.style.filter = "alpha(opacity=" + opacity*100 + ")";
		this.el.style.opacity = opacity;
		if (opacity == 0) this.el.style.visibility = "hidden";
		else this.el.style.visibility = "visible";
	},

	toggle: function() {
		if (this.now > 0) this.custom(1, 0);
		else this.custom(0, 1);
	}
});

//transitions
fx.sinoidal = function(pos){
	return ((-Math.cos(pos*Math.PI)/2) + 0.5);
	//this transition is from script.aculo.us
}
fx.linear = function(pos){
	return pos;
}
fx.cubic = function(pos){
	return Math.pow(pos, 3);
}
fx.circ = function(pos){
	return Math.sqrt(pos);
}

/*
moo.fx pack, effects extensions for moo.fx.
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE
for more info visit (http://moofx.mad4milk.net).
Sunday, February 05, 2006
v 1.2
*/

//smooth scroll
fx.Scroll = Class.create();
fx.Scroll.prototype = Object.extend(new fx.Base(), {
	initialize: function(options) {
		this.setOptions(options);
	},

	scrollTo: function(el){
		var dest = Position.cumulativeOffset($(el))[1];
		var client = window.innerHeight || document.documentElement.clientHeight;
		var full = document.documentElement.scrollHeight;
		var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		if (dest+client > full) this.custom(top, dest - client + (full-dest));
		else this.custom(top, dest);
	},

	increase: function(){
		window.scrollTo(0, this.now);
	}
});

//text size modify, now works with pixels too.
fx.Text = Class.create();
fx.Text.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.setOptions(options);
		if (!this.options.unit) this.options.unit = "em";
	},

	increase: function() {
		this.el.style.fontSize = this.now + this.options.unit;
	}
});

//composition effect: widht/height/opacity
fx.Combo = Class.create();
fx.Combo.prototype = {
	setOptions: function(options) {
		this.options = {
			opacity: true,
			height: true,
			width: false
		}
		Object.extend(this.options, options || {});
	},

	initialize: function(el, options) {
		if (!el){
			return null;
		}

		this.el = $(el);
		this.setOptions(options);
		this.isOpen = false;
		if (this.options.opacity) {
			this.el.o = new fx.Opacity(el, options);
			options.onComplete = null;
		}
		if (this.options.height) {
			this.el.h = new fx.Height(el, options);
			options.onComplete = null;	
		}
		if (this.options.width) this.el.w = new fx.Width(el, options);
	},
	
	toggle: function() {
		this.checkExec('toggle'); 
		this.isOpen = !this.isOpen;
	},

	hide: function(){
		this.checkExec('hide'); 
		this.isOpen = false;
	},
	
	clearTimer: function(){ this.checkExec('clearTimer'); },
	
	checkExec: function(func){
		if (this.el.o) this.el.o[func]();
		if (this.el.h) this.el.h[func]();
		if (this.el.w) this.el.w[func]();
	},
	
	//only if width+height
	resizeTo: function(hto, wto) {
		if (this.el.h && this.el.w) {
			this.h.custom(this.el.offsetHeight, this.el.offsetHeight + hto);
			this.w.custom(this.el.offsetWidth, this.el.offsetWidth + wto);
		}
	},

	customSize: function(hto, wto) {
		if (this.el.h && this.el.w) {
			this.h.custom(this.el.offsetHeight, hto);
			this.w.custom(this.el.offsetWidth, wto);
		}
	}
}

fx.Accordion = Class.create();
fx.Accordion.prototype = {
	setOptions: function(options) {
		this.options = {
			delay: 100,
			opacity: false
		}
		Object.extend(this.options, options || {});
	},

	initialize: function(togglers, elements, options) {
		this.elements = elements;
		this.setOptions(options);
		elements.each(function(el, i){
			options.onComplete = function(){
				if (el.offsetHeight > 0) el.style.height = '1%';
			}
			el.fx = new fx.Combo(el, options);
			el.fx.hide();
		});

		togglers.each(function(tog, i){
			tog.onclick = function(){
				this.showThisHideOpen(elements[i]);
			}.bind(this);
		}.bind(this));
	},

	showThisHideOpen: function(toShow){
		if (toShow.offsetHeight == 0) setTimeout(function(){this.clearAndToggle(toShow);}.bind(this), this.options.delay);
		this.elements.each(function(el, i){
			if (el.offsetHeight > 0 && el != toShow) this.clearAndToggle(el);
		}.bind(this));
	},

	clearAndToggle: function(el){
		el.fx.clearTimer();
		el.fx.toggle();
	}
}

var Remember = new Object();
Remember = function(){};
Remember.prototype = {
	initialize: function(el, options){
		this.el = $(el);
		this.days = 365;
		this.options = options;
		this.effect();
		var cookie = this.readCookie();
		if (cookie) {
			this.fx.now = cookie;
			this.fx.increase();
		}
	},

	//cookie functions based on code by Peter-Paul Koch
	setCookie: function(value) {
		var date = new Date();
		date.setTime(date.getTime()+(this.days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = this.el+this.el.id+this.prefix+"="+value+expires+"; path=/";
	},

	readCookie: function() {
		var nameEQ = this.el+this.el.id+this.prefix + "=";
		var ca = document.cookie.split(';');
		for(var i=0;c=ca[i];i++) {
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return false;
	},

	custom: function(from, to){
		if (this.fx.now != to) {
			this.setCookie(to);
			this.fx.custom(from, to);
		}
	}
}

fx.RememberHeight = Class.create();
fx.RememberHeight.prototype = Object.extend(new Remember(), {
	effect: function(){
		this.fx = new fx.Height(this.el, this.options);
		this.prefix = 'height';
	},
	
	toggle: function(){
		if (this.el.offsetHeight == 0) this.setCookie(this.el.scrollHeight);
		else this.setCookie(0);
		this.fx.toggle();
	},
	
	resize: function(to){
		this.setCookie(this.el.offsetHeight+to);
		this.fx.custom(this.el.offsetHeight,this.el.offsetHeight+to);
	},

	hide: function(){
		if (!this.readCookie()) {
			this.fx.hide();
		}
	}
});

fx.RememberText = Class.create();
fx.RememberText.prototype = Object.extend(new Remember(), {
	effect: function(){
		this.fx = new fx.Text(this.el, this.options);
		this.prefix = 'text';
	}
});

//useful for-replacement
Array.prototype.each = function(func){
	for(var i=0;ob=this[i];i++) func(ob, i);
}

//Easing Equations (c) 2003 Robert Penner, all rights reserved.
//This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html.

//expo
fx.expoIn = function(pos){
	return Math.pow(2, 10 * (pos - 1));
}
fx.expoOut = function(pos){
	return (-Math.pow(2, -10 * pos) + 1);
}

//quad
fx.quadIn = function(pos){
	return Math.pow(pos, 2);
}
fx.quadOut = function(pos){
	return -(pos)*(pos-2);
}

//circ
fx.circOut = function(pos){
	return Math.sqrt(1 - Math.pow(pos-1,2));
}
fx.circIn = function(pos){
	return -(Math.sqrt(1 - Math.pow(pos, 2)) - 1);
}

//back
fx.backIn = function(pos){
	return (pos)*pos*((2.7)*pos - 1.7);
}
fx.backOut = function(pos){
	return ((pos-1)*(pos-1)*((2.7)*(pos-1) + 1.7) + 1);
}

//sine
fx.sineOut = function(pos){
	return Math.sin(pos * (Math.PI/2));
}
fx.sineIn = function(pos){
	return -Math.cos(pos * (Math.PI/2)) + 1;
}
fx.sineInOut = function(pos){
	return -(Math.cos(Math.PI*pos) - 1)/2;
}

/*
 * Moojax
 */
 
Moojax = Class.create();
Moojax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'get';
		if (options.postBody){
			this.method = 'post';
		}
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		this.request(url);
	},

	request: function(url){
		this.transport.open(this.method, url, true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},

	onStateChange: function(){
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete) 
				setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
			if (this.update)
				setTimeout(function(){
					this.update.innerHTML = this.transport.responseText;
					Behaviour.apply(this.update);
				}.bind(this), 10);
			this.transport.onreadystatechange = function(){};
		}
	},

	getTransport: function() {
		if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest) return new XMLHttpRequest();
		else return false;
	}
}; 

/*
 * Form serializer
 */
 
Form = Class.create();
Form.prototype = {
	initialize : function(el){
		this.form = el;
	},
	serialize : function(){
		var element,elements=[], list = this.form.getElementsByTagName("*");
		
		for (var i=0;element=list[i];i++){
			if (!element.value){
				continue;
			}
			elements.push(element.name + '=' + escape(element.value));
		}
		
		return elements.join('&');
	}
}; 