function hover(Elem)
{
	var Klasse = Elem.className;
	if (Klasse.match(/\w*Hover/)) {
		Element.removeClassName(Elem,Klasse.match(/\w*Hover/));
	} else {
		Element.addClassName(Elem,Klasse + 'Hover');
	}
	return true;
}

function setTooltips() {
	$$("a.help").each( function(link) {
		new Tooltip(link, {mouseFollow: false});
	});
	$$("button.help").each( function(link) {
		new Tooltip(link, {mouseFollow: false});
	});
	$$("input.help").each( function(link) {
		new Tooltip(link, {mouseFollow: false});
	});
	$$("select.help").each( function(link) {
		new Tooltip(link, {mouseFollow: false});
	});
}

function userAction(what,uid) {
	var vals = "uid="+uid+"&a="+what;
	var uri = "admin/users.php";
	var myAjax = new Ajax.Updater('overlayContent', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: new Effect.Appear('overlayContent',{ duration: 1.0 })
	} );
}

function authorAction(what,aid) {
	var vals = "aid="+aid+"&act="+what;
	var uri = "admin/authors.php";
	var myAjax = new Ajax.Updater('overlayContent', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: new Effect.Appear('overlayContent',{ duration: 1.0 })
	} );
}

function doEditAuthor() {
	var vals = Form.serialize('userForm');
	var uri = "admin/authors.php";
	var myAjax = new Ajax.Updater('infoBar', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: _none = function() {
			$('infoBar').style.display = 'block';
			window.setTimeout("new Effect.Fade('infoBar');",2000);
			updateAuthorList();
		}
	} );
}

function deleteAuthor() {
	var vals = "act=delete&aid="+$('aAid').value;
	var uri = "admin/authors.php";
	var myAjax = new Ajax.Updater('infoBar', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: _none = function() {
			$('infoBar').style.display = 'block';
			window.setTimeout("new Effect.Fade('infoBar');",2000);
			$('editButton').disabled = true;
			window.setTimeout("hideMe();",2000);	
			updateAuthorList();
		}
	} );
}

function doEditUser() {
	if (!checkUserForm()) return false;
	$('uPassword').value = hex_sha1($('uPassword').value);
	var vals = Form.serialize('userForm');
	var uri = "admin/users.php";
	var myAjax = new Ajax.Updater('infoBar', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: _none = function() {
			$('infoBar').style.display = 'block';
			window.setTimeout("new Effect.Fade('infoBar');",2000);
			if ($('uAction').value == "insert") {
				$('editButton').disabled = true;
				window.setTimeout("hideMe();",2000);	
			} else {
				$('uPassword').value = "";
			}
			updateUserList();
		}
	} );
}

function deleteUser() {
	var vals = "a=delete&uid="+$('uUid').value;
	var uri = "admin/users.php";
	var myAjax = new Ajax.Updater('infoBar', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: _none = function() {
			$('infoBar').style.display = 'block';
			window.setTimeout("new Effect.Fade('infoBar');",2000);
			$('editButton').disabled = true;
			window.setTimeout("hideMe();",2000);	
			updateUserList();
		}
	} );
}

function checkUsername() {
	if ($('uAction').value == "insert") {
		$('uUsername').removeClassName('required');
		$('infoBar').style.display = 'none';
		var uri = "admin/users.php";
		var myAjax = new Ajax.Request(uri, {
			parameters: "a=checkUsername&value="+$('uUsername').value,
			method: 'post',
			onSuccess: function(transport) {
			  if (transport.responseText == "true") {
			  	$('infoBar').innerHTML = 'The username you entered already exists! Please use another one!';
			  	$('infoBar').style.display = 'block';
			  	window.setTimeout("new Effect.Fade('infoBar');",5000);
			  	$('uUsername').addClassName('required');
			  }
			}
		});
	}
}

function checkUserForm() {
	var required = Array("uUsername", "uRealname","uEmail");
	var check = true;
	$('infoBar').style.display = 'none';
	for (var i=0; i<required.length; i++) {
		$(required[i]).removeClassName('required');
		if ($F(required[i]).length < 2) { 
			$(required[i]).addClassName('required');
			check = false;
		}
	}
	if (!check) {
		$('infoBar').innerHTML = "Please fill in the required fields properly";
		$('infoBar').style.display = 'block';
	}
	return check;
}

function updateUserList() {
	var uri = "admin/users.php";
	var myAjax = new Ajax.Updater('tableUserList',uri, {
		parameters: "a=updateList",
		method: 'post'
	});
}

function updateAuthorList() {
	var uri = "admin/authors.php";
	var myAjax = new Ajax.Updater('tableUserList',uri, {
		parameters: "act=updateList",
		method: 'post'
	});
}

