Event.observe(window, 'load', startUp);
isLoading = false;

function showHistory(theRoom) {
	if(isLoading) return false;
	
	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);

	if($('geekchat-window')) {
		$('geekchat-window').innerHTML = '<div style="padding:20px;">Switching to history view...<img src="themes/'+theme+'/images/searching.gif" alt="wait.." /></div>';
		$('geekchat-input').style.display = 'none';
		$('gc-userlist').style.display = 'none';
	} else {
		$('gc-history-window').innerHTML = '<div style="padding:10px;">Switching history view to "'+theRoom+'"...<img src="themes/'+theme+'/images/searching.gif" alt="wait.." /></div>';
	}

	isLoading = true;
	new Ajax.Updater('geekchat', 'geekchat.php', 
										{
											method: 'post',
											parameters: 'type=history&room=' + theRoom,
											evalScripts: true,
											onComplete: function() { isLoading = false; }
										});
}

function toggleDates() {
	if($('gc-date-list').style.display == 'none') {
		$('gc-date-list').style.display = 'block';
		$('show-dates').innerHTML = 'Hide Dates';
		$('filter-holder').style.width = '434px';
	} else {
		$('gc-date-list').style.display = 'none';
		$('show-dates').innerHTML = 'Show Dates';
		$('filter-holder').style.width = '440px';
	}
}

function checkKey(e) {
	if(e.keyCode == 3 || e.keyCode == 13) sendChat();
}

function setThemeName(themeName) {
	theme = themeName;

  for(i = 0; (a = document.getElementsByTagName('link')[i]); i++) {
  	
    if(a.getAttribute('rel').indexOf('alternate stylesheet') != -1 && a.getAttribute('title')) {
    	styleTitle = a.getAttribute('title')
    	if(styleTitle.substring(styleTitle.indexOf('-')) == '-theme') a.disabled = true;
      if(styleTitle == theme + '-theme') a.disabled = false;
    }

  }
}

function setRoomName(theName, maxLines, messageText) {
	roomName = theName;
	maxlines = maxLines;
	defaultText = messageText;
	
	removeOldMessages();

	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);
		
	refreshSet = setInterval('doRefresh()', 2500);
	observeTimeout = setTimeout("Event.observe('gc-message', 'keydown', checkKey)", 500);
}

function toggleSmileBox() {
	if($('gc-message').value == defaultText) {
		$('gc-message').value = '';
		$('gc-message').style.color = '#000000';
	}
	
	if($('smiley-box').style.display == 'none') {
		$('smiley-box').style.display = 'block';
		$('geekchat-input').style.height = '40px';
	}	else { 
		$('smiley-box').style.display = 'none';
		$('geekchat-input').style.height = '20px';
	}
}

function addText(thisText) {
	if($('gc-message').value == defaultText) {
		$('gc-message').value = '';
		$('gc-message').style.color = '#000000';
	}
	
	$('gc-message').value += thisText;
	toggleSmileBox();
	$('gc-message').focus();
}

function startUp() {
	var mydate = new Date();
	var hour = mydate.getHours();
	var whichRoom;

	url = document.location.href;
	if(url.indexOf('?') != -1) {
		var urlSplit = new Object();
		var urlSplit = url.split('?');
		var i = 0;
		if(urlSplit != url) {
			while(i <  urlSplit.length) {
				var checkPara = urlSplit[i].split('=');
				if(checkPara[0] == 'load_room')
					var whichRoom = checkPara[1];
				if(checkPara[0] == 'load_theme')
					var whichTheme = checkPara[1];
				i++;
			}
		}
		var b = 0;
		var urlSplit = url.split('&');
		while(b <  urlSplit.length) {
			var checkPara = urlSplit[b].split('=');
			if(checkPara[0] == 'load_room')
				var whichRoom = checkPara[1];
			if(checkPara[0] == 'load_theme')
				var whichTheme = checkPara[1];
			b++;
		}	
	}
	
	new Ajax.Updater('geekchat', 'geekchat.php', 
									{
									method: 'post',
									parameters: 'type=init&loadroom='+whichRoom+'&loadtheme='+whichTheme+'&ctime=' + hour,
									evalScripts: true,
									onComplete: function() { 	setTimeout("if($('gc-message')) $('gc-message').focus();", 100); makeZebra();}
									});
}

