/* Script Version 7.5.6 */

var firstshout = 0;
var lastshout = 0;
var shoutTimer;
var shoutBox = 1;
var is_pending = 0;
var userlist = {};
var re_shout_user = /<a href="(?:.*?)"><span(?:[^>]*?)>([^<]+)<\/span><\/a>:&nbsp;/;
var shout_timeout = 15000;

function shoutit() {

	if (is_pending) return;
	is_pending = 1;

	obj = document.shoutbox;
	shouttext = obj.shoutbody.value;
	if (!shouttext) {
		is_pending = 0;
		return;
	}
	if (!s_priv) {
		alert(notLogged);
		return;
	}

	stopTimer();

	obj.shoutbody.value = "";

	shoutfield = get_object('shout_field');
	shoutfield.style.display = "none";

	sendingfield = get_object('sending_field');
	sendingfield.style.display = "";

	var url = script;
	var ajax = new ubbtAJAX(url, getShouts);
	ajax.sendData("POST","ubb=shoutit&shout=" + encodeURIComponent(shouttext));

}

function getShoutsLater() {
    restartTimer(2000);
}

function getShouts() {

	stopTimer();
	var url = script;
	var ajax = new ubbtAJAX(url, updateShout, 'xml');
	ajax.sendData("POST","ubb=getshouts&shout=" + lastshout);
	is_pending = 0;

}

function updateShout(responseXML) {

	var shoutData = responseXML;
	if (shoutData == null) return;
	var lastShout = shoutData.getElementsByTagName("lastshout");
	if (lastShout.length == 0) return;
	var shoutNode = lastShout[0];
	if (!shoutNode) return;
	if (shoutNode.childNodes[0]) {
		var shoutTextNode = shoutNode.childNodes[0];
		var last_shoutid = shoutTextNode.nodeValue;
		if (last_shoutid > 0) {
			lastshout = last_shoutid;
		}
	}
	var shoutNode = shoutData.getElementsByTagName("firstshout")[0];
	if (shoutNode.childNodes[0]) {
		var shoutTextNode = shoutNode.childNodes[0];
		var first_shoutid = shoutTextNode.nodeValue;
		if (!firstshout) {
			firstshout = first_shoutid;
		}
	}

	var shouts = shoutData.getElementsByTagName("shoutdata");

	if (shouts.length) {

		for (var i = 0 ; i < shouts.length ; i++) {
			var nameNode = shoutData.getElementsByTagName("shoutdata")[i];
			var nameTextNode = nameNode.childNodes[0];
			var name = nameTextNode.nodeValue;
			obj = get_object('shout_content');
			obj.innerHTML += name;
			addUserFromShout(name);
		}

		for (x = firstshout - 1; x <=last_shoutid; x++) {
			if (x < (last_shoutid - 30) ) {
				obj = get_object("shout" + x);
				if (obj) {
					obj.innerHTML = '';
					obj.style.display = "none";
				}
			}
		}
	}

	shoutfield = get_object('shout_field');
	shoutfield.style.display = "";

	sendingfield = get_object('sending_field');
	sendingfield.style.display = "none";

	startTimer();

	// IE has a problem with scrolling before the shoutbox
	// is filled in.  A 1 millisecond timer fixes this.  *shrug*
	if (shouts.length) {
		scrollTimer = setTimeout("scrollBottom()",1);
	}

}

function scrollBottom() {
		var objDiv = get_object("shout_box");
		if (objDiv.scrollHeight) {
			objDiv.scrollTop = objDiv.scrollHeight;
		} else if (objDiv.offsetHeight) {
			objDiv.scrollTop = objDiv.offsetHeight;
		}
		return true;
}

function startTimer(){
	shoutTimer = setTimeout("getShouts()",shout_timeout);
}

function stopTimer() {
	clearTimeout(shoutTimer);
}

function restartTimer(timeout) {
    if (!timeout) {
        timeout = shout_timeout;
    }
    clearTimeout();
    shoutTimer = setTimeout("getShouts()", timeout);
}

function confirmDelete(id)	{

	input_box=confirm(confirmText + id + "?");

	if (input_box==true)	{
		obj = get_object("shout" + id);
		obj.innerHTML = '';
		obj.style.display = "none";
    		var url = script + "?ubb=shoutdelete&id=" + id;
    		var ajax = new ubbtAJAX(url);
    		ajax.sendData("GET");
	}
}

function addUserFromShout(shout) {
    var user = parseUserFromShout(shout);
    return addShoutUser(user);
}

function parseUserFromShout(shout) {
    var mat = shout.match(re_shout_user);
    if (mat && mat[1]) {
        return repairString(mat[1]);
    }
    return undefined;
}

function repairString(str) {
   var temp_div = document.createElement('div');
   temp_div.innerHTML = str;
   return temp_div.firstChild.nodeValue;
}

function addShoutUser(user) {
    if (!user) return false;
    var ul = user.toLowerCase();
    if (!userlist.hasOwnProperty(ul)) {
        userlist[ul] = user;
        return true;
    }
    return false;
}

// takes a text field and an array of strings for autocompletion
function autocomplete(input, data) {
    var str = input.value.toLowerCase();
    if (str.length == input.selectionStart && str.length == input.selectionEnd) {
        var candidates = [];
        // filter data to find only strings that start with existing value
        for (var d in data) {
            if (data.hasOwnProperty(d)) {
                if (d.indexOf(str) === 0 && data[d].length >= str.length) {
                    candidates.push(data[d]);
                }
            }
        }

        if (candidates.length > 0) {
            // some candidates for autocompletion are found
            if (candidates.length == 1) {
                input.value = candidates[0] + ': ';
            } else {
                input.value = longestInCommon(candidates, str.length);
            }
            return true;
        }
    }
    return false;
}

// finds the longest common substring in the given data set.
// takes an array of strings and a starting index
function longestInCommon(candidates, index) {
    var i, ch, memo;
    do {
        memo = null;
        for (i=0; i < candidates.length; i++) {
            ch = candidates[i].charAt(index);
            if (!ch) break;
            if (!memo) memo = ch;
            else if (ch != memo) break;
        }
    } while (i == candidates.length && ++index);

    return candidates[0].slice(0, index);
}

// catch TAB keypresses in text input
function activateShoutboxTabCompletion() {
    var shoutbox_input = get_object('shoutbody');
    if (shoutbox_input) {
        shoutbox_input.addEventListener('keydown', function(e) {
            if (e.keyCode == 9 && autocomplete(this, userlist)) {
                e.preventDefault();
            }
        }, false);
    }
}

