	// G L O B A L   C O N S T A N T S
var _minWidth = 153	// the sidebar is not allowed to shrink below this size. It will begin to strafe instead.
var _zeroWidth = 6	// the sidebar is not allowed to strafe below this size. Provides a handle to drag it
var _SNAP = 30	// when close to the border (within _SNAP), we take control from the user and snap the sidebar to _zeroWidth 
var _itemMin = 66 // the thumbs are not allowed to shrink below this size
var _itemSpace = 0	// see in css: .items a {margin:0 Xpx Xpx 0}
var _EASE = [0,12,23,33,42,51,59,66,73,79,84,88,92,95,97,99,100]	// hardcoded ease out steps. See Penner Equation.




	// G L O B A L   V A R I A B L E S
var _a	// holds the active sidebar
var _s1, _s2	// the aliases of _s1 and _s2 from CSS (short form needed to avoid code redundancy)
var _aboveDragger // remembers if the mouse is above a dragger, usefull when letting go of a sidebar
var _dragging = 0; // 0(not dragging) 1(mouse pressed) 2(dragging)
var blocker, content, cover, field, go, _all	//important IDs from CSS
var ie = navigator.appName.indexOf('Internet Explorer') != -1
var ie6 = navigator.appName.indexOf('Microsoft Internet Explorer') != -1




	// T O O L   F U N C T I O N S   (functions that are used to reduce code redundancy)
function setCursor(type) {document.body.style.cursor = type
//content.contentWindow.document.body.style.cursor = type;
}
function setBgDrag(o) {o.style.backgroundPosition = "-12px 3px"}
function setBgNormal(o) {o.style.backgroundPosition = "-6px 3px"}
function setBgHover(o) {o.style.backgroundPosition = "0 3px"}
function pngfix(id){
	var obj = document.getElementById(id)
	obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='img/"+id+".png', sizingMethod='scale')";
	obj.style.background = ''}
function blockSearchLinks(id) {
	var tags = document.getElementById(id).getElementsByTagName('a');
	for (var i=0; i<tags.length; i++) {
		tags[i].onclick = function() {
			field.value = this.innerHTML
			prepareForIncomingSearchResults(_s2)
			return false;}}}
function checkScroll(o) {
	var viewport = o.items.offsetHeight - o.items.offsetTop
	var temp = Math.floor((o.items.scrollTop + viewport)/o.itemSize)*o.columns + o.columns

	if (temp >= o.itemCount) o.scrollerDown.style.visibility = 'hidden'
	else o.scrollerDown.style.visibility = 'visible'
	if (o.items.scrollTop == 0) o.scrollerUp.style.visibility = 'hidden'
	else o.scrollerUp.style.visibility = 'visible'

	temp = temp<=o.itemCount? temp : o.itemCount
	if (temp > o.lastVisible) {
		var elements = o.items.getElementsByTagName('img');
		for (var i=o.lastVisible; i<temp; i++){
			var tempArray = elements[i].parentNode.href.split('/')
				// maybe the link was for 'aurelain', which is cut (being redundant) by php
			if (tempArray[tempArray.length - 1].indexOf('_')<0) elements[i].src = 'thumb/aurelain_' + tempArray[tempArray.length - 1] + '.jpg'
			else elements[i].src = 'thumb/' + tempArray[tempArray.length - 1] + '.jpg'}
		o.lastVisible = temp;
		session('visible'+o.nr+'='+temp);}	
	
	}



	// F U N C T I O N S
