(function(){
	if (typeof MKAvail === 'boolean') {return;}

	var MK = function(ls) {
		this.els = [];
		for (var i = 0, k = ls.length; i < k; i++) {
			var l = ls[i];
			if (typeof l === 'string') l = $i(l);
			this.els.push(l);
		}
		return this;
	}

	MK.prototype = {
		push : function(a) {
			for (var j = 0, p = a.length; j < p; j++) {
				this.els.push(a[j]);
			}
			return this;
		},

		all : function(f) {
			for (var i = 0, xn = this.els.length; i < xn; ++i) {
				f.call(this, this.els[i]);
			}
			return this;
		},

		on : function(t, f) {
			var lsn = function(el) {
				if (window.addEventListener) {
					el.addEventListener(t, f, false);
				} else if (window.attachEvent) {
					el.attachEvent('on' + t, function() {
							f.call(el, window.event);
						}
					);
				}
			};
			this.all(function(el) {
				lsn(el);
			});
			return this;
		},

		style : function(p, v) {
			this.all(function(el) {
				var u = v;
				if (p === 'opacity') {
					el.style['filter'] = 'alpha(opacity='+ u +')';
					u = u / 100;
				}
				el.style[p] = u;
			});
			return this;
		},

		css : function(o) {
			for (var p in o) {
				this.style(p, o[p]);
			}
			return this;
		},

		anim : function(f, b, e, t, c) {
			var that = this;
			for (var p in b) {
				if (p !== 'opacity' || p !== 'zIndex') {
					e[p] = (e[p] - b[p]);
				}
			} 
			var nd = new Date().getTime() + t;
			setTimeout(function() {
				var k = (t - (nd - new Date().getTime()));
				if (t <= k) k = t;	
				for (var p in b) {
					if (p === 'scrollLeft' || p === 'scrollTop') {
						that.all(function(el) {
							el[p] = f(k, b[p], e[p], t);
						});
					} else {
						var prt = (p === 'zIndex' || p === 'opacity') ? '' : 'px';
						that.style(p, Math.floor(f(k, b[p], e[p], t)) + prt);
					}
				}
				if (k === t) {
					if (c) c();
				} else {
					setTimeout(arguments.callee, 30);
				}
			}, 30);
			return this;
		}
	};

	window.$ = function() {
		return new MK(arguments);
	};

	$i = function(o) {
		if (typeof o == 'string') {
			return document.getElementById(o);
		}
		return o;
	};

	$e = function(i, e) {
		var d = i ? $i(i) : document;
		return d.getElementsByTagName(e);
	};

	$c = function(c, e) {
		var d = e ? $i(e) : document;
		if (!document.getElementsByClassName) {
			var r = [];
			c = new RegExp('\\b'+c+'\\b');
			d = d.getElementsByTagName('*');
			for (var i = 0;i < d.length;i++) {
				if (c.test(d[i].className)) {
					r.push(d[i]);
				}
			}
			return r;
		}
		return d.getElementsByClassName(c);
	};

	xhr = function(u, p, s, f) {
		var X = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
		if (p == '') {
			X.open('GET', u, true);
		} else {
			X.open('POST', u, true);
			X.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		}
		X.onreadystatechange = function() {
			if (X.readyState === 4) {
				var r = X.responseText;
				if (X.status === 200) {
					if (s) s(r, X);
				} else {
					if (f) f(r, X);
				}
			}
		};
		X.send(p);
	};

	load = function(s, c) {
		var f = document.createElement('script');
		f.type = 'text/javascript';
		f.setAttribute('async', 'true');
		f.onloadDone = false;
		if (c) {
            f.onload = function() {
	     		f.onloadDone = true;        
            	c();
            };
	     	f.onreadystatechange = function() {
	     		if (('loaded' === f.readyState || 'complete' === f.readyState) && !f.onloadDone) {
		     		f.onloadDone = true;
	     			c();
	     		}
	     	};
        }
		f.src = s;
		var h = $e(document, 'head')[0];
		h.insertBefore(f, h.firstChild);
	};

	offSet = function(o) {
		var l = 0;
		var t = 0;
		if (o.offsetParent) {
			do {
				l += o.offsetLeft;
				t += o.offsetTop;
			} while(o = o.offsetParent);
			return [l, t];
		}
	};

	preventDefault = function(e) {
		if (!e) e = window.event;
		e.cancelBubble = true;
		e.returnValue = false;
		if (e.preventDefault) {
			e.preventDefault();
		}
	};

	if (!Array.indexOf) {
		Array.prototype.indexOf = function(o, i) {
			for(var j = this.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0; i < j && this[i] !== o; i++);
			return j <= i ? -1 : i
		}
	}

	ease = {
		cubic : function(t, b, c, d) {
			if((t /= d / 2) < 1){
				return (c / 2 * t * t * t + b) * 1;
			}
			return (c / 2 * ((t -= 2) * t * t + 2) + b) * 1;
		},

		bounce : function(t, b, c, d) {
			if((t /= d) < (1 / 2.75)) {
				return c * (7.5625 * t * t) + b;
			} else if(t < (2 / 2.75)) {
				return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
			} else if(t < (2.5 / 2.75)) {
				return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
			}else{
				return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
			}
		}
	}
	MKAvail = true;
})();

