/**
*
* @package Brylle
* @version 1.0
* @copyright (c) 2007 J. Seyfried, http://www.joerg-seyfried.de
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
* Demo at http://www.macmini-forum.de
*/

// brylle.js - AJAX functionality
// depends on inclusion of brylle_common.js

function fadein(id) {
	el = document.getElementById(id);
	duration = readCookie("duration");
	if (!duration) duration = 0;
	duration=10+parseInt(duration);
	duration=Math.max(10, duration);
	duration=Math.min(duration, 110);

	speed=30;
	mode = readCookie("blending");

	if ((mode==null) || (mode==1) || (mode==0)) { // standard fade

		el.style.opacity = '0';
		el.style.display = 'block';
		for (var i = 0; i < duration; i++) {
			val = 1/(1+Math.exp((-8.0*(i+1)/duration)+5));
			setTimeout('setOpacity("'+id+'", '+val+');', i * speed);
		}
		setTimeout('setOpacity("'+id+'", '+1+');', (i+1) * speed);
	} else if (mode == 2) { // color fade
		el.style.backgroundColor = colorfade_from;
		el.style.display = 'block';
		redfrom   = parseInt(colorfade_from.substr(0,2) ,16);
		redto     = parseInt(colorfade_to.substr(0,2) ,16);
		reddiff   = redto-redfrom;
		greenfrom = parseInt(colorfade_from.substr(2,2) ,16);
		greento   = parseInt(colorfade_to.substr(2,2) ,16);
		greendiff = greento-greenfrom;
		bluefrom  = parseInt(colorfade_from.substr(4,2) ,16);
		blueto    = parseInt(colorfade_to.substr(4,2) ,16);
		bluediff  = blueto-bluefrom;
		for (var i = 0; i < duration; i++) {
			val = hex(i/duration*reddiff+redfrom) +
				  hex(i/duration*greendiff+greenfrom) +
				  hex(i/duration*bluediff+bluefrom);
			setTimeout('setBgColor("'+id+'", "'+val+'");', i * speed);
		}
		setTimeout('setBgColor("'+id+'", "'+colorfade_to+'");', (i+1) * speed);
	} else { // no effect
		el.style.display = 'block';		
	}
}

function hex(d) {
	var hD="0123456789ABCDEF";
	var h = hD.substr(d&15,1);
	if (d<15) { s="0"; } else { s=""; }
	while(d>15) {d>>=4;h=hD.substr(d&15,1)+h;}	
	return s+h;
}

function setBgColor (element, value) {
	style = document.getElementById(element).style;
	style.backgroundColor = value;
}

// see http://www.brainerror.net/scripts_js_blendtrans.php
function setOpacity(element, value) {
	style = document.getElementById(element).style;
	style.opacity = value;
	style.MozOpacity = value; 
	style.KhtmlOpacity = value; 
	style.filter = "alpha(opacity=" + Math.floor(value*100) + ")"; 
}

// http://www.quirksmode.org/js/cookies.html
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//
// trimList()
// trims the list of shoutbox entries to $displayentries
// (defined in brylleconf.php, imported to JS via index.php)
//
function trimList() {
	var i;
	var eol=false;
	var brylleLi = document.getElementById("brylle");
	var li;
	var num=-1;
	if (readCookie("numEntries")!=null) num = readCookie("numEntries");
	if (num<=0) num=displayentries;
	
	num = Math.min(num, displayentries);
	
	li = brylleLi.getElementsByTagName("li")[num];

	while (li) {
		brylleLi.removeChild(li);
		li = brylleLi.getElementsByTagName("li")[num];
	}
	
}

