var threads = null;
var posts = null;
var xmlRet = null;
var notify = false;
var activeThreadID = 0;
var lastPostID = 0;
var threadLocked = false;
var page = -1;
var editPostID = 0; 

var smileys = {
  ":)" : 'smile',
	":-)" : 'smile',
	"(-:" : 'smile',
	
	";)" : 'wink',
	";-)" : 'wink',
	",-)"  : 'wink',
	
	":(" : 'sad',
	":<" : 'sad', 
	":C" : 'sad',	
	":-<" : 'sad', 
	":-C" : 'sad',
	":-(" : 'sad',
	
	":@" : 'angry',
	":-@" : 'angry',
	"8o|" : 'angry',
	"80|" : 'angry',
	
	":S" : 'confused',
	":Z" : 'confused',
	":-S" : 'confused',
	":-Z" : 'confused',
	
	":'(" : 'crying',
	":`(" : 'crying',
	
	"|-)" : 'sleepy',
	
	"*-)" : 'thinking',
	"*)" : 'thinking',
	
	":D" : 'big_smile',
	":-D" : 'big_smile',
	
	"8-|" : 'nerd',
	"8-)" : 'nerd',
	
	"<:0)" : 'party',
	"<:o)" : 'party',
	
	":$" : 'embarrased',
	":-$" : 'embarrased',
	
	":->" : 'sarcastic',
	"^o)" : 'sarcastic',
	"^0)" : 'sarcastic',
	
	
	":-0" : 'surprised',
	":-O" : 'surprised',
	
	":0" : 'surprised',
	":O" : 'surprised',
	
	":P" : 'silly',
	":-P" : 'silly',
	
	":|" : 'disappointed',
	":-|" : 'disappointed',
	
	"+O(" : 'sick',
	"+0(" : 'sick'
}
	
function ReloadThreads()
{
	page = 0;
	LoadThreads();
	alert('Reload Complete');
}
	
function LoadThreads()
{
	xmlRet = XMLReq('/cgi-bin/forum/getThreads.pl');
	if (xmlRet == null) return;
	if (selectSingleNode(xmlRet.responseXML, '/OceanWard/BlackListed') != null) return location.replace('about:blank');
	if (selectSingleNode(xmlRet.responseXML, '/OceanWard/User') == null) return location.replace('/login.asp?path=' + escape(location.pathname)); // The user is not logged in
	document.getElementById('htli').style.display = 'block';
	threads = selectNodes(xmlRet.responseXML, '/OceanWard/Threads/Thread');
	if (page == -1) page = GetCookie('threadPage',0);
	WriteThreads(page, null);
}

function WriteThreads(pg, offset)
{
	var numPages = Math.ceil(threads.length / 9);
	if (pg == null) page = Math.max(Math.min(numPages - 1, page + offset), 0);
	if (offset == null) page = pg;
	page = Math.min(Math.max(0, page), numPages); 

	var firstThread = page * 9;
	var now = new Date;
	var nowSecs = now.getTime() / 1000;
	nowSecs -= now.getTimezoneOffset() * 60;
	for (var x = 0; x < 9; x++) {
		document.getElementById('subject' + x).innerHTML = '';
		document.getElementById('author' + x).innerHTML = '';
		document.getElementById('replies' + x).innerHTML = '';
	}
	for (var x = 0; x < 9; x++) {
		var t = firstThread + x;
		if (t >= threads.length) continue;
	
		if (parseInt(getText(threads[t], 'Locked')) > 0) document.getElementById('lock' + x).style.backgroundImage = 'url(/images/padlock.png)';
		else document.getElementById('lock' + x).style.backgroundImage = '';
				 
		document.getElementById('subject' + x).innerHTML = '<a href="view.asp?threadID=' + threads[t].getAttribute('ID') + '">' + getText(threads[t], 'Subject') + '</a>';
		document.getElementById('replies' + x).innerHTML = '<nobr>' + threads[t].getAttribute('NumPosts') + '&nbsp;&nbsp;-&nbsp;&nbsp;' + GetElapsedTime(nowSecs - parseInt(getText(threads[t], 'LastPost'))) + '&nbsp;&nbsp;-&nbsp;&nbsp;' + getText(threads[t], 'LastPoster') + '</nobr>'
		document.getElementById('author' + x).innerHTML = getText(threads[t], 'User/Nickname')
	}
	var firstPage = Math.max(0, page - 5);
	var lastPage = firstPage + 10;
	if (lastPage > numPages) {
		lastPage = numPages;
		firstPage = Math.max(0, numPages - 10);
	}
	var pageArr = new Array;
	for (var x = firstPage; x < lastPage; x++) 
		pageArr[pageArr.length] = '<a href="" style="color:#000000" onclick="WriteThreads(' + x + ', null); return false;">' + (x + 1) + '</a>';
	document.getElementById('pageNums').innerHTML = pageArr.join(' <b style="color:#F99B2A">|</b> ');
}

