window.onload = function(e){
	if(typeof init !== 'undefined') init();
	initSearch();
}

function initSearch()
{
	var s = $('search');
	s.onclick = bind(this, searchClickHandler);
	
	this.search = document.createElement('div');
	this.search.id = 'searchPopUp';
	this.search.style.display = 'none';
	
	var sicon = document.createElement('div');
	sicon.id = 'searchIcon';
	this.search.appendChild(sicon);
	
	var sbody = document.createElement('div');
	sbody.id = 'searchBody';
	this.search.appendChild(sbody);
	
	var header = document.createElement('div');
	header.id = 'searchHeader';
	
	this.q = document.createElement('input');
	this.q.onkeyup = bind(this, searchHandler);
	header.appendChild(this.q);
	
	sbody.appendChild(header);
	
	this.list = document.createElement('ul');
	sbody.appendChild(this.list);
	
	/*
		<searchPopUp>
			<icon></icon>
			<body>
				<header>input</header>
				<list></list>
			</body>
		</searchPopUp>
	*/
	
	document.body.appendChild(this.search);
}

function searchClickHandler()
{
	
	this.search.style.display = 'block';
	tag(this.search, 'input')[0].focus();
	
	document.body.onmousedown = searchClickOutside;
	
	return false;
}

function searchClickOutside(e){
	
	var target = (e && e.target) || (event && event.srcElement);
	
	var ff = false;
	while(target.parentNode){
		if(target == window.search){
			ff = true;
			break;
		}
		target = target.parentNode;
	}
	
	if(!ff){
		window.search.style.display = 'none';
		document.body.onmousedown = null;
	}
	
	return false;
}

function searchHandler()
{
	var s = this.q.value;
	if(s.length >= 2)
	{
		_gaq.push(['_trackEvent', 'Search', 'input', s]);
		
		var client = new XMLHttpRequest();
		var ref = this;
		client.onreadystatechange = function(){
			if(this.readyState == 4 && this.status == 200) {
				ref.searchHandleResult(this.responseText);	
			} else if (this.readyState == 4 && this.status != 200) {
				ref.searchHandleResult(null);
			}
		};
		client.open("GET", '/search/' + s);
		client.send();
	}else{
		while( this.list.childNodes.length >= 1 ){
			this.list.removeChild( this.list.firstChild );       
		}
	}
}

function searchHandleResult(data)
{
	var result = eval(data);
	
	var li;
	
	while( this.list.childNodes.length >= 1 ){
		this.list.removeChild( this.list.firstChild );       
	}
	
	var l = Math.min(result.length, 9);
	
	for(var i=0; i < l; i++){
		if(result[i] != null){
			li = document.createElement('li');
			li.innerHTML = '<a href="'+ result[i].url + '">'+ result[i].word + '<br/>' + result[i].desc + '</a>';
			this.list.appendChild(li);
		}
	}
	
}

/* Utils */

$ = function(a){return document.getElementById(a);};
tag = function(a, b){return a.getElementsByTagName(b);};

function bind(a, b){
	if(arguments.length > 2){
		var p = [];
		for(var n = 2; n < arguments.length; ++n) p.push(arguments[n]);
		return function() { return b.apply(a,p); }
	}else{
		return function() { return b.call(a); }
	}
}

/* Regular JS TWEEN */

function Tween(target, duration, vars){
	
	if(!Tween.inited)
	{
		Tween._time = new Date().getTime() * 0.001;
		Tween._timer = setInterval(Tween.updateAll, 20);
		Tween.masterList = [];
		Tween.reservedProps = {ease:1, delay:1, overwrite:1, onComplete:1, onCompleteParams:1};
		Tween.inited = true;
	}
	
	this.vars = vars;
	this.duration = duration;
	this.active = (duration == 0 && this.vars.delay == 0);
	this.target = target;
	this.ease = vars.ease == 'out' ? Tween.easeOut : Tween.easeInOut;
	this.propTweens = [];
	this.inited = false;
	
	this.DOM = typeof target.style === "object";
	
	var delay = ("delay" in this.vars) ? this.vars.delay : 0;
	this.startTime = Tween._time + delay;
	
	var a = Tween.masterList[target];
	
	if(a == null || this.vars.overwrite == true){
		Tween.masterList[target] = [this];
	}else{
		a[a.length] = this;
	}
	
	if(this.active) renderTime(0);

}