function getBryll(pos) {
	if (xmlreqs[pos] && xmlreqs[pos].req) {
		if (xmlreqs[pos].req.readyState == 4) {
			state = xmlreqs[pos].req.status;
			if (state==200) {
				eText = xmlreqs[pos].req.responseText;
				if (eText.length>0) {
					entry = eText.split("\n");
					lastId = parseInt(entry[0]);
					entry.shift();
					eText = entry.join("\n");
					
					entry = eText.split('<&');
					brylleLi = document.getElementById("brylle");
					while (entry.length) {		
						curId++;
						n = document.createElement('li');
						n.id='b'+curId;
						n.innerHTML += entry[entry.length-1];
						//n.setAttribute('class', 'bryll'); // fails in IE
						n.className = 'bryll';
						n.style.display='none';
						// IE: fades only elements with one of (height, width, abs pos.) defined.
						// Stupid as hell...
						n.setAttribute('width', '190px'); // does not work. This one does:
						n.style.zoom="1";
						//n.style.width="190";
						brylleLi.insertBefore(n, brylleLi.firstChild);
						fadein('b'+curId);
						entry.length -= 1;
					}
					trimList();
					curId = lastId;
				}
			}
			isLoading = false;
			deleteHTTPObject(pos); 
		}
	} else isLoading = false;
}

function loadNext() {
	var pos;

	if (isLoading) {
		return;
	}
	retries = 0;
	isLoading = true;
	pos = getHTTPObject();

	xmlreqs[pos].req.open("GET", baseURL+"fetch.php?id="+(curId+1)+"&t="+Date.parse(new Date()), true);
	xmlreqs[pos].req.onreadystatechange = function() { getBryll(pos); }
	try {
		xmlreqs[pos].req.setRequestHeader('Content-Type','charset=utf-8');
	} catch(e) {}
	xmlreqs[pos].req.send("");
	load = setTimeout('loadNext()', reloadInt);
//document.getElementById('debug').innerHTML += "ln("+curId+")";		
}



function reloadAfterPost(pos) {
	if (xmlreqs[pos].req.readyState == 4) {
		deleteHTTPObject(pos); 
		isLoading = false;
		loadNext();
 	}
}


function replaceEntry(pos) {
	if (xmlreqs[pos].req.readyState == 4) {
		if (xmlreqs[pos].req.status == 200) {	
			eText = xmlreqs[pos].req.responseText;
			entry = eText.split("\n");

			document.getElementById('b'+id).innerHTML = entry[1];
			fadein('b'+id);
			deleteHTTPObject(pos); 
		}
	}
}

function reloadEntry(tid) {
	pos = getHTTPObject();
	xmlreqs[pos].req.open("GET", baseURL+"fetch.php?id="+tid+"&s=1&t="+Date.parse(new Date()), true);
	id=tid;
	xmlreqs[pos].req.onreadystatechange = function() { replaceEntry(pos); }
	xmlreqs[pos].req.send("");
	document.getElementById('b'+tid).style.backgroundColor=oldcolor;
}

function postEntry(dummy) {
	clearTimeout(load);
	message = document.getElementById('message').value;
	params = 'message='+encodeURIComponent(message);
	if (document.getElementById('name')) {
		if (document.getElementById('name').value!='') {
			params = params +'&name='+encodeURIComponent(document.getElementById('name').value);
		} else {
			alert("Benutzername erforderlich!");
			return;
		}
	}
	if (message.length>maxLength) {
		alert("Nachricht um "+(message.length-maxLength)+" Zeichen zu lang, sorry!");
	} else {
		document.getElementById('message').value = "";
		document.getElementById('message').focus();
		textCounter(document.getElementById('message'),document.getElementById('Rest'),200);
		//httpReq.abort(); should do the trick, but Firefox keeps on crashing, so we do:
		pos = getHTTPObject();
		xmlreqs[pos].req.open("POST", path+"post.php", true);
		xmlreqs[pos].req.onreadystatechange = function() { reloadAfterPost(pos); };
		try {
			xmlreqs[pos].req.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=utf-8');
			xmlreqs[pos].req.setRequestHeader("Content-length", params.length);
		} catch(e) {}
		xmlreqs[pos].req.send(params);
	}
}
