(function(){
	function MK(ls){
		this.els = [];
		for(var i = 0;i < ls.length;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;j<a.length;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){
			var that = this;
			this.all(function(el){
				for(var p in o){
					that.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;
			var _a = window.setInterval(function(){
				var k = (t - (nd - new Date().getTime()));
				if(t <= k){
					window.clearInterval(_a);
					k = t;
				}
				that.all(function(el){
					for(var p in b){
						if(p == 'scrollLeft' || p == 'scrollTop'){
							el[p] = Math.floor(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(t == k && c){
					c();
				}
			},15);
			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 = e ? $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.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;
		$e(document, 'head')[0].appendChild(f);
	};

	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;
})();

// NAV
$(window).on('load', function(){
	$().push($e('nav', 'li')).all(function(el){
		var sLnk = $e(el, 'a')[0].href;
		if(document.location == sLnk){
			el.className = 'cur';
		}	
	}).on('mouseover', function(){
		if(this.className == 'cur'){return;}
		$(this).css({backgroundImage:'url(/media/img/v4/nbgi.png)'});
	}).on('mouseout', function(){
		if(this.className == 'cur'){return;}
		$(this).css({backgroundImage:'none'});	
	});
	$().push($c('pLoad')).css({visibility: 'visible'});	
});

// Search
$(window).on('load', function(){
	if(!$i('slideSearch')){
		return;
	}
	
	var innerTEXT = function(el){
		if(!el.innerTEXT){
			return $i(el).textContent;
		} else {
			return $i(el).innerTEXT;		
		}	
	};

	var slidrs = $c('sldr');
	
	for(var d = 0, s = slidrs.length; d < s; d++){
		(function(){
			var colList = $i(slidrs[d]);
			$(colList).css({width: '790px', marginTop: '5px', height: '50px', overflow: 'hidden'});

			var frag = document.createDocumentFragment();

			var track = document.createElement('div');
			$(track).css({width: '18100px', textAlign: 'left'});

			frag.appendChild(track);

			while(colList.firstChild){
				track.appendChild(colList.firstChild);
			}

			var lbs = $().push($e(track, 'label'));
			lbs.all(function(el){
				$($e(el,'input')[0]).css({position: 'absolute', left: '-9999px'});
				if(document.all){
					$(el).css({display: 'inline'});				
				}
			}).on('mouseover', function(e){
				if(this.className != 'sel'){
					$i(this).className = 'pms';
				}
			}).on('mouseout', function(e){
				if(this.className != 'sel'){
					this.className = this.className.replace('pms', '');
				}
			}).on('click', function(e){
				preventDefault(e);
				$e(this,'input')[0].checked = true;
				lbs.all(function(el){el.className = '';});
				$i(this).className = 'sel';	
			});	
		
			colList.appendChild(frag);

			var trkWidth = 0;	
			lbs.all(function(el){
				trkWidth = trkWidth + (el.offsetWidth + 50);
			});
			$(track).css({width: trkWidth + 'px'});

			var working = false;
			var moving;
			var scrolling = function(d){	
				clearInterval(moving);
				moving = setInterval(function(){
					if(working){
							$i(colList).scrollLeft = $i(colList).scrollLeft + d;
					}
				}, 5);
			};

			var pX, pY;
			var sX = offSet(colList)[0];
			var pmY = offSet(colList)[1];
			var pmX = sX + colList.offsetWidth;
			var pmW = $i('pm').offsetWidth / 2;
	
			$(document).on('mousemove', function(e){
				if(!e) var e = window.event;
				if(e.pageX || e.pageY){
					pX = e.pageX;
					pY = e.pageY;
				}
				else if(e.clientX || e.clientY){
					pX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
					pY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
				}
				$i('diag').innerHTML = 'X:'+ pX +' - Y:'+ pY;
		
				if(pY > pmY && pY < (pmY + colList.offsetHeight) && pX > sX && pX < pmX){
					$i('pm').style.display = 'block';				
					$i('pm').style.left = (pX - pmW) +'px';
					$i('pm').style.top = (pmY - 35) +'px';
					if(pX > (sX + 100) && pX < (pmX - 100)){
						working = false;
						return;
					}
					if(pX > (pmX - 100)){
						working = true;
						scrolling(13);	
					}
					if(pX <  (sX + 100)){
						working = true;
						scrolling(-13);	
					}
				} else {
					working = false;
				}
			});
		})();
	}
});

// OVERLAY
$(window).on('load', function(){
	if(!$i('imgs')){ 
		return; 
	}

	var tobeLaid = $().push($e('imgs', 'a'));
	tobeLaid.anim(ease.cubic, {opacity: 100}, {opacity: 90}, 1000);
	
	var controls = ['loadingTMB.gif', 'closeTMB.png', 'gal_left.png', 'gal_right.png'];
	for (var i = 0, j = controls.length; i < j; i++) {
		var cImg = document.createElement('img');
		cImg.id = controls[i].split('.')[0];
		cImg.src = '/media/img/'+ controls[i];
		$(cImg).css({position: 'absolute', left: '-9999px', zIndex: 999999});
		if(controls[i] === 'loadingTMB.gif'){
			$(cImg).css({backgroundImage: 'url(/media/img/loading_bg.png)'});			
		}
		$e(document, 'body')[0].appendChild(cImg);
	}
	
	$('gal_left', 'gal_right').css({opacity: 40}).on('mouseover', function(){
		$(this).css({opacity: 100});
	}).on('mouseout', function(){
		$(this).css({opacity: 60});	
	});
		
	var sImg = false;
	$('gal_left', 'gal_right').on('click', function(e){
		preventDefault(e);
		if (this.id == 'gal_left') {
			curtblIdx--;
			var tLeft = true;
			if (curtblIdx === 1) {
				$('gal_left').css({display: 'none'});	
			}
			$('gal_right').css({display: 'block'});					
		} else {
			curtblIdx++;
			var tLeft = false;			
			if (curtblIdx === tblIdx) {
				$('gal_right').css({display: 'none'});
			}
			$('gal_left').css({display: 'block'});				
		}
		var oldImg = $i('overlay').firstChild;
		oldImg.src = tobeLaid.els[curtblIdx - 1].getAttribute('href');
	});	
	
	var tblIdx = 0;
	tobeLaid.all(function(el){
		tblIdx++;	
		el.setAttribute('tblIdx', tblIdx);
		var pLoad = new Image();
		pLoad.src = el.href;
	}).on('click', function(e){
		preventDefault(e);
		curtblIdx = parseInt(this.getAttribute('tblIdx'), 10);
		var pageScroll = document.body.scrollTop || document.documentElement.scrollTop;
		var tarImg = this;
		$('loadingTMB').css({top: (offSet(tarImg)[1] + (tarImg.offsetHeight / 2 - 18)) + 'px', left: (offSet(tarImg)[0] + (tarImg.offsetWidth / 2 - 18)) + 'px'});

		$i('closeTMB').onclick = function(){
			$('closeTMB', 'gal_left', 'gal_right').css({display: 'none'});
			$('overlay').anim(ease.cubic, {top: offSet($i('overlay'))[1], left: offSet($i('overlay'))[0], width: $i('content').offsetWidth, height: $i('overlay').offsetHeight, opacity: 100}, {top: offSet(tarImg)[1], left: offSet(tarImg)[0], width: tarImg.offsetWidth, height: tarImg.offsetHeight, opacity: 0}, 500, function(){
				$('overlay').css({display: 'none'});
				if($i('overlay').firstChild){
					$i('overlay').removeChild($i('overlay').firstChild);
				}
			});
			sImg = false;
		};		

		if(!$i('overlay')){
			var ovl = document.createElement('div');
			ovl.id = 'overlay';
			$e(document, 'body')[0].appendChild(ovl);
		}
			
		var ovly = $('overlay');
		ovly.css({position: 'absolute', opacity: 0, display: 'block', top: offSet(tarImg)[1] + 'px', left: offSet(tarImg)[0] + 'px', width: tarImg.offsetWidth + 'px', height: tarImg.offsetHeight + 'px', overflow: 'hidden'});
		
		var limg = new Image()
		limg.onload = function(){
			if (sImg) { return; }
			sImg = true;
			while($i('overlay').firstChild){
				$i('overlay').removeChild($i('overlay').firstChild);
			}
			limg.style.width = '100%';
			limg.style.height = 'auto';
			$i('overlay').appendChild(limg);
			ovly.anim(ease.cubic, {top: offSet(tarImg)[1], left: offSet(tarImg)[0], width: tarImg.offsetWidth, height: tarImg.offsetHeight, opacity: 0}, {top: pageScroll, left: offSet($i('content'))[0], width: $i('content').offsetWidth, height: 700, opacity: 100}, 500, function(){
				$('loadingTMB').css({left: '-9999px'});	
				$('closeTMB').css({display: 'block', cursor: 'pointer', top: (2 + pageScroll) + 'px', left: ((offSet($i('content'))[0] + $i('overlay').offsetWidth) - 40) + 'px', opacity: 0}).anim(ease.bounce, {opacity: 0}, {opacity: 100}, 800);
				if (curtblIdx <= tblIdx && tblIdx != 1) {
					$('gal_left', 'gal_right').css({display: 'block', cursor: 'pointer', left: offSet($i('content'))[0] + 'px', top: (offSet($i('overlay'))[1] + (($i('overlay').offsetHeight / 2) - ($i('gal_left').offsetHeight / 2))) + 'px'});
					$('gal_right').css({left: (offSet($i('overlay'))[0] + $i('overlay').offsetWidth - $i('gal_left').offsetWidth) + 'px'});
					if (curtblIdx === tblIdx) {
						$('gal_right').css({display: 'none'});
					}
					if (curtblIdx === 1){
						$('gal_left').css({display: 'none'});					
					}
				}
			});
		};
		limg.src = tarImg.href;		
	}).on('mouseover', function(){
		$(this).css({opacity: 100});
	}).on('mouseout', function(){
		$(this).css({opacity: 90});
	});
});

// PREDICTIVE SEARCH
$(window).on('load', function(){
	xhr('/modules/gaffs/predictive/', '', function(t){
		var srcBox = $e('hdr', 'input')[0];
		
		var resultDiv = document.createElement('div');
		resultDiv.id = 'predictiveResults';
		$e(document, 'body')[0].appendChild(resultDiv);
		
		var searchDiv = document.createElement('div');
		searchDiv.innerHTML = t;		
		var sDvs = $e(searchDiv, 'div');
		var sDvl = sDvs.length;
		
		$($e('hdr', 'input')[0]).on('keyup', function(e){

			preventDefault(e);
			var sTrm = this.value.toLowerCase();
			if(sTrm.length < 2){
				resultDiv.style.display = 'none';
			 	return;
			 }
			
			resultDiv.innerHTML = '';
			var rslts = [];
			var cCol = '';
			var cCtr = 0;

			for(var i = 0; i < sDvl; i++){
				var cSearch = sDvs[i].innerHTML.toLowerCase();
				if(cSearch.indexOf(sTrm) > -1){
					if(sDvs[i].className == 'p'){	
						var cInst = 'Page matches';	
					} else {
						var cInst = cSearch.split(', ')[0];
					}
					if(cCol != cInst){
						if(sDvs[i].className == 'p'){						
							rslts.push('<h3>Page matches:</h3>');
						} else {
							rslts.push('<h3>'+ sDvs[i].innerHTML +':</h3>');						
						}
						cCol = cInst;
						cCtr = 0;
					}
					if(cCtr < 4){
						if(cInst == 'Page matches'){
							rslts.push('<a href=\''+ sDvs[i].getAttribute('rel') +'\'>'+ sDvs[i].getAttribute('title') +'</a>');						
						} else {
							rslts.push('<a href=\'/modules/accommodation/'+ cInst.replace(/ /g, '+') +'/?'+ sDvs[i].getAttribute('rel') +'\'>'+ sDvs[i].getAttribute('title') +'</a>');
						}
					}
					if(cCtr == 4){
						if(cInst != 'Page matches'){
							rslts.push('<a href=\'/modules/gaffs/?colleges='+ cInst +'\'><strong>Find more</strong></a>');
						} else {
							rslts.push('<a href=\'/modules/search/?searchterm='+ sTrm +'\'><strong>Find more</strong></a>');						
						}
					}
					cCtr++;					
				}
			}
			if(rslts.length != 0){
				resultDiv.innerHTML = rslts.join('');
				$(resultDiv).css({display: 'block', top: (offSet(srcBox)[1] + 17) + 'px', left: (offSet(srcBox)[0] + 2) + 'px'});
			} else {
				resultDiv.style.display = 'none';			
			}	
		});
	});	
});

// STATS
(function(){
	load('http://www.google-analytics.com/ga.js', function(){
		try {
			var pageTracker = _gat._getTracker('UA-9565195-1');
			pageTracker._trackPageview();
		} catch(err) {}
	});
})();