Tween.prototype.init = function(){
	var num;
	for(var p in this.vars){
		if(Tween.reservedProps[p] != 1)
		{
			if(p == 'scrollposition'){
				num = this.getScroll();
			}else if(this.DOM){
				num = parseInt(this.target.style[p]);
			}else{
				num = this.target[p];
			}
			
			if(isNaN(num)) num = 1;
			this.propTweens[ this.propTweens.length ] = [p, num, (typeof(this.vars[p]) == "number") ? this.vars[p] - num : this.vars[p]]; //[property, start, change]
		}
	}
	this.inited = true;
};

Tween.prototype.getScroll = function(){
    if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
};

Tween.prototype.setScroll = function(v){
	window.scrollTo(0,v);
};

Tween.prototype.renderTime = function(time){
	if(!this.inited) this.init();
	
	var pt, i = this.propTweens.length;
	
	if(time >= this.duration){
		time = this.duration;
		this.ratio = 1;
	}else if(time <= 0){
		this.ratio = 0;
	}else{
		this.ratio = this.ease(time, 0, 1, this.duration);
	}
	
	while(--i > -1){
		pt = this.propTweens[i];
		if(this.DOM){
		switch(pt[0]){
			case 'left':
			case 'top':
			case 'right':
			case 'bottom':
			case 'width':
			case 'height':
				this.target.style[pt[0]] = (pt[1] + (this.ratio * pt[2])) + 'px';
			break;
			case 'opacity':
				this.target.style[pt[0]] = pt[1] + (this.ratio * pt[2]);
				this.target.style.filter = 'alpha(opacity=' + (pt[1] + (this.ratio * pt[2]))*100 + ')';
			break;
			case 'scrollposition':
				this.setScroll( pt[1] + (this.ratio * pt[2]) );
			break;
			default:
				this.target.style[pt[0]] = pt[1] + (this.ratio * pt[2]);
			break;
		}
		}else{
			this.target[pt[0]] = pt[1] + (this.ratio * pt[2]);
		}
		
	}
	
	if(time == this.duration) this.complete(true);
};

Tween.prototype.complete = function(){
	this.kill();
	if(this.vars.onComplete != null) this.vars.onComplete.apply(null, this.vars.onCompleteParams);
};

Tween.prototype.kill = function(){
	this.gc = true;
	this.active = false;
};

Tween.to = function(target, duration, vars){
	return new Tween(target, duration, vars);
};

Tween.set = function(target, vars){
	var t = new Tween(target, 0, vars);
	t.renderTime(0);
	t = null;
};

Tween.updateAll = function(){
	Tween._time = new Date().getTime() * 0.001;
	
	var ml = Tween.masterList;
	var a, tgt, i, y, tween;
	
	for(tgt in ml){
		a = ml[tgt];
		i = a.length;
		while(--i > -1){
			tween = a[i];
			t = Tween._time;
			if(tween.active || (!tween.gc && t >= tween.startTime)){
				tween.renderTime(t - tween.startTime);
			}else if(tween.gc){
				a.splice(i, 1);
			}
		}
		
		if(a.length == 0){
			delete ml[tgt];
			for(i in Tween.masterList){
				return;
			}
			clearInterval(Tween._timer);
			Tween.inited = false;
		}
	}
	
};

Tween.kill = function(target){
	if(Tween.masterList[target]){
		delete Tween.masterList[target];
	}
}

Tween.easeOut = function(t, b, c, d){
	return -1 * (t /= d) * (t - 2);
};

Tween.easeInOut = function(t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};
