// GWC LIVECOMM by Geoff Creighton
// Copyright ©2007-2008 GWC Media. All Rights Reserved.
//
// This copy is licensed for use and modification by autosport.com
// Seek written permission for any other use

var ajax = null;
var statusArea = 'postresult';
var maxLength = 650;
var inhibitPost = false;
var ignoreList = '';
var userName = '';
var scrollFlag = true;
var longPost = false;
var usingRight = true;
var postUser = 0;
var postId = 0;
var startDate = null;

Ajax.Responders.register ({ 
	onCreate: function(requester) 
	{
		var date = new Date();
		
		//Append a timestamp salt to the Ajax request URL so that IE does not use a cached response
		requester.url =
			requester.url + (requester.url.indexOf('?') == -1 ? '?' : '&') +
			'salt=' + date.getTime();
	 }
  });
  
var align = getCookie('align');
if (!align) 
{
	align = 'left';
}

function startUpdate()
{
	startDate = new Date();
	setTimeout("doUpdate()", 2000);
	setInterval("doUpdate()", 15000);
	setInterval("googlePing()", 60000);
}

function doUpdate()
{
	try
	{
		ajax = 	new Ajax.Request('/liveupdate.php', {
		method:'get',
		evalScripts: false,
		parameters: {id: id, sequence: usn},
		onSuccess: function(transport)
		{    	
			//check response is valid xml
			if ((('responseXML' in transport) && transport.responseXML != null)
				&& transport.responseXML.firstChild)
			{
				var newUsn = transport.responseXML.getElementsByTagName("usn")[0].childNodes[0].nodeValue;
				
	
				if(usn == newUsn)
				{    		
					//test if usn has changed
					//don't go any further if not
					transport = null;
					return false;
				}
				else
				{
					usn = newUsn;
				}
				
				var update = transport.responseXML.getElementsByTagName("pageitems")[0].childNodes;
				
				for (var i=0; i < update.length; i++) 
				{
					if(update[i].attributes[0].nodeValue == 'add')
					{
						var commentsDiv = document.getElementById(update[i].nodeName);
						
						if(!commentsDiv)
						{
							//page does not have this element
							continue;
						}
						
						for (var j=0; j < update[i].childNodes.length; j++) 
						{
							//go through all new comments
							var comment = update[i].childNodes[j];
							
							if(comment.nodeValue == "\n")
							{
								continue;
							}
							var commentId = comment.lastChild.attributes[0].nodeValue;
							var content = '';
							
							if(null != comment.lastChild.firstChild)
							{
								content = comment.lastChild.firstChild.nodeValue;
							}
							
							var obj = document.getElementById(commentId);
							
							if(!obj)
							{
								if(content == '')
								{
									//ignore empty content for addition - comment may be not visible
									continue;
								}
								
								//do not have this comment - add it
								obj = document.getElementById('prototype_comment').cloneNode(false);
								obj.id = commentId;
								obj.innerHTML = content;
								
								if(update[i].nodeName == 'bbposts')
								{
									try
									{
										if(!isPosterIgnored(comment.lastChild.attributes.getNamedItem('forumuser').nodeValue))
										{
											//add post if not ignored
											commentsDiv.appendChild(obj);
										}
									}
									catch(err)
									{
										//user not specified so just add
										commentsDiv.appendChild(obj);
									}
									
									scrollPosts();
								}
								else
								{
									//append at top
									commentsDiv.insertBefore(obj, commentsDiv.firstChild);
								}
							}
							else
							{
								if(content == '')
								{
									//post has been deleted
									obj.parentNode.removeChild(obj);
								}
								else
								{
									//edit
									obj.innerHTML = content;
								}
							}
							
							
						}
					}
					else
					{
						if(update[i].nodeName)
						{
							var obj = document.getElementById(update[i].nodeName);
						}
						else
						{
							continue;
						}
						
						if(obj)
						{
							//find and replace
							if(null != update[i].firstChild.lastChild.firstChild)
							{
								var newElement = obj.cloneNode(false);
								newElement.innerHTML = update[i].firstChild.lastChild.firstChild.nodeValue;
								
								if(obj.nextSibling)
								{
									obj.parentNode.insertBefore(newElement, obj.nextSibling);
								}
								else
								{
									obj.parentNode.appendChild(newElement);
								}
								
								obj.parentNode.removeChild(obj);
								
								obj = null;
								newElement = null;
							}
						}
					}
				}
				
			}
		}});
    }
	catch(err)
	{
		//ignore and continue
	}
}