function GetElapsedTime(secs)
{
	var ret = '';
	secs = Math.max(0, secs); // Don't allow negative numbers in here..
	var wks = Math.floor(secs / 604800); 	secs -= wks * 604800;
	var dys = Math.floor(secs / 86400);    secs -= dys * 86400;
	var hrs = Math.floor(secs / 3600);    secs -= hrs * 3600;
	var mns = Math.floor(secs / 60);
	if (wks > 0) ret = wks + ' wks ';
	if (dys > 0) ret += dys + ' days ';
	if (wks > 0) return ret.replace(/\s+$/,'');
	if (hrs > 0) ret += hrs + ' hours ';
	if (dys > 0) return ret.replace(/\s+$/,'');
	ret += mns + ' mins';
	return ret;
}

function ViewThread(threadID)
{
	var top = 0;
	if (!threadID) return location.replace('/family/forum'); 
	var postData = new Object;
	postData.threadID = activeThreadID = threadID;
	postData.lastPostID = lastPostID;
	xmlRet = XMLReq('/cgi-bin/forum/getPosts.pl', postData);
	if (xmlRet == null) return;
	
	if (selectSingleNode(xmlRet.responseXML, '/OceanWard/User') == null) return location.replace('/login.asp?path=' + escape(location.href)); // The user is not logged in
	if (selectSingleNode(xmlRet.responseXML, '/OceanWard/BlackListed') != null) return location.replace('about:blank');
	
	posts = selectNodes(xmlRet.responseXML, '/OceanWard/Posts/Post');
	var user = selectSingleNode(xmlRet.responseXML, '/OceanWard/User');
	
	var now = new Date;
	var nowSecs = now.getTime() / 1000;
	nowSecs -= now.getTimezoneOffset() * 60;
	
	var threadNode = selectSingleNode(xmlRet.responseXML, 'OceanWard/Thread');

	threadLocked = parseInt(getText(threadNode, 'Locked')) > 0;
	var superUser = user.getAttribute('SuperUser') == '1';
	var allowReport = user.getAttribute('AllowReport') == '1';
	notify = user.getAttribute('Notify') == '1';
	
	var parentDiv = document.getElementById('postsDiv');
	
	for (var x = 0; x < posts.length; x++) {
		var tbl = document.createElement('TABLE');
		tbl.cellPadding = tbl.cellSpacing = 0;
		tbl.style.width = '814px';
		tbl.id = 'postTbl_' + posts[x].getAttribute('ID');
		
		var reported = posts[x].getAttribute('Reported') == '1'; 
		
		var cell = tbl.insertRow(-1).insertCell(-1);
		cell.colSpan = 2;
		cell.height = 21;
		if (x == 0) cell.style.backgroundImage = 'url(/images/forum/top_bar.jpg)';
		else cell.style.backgroundImage = 'url(/images/forum/bar.jpg)';
		cell.className = 'dateCell';
		cell.innerHTML = ConvertDate(parseInt(getText(posts[x], 'DateAdded')), LONG_DATETIME_FORMAT);
		
		var row = tbl.insertRow(-1);
		row.vAlign = 'top';
		cell = row.insertCell(-1);
		cell.rowSpan = 2
		cell.align = 'right';
		cell.width = 91;
		cell.innerHTML = '<img width=91 height=79 src="/images/profile/' + getText(posts[x], 'User/Image') + '" alt=""><br><p style="margin:0px 7px 7px 0px"><b>' + getText(posts[x], 'User/Nickname') + 
			'</b><br><span style="font-size:10px; color:#A2A2A2">Reg: ' + ConvertDate(parseInt(getText(posts[x], 'User/Joined')), "%d/%m/%y") + '</span></p>';

		var body = getText(posts[x], 'Body');
		body = body.replace(/\r/g, '');		
		body = body.replace(/</g, '&lt;');
		body = body.replace(/>/g, '&gt;');
		body = body.replace(/\n/g, '<br>');
		body = body.replace(/(http:[\w+|\.|\\|\/]+|www.[\w+|\.|\\|\/]+)/gi,
			function(d, match) {
				if (match.toLowerCase().indexOf('http:') != 0) return '<a href="http://' + match + '" target="_blank">' + match + '</a>';
				return '<a href="' + match + '" target="_blank">' + match + '</a>';
			}); 
		
		body = body.replace(/  /g, '&nbsp;&nbsp;');
 		for (var f in smileys) {
 			var m = f;
			m = m.replace(/\\/g, '\\\\');
			m = m.replace(/\|/g, '\\\|');
			m = m.replace(/\*/g, '\\\*');
			m = m.replace(/\(/g, '\\\(');
			m = m.replace(/\)/g, '\\\)');
			m = m.replace(/\+/g, '\\\+');
			m = m.replace(/</g, '&lt;');
			m = m.replace(/>/g, '&gt;');
			var reg = new RegExp(m, 'gi');
			body = body.replace(reg, '<img class="smiley" src="/images/forum/' + smileys[f] + '.jpg" width=19 height=19 title="'+ smileys[f] + '" alt="' + smileys[f] + '">');
			
			lastPostID = Math.max(lastPostID, parseInt(posts[x].getAttribute('ID')));   
		}
		cell = row.insertCell(-1);
		cell.width = 723;
		cell.className = 'bodyCell';
		cell.innerHTML = body;
		if (x == posts.length - 1) cell.style.color = '#000000';
		if (reported) cell.style.color = '#c0c0c0';
		
		row = tbl.insertRow(-1);
		row.vAlign = 'bottom';
		cell = row.insertCell(-1);
		cell.className = 'optionsCell';


		var opts = new Array();
		opts[opts.length] = '<a onclick="PostReply(\'' + posts[x].getAttribute('ID') + '\'); return false" href="" class=postReply>Post Reply</a>';
		if (notify) opts[opts.length] = '<a href="" onclick="ToggleNotify(); return false" id="notify' + x + '" class=optNormal>Unsubscribe from thread</a>';
		else opts[opts.length] = '<a href="" onclick="ToggleNotify(); return false" id="notify' + x + '" class=optNormal>Subscribe to thread</a>';
		if (superUser) {
			if (reported) opts[opts.length] = '<a onclick="KeepPost(' + posts[x].getAttribute('ID') + '); return false" href="" class=optNormal>Keep Post</a>';
			opts[opts.length] = '<a onclick="DelPost(' + posts[x].getAttribute('ID') + '); return false" href="" class=optNormal>Delete Post</a>';
		} else {
			if (allowReport) opts[opts.length] = '<a onclick="ReportPost(' + posts[x].getAttribute('ID') + '); return false" href="" class=optNormal>Report as Inappropriate</a>';
		}
		if (getText(posts[x], 'CanEdit') == '1') opts[opts.length] = '<a onclick="EditPost(' + posts[x].getAttribute('ID') + '); return false" href="" class=optNormal>Edit</a>'; 
		
		
		cell.style.paddingBottom = '5px';		
		cell.innerHTML = opts.join('<b> | </b>');
		parentDiv.appendChild(tbl); 
	}
	
	FW_PositionFooter();
}