var filterByTech = function(term) {
	var rslt = [];
	for (var i = 0, j = portfolio.sites.length; i < j; i++) {
		if (portfolio.sites[i].tech.indexOf(term) > -1) {
			rslt.push(i);
		}
	}
	return rslt;
};

var generateTags = function() {
	var tagList = [];
	for (var i = 0, j = portfolio.sites.length; i < j; i++) {
		for (var k = 0, p = portfolio.sites[i].tech.length; k < p; k++) {
			var curTech = portfolio.sites[i].tech[k];
			if (tagList.indexOf(curTech) == -1) {
				tagList.push(curTech);
			}
		}
	}
	
	tagList.sort(function(a, b) {
		a = a.toLowerCase();
		b = b.toLowerCase();
		if (a > b) return 1;
		if (a < b) return -1;
		return 0; 
	});
	
	var rslt = [];
	for (var i = 0, j = tagList.length; i < j; i++) {
		var tagDtl = [tagList[i], filterByTech(tagList[i]).length];
		rslt.push(tagDtl);
	}
	return rslt;
};

var back = function() {
	if (tumMode || busy) {
		return;
	}
	
	if ($i('splashTitle')) {
		$('splashTitle', 'splashUri').css({display: 'none'});
	}

	$('moveBack').css({opacity: 20});
	setTimeout(function() {
		if (curSet == 1) {
			$('moveBack').css({opacity: 20, cursor: 'default'});
		} else {
			$('moveBack').css({opacity: 100, cursor: 'pointer'});
		}
		$('moveForward').css({opacity: 100, cursor: 'pointer'});						
	}, 100);


	var cTop =  offSet($i('rail'))[1];
	var imgRail = $('rail');
	var secs = $().push($e('rail', 'section'));
	
	if (curSet == 1) {
		return;
	}

	curSet--;
	busy = true;

	if ((curSet % 2) === 0) {
		var pLeft = $i('portfolio').offsetWidth;
	} else {
		var pLeft = 0;
	}
	
	if (((curSet % 2) === 0)) {
		pLeft = $i('portfolio').offsetWidth;
		var rTop = $i('portfolio').scrollTop - $i('portfolio').offsetHeight;
	} else {
		var rTop = $i('portfolio').scrollTop;
	}

	$('portfolio').anim(ease.cubic, {opacity: 100, top: cTop}, {opacity: 0, top: (cTop + 200)}, 250, function() {
		$i('portfolio').scrollTop = (rTop - 5);
		$i('portfolio').scrollLeft = pLeft;
		$('portfolio').anim(ease.cubic, {opacity: 0, top: 0}, {opacity: 100, top: cTop}, 300);
	});
	
	var bgImg = $('bg');
	bgImg.anim(ease.cubic, {left: -160, opacity: 100}, {left: -800, opacity: 0}, 250, function() {
		bgImg.anim(ease.cubic, {left: 800, opacity: 0}, {left: -160, opacity: 100}, 300, function() {
			busy = false;	
		});
	});
};