function addTab(tabNum) {
	if(isLoading) return false;
	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);

	$('add-room').innerHTML = '<img src="themes/' + theme + '/images/searching.gif" alt="loading" />';
	new Ajax.Request('geekchat.php',
									{
										method: 'post',
										parameters: 'type=addtab&tabnum=' + tabNum
									});
	setTimeout("switchTab('" + tabNum + "', 'listrooms')", 300);
}

function switchTab(tabName, switchType, fromRoom) {
	if(isLoading) return false;
	
	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);
	
	var tabID = 'gc-' + tabName;
	if($('gc-list-' + tabName))
			$('gc-list-' + tabName).innerHTML += '<img style="margin-top:-2px;margin-right:-5px;" src="themes/' + theme + '/images/searching.gif" alt="loading" />';
	else {
		if($(tabID))
			$(tabID).innerHTML = '<div style="float:left;">' + tabName + '</div> <img style="margin-top:-2px;margin-right:-2px;" src="themes/' + theme + '/images/searching.gif" alt="loading" />';
	}
	isLoading = true;
	new Ajax.Updater('geekchat', 'geekchat.php',
									{
										method: 'post',
										parameters: 'type='+switchType+'&tabname=' + tabName + '&fromroom=' + fromRoom,
										onComplete: function () { if($('gc-message')) $('gc-message').focus(); isLoading = false;},
										evalScripts: true
									});
}

function closeTab(thisTab) {
	if(isLoading) return false;
	
	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);

	var tabID = 'gc-tab-' + thisTab;
	isLoading = true;
	var closeEffect =
	 new fx.Opacity(tabID, {
	 	duration: 700,
	 	onComplete: function() {
			new Ajax.Updater('geekchat', 'geekchat.php',
										{
											method: 'post',
											parameters: 'type=removetab&removeroom=' + thisTab,
											onComplete: function () { if($('gc-message')) $('gc-message').focus(); isLoading = false;},
											evalScripts: true
										});
	 	}});
	 	closeEffect.toggle();
}

function joinPrivateRoom() {
	if(isLoading) return false;
	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);

	$('gc-join').innerHTML = '<img style="margin-top:-4px;margin-left:-2px;" src="themes/' + theme + '/images/searching.gif" alt="loading" />';
	isLoading = true;
	new Ajax.Updater('geekchat', 'geekchat.php',
									{
										method: 'post',
										parameters: 'type=roompw&password=' + $('password').value + '&forroom=' + $('roomname').value,
										onComplete: function() { isLoading = false; },
										evalScripts: true
									});
	return false;
}

function setNickName() {
	if(isLoading) return false;
	
	if(typeof refreshSet != 'undefined')
		clearInterval(refreshSet);

	$('gc-join').innerHTML = '<img style="margin-top:1px;margin-left:-2px;" src="themes/' + theme + '/images/searching.gif" alt="loading" />';
	isLoading = true;
	new Ajax.Updater('geekchat', 'geekchat.php',
									{
										method: 'post',
										parameters: 'type=setnick&nickname=' + $('nickname').value + '&password=' + $('namepw').value + ' &forroom=' + $('roomname').value,
										onComplete: function() { isLoading = false; },
										evalScripts: true
									});
	return false;
}

function setText(thistext) {
	$('gc-message').focus();
	$('gc-message').value = thistext;
}

function startIM(person) {
	var date = new Date();
	var minutes = date.getMinutes();
	var seconds = date.getSeconds();
	var imname = minutes + seconds;
	window.open('geekchat.php?type=startim&room='+roomName+'&to='+person,'im'+imname,'height=520,width=500');
}

function acceptIM(sessionid, inviter) {
	var date = new Date();
	var minutes = date.getMinutes();
	var seconds = date.getSeconds();
	var imname = minutes + seconds;
	window.open('geekchatim.php?type=accept&roomfrom='+roomName+'&inviter='+inviter+'&imsession='+sessionid+'','im'+imname+'','height=520,width=500');
}

function refreshUserList() {
	new Ajax.Updater('gc-userlist', 'geekchat.php',
									{
										method: 'post',
										parameters: 'type=userlist&tabname=' + roomName, 
										evalScripts: true
									});
}

function doRefresh() {
	new Ajax.Request('geekchat.php', 
													{
													method: 'post',
													parameters: 'type=refresh&room='+roomName,
													onComplete: showResponse
													});
}