function addPopup(Div) {
	var newId = Math.ceil(Math.random()*1000000);
	var uri = "include/add.php";
	var vals = "a="+Div;
	var Adresse = uri+'?'+vals;

	if (typeof windowobject == 'undefined' || windowobject.closed)
		windowobject = window.open(Adresse,"popupWindow_"+newId,"width=600,height=500,scrollbars=yes,toolbar=no,resizable=no");      
	else
	  windowobject.focus();
	if (windowobject.opener == null) windowobject.opener = self;
	return(false);
}

function showAdd(WHAT) {
	var vals = "a="+WHAT;
	var uri = "include/add.php";
	var myAjax = new Ajax.Updater('overlayContent', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: _none = function() {
			new Effect.Appear('overlayContent',{ duration: 1.0 });
			Element.hide('q_author');
			Element.hide('q_book');
		}
	} );
}

function showEditDatafile(DID) {
	var vals = "id="+DID;
	var uri = "include/editDatafile.php";
	var myAjax = new Ajax.Updater('overlayContent', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: _none = function() {
			new Effect.Appear('overlayContent',{ duration: 1.0 });
		}
	} );
}

function doEditDatafile() {
	var vals = Form.serialize('editForm');
	var uri = "include/editDatafile.php";
	var myAjax = new Ajax.Updater('infoBar', uri,  { 
		parameters: vals, 
		method: 'post',
		onSuccess: _none = function() {
			$('infoBar').style.display = 'block';
			updateDatalist();
		}
	} );
}

function updateDatalist() {
	var vals = "ajax=true";
	var uri = "pages/my_datafiles.php";
	var myAjax = new Ajax.Updater('tableDataList', uri,  { 
		parameters: vals, 
		method: 'post'
	} );
}

function keepStill() {
	if (!$('overlayContent').style.display == 'block') return false;
	var x,y,he,wi;
	//$('overlayContent').innerHTML = "";
	if (self.pageYOffset) // all except Explorer
	{
		x = self.pageXOffset;
		y = self.pageYOffset;
		//$('overlayContent').innerHTML += "self.pageXOffset = "+ x + "<br/>";
		//$('overlayContent').innerHTML += "self.pageYOffset = "+ y + "<br/>";
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
		//$('overlayContent').innerHTML += "documentElement.scrollLeft = "+ x + "<br/>";
		//$('overlayContent').innerHTML += "documentElement.scrollTop = "+ y + "<br/>";
	}
	else if (document.body) // all other Explorers
	{
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
		//$('overlayContent').innerHTML += "body.scrollLeft = "+ x + "<br/>";
		//$('overlayContent').innerHTML += "body.scrollTop = "+ y + "<br/>";
	}
	var dimensions = document.viewport.getDimensions();
	wi = dimensions.width;
	he = dimensions.height;
	if (wi == 0) {
		wi = document.body.clientWidth;
		he = document.body.clientHeight;
	}
	
	$('overlayContent').style.top = y+(he - (he /2) - 250)+"px";		
	$('overlayContent').style.left = wi - (wi / 2) - 200 +'px';
	
	window.setTimeout("keepStill()",100);
}

function hideMe() {
	new Effect.Fade('overlayContent');
	//$('overlayContent').style.display = 'none';
	if ($('q_author')) Element.show('q_author');
	if ($('q_book')) Element.show('q_book');
}

function doAdd(WHAT) {
	var vals = Form.serialize('addForm');
	var uri = "include/add.php";
	var myAjax = new Ajax.Updater('infoBar', uri,  { 
		parameters: vals, 
		method: 'post',
		onSuccess: window.setTimeout("putVals('"+WHAT+"')",1000)
	} );
}

function checkAuthor() {
	var required = Array("aLastname", "aFirstname");
	var check = true;
	$('infoBar').style.display = 'none';
	for (var i=0; i<required.length; i++) {
		$(required[i]).removeClassName('required');
		if ($F(required[i]).length < 2) { 
			$(required[i]).addClassName('required');
			check = false;
		}
	}
	if (!check) {
		$('searchResults').innerHTML = "";
		$('searchResults').style.display = 'none';
		$('infoBar').innerHTML = "Please fill in the required fields properly";
		$('infoBar').style.display = 'block';
	}	else {
		
		findAlternatives('Author');
	}
}