var next = function() {
	if (tumMode || busy) {
		return;
	}

	if ($i('splashTitle')) {
		$('splashTitle', 'splashUri').css({display: 'none'});
	}

	$('moveForward').css({opacity: 20});
	setTimeout(function() {
		$('moveBack').css({opacity: 100, cursor: 'pointer'});
		if (curSet >= (curImgs.els.length / 4)) {
			$('moveForward').css({opacity: 20, cursor: 'default'});	
		} else {
			$('moveForward').css({opacity: 100, cursor: 'pointer'});
		}
	}, 100);

	var cTop =  offSet($i('rail'))[1];
	var imgRail = $('rail');
	var secs = $().push($e('rail', 'section'));
	
	curSet++;

	if (curSet > (curImgs.els.length / 4)) {
		curSet = (curImgs.els.length / 4);
		return;
	}
	
	busy = true;

	if ((curSet % 2) === 0) {
		var pLeft = $i('portfolio').offsetWidth;
	} else {
		var pLeft = 0;
	}
	
	if (((curSet % 2) === 1) && (curSet != 2)) {
		pLeft = 0;
		var rTop = $i('portfolio').scrollTop + $i('portfolio').offsetHeight;
	} else {
		var rTop = $i('portfolio').scrollTop;
	}

	$('portfolio').anim(ease.cubic, {opacity: 100, top: cTop}, {opacity: 0, top: 0}, 250, function() {
		$i('portfolio').scrollTop = (rTop + 5);
		$i('portfolio').scrollLeft = pLeft;
		$('portfolio').anim(ease.cubic, {opacity: 0, top: (cTop + 200)}, {opacity: 100, top: cTop}, 300);
	});
	
	var bgImg = $('bg');
	bgImg.anim(ease.cubic, {left: -160, opacity: 100}, {left: 800, opacity: 0}, 250, function() {
		bgImg.anim(ease.cubic, {left: -800, opacity: 0}, {left: -160, opacity: 100}, 300, function() {
			busy = false;	
		});
	});
};

var thumbToggle = function() {
	if (busy) {return;}
	busy = true;
	
	if ($i('splashTitle')) {
		$('splashTitle', 'splashUri').css({display: 'none'});
	}
	
	if (tumMode) {
		$('togTum').css({opacity: 50});
		if (curSet > 1) {
			$('moveBack').css({opacity: 100, cursor: 'pointer'});
		}
		if (curSet < (curImgs.els.length / 4)) {
			$('moveForward').css({opacity: 100, cursor: 'pointer'});		
		}
		showThumbs();
	} else {
		$('togTum').css({opacity: 100});		
		$('moveBack', 'moveForward').css({opacity: 20, cursor: 'default'});
		showAll();
	}
};

var showAll = function() {
	pst = $i('portfolio').scrollTop;
	psl = $i('portfolio').scrollLeft;

	$('portfolio').anim(ease.cubic, {top: 185, height: 130, scrollTop: pst, scrollLeft: psl}, {top: 50, height: 500, scrollTop: 0, scrollLeft: 0}, 450, function() {
		$('controls').anim(ease.cubic, {bottom: -200}, {bottom: 20}, 500, function() {
			busy = false;
		});
	});
	
	curPreview.css({opacity: 100, marginLeft: 0}).anim(ease.cubic, {width: 200, height: 100}, {width: 92, height: 70}, 500);
	tumMode = true;
};

var showThumbs = function() {
	tumMode = false;
	$('controls').anim(ease.cubic, {bottom: 20}, {bottom: -200}, 500);
	$('portfolio').anim(ease.cubic, {top: 50, height: 500, scrollTop: 0, scrollLeft: 0}, {top: 185, height: 130, scrollTop: pst, scrollLeft: psl}, 450);
	
	curPreview.anim(ease.cubic, {width: 92, height: 70}, {width: 200, height: 100}, 500, function() {
		curImgs.css({opacity: 100});
		busy = false;
	});
};