window.onload = function () {
		// memorize some important IDs, so as to avoid redundant getElementById 
	blocker = document.getElementById('blocker');
	content = document.getElementById('content')
	cover = document.getElementById('cover')
	field = document.getElementById('field')
	go = document.getElementById('go')
	_s1 = document.getElementById('sidebar1')
	_s2 = document.getElementById('sidebar2')
	_all = document.getElementById('all');
	
		// create the parasite properties
	_s1.dragger = document.getElementById('dragger1')
	_s2.dragger = document.getElementById('dragger2')
	_s1.items = document.getElementById('related')
	_s2.items = document.getElementById('results')
	_s1.scrollerUp = document.getElementById('scrollerup1')
	_s1.scrollerDown = document.getElementById('scrollerdown1')
	_s2.scrollerUp = document.getElementById('scrollerup2')
	_s2.scrollerDown = document.getElementById('scrollerdown2')
	_s1.info = document.getElementById('info1')
	_s2.info = document.getElementById('info2')
	_s1.itemCount = _s1.items.getElementsByTagName('a').length
	_s2.itemCount = _s2.items.getElementsByTagName('a').length
	_s1.nr = 1
	_s2.nr = 2			
		
		// use any values that came from the outside (php)
	_s1.initialWidth = initialWidth1
	_s2.initialWidth = initialWidth2
	_s1.minimized = minimized1
	_s2.minimized = minimized2
	_s1.lastVisible = lastVisible1
	_s2.lastVisible = lastVisible2

     	// dragger events
	var dragger1 = document.getElementById('dragger1')
	var dragger2 = document.getElementById('dragger2')
     dragger1.onmouseover = dragger2.onmouseover = function() {
     	_aboveDragger = this.parentNode.nr
          if (_dragging) return 
		setBgHover(this)                       
          setCursor('e-resize')}
     dragger1.onmouseout = dragger2.onmouseout = function() {
     	_aboveDragger = 0
          if (_dragging) return
          setBgNormal(this)
          setCursor('auto')}
     dragger1.onmousedown = dragger2.onmousedown = mousedown;	


		// scroller events
	_s1.items.onscroll = _s2.items.onscroll = function() {
		var o = this.parentNode
		if (o.slideInProgress) return		
		clearInterval(o.scrollSave);
		o.scrollSave = setInterval(function(){
			session('scroll'+o.nr+'='+o.items.scrollTop)
			clearInterval(o.scrollSave);
			checkScroll(o);
			},100);}
	_s1.scrollerUp.onclick = _s2.scrollerUp.onclick = _s1.scrollerDown.onclick = _s2.scrollerDown.onclick = function() {
		var o = this.parentNode;
		if (o.slideInProgress) return
		if (this.className=='scroller up')var temp = Math.ceil((o.items.scrollTop - o.items.offsetHeight + o.items.offsetTop)/o.itemSize)*o.itemSize;
		else var temp = Math.floor((o.items.scrollTop + o.items.offsetHeight - o.items.offsetTop)/o.itemSize)*o.itemSize;
		scrollTo(o,temp)
		return false}
	 

		// the "Search Link" Events
	blockSearchLinks('barcontent1')
	blockSearchLinks('barcontent2')
	document.getElementById('info1').onclick =
	document.getElementById('info2').onclick =
	document.getElementById('home').onclick = null
	var tags = document.getElementById('description').getElementsByTagName('a');
	for (var i=0; i<tags.length; i++) tags[i].onclick = null; 
				
		// the search controls behaviour 
	field.onkeydown = function(e) {
		e = ie? event : e
		if (e.keyCode == 13) prepareForIncomingSearchResults(_s2)}
	go.onmouseover = function() {go.style.backgroundPosition = '-30px 0'}
	go.onmouseout  = function() {go.style.backgroundPosition = '0'}
	go.onclick = _all.onchange = function() {prepareForIncomingSearchResults(_s2)}
	if (ie) {_all.onchange = null; _all.onclick = function() {prepareForIncomingSearchResults(_s2)}}
						
		// navigator behaviour
	if (navigatorIsVisible){
		var nav = document.getElementById('nav')
		var prev = document.getElementById('prev')
		var next = document.getElementById('next')
		var maxi = document.getElementById('maxi')
		prev.onmouseover = function() {nav.style.left = '-200px'}
		next.onmouseover = function() {nav.style.left = '-300px'}
		prev.onmouseout = maxi.onmouseout = next.onmouseout = function() {nav.style.left = '0'}
		maxi.onmouseover = function() {nav.style.left = '-100px'}
		maxi.onclick = function() {toggleHud();}}
	
		// refresh the Items
	calculateGridParameters(_s1)
	calculateGridParameters(_s2)
	
	_s1.items.scrollTop = scroll1
	_s2.items.scrollTop = scroll2
	checkScroll(_s1)
	checkScroll(_s2)
	
		// PNG fix
	if (ie6) {
		pngfix('shadow1');pngfix('shadow2')
		if (navigatorIsVisible) pngfix('nav')}	
}