function DelPost(postID)
{
	if (!confirm('Are you sure you want to delete this post?')) return;
	var postData = new Object;
	postData.postID = postID;
	XMLReq('/cgi-bin/forum/delete.pl', postData);
	//location.reload();
	document.getElementById('postTbl_' + postID).style.display = 'none';
}

function KeepPost(postID)
{	
	var postData = new Object;
	postData.postID = postID;
	XMLReq('/cgi-bin/forum/keep.pl', postData);
	location.reload();
}

function ReportPost(postID)
{
	if (!confirm('Are you sure you want to report this message as inappropriate?\nInappropriate use of this feature may result in you being blacklisted from the site.')) return;
	var postData = new Object;
	postData.postID = postID;
	XMLReq('/cgi-bin/forum/report.pl', postData);	
}

function ToggleNotify()
{
	var postData = new Object;
	postData.threadID = activeThreadID;
	postData.notify = 0;
	if (!notify) postData.notify = 1;
	
	var ret = XMLReq('/cgi-bin/forum/notify.pl', postData);
	if (ret == null) return;
	if (postData.notify == 0) {
		alert('No more notification emails will\nbe sent to you regarding this thread.'); 
		for (var x = 0; x < posts.length; x++) 
			document.getElementById('notify' + x).innerHTML = 'Subscribe to thread';
		notify = false;
	} else {
		alert('You will receive a notification\nemail when this thread is added to.'); 
		for (var x = 0; x < posts.length; x++) 
			document.getElementById('notify' + x).innerHTML = 'Unsubscrive from thread';
		notify = true;
	} 
}

function ShowSmileys(event)
{
	FW_RelPlaceObj('simleysImg', 'smileyDiv', 74, 0);
	document.getElementById('smileyDiv').style.display = 'block';
	event.cancelBubble = true;
}

function SG(img)
// Simley mouseover
{
	img.style.backgroundColor = '#A1E8FC';
	img.style.border = '1px solid #3FC9EE';
}

function SN(img)
// Simley mouseout
{
	img.style.backgroundColor = '';
	img.style.border = '1px solid #A1E8FC';
}