var closeDetail = function() {
	if (offSet($i('detail'))[1] != -10) return;
	
	$('closeBut').css({opacity: 30});

	setTimeout(function() {
		$('closeBut').css({opacity: 600});	
	}, 200);
	
	$('detail').anim(ease.cubic, {top: -10}, {top: -500}, 500, function() {
		if (tumMode) {
			$('controls').anim(ease.cubic, {bottom: -200}, {bottom: 20}, 500);	
		}
		drawDetail = false;		
	});
}

var showDetail = function(idx) {
	$('splashTitle', 'splashUri').css({display: 'none'});

	if (tumMode) {
		$('controls').anim(ease.cubic, {bottom: 20}, {bottom: -200}, 500);
	}
	
	drawDetail = true;

	var txt = '<h1>'+ portfolio.sites[idx].name +'</h1><p>'+ portfolio.sites[idx].blurb +'</p><p><strong>My contribution</strong><br />'+ portfolio.sites[idx].detail +'</p><p><strong>Technologies / techniques / tools</strong><br />'+ portfolio.sites[idx].tech.join(', ') +'.</p>';
	if (portfolio.sites[idx].uri != '#') {
		txt += '<p><strong>Visit:</strong> <a target="_new" href="http://'+ portfolio.sites[idx].uri +'">'+ portfolio.sites[idx].uri +'</a></p>';
	}

	$i('tmbs').scrollTop = 0;
	$i('tmbs').innerHTML = '';
	$i('dtls').innerHTML = txt;
	$i('pic').innerHTML = '<img src="img/'+ portfolio.sites[idx].img[0] +'" alt="'+ portfolio.sites[idx].imgDesc[0] +'" />';
	$i('tmbDtl').innerHTML = portfolio.sites[idx].imgDesc[0];
		
	$('detail').anim(ease.cubic, {top: -500}, {top: -10}, 500, function() {
		var tmb = $i('tmbs');
		for (var i = 0, j = portfolio.sites[idx].img.length; i < j; i++) {
			var img = new Image();
			img.onload = function() {
				tmb.appendChild(this);			
				$(this).anim(ease.cubic, {opacity: 0}, {opacity: 100}, 800);
			};
			img.setAttribute('alt', portfolio.sites[idx].imgDesc[i]);
			img.onclick = function() {
				showPic(this);
			};
			$(img).css({opacity: 0});
			img.src = 'img/'+ portfolio.sites[idx].img[i];			
		}
	});
};

var showPic = function(npic) {
	if (busy) return;
	
	busy = true;
	var cImg = $e('pic', 'img')[0];
	$('pic').css({backgroundImage: 'url('+ npic.src +')'});
	$(cImg, 'tmbDtl').anim(ease.cubic, {opacity: 100}, {opacity: 0}, 700, function() {
		cImg.src = npic.src;				
		$(cImg).css({opacity: 100});
		$i('tmbDtl').innerHTML = npic.getAttribute('alt');		
		$('tmbDtl').anim(ease.cubic, {opacity: 0}, {opacity: 100}, 600, function() {
			busy = false;
		});
	});
};

var addSection = function(str) {
	var sec = document.createElement('section');
	sec.innerHTML = str;
	$i('rail').appendChild(sec);
};

var filterAll = function(str) {
	var rsltSet = filterByTech(str).split(',')
};