function googlePing()
{
	if (typeof (pageTracker) != null && typeof (pageTracker) != "undefined" && typeof (pageTracker != "function")) 
	{
		var pingDate = new Date();
		var pingTime = pingDate.getTime();
		pageTracker._trackEvent("Live_"+id, Math.floor((pingTime - startDate.getTime()) / 60000) + "_mins_dwell");
	}
}

function isPosterIgnored(user)
{
	if((typeof(ignoreList) != "undefined") && ignoreList != null && ignoreList != '')
	{
		if(ignoreList.include(user))
    	{
			return true;
    	}
    	else
    	{
    		return false;
    	}
	}
	else
	{
		return false;
	}
}

function scanForIgnored()
{
	if((typeof(ignoreList) == "undefined") || ignoreList == null || ignoreList == '')
	{
		return;
	}
	
	var postCont = document.getElementById('bbposts');
	
	if(null != postCont)
	{
		for(var n = postCont.firstChild; n != null; n = n.nextSibling)
		{
    		try
    		{				
				if(null == n || n.nodeType == "3")
				{
					continue;
				}
				
				if(isPosterIgnored(n.attributes.getNamedItem('forumuser').nodeValue))
				{
					//hide ignored post
					n.style.display = 'none';
				}
    		}
    		catch(err)
    		{
    			//ignore and continue
    		}
    	}
    }
}

function forumPost(pos)
{
	if(inhibitPost)
	{
		return;
	}
	
	inhibitPost = true;
	Element.update(pos+statusArea, 'Please Wait.');
	
	//wipe out any trailing newlines
	$(pos+'message').value = $(pos+'message').value.replace(/(\s*(\r?\n|\r))+$/, '');
	
	new Ajax.Request('/forum/forumpost.php', {
    method:'post',
    evalScripts: false,
    parameters: $(pos+'forum_post').serialize(true),
    onSuccess: function(transport)
    {
    	Element.update(pos+statusArea, transport.responseText);
    	
    	if(!transport.responseText.include('Sorry'))
    	{
			setTimeout("doUpdate()", 500);
			Form.reset(pos + 'forum_post');
			
    	}
    	
    	inhibitPost = false;
    	setTimeout("forumReady()", 5000);
    },
	onFailure: function (transport)
	{}
    });
}

function forumReady()
{
	var nameStr = '';
	
	if(userName != '')
	{
		nameStr = '<br>User: ' + userName;
	}
	
	Element.update('side_'+ statusArea, 'Quick Post Ready ' + nameStr);
	//Element.update('under_'+ statusArea, 'Quick Post Ready ' + nameStr);
	inhibitPost = false;
}

function showPostTools(post, user)
{	
	if(usingRight)
	{
		$('forumform').style.display = 'none';
	}
	
	Element.update('reportresult', 'Enter reason for post report');
	
	$('posttools').style.display = 'inline';
	
	postUser = user;
	postId = post;

}

function hidePostTools()
{
	$('posttools').style.display = 'none';
	
	if(usingRight)
	{
		$('forumform').style.display = 'inline';
	}
}

function showProfile()
{
	window.open('http://forums.autosport.com/index.php?showuser='+postUser);
}

function pmUser()
{
	window.open('http://forums.autosport.com/index.php?act=Msg&CODE=4&MID='+postUser);
}

function reportPost()
{	
	var answer = confirm("Are you sure you want to report this post? This is only to be used to report spam, advertising messages, and problematic (harassment, fighting, or rude) posts.");
	
	if (answer)
	{
		new Ajax.Request('/forum/forumreport.php', {
		method:'post',
		evalScripts: false,
		parameters: {threadid: $('report_threadid').value, postid: postId, reason: $('report_reason').value},
		onSuccess: function(transport)
		{
			Element.update('reportresult', transport.responseText);
			
			if(!transport.responseText.include('Sorry'))
			{
				Form.reset('post_tools');
				setTimeout("hidePostTools()", 5000);
			}
			
		},
		onFailure: function (transport)
		{}
		});
    }
}

function smilie(smile, pos)
{
    var postBox = document.getElementById(pos+'message');
    smile = ' ' + smile + ' ';
    
    if(!postBox)
    {
    	return;
    }
    
	if (document.selection) 
	{
		postBox.focus();
		sel = document.selection.createRange();
		sel.text = smile;
		postBox.focus();
	}
	else if (postBox.selectionStart || postBox.selectionStart == '0') 
	{
		var startPos = postBox.selectionStart;
		var endPos = postBox.selectionEnd;
		var scrollTop = postBox.scrollTop;
		postBox.value = postBox.value.substring(0, startPos)
		              + smile 
                      + postBox.value.substring(endPos, postBox.value.length);
		postBox.focus();
		postBox.selectionStart = startPos + smile.length;
		postBox.selectionEnd = startPos + smile.length;
		postBox.scrollTop = scrollTop;
	} 
	else 
	{
		postBox.value += smile;
		postBox.focus();
	}
}