function InsertAtCursor(obj, txt) 
{ 
	if (document.selection) { 
		obj.focus(); 
		sel = document.selection.createRange(); 
		sel.text = txt; 
	} else if (obj.selectionStart || obj.selectionStart == '0') { 
		var startPos = obj.selectionStart; 
		var endPos = obj.selectionEnd; 
		obj.value = obj.value.substring(0, startPos)+ txt + obj.value.substring(endPos, obj.value.length);
		obj.selectionStart += txt.length;
		 
	} else { 
		obj.value += txt; 
	}
	obj.focus(); 
} 


function AS(img)
// Add smiley.
{
	var s = img.src;
	s = s.replace(/\\/g, '/');
	var parts = s.split('/');
	s = parts[parts.length - 1];
	s = s.replace(/\..../i, '').toLowerCase();
	for (var f in smileys) {
		if (smileys[f] == s) {
			SN(img);
			document.getElementById('smileyDiv').style.display = 'none';
			var ip = document.getElementById('postMsg');
			InsertAtCursor(ip, f);
			return;
		}
	}
	alert('Error');
}

function CheckLength(l)
{	
	document.getElementById('lenspan').innerHTML = l;
	if (l > 3800) document.getElementById('lenspanall').style.color = '#ff0000';
	else document.getElementById('lenspanall').style.color = '';
}


function SendMsg()
{
	var postData = new Object;
	postData.body = document.getElementById('postMsg').value.replace(/\s+$/g, '');
	postData.postID = editPostID;
	if (postData.body.length > 4000) return alert('Sorry each message is limited to 4000 characters.');
	if (postData.body == '') return; // Nothing to add...
	postData.threadID = activeThreadID;
	if (document.getElementById('notifycb').checked) postData.notify = 1;
	var ret = XMLReq('/cgi-bin/forum/addPost.pl', postData);
	if (ret == null) return;
	
	//ViewThread(activeThreadID);
	//document.getElementById('postMsg').value = ''; // Clear out the last post.
	//document.getElementById('newMsg').style.display = 'none';
	//CheckLength(0);
	//if (editPostID != 0) 
	location.reload();
}

function CreateNewThread()
{
	var postData = new Object;
	postData.body = document.getElementById('postMsg').value.replace(/\s+$/g, '');
	if (postData.body.length > 4000) return alert('Sorry each message is limited to 4000 characters.');
	if (postData.body == '') return; // Nothing to add...
	postData.subject = document.getElementById('threadSubject').value.replace(/^\s+|\s+$/g, '');
	if (postData.subject == '') return document.getElementById('threadSubject').focus();
	postData.notify = (document.getElementById('notifyonpost').checked) ? '1' : '0';
	
	var ret = XMLReq('/cgi-bin/forum/newThread.pl', postData);
	if (ret == null) return;
	location.replace('/family/forum');
}

function PostReply(id)
{
	if (threadLocked) {
		alert('Sorry this thread is currently locked. Please visit again later');    
		return;
	}
	FW_RelPlaceObj('postTbl_' + id, 'newMsg', 814, document.getElementById('postTbl_' + id).offsetHeight);
	var nm = document.getElementById('newMsg');
	nm.style.height = '356px';
	nm.style.width = '1px';
	nm.style.display = 'block';
	document.getElementById('newMsg').startPos = null;
	animationCtrl.SetWanted('newMsg', '-814', null, 814, null, null, ReplyUp).numSteps = 10;
	animationCtrl.Start();
	editPostID = 0;
}

function ClosePostMsg()
{
	animationCtrl.Revert('newMsg', ReplyDown).numSteps = 10;
	animationCtrl.Start();
} 

function ReplyDown()
{
	document.getElementById('newMsg').style.display = 'none';
}

function ReplyUp()
{
	document.getElementById('postMsg').focus();
}

function EditPost(id)
{
	if (threadLocked) {
		alert('Sorry this thread is currently locked.');    
		return;
	}
	var node = selectSingleNode(xmlRet.responseXML, '/OceanWard/Posts/Post[@ID=' + id + ']');
	document.getElementById('postMsg').value = getText(node, 'Body'); 
	PostReply(id);
	editPostID = id;	
	
}

function GetCookie(name, defval)
{
	var cookies = document.cookie.split('; ');
	for (var x = 0; x < cookies.length; x++) {
		var parts = cookies[x].split('=');
		if (parts[0] == name) return unescape(parts[1]);
	}
	return defval;
}

function SetCookie(name, value, expires, path, domain, secure)
{
	if (!path) path = '/';
	if (expires == -1) expires = new Date(2037, 0, 31, 0, 0, 0, 0);
	var curCookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") + 
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = curCookie;	
}