var initUI = function() {	
	$('bg').anim(ease.cubic, {left: -800, opacity: 0}, {left: -160, opacity: 100}, 1000);
	
	var cName = $i('splashTitle');
	if (!cName) {
		var cName = document.createElement('div');
		cName.id = 'splashTitle';
		document.body.appendChild(cName);
		var cUri = document.createElement('div');
		cUri.id = 'splashUri';
		document.body.appendChild(cUri);
	}

	$().push($e('rail', 'div')).anim(ease.cubic, {opacity: 0, marginLeft: 500}, {opacity: 100, marginLeft: 0}, 1000, function() {
		var loadSpinner = $i('loading');
		if (loadSpinner) {
			loadSpinner.parentNode.removeChild(loadSpinner);
		}

		$('nav').anim(ease.cubic, {opacity: 0}, {opacity: 100}, 700);
		
		var nStr = '';
		var buildCount = 0;
		for (var i = 8, j = portfolio.sites.length; i < j; i++) {
			nStr += '<div><img class="'+ i +'" src="img/'+ portfolio.sites[i].img[0] +'" alt="'+ portfolio.sites[i].name +'" /></div>';
			if (i === (j - 1)) {
				var nImg = new Image();
				nImg.onload = function() {
					$().push($e('rail', 'img'));
				};
				nImg.src = 'img/'+ portfolio.sites[i].img[0];
			}
			buildCount++;
			if (buildCount == 8) {
				addSection(nStr);
				nStr = '';
				buildCount = 0;
			}
		}

		if (!loaded) {
			loaded = true;
		}
		
		curPreview = $().push($e('rail', 'div'));
		curImgs = $().push($e('rail', 'img'));

		curPreview.css({opacity: 100}).on('mouseover', function() {
			if (busy) return;
			
			var cImg = $e(this, 'img')[0];
			var cImgSrc = cImg.src;
			var cId = cImg.className;

			curImgs.css({opacity: 20});
			$(cImg).css({opacity: 100});				
				
			var cUri = $i('splashUri');			
			cName.innerHTML = portfolio.sites[cId].name;
			var cLeft = offSet(this)[0] - $i('portfolio').scrollLeft;
			var cWidth = this.offsetWidth;
			var cTop = (offSet(this)[1] + (this.offsetHeight)) - $i('portfolio').scrollTop;			

			if (!tumMode) {				
				$(cName).css({display: 'block', top: (cTop) + 'px', textAlign: 'left'}).anim(ease.cubic, {opacity: 0, left: (cLeft + (cWidth / 2))}, {opacity: 100, left: cLeft}, 500);
				
				var cUriVal = portfolio.sites[cId].uri;
				if (cUriVal != '#') {
					cUri.innerHTML = cUriVal;
					$(cUri).css({display: 'block', top: (cTop + 20) + 'px'}).anim(ease.cubic, {opacity: 0, left: cLeft - 20}, {opacity: 100, left: (cLeft + (cWidth / 2))}, 500);		
				}
			} else {
				cLeft = cLeft - (((cWidth / 2) - (cName.offsetWidth / 2)) / 2);
				$(cName).css({left: cLeft + 'px', top: cTop + 'px', textAlign: 'center', opacity: 100, display: 'block'});
				
				var curIdx = parseInt(cImg.className, 10);
				var curTech = portfolio.sites[curIdx].tech;
				var tagList = $e('controls', 'a');
				
				for (var i = 0, j = tagList.length; i < j; i++) {
					var isTech = false;
					if (curTech.indexOf(tagList[i].innerHTML) > -1) {
						isTech = true;
					}
					if (!isTech) {
						tagList[i].className += ' ghost';
					}
				}
			}
		}).on('mouseout', function() {
			$('splashTitle', 'splashUri').css({display: 'none'});
			
			if (tumMode) {
				controlTags.all(function(el) {
					el.className = el.className.replace(' ghost', '');
				});	
			}
		});
		
		curImgs.on('click', function() {
			if (!drawDetail) {
				showDetail(this.className);
			}
		});
		
		$('rail').on('mouseout', function() {
			if (!tumMode) {
				curImgs.css({opacity: 100});
			}
		});
		
		controlTags.on('mouseover', function() {
			controlTags.all(function(el) {
				el.className += ' ghost';
			});
			this.className = this.className.replace(' ghost', '');
			var curMatches = filterByTech(this.innerHTML);
			var allImgs = $e('rail', 'img');
			var hideEls = [];
			for (var i = 0, j = allImgs.length; i < j; i++) {
				var curImg = allImgs[i]
				if (curMatches.indexOf(parseInt(curImg.className, 10)) == -1) {
					hideEls.push(curImg);
				}
			}
			$().push(allImgs).css({opacity: 100});
			$().push(hideEls).css({opacity: 20});
			
		}).on('mouseout', function() {
			controlTags.all(function(el) {
				el.className = el.className.replace(' ghost', '');
			});			
		}).on('click', function(e) {
			preventDefault(e);
		});
	});
};