function calculateGridParameters(o) {
	var size = o.offsetWidth - 9 - 17;
	var n = Math.floor( size / (_itemMin + _itemSpace));
     var h = document.documentElement.clientHeight - o.items.offsetTop
	size = Math.floor((size - n * _itemSpace)/n)
     o.itemSize = size;
	o.columns = n;
	o.lines = Math.floor(h / (size + _itemSpace))
	o.maxLine = Math.ceil(o.itemCount/n)}



function scrollTo(o,y) {
	var step = 0
	var startPos = o.items.scrollTop
	var travel = startPos - y
	o.slideInProgress = true
	o.slideInterval = setInterval(function(){
		o.items.scrollTop = startPos - travel * _EASE[step]/100
		if (step > 15) {
			session('scroll'+o.nr+'='+o.items.scrollTop)
			checkScroll(o)
			o.slideInProgress = false
			clearInterval(o.slideInterval)
			return}
		else step ++
		},30);}


	

function mousedown(e) {
	_a = this.parentNode;
	setBgDrag(this);
     _dragging = 1;
     blocker.style.visibility='visible';
     setCursor('e-resize');
     if (!_a.minimized) _a.initialWidth =  _a.offsetWidth
	e = ie? event : e;  
	_a.deviation =   _a.nr == 1?   _a.offsetWidth + _a.offsetLeft - e.clientX   :   e.clientX - _a.offsetLeft + 1
     document.onmousemove = mousemove;
     document.onmouseup = mouseup;
	return false;}
     

function mousemove(e) {
     _dragging = 2;
     e = ie? event : e;
	var temp = _a.nr == 1? e.clientX + _a.deviation - 9   :   document.documentElement.clientWidth - e.clientX + _a.deviation - 9
	resizeSidebar(_a, temp, _SNAP)
     return false;}


function mouseup(e) {
     document.onmousemove = null;
     document.onmouseup = null;
     
	if (_aboveDragger == _a.nr) setBgHover(_a.dragger)
	else
		if (!_aboveDragger)	{setCursor('auto'); setBgNormal(_a.dragger)}
		else {setBgNormal(_a.dragger); setBgHover( _a.nr == 1?   _s2.dragger   :   _s1.dragger)}
		 
	if (_dragging == 1) automateSidebar(_a)
	else {	// the user had moved the mouse, thus provoking a real drag
		_dragging = 0;
		saveSidebarSettings(_a)}
     blocker.style.visibility='hidden';
	return false}


function toggleHud(){
	if ((coverIsVisible && _s1.minimized) || (!coverIsVisible && !_s1.minimized)) automateSidebar(_s1)
	if ((coverIsVisible && _s2.minimized) || (!coverIsVisible && !_s2.minimized)) automateSidebar(_s2)
	var step = 0
	var interval = setInterval(function(){
		cover.style.opacity = coverIsVisible? 1 - _EASE[step]/100 : _EASE[step]/100;		
		cover.style.filter = coverIsVisible? 'alpha(opacity='+(100 - _EASE[step])+')' : 'alpha(opacity='+ _EASE[step]+')';
		if (step > 15) {
			clearInterval(interval)
			coverIsVisible = coverIsVisible? 0 : 1
			session('cover='+coverIsVisible)
			return}
		else step ++
		},30);}
		
	
function automateSidebar(o) {
	setCursor('auto')
	o.items.style.display = 'none'
	var minimized = o.minimized? true : false; // remember the state, because while automating, o.minimized will change and thus is not reliable
	var step = 0
	var size = o.initialWidth - _zeroWidth;
	var interval = setInterval(function(){
		var temp = minimized? Math.round(_zeroWidth + _EASE[step]*size/100) : Math.round(_zeroWidth + size - _EASE[step]*size/100)
		resizeSidebar(o, temp, 0)
		if (step > 15) {
			o.items.style.display = 'block'
			resizeItems(o,temp)
			_dragging = 0
			setBgNormal(o.dragger)
			clearInterval(interval)
			saveSidebarSettings(o)
			return}
		else step ++
		},30);}
		




		