var curHeight = 0;
var curPos = 0;
var newPos = 0;
var mouseStatus = 'up';
var minHeight = 260;
var maxHeight = minHeight;

function setPos(e)
{
	curEvent = (typeof event == 'undefined'?e:event);
	mouseStatus = 'down';
	curPos = curEvent.clientY;
	curHeight = getHeight();
}

function getPos(e)
{
	if(mouseStatus=='down')
	{
		curevent = (typeof event == 'undefined'?e:event);
		newPos = curevent.clientY;
		var pxMove = parseInt(newPos - curPos);
		var newHeight = parseInt(curHeight - pxMove);
		
		if(newHeight > (maxHeight))
		{
			newHeight = maxHeight;
		}
		else if(newHeight < minHeight)
		{
			newHeight = minHeight;
		}
		
		document.getElementById('forumpane').style.height = newHeight + 'px';
		document.getElementById('maincontent').style.padding = '0 0 ' + newHeight + 'px 0';
		scrollPosts();
		//document.selection.empty();
	}
}

function getHeight()
{
	tempHeight = document.getElementById('forumpane').style.height;
	heightArray = tempHeight.split('p');
	return parseInt(heightArray[0]);
}

function revealPane(doScroll)
{
	$('pane_wait').style.display='inline';
	
	if($('autoscroll').checked)
	{
		scrollFlag = true;
	}
	else
	{
		scrollFlag = false;
	}
	
	maxHeight = 0.6 * document.body.clientHeight;

	document.getElementById('maincontent').style.padding = '0 0 ' + getHeight() + 'px 0'; 
	new Effect.toggle('headline', 'blind', {duration: 0.1});
	new Effect.toggle('forumpane', 'blind', {duration: 0.1});
	Effect.BlindUp('sidebar_ad');
	
	if(doScroll)
	{
		setTimeout("scrollPosts()", 200);
	}

}

function hidePane()
{
	$('pane_wait').style.display='none';
	$('sidebar_ad').style.display='inline';
	$('interactbar').style.display='inline';
	new Effect.toggle('forumpane', 'blind', {duration: 0.1});
	new Effect.toggle('headline', 'blind', {duration: 0.1});
	document.getElementById('maincontent').style.padding = '0 0 1em 0';
}

function scrollPosts()
{
	if(scrollFlag)
	{
		var objDiv = document.getElementById('forumposts');
		objDiv.scrollTop = objDiv.scrollHeight;
	}
}

function toggleAutoscroll(changeCheck)
{
	if(scrollFlag)
	{
		if(changeCheck)
		{
			$('autoscroll').checked = false;
		}
		
		scrollFlag = false;
		return;
	}
	else
	{
		if(changeCheck)
		{
			$('autoscroll').checked = true;
		}
		
		scrollFlag = true;
		scrollPosts();
		return;
	}
}

function movePostBox()
{
	if(usingRight)
	{
		usingRight = false;
	}
	else
	{
		usingRight = true;
	}
	
	new Effect.toggle('underforumform', 'blind', {duration: 0.1});
	new Effect.toggle('forumform', 'blind', {duration: 0.1});
	setTimeout("scrollPosts()", 200);
}

function getCookie(name) 
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

function alignWindow(link)
{
	window.open(link,"align","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,scrollbars=no,resizable=no,copyhistory=no,width=10,height=10");
}

function checkPostLength(pos)
{
	 var postBox = document.getElementById(pos+'message');
	 
	 if(postBox.value.length >= maxLength - 50)
	 {
	 	longPost = true;
	 	
	 	if(postBox.value.length >= maxLength)
	 	{
	 		Element.update(pos + statusArea, 'Sorry, your post is too long.');
	 		inhibitPost = true;
	 	}
	 	else
	 	{
	 		Element.update(pos + statusArea, maxLength - postBox.value.length+ ' characters remaining.');
	 		inhibitPost = false;
	 	}
	 }
	 else
	 {
	 	if(longPost)
	 	{
	 		forumReady();
	 		longPost = false;
	 		inhibitPost = false;
	 	}
	 	
	 	return;
	 }
}