var loaded = false;
var loadCounter = [];
var busy = false;
var portfolio;
var contact;
var tumMode = false;
var drawDetail = false;
var scrolling = false;
var curPreview;
var curImgs;
var imageRail;
var controlTags;
var curSet = 1;
var pst = 0;
var psl = 0;

$(window).on('load', function() {
	var clientWidth = document.documentElement.clientWidth;
	$('portfolio', 'detail').css({left: ((clientWidth / 2) - 430) + 'px'});
	$('controls').css({left: ((clientWidth / 2) - 300) + 'px'});
	$('nav').css({left: ((clientWidth / 2) - 36) + 'px', opacity: 0, display: 'block'});
	
	$('togTum').css({opacity: 50, cursor: 'pointer'}).on('click', function() {
		thumbToggle();
	});
	
	$('moveBack').css({opacity: 20}).on('click', function() {
		back();
	});

	$('moveForward').css({cursor: 'pointer'}).on('click', function() {
		next();
	});
	
	$('closeBut').on('click', function() {
		closeDetail();
	});
		
	xhr('data.js', '', function(t) {
		eval('portfolio = '+ t);
	
		var tagStr = '';
		var tags = generateTags();
		for (var i = 0, j = tags.length; i < j; i++) {
			var curTag = tags[i];
			var curWeight = curTag[1];
			var curClass = 'huge';
			if (curWeight < 20) curClass = 'big';
			if (curWeight < 13) curClass = 'med';
			if (curWeight < 6) curClass = 'sml';
			if (curWeight < 3) curClass = 'tny';
			tagStr += '<a href="#" class="'+ curClass +'">'+ curTag[0] +'</a> '
		}
		$i('controls').innerHTML = tagStr;
		
		controlTags = $().push($e('controls', 'a'));
		imageRail = $i('rail');
		
		var nStr = '';
		for (var i = 0, j = 8; i < j; i++) {
			nStr += '<div><img class="'+ i +'" src="img/'+ portfolio.sites[i].img[0] +'" alt="'+ portfolio.sites[i].name +'" /></div>';
			var nImg = new Image();
			nImg.onload = function() {
				loadCounter.push(' ');	
			};
			nImg.src = 'img/'+ portfolio.sites[i].img[0];
		}

		imageRail.innerHTML += '<section>' + nStr +'</section>';
		
		var checkNum = setInterval(function() {	
			if (loadCounter.length === 8) {
				clearInterval(checkNum);
				initUI();
			}
		}, 50);
	}, function(t) {
		alert('Something bad has happened, please reload to try again.\n\n\n'+ t);
	});
	
	contact = $('contact');
	$().push($e('contact', 'img')).on('mouseover', function() {
		$(this).anim(ease.cubic, {marginLeft: -5, marginTop: 0}, {marginLeft: 5, marginTop: -10}, 200);
//		contact.anim(ease.cubic, {bottom: -175}, {bottom: -165}, 200);
	}).on('mouseout', function() {
		$(this).anim(ease.cubic, {marginLeft: 5, marginTop: -10}, {marginLeft: -5, marginTop: 0}, 200);
//		contact.anim(ease.cubic, {bottom: -165}, {bottom: -175}, 200);	
	}).on('click', function() {
		contact.anim(ease.cubic, {bottom: -165, left: -5}, {bottom: 100, left: 50}, 500);
	});
		
	$(document).on('keydown', function(e) {
		var evt = e || window.event;		
		if (!busy) { 
			if (evt.keyCode == 39) next();
			if (evt.keyCode == 37) back();		
			if (evt.keyCode == 27) closeDetail();
			if (evt.keyCode == 32) thumbToggle();			
		}
		preventDefault(evt);		
	}).on('mousemove', function(e) {
		if (!drawDetail) return;

		if (!e) e = window.event;
		if (e.pageY) {
			var pY = e.pageY;
		} else if (e.clientY) {
			var pY = e.clientY;
		}
	
		$i('tmbs').scrollTop = (pY - 60) * 2.2;		
	});
	
	setTimeout(function() {
		xhr('stat/', '');
	}, 10);	
});