function showResponse(therequest) {
	if(therequest.responseText != '' & therequest.responseText != null) {
		if(therequest.status == 403) {
			var mydate = new Date();
			var hours = mydate.getHours();
			var minutes = mydate.getMinutes();
			if (hours > 12) {
				hours = hours-12;
			}
			if (hours == 0) hours = 12;
			if (hours < 10) hours = '0' + hours;
			if (minutes <= 9) minutes = '0' + minutes;
			var cdate = hours + ':' + minutes
			$('geekchat-window').innerHTML += '<div name="gcmessage" class="geekchat-message alert"><span style="color:#BD0000;"><em>[' + cdate + ']</em> [ALERT]</span> <span>Error 403: Forbidden. Something went wrong when sending your message.</span></div>';
		} else {
			$('geekchat-window').innerHTML += therequest.responseText;
			refreshUserList();
		}
		removeOldMessages();
	}
}

function removeOldMessages() {
	var divs = document.getElementsByTagName('div');
	var a = 0;
	var divlength = divs.length;
	for(var i = 0; i < divs.length; i++) {
		var divName = String(divs[i].getAttribute('name'));
		if(divName.toLowerCase().match('gcmessage')) 
			a++;
	}
	if(a > (maxlines-1)) {
		for(var i = 0; i < divs.length; i++) {
			var divName = String(divs[i].getAttribute('name'));
			if(divName.toLowerCase().match('gcmessage')) {
				if(a > maxlines)
					divs[i].parentNode.removeChild(divs[i]);
				a--;
			}
		}
	}
	makeZebra();
}

function makeZebra() {
	if(typeof switchZebra == 'undefined')
		switchZebra = true;

	var divs = document.getElementsByTagName('div');
	for(var i = 0; i < divs.length; i++) {
		if(divs[i].getAttribute('name') == 'gcmessage') {
			if(switchZebra)
				Element.addClassName(divs[i].getAttribute('id'), 'zebra');
			else
				Element.removeClassName(divs[i].getAttribute('id'), 'zebra');
		}
			switchZebra = !switchZebra;
	}
}

function denyIM(table, fromname) {
	new Ajax.Request('geekchat.php', 
									{
										method: 'post',
										parameters: 'type=deny&table='+table+'&from='+fromname,
										onComplete: showResponse
									});
}

function sendChat() {
	if($('smiley-box').style.display == 'block') { 
		$('smiley-box').style.display = 'none';
		$('geekchat-input').style.height = '20px';
	}

	if($('gc-message').value == defaultText) {
		$('gc-message').focus();
		return false;
	}

	new Ajax.Request('geekchat.php',
									{
										method: 'post',
										parameters: 'type=send&room='+roomName+'&message=' + escape($F('gc-message').replace(/\+/gi, "[*PLUS*]")),
										onComplete: showResponse
									});
	$('gc-message').value = '';
	
}

function doSearch(startPoint) {
	if(isLoading) return false;
	
	if(escape($F('search-term')) == '') 
		$('gc-history-window').innerHTML = '<h4 style="margin-bottom:25px;">Loading history...</h4>';
	isLoading = true;
	new Ajax.Request('geekchat.php', 
					{
					onLoading: function() { Element.show('search-spin'); Element.hide('search-done'); },
					method: 'post',
					parameters: 'type=search&room='+historyRoom+'&start=' + escape(startPoint) + '&q=' + escape($F('search-term')).replace(/\+/gi, "[*PLUS*]"),
					onComplete: function(request) {
							$('gc-history-window').innerHTML = request.responseText;
							Element.hide('search-spin');
							Element.show('search-done');
							$('gc-history-window').style.height = 'auto';
							makeZebra();
							isLoading = false;
						}
					});
}

function getHistory(historyType, startID) {
	if(isLoading) return false;
	if(typeof allFrom == 'undefined') allFrom = 'false';
	isLoading = true;
	var resultsUp = 
		new fx.Height('gc-history-window', {
			duration: 200,
			onComplete: function() {
				new Ajax.Request('geekchat.php', {
					onLoading: function() { Element.show('search-spin'); Element.hide('search-done'); },
					method: 'post',
					parameters: 'type='+historyType+'&room='+historyRoom+'&i=' + startID,
					onComplete: function(request) {
						$('gc-history-window').innerHTML = request.responseText;
						Element.hide('search-spin'); 
						Element.show('search-done');
						var resultsDown = new fx.Height('gc-history-window', { duration:200 });
						resultsDown.toggle();
						setTimeout("$('gc-history-window').style.height = 'auto'", 300);
						makeZebra();
						isLoading = false;
					}
				});
			}
		});
	resultsUp.toggle();
}