function checkBook() {
	var required = Array("bTitle","bYear","bAuthor");
	var check = true;
	$('infoBar').style.display = 'none';
	for (var i=0; i<required.length; i++) {
		$(required[i]).removeClassName('required');
		if (required[i] == "bTitle" && $F(required[i]).length < 2) { 
			$(required[i]).addClassName('required');
			check = false;
		}
		else if (required[i] == "bYear" && isNaN($F(required[i]))) { 
			$(required[i]).addClassName('required');
			check = false;
		}
		else if (required[i] == "bAuthor" && $(required[i]).selectedIndex == -1) { 
			$(required[i]).addClassName('required');
			check = false;
		}
	}
	if (!check) {
		$('searchResults').innerHTML = "";
		$('searchResults').style.display = 'none';
		$('infoBar').innerHTML = "Please fill in the required fields properly";
		$('infoBar').style.display = 'block';
	}	else {
		
		findAlternatives('Book');
	}
}

function findAlternatives(WHAT) {
	var uri = "include/add.php";
	var vals = Form.serialize('addForm');
	vals += '&check'+WHAT+'=true';

	var myAjax = new Ajax.Updater('searchResults', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: showResults()
	} );
}

function showResults() {
	$('addForm').style.display = 'none';
	$('searchResults').style.display = 'block';
}

function putVals(Div) {
	var vals = Form.serialize(Div+'Check');
	vals += '&b='+Div+'&r=refresh';
	var uri = "include/add.php";
	var myAjax = new Ajax.Updater(Div+'Update', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: hideMe()
	} );
}

function showAlpha(Alpha) {
	var uri = "include/search.php";
	var vals = "type=alpha&value="+Alpha;
	var myAjax = new Ajax.Updater('alphaResults', uri, {
		parameters: vals,
		method: 'post'
	} );
}

function findQuantlets() {
	var uri = "include/search.php";
	var vals = "type="+$('searchby').value+"&value="+$('searchField').value;
	var myAjax = new Ajax.Updater('qResults', uri, {
		parameters: vals,
		method: 'post',
		onSuccess: Element.show('qResult')
	} );
}

function checkForm() {
	var req = "";
	if ($('q_version').value == "") req += "Software-Version, ";
	if ($('q_name').value == "") req += "Name, ";
	if ($('q_author_1').value == "" && ($('q_author_9999') && $('q_author_9999').value == "")) {
		req += "Author, ";
	}
	if ($('q_sourcecode').value == "") req += "Sourcecode ";
	if (req != "") { 
		alert("Please fill in the following required fields:\n"+req); return false;
	} else { return true; }
}