function resizeSidebar(o,size,snap){
	var maxWidth = document.documentElement.clientWidth / 2 - 9
	if (size > maxWidth) {
		o.style.width = maxWidth + 'px' // we could insert a check, so as not to resize when already maxed, but seems too much code
		resizeItems(o,maxWidth)}
	else
		if ( (!o.frozen && size <= _minWidth) || (o.frozen && ((_minWidth - size) >= 0)) ) {
			if (!o.frozen) { // first time we're crossing the border into FREEZE mode 
				o.style.width = _minWidth + 'px'
				if (snap) resizeItems(o, _minWidth)
				o.frozen = true}
			if (size <= Number(_zeroWidth) + Number(snap)) { // we've hit the bottom
				size = Number(_zeroWidth)
				if (!o.minimized) {o.dragger.style.backgroundImage = 'url(img/arrows'+(o.nr==1?2:1)+'.gif)'; o.minimized = true;}} 
			else 
				if (o.minimized) {o.dragger.style.backgroundImage = 'url(img/arrows'+o.nr+'.gif)'; o.minimized = false;}
			if (o.nr == 1) o.style.left = -(_minWidth - size) +'px'
			else o.style.right = -(_minWidth - size) +'px'}
		else {
			if (o.frozen) { // first time we're coming back to NORMAL mode
				if (o.nr == 1) o.style.left = '0px'
				else o.style.right = '0px'
				o.frozen = false}
			o.style.width = size + 'px'
			if (snap) resizeItems(o,size)}}




function resizeItems(o,size) {
	calculateGridParameters(o)
	var anchors = o.items.getElementsByTagName('img');
	var css = 'width:' + o.itemSize + 'px; height:'+o.itemSize+'px;';
	for (var i=0; i<anchors.length; i++) anchors[i].style.cssText = css;
	checkScroll(o)
	}


function prepareForIncomingSearchResults(o) {
	if (navigatorIsVisible) document.getElementById('navigator').style.display = 'none'
	go.style.backgroundPosition = '-270px 0'
	o.items.innerHTML = ''
	o.info.innerHTML = 'Searching...'
	session('all=' + _all.checked + '&search=' + field.value)}


function session(parameters){
	var req 
	if (window.XMLHttpRequest) req = new XMLHttpRequest();
	else req = new ActiveXObject("Microsoft.XMLHTTP");
	req.onreadystatechange = function(){
		if (req.readyState == 4 && req.status == 200) {
			if (req.responseText == '' && _s2.info.innerHTML != 'Searching...') return;
			go.style.backgroundPosition = '-240px 0'
			if (req.responseText == '') _s2.info.innerHTML = 'Results (0)';
			else {
				var arr = req.responseText.split('#')
				var len = arr.length
				
				_s2.info.innerHTML = 'Results ('+len+')';
				_s2.itemCount = len
				var fragment = document.createDocumentFragment();
				for (var i=0; i<len; i++) {
					var a = document.createElement('a')
						// maybe it's an "aurelain" link, so we must cut the "aurelain"
					var temp = arr[i].split('_')
					if (temp[0]=='aurelain') {a.href=temp[1]; temp[1]=temp[1].substr(0,1).toUpperCase()+temp[1].substr(1); a.title = temp[1] }
					else {
						a.href = arr[i];
						temp[0]=temp[0].substr(0,1).toUpperCase()+temp[0].substr(1);
						temp[1]=temp[1].substr(0,1).toUpperCase()+temp[1].substr(1);
						a.title = temp[0] + ' ' + temp[1];}
					var img = document.createElement('img')
					img.src = 'thumb/none.jpg'
					img.style.cssText = 'width:' + _s2.itemSize + 'px; height:' + _s2.itemSize + 'px'
					a.appendChild(img)
					fragment.appendChild(a)}
				_s2.lastVisible = 0;
				var dummy = document.createElement('div')
				dummy.id = 'dummy2'
				fragment.appendChild(dummy)
				_s2.items.appendChild(fragment)
				calculateGridParameters(_s2)
				checkScroll(_s2)
				}}}
     req.open("GET", 'session.php?'+parameters, true);
     req.send(null);}

function saveSidebarSettings(o) {
	var temp = o.minimized? o.initialWidth : o.offsetWidth
	if (o.nr==1) session('left1='+(o.style.left? o.style.left : '0px')+'&width1='+(o.offsetWidth-9)+'px&initialWidth1='+temp+'&scroll1='+o.items.scrollTop+'&item1='+o.itemSize+'&minimized1='+o.minimized);
	else session('right2='+ (o.style.right? o.style.right : '0px')+'&width2='+(o.offsetWidth-9)+'px&initialWidth2='+temp+'&scroll2='+o.items.scrollTop+'&item2='+o.itemSize+'&minimized2='+o.minimized);
	
}

	