var inputId = 1;
var outputId = 1;
var exampleId = 1;
var authorId = 2;
function addElement(Div) {
	var newId = Math.ceil(Math.random()*1000000);
	
	
	var wrapper_id = 'elements_' + Div;
	var wrapper = document.getElementById(wrapper_id);
	switch (Div) {
		case "seealso" : {
			var newel = document.createElement('p');
			var i1 = document.createElement('input');
			i1.setAttribute('type','text');
			i1.setAttribute('name','qseealso[]');
			i1.className = 'w150';
			newel.appendChild(i1);
		} break;
		case "input" : {
			var newel = document.createElement('tr');
			var td1 = document.createElement('td');
			td1.innerHTML = "Name:<br/>";
			var i1 = document.createElement('input');
			i1.setAttribute('name','input['+inputId+'][name]');
			i1.className = 'w100';
			td1.appendChild(i1);
			newel.appendChild(td1);
			var td2 = document.createElement('td');
			td2.innerHTML = "Dimension:<br/>";
			var i2 = document.createElement('input');
			i2.setAttribute('name','input['+inputId+'][dimension]');
			i2.className = 'w50';
			td2.appendChild(i2);
			newel.appendChild(td2);
			
			var newel2 = document.createElement('tr');
			var td3 = document.createElement('td');
			td3.setAttribute('colspan','2');
			td3.innerHTML = "Description:<br/>";
			var i3 = document.createElement('textarea');
			i3.setAttribute('name','input['+inputId+'][description]');
			i3.className = 'ta';
			td3.appendChild(i3);
			
			newel2.appendChild(td3);
			inputId++;
		} break;
		case "output" : {
			var newel = document.createElement('tr');
			var td1 = document.createElement('td');
			td1.innerHTML = "Name:<br/>";
			var i1 = document.createElement('input');
			i1.setAttribute('name','output['+outputId+'][name]');
			i1.className = 'w100';
			td1.appendChild(i1);
			newel.appendChild(td1);
			var td2 = document.createElement('td');
			td2.innerHTML = "Dimension:<br/>";
			var i2 = document.createElement('input');
			i2.setAttribute('name','output['+outputId+'][dimension]');
			i2.className = 'w50';
			td2.appendChild(i2);
			newel.appendChild(td2);
			
			var newel2 = document.createElement('tr');
			var td3 = document.createElement('td');
			td3.setAttribute('colspan','2');
			td3.innerHTML = "Description:<br/>";
			var i3 = document.createElement('textarea');
			i3.setAttribute('name','output['+outputId+'][description]');
			i3.className = 'ta';
			td3.appendChild(i3);
			
			newel2.appendChild(td3);
			outputId++;
		} break;
		case "example" : {
			var newel = document.createElement('span');
			newel.className = 'divider';
			
			var p1 = document.createElement('p');
			var l1 = document.createElement('label');
			l1.setAttribute('for','q_code_'+newId);
			l1.innerHTML = 'Code';
			var i1 = document.createElement('textarea');
			i1.setAttribute('name','example['+exampleId+'][code]');
			i1.setAttribute('id','q_code_'+newId);
			i1.className = 'ta';
			p1.appendChild(l1);
			p1.appendChild(i1);
			newel.appendChild(p1);
			
			var p2 = document.createElement('p');
			var l2 = document.createElement('label');
			l2.setAttribute('for','q_result_'+newId);
			l2.innerHTML = 'Result:';
			var i2 = document.createElement('textarea');
			i2.setAttribute('name','example['+exampleId+'][result]');
			i2.setAttribute('id','q_result_'+newId);
			i2.className = 'ta';
			p2.appendChild(l2);
			p2.appendChild(i2);
			newel.appendChild(p2);
			
			var p4 = document.createElement('p');
			var l4 = document.createElement('label');
			l4.setAttribute('for','q_desc_'+newId);
			l4.innerHTML = 'Description:';
			var i4 = document.createElement('textarea');
			i4.setAttribute('name','example['+exampleId+'][description]');
			i4.setAttribute('id','q_desc_'+newId);
			i4.className = 'ta';
			p4.appendChild(l4);
			p4.appendChild(i4);
			newel.appendChild(p4);
			
			var p3 = document.createElement('p');
			var l3 = document.createElement('label');
			l3.setAttribute('for','q_upload_'+newId);
			l3.innerHTML = 'Picture:';
			var i3 = document.createElement('input');
			i3.setAttribute('name','example['+exampleId+'][upload]');
			i3.setAttribute('id','q_upload_'+newId);
			i3.setAttribute('type','file');
			p3.appendChild(l3);
			p3.appendChild(i3);
			newel.appendChild(p3);
			exampleId++;
		} break;
	case "author" : {
			var newel = document.createElement('p');
			var i1 = document.createElement('input');
			i1.setAttribute('type','text');
			i1.setAttribute('name','author[]');
			i1.setAttribute('id','q_author_'+authorId);
			i1.className = 'w200';
			newel.appendChild(i1);
			var b1 = document.createElement('button');
			b1.setAttribute('name','addAuthorField_'+authorId);
			b1.setAttribute('id','addAuthorField_'+authorId);
			b1.setAttribute('onClick',"addElement('author'); return false;");
			b1.setAttribute('title',"Click here to add a new field");
			b1.className = 'addFieldButton help';
			var img = document.createElement('img');
			img.setAttribute('src','style/bullet_add.png');
			b1.appendChild(img);
			newel.appendChild(b1);
			var img2 = document.createElement('img');
			img2.setAttribute('src','graphics/ajax-loader.gif');
			img2.setAttribute('id','search_spinner'+authorId*4);
			img2.setAttribute('style','display:none;');
			newel.appendChild(img2);
			var div1 = document.createElement('div');
			div1.setAttribute('id','author_res_'+authorId);
			div1.className = 'autocomplete';
			newel.appendChild(div1);
			
		} break;
	}
	wrapper.appendChild(newel);
	if (newel2) wrapper.appendChild(newel2);
	if (Div == "author") {
		new Ajax.Autocompleter("q_author_"+authorId, "author_res_"+authorId, "include/authors.php", 
			{	paramName: "value", 
				minChars: 1, 
				indicator: 'search_spinner'+authorId*4,
				tokens: [',', ';']
			});
		$('addAuthorField_'+(authorId-1)).style.display = 'none';
		$$("button.help").each( function(link) {
			new Tooltip(link, {mouseFollow: false});
		});
		authorId++;
	}
}

/***************************************************************************************************************/

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

/*
 * Perform a simple self-test to see if the VM is working
 */
function sha1_vm_test()
{
  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}

/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}

/*
 * Calculate the HMAC-SHA1 of a key and some data
 */
function core_hmac_sha1(key, data)
{
  var bkey = str2binb(key);
  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
  return core_sha1(opad.concat(hash), 512 + 160);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert an 8-bit or 16-bit string to an array of big-endian words
 * In 8-bit function, characters >255 have their hi-byte silently ignored.
 */
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
  return bin;
}

/*
 * Convert an array of big-endian words to a string
 */
function binb2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
  return str;
}

/*
 * Convert an array of big-endian words to a hex string.
 */
function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of big-endian words to a base-64 string
 */
function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}


// Tooltip Object
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(el, options) {
		this.el = $(el);
		this.initialized = false;
		this.setOptions(options);
		
		// Event handlers
		this.showEvent = this.show.bindAsEventListener(this);
		this.hideEvent = this.hide.bindAsEventListener(this);
		this.updateEvent = this.update.bindAsEventListener(this);
		Event.observe(this.el, "mouseover", this.showEvent );
		Event.observe(this.el, "mouseout", this.hideEvent );
		
		// Removing title from DOM element to avoid showing it
		this.content = this.el.title;
		this.el.title = "";

		// If descendant elements has 'alt' attribute defined, clear it
//		this.el.descendants().each(function(el){
//			if(Element.readAttribute(el, 'alt'))
//				el.alt = "";
//		});
	},
	setOptions: function(options) {
		this.options = {
			backgroundColor: '#000', // Default background color
			borderColor: '#666', // Default border color
			textColor: '', // Default text color (use CSS value)
			textShadowColor: '', // Default text shadow color (use CSS value)
			maxWidth: 250,	// Default tooltip width
			align: "left", // Default align
			delay: 250, // Default delay before tooltip appears in ms
			mouseFollow: true, // Tooltips follows the mouse moving
			opacity: .80, // Default tooltips opacity
			appearDuration: .25, // Default appear duration in sec
			hideDuration: .25 // Default disappear duration in sec
		};
		Object.extend(this.options, options || {});
	},
	show: function(e) {
		this.xCord = Event.pointerX(e) + 30;
		this.yCord = Event.pointerY(e);
		if(!this.initialized)
			this.timeout = window.setTimeout(this.appear.bind(this), this.options.delay);
	},
	hide: function(e) {
		if(this.initialized) {
			this.appearingFX.cancel();
			if(this.options.mouseFollow)
				Event.stopObserving(this.el, "mousemove", this.updateEvent);
			new Effect.Fade(this.tooltip, {duration: this.options.hideDuration, afterFinish: function() { Element.remove(this.tooltip) }.bind(this) });
		}
		this._clearTimeout(this.timeout);
		
		this.initialized = false;
	},
	update: function(e){
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		this.setup();
	},
	appear: function() {
		// Building tooltip container
		this.tooltip = Builder.node("div", {className: "tooltip", style: "display: none;" }, [ /*
			Builder.node("div", {className:"xtop"}, [
				Builder.node("div", {className:"xb1", style:"background-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"})
			]),*/
			Builder.node("div", {className: "xboxcontent", style: "background-color:" + this.options.backgroundColor + 
				"; border-color:" + this.options.borderColor + 
				((this.options.textColor != '') ? "; color:" + this.options.textColor : "") + 
				((this.options.textShadowColor != '') ? "; text-shadow:2px 2px 0" + this.options.textShadowColor + ";" : "")}, this.content)/*,
			Builder.node("div", {className:"xbottom"}, [
				Builder.node("div", {className:"xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
				Builder.node("div", {className:"xb1", style:"background-color:" + this.options.borderColor + ";"})
			]),
		*/]);
		document.body.insertBefore(this.tooltip, document.body.childNodes[0]);
		
		Element.extend(this.tooltip); // IE needs element to be manually extended
		this.options.width = this.tooltip.getWidth();
		this.tooltip.style.width = this.options.width + 'px'; // IE7 needs width to be defined
		
		this.setup();
		
		if(this.options.mouseFollow)
			Event.observe(this.el, "mousemove", this.updateEvent);
			
		this.initialized = true;
		this.appearingFX = new Effect.Appear(this.tooltip, {duration: this.options.appearDuration, to: this.options.opacity });
	},
	setup: function(){
		// If content width is more then allowed max width, set width to max
		if(this.options.width > this.options.maxWidth) {
			this.options.width = this.options.maxWidth;
			this.tooltip.style.width = this.options.width + 'px';
		}
			
		// Tooltip doesn't fit the current document dimensions
		if(this.xCord + this.options.width >= Element.getWidth(document.body)) {
			this.options.align = "right";
			this.xCord = this.xCord - this.options.width + 20;
		}
		
		this.tooltip.style.left = this.xCord - 7 + "px";
		this.tooltip.style.top = this.yCord + 12 + "px";
	},
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};

