/* Javascript functions for ICGamers legacy frontpage
   (c) 2006 Xboxic
   
   Most of this code is modified from crisp's excellent menu code for the Gathering of Tweakers
   forum (http://gathering.tweakers.net), used with permission.
*/

//-- Time manipulation
var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var globdate = new Date();
document.cookie = '__timezoneoffset='+escape(globdate.getTimezoneOffset())+'; path=/';
var $time = Date.now || function(){
	return new Date().getTime();
};
function localizeTime(timestamp)
{
	return timestamp-(globdate.getTimezoneOffset()*60);
}
function formatLongDate(timestamp)
{
	var date = new Date(localizeTime(timestamp)*1000);
	return weekdays[date.getDay()]+' '+months[date.getMonth()]+' '+date.getDate()+' '+date.getFullYear()+' '+date.getHours()+':'+padLZ(date.getMinutes(), 2);
}
function formatLocalDate(timestamp)
{
	return new Date(localizeTime(timestamp)*1000).toLocaleString();
}
function formatShortDate(timestamp)
{
	var date = new Date(localizeTime(timestamp)*1000);
	var diff = $time()/1000 - timestamp;
	if(diff < 24*3600)
		return padLZ(date.getHours(),2) + ':' + padLZ(date.getMinutes(),2);
	else if(diff < 365*24*3600)
		return padLZ(date.getDate(),2) + '-' + padLZ(date.getMonth()+1,2);
	return padLZ(date.getMonth()+1,2) + '-\'' + padLZ(date.getFullYear()%100,2);	
}
function padLZ(number, length)
{
	var output = number.toString();
	while(output.length < length)
		output = '0'+output;
	return output;
}
function fixTimes()
{
	var els = getElementsByClassName('time');
	var re = new RegExp('(^|\\s)long(\\s|$)');
	for(var i = 0; i < els.length; i++) {
		var el = els[i];
		if(el.className && re.test(el.className))
			el.innerHTML = formatLongDate(el.title);
		else
			el.innerHTML = formatShortDate(el.title);
		el.title = formatLocalDate(el.title);
	}	
}

//-- Nested comments functions (cheers Brian at http://meidell.dk//index.php/archives/2004/09/04/nested-comments/)
function findBody(el)
{
	var divs = el.getElementsByTagName("div");
	var ret;
	for(var i = 0; i < divs.length; ++i) {
		if(divs.item(i).className.indexOf("body") > -1)
			return divs.item(i);
	}
	return false;
}

function onAddComment() {
	checkDocumentIntegrity();
	var el = document.getElementById("commentform");
	if(!el)
		alert("Woohay!");
	// Future release: Check if form is filled correctly and mark the form fields.
	el.submit();
}

function moveAddCommentBelow(theId, threadId, collapse)
{
	var addComment = document.getElementById("addcomment");
	if(!addComment)
	{
		alert("ERROR 1"); 
		return
	}
	var comment = document.getElementById(theId);
	addComment.parentNode.removeChild(addComment);
	//comment.insertBefore(addComment, node_after(getChildrenByClassName(comment, 'commentbody')[0]));
	comment.appendChild(addComment);
	addComment.style.marginLeft = "2em";
	if(comment.className.indexOf("alt")>-1) {
		addComment.className = addComment.className.replace(" alt", "");					
	} else {
		addComment.className += " alt";
	}
	var replyId = document.getElementById("comment_reply_ID");
	if(replyId == null)
	{
		alert("ERROR 2");
	}
	replyId.value = threadId;
	var reRootElement = document.getElementById("reroot");
	if(reRootElement == null)
	{
		alert("ERROR 3");
	}
	reRootElement.style.display = "block";
	var aTags = comment.getElementsByTagName("A");
	var anc = aTags.item(0).id;
	document.location.href = "#"+anc;
	document.getElementById("comment").focus();
}

function checkDocumentIntegrity()
{
	str = "";
	
	str += checkElement("reroot","div tag");
	str += checkElement("addcomment", "div tag");
	str += checkElement("comment_reply_ID", "hidden form field");
	str += checkElement("content", "div tag");
	str += checkElement("comment", "textfield");
	str += checkElement("addcommentanchor", "anchor tag");
	
	if(str != "")
		alert("ERROR 4");
}
	   
function checkElement(theId, elDesc)
{
	var el = document.getElementById(theId);
	if(!el)
	{
		if(elDesc == null)
			elDesc = "element";
		return "- The "+elDesc+" with the ID '" +theId + "' is missing\n"; 
	}
	else 
		return "";
}

function reRoot()
{
	var addComment = document.getElementById("addcomment");		
	addComment.style.marginLeft = "0";
	var reRootElement = document.getElementById("reroot");
	reRootElement.style.display = "none";
	var content = document.getElementById("comments");
	addComment.parentNode.removeChild(addComment);
	content.appendChild(addComment);
	addComment.className = addComment.className.replace(" alt", "");
	document.location.href = "#addcommentanchor";
	document.getElementById("comment").focus();				
	document.getElementById("comment_reply_ID").value = "0";
}			

function changeCommentSize(d)
{
	var el = document.getElementById("comment");
	var height = parseInt(el.style.height);
	if(!height && el.offsetHeight)
		height = el.offsetHeight;
	height += d;
	if(height < 20) 
		height = 20;
	el.style.height = height+"px";
}	

//-- Search functions
function clear_search()
{
	var input = document.getElementById('s');
	if(input.value == "Search news...")
		input.value = "";
}

function leave_search()
{
	var input = document.getElementById('s');
	if(input.value == "")
		input.value = "Search news...";
}

//-- Menu
var nav_current = [], nav_hide_delay = [];

function init_menu()
{
	var li = first_child(document.getElementById('mainmenulist'));
	while (li)
	{
		li.menuid = 'mainmenu';
		li.onmouseover = siteNavHover;
		li.onmouseout = siteNavHideCurrentSetDelay;
		li.submenu = init_submenu(li, 'mainmenu');
		li = node_after(li);
	}
}

function unload_menu()
{
	var li = first_child(document.getElementById('mainmenulist'));
	while (li)
	{
		li.submenu = null;
		li = node_after(li);
	}
}
window.onunload = unload_menu;

function init_submenu(menuitem, menuid)
{
	var submenu = first_child(menuitem);
	while (submenu)
	{
		if (submenu.tagName.toLowerCase() == 'div')
		{
			submenu.menuid = menuid;
			submenu.onmouseover = siteNavHideClearDelay;
			submenu.onmouseout = siteNavHideCurrentDelay;
			return submenu;
		}
		submenu = node_after(submenu);
	}

	return null;
}

function siteNavHover()
{
	if (this.menuid)
	{
		var submenu = this.submenu;
		var menuid = this.menuid;

		siteNavHideCurrent(menuid, submenu);

		if (submenu)
		{
			nav_current[menuid] = submenu;
			submenu.style.visibility = 'visible';
		}
	}
}

function siteNavHideCurrent(menuid, submenu)
{
	siteNavHideClearDelay(0, menuid);

	if (nav_current[menuid] && nav_current[menuid] != submenu)
	{
		nav_current[menuid].style.visibility = 'hidden';
		nav_current[menuid] = null;
	}
}

function siteNavHideCurrentFade(menuid)
{
	if (nav_current[menuid])
	{
		var opacity = nav_current[menuid].opacity - 0.05;
		if (opacity <= 0)
		{
			siteNavHideCurrent(menuid);
		}
		else
		{
			setOpacity(nav_current[menuid], opacity);
			nav_hide_delay[menuid] = setTimeout('siteNavHideCurrentFade(\''+menuid+'\')', 50);
		}
	}
}

function siteNavHideCurrentDelay()
{
	if (this.submenu)
	{
		siteNavHideCurrentSetDelay(0, this.menuid);
		return true;
	}

	return false;
}

function siteNavHideCurrentSetDelay(e, menuid)
{
	if (!menuid && this) menuid = this.menuid;

	if (menuid)
	{
		nav_hide_delay[menuid] = setTimeout('siteNavHideCurrent(\''+menuid+'\')', 500);
	}
}

function siteNavHideClearDelay(e, menuid)
{
	if (!menuid && this) menuid = this.menuid;

	if (menuid && nav_hide_delay[menuid])
	{
		clearTimeout(nav_hide_delay[menuid]);
		nav_hide_delay[menuid] = null;
	}
}

/* DOM functions */
function is_ignorable( nod )
{
	return (nod.nodeType == 8 || (nod.nodeType == 3 && !/[^\t\n\r ]/.test(nod.data)));
}

function node_before( sib )
{
	if (sib)
	{
		while ((sib = sib.previousSibling))
		{
			if (!is_ignorable(sib)) return sib;
		}
	}

	return null;
}

function node_after( sib )
{
	if (sib)
	{
		while ((sib = sib.nextSibling))
		{
			if (!is_ignorable(sib)) return sib;
		}
	}

	return null;
}

function last_child( par )
{
	if (par && par.nodeType == 1)
	{
		var res=par.lastChild;
		do
		{
			if (!is_ignorable(res)) return res;
		}
		while ((res = res.previousSibling));
	}

	return null;
}

function first_child( par )
{
	if (par && par.nodeType == 1)
	{
		var res=par.firstChild;
		do
		{
			if (!is_ignorable(res)) return res;
		}
		while ((res = res.nextSibling));
	}

	return null;
}

function getElementsByClassName(needle, tagname)
{
	if (!tagname) tagname = '*';
	var s = document.getElementsByTagName(tagname), i = s.length, e, r = [];
	var re = new RegExp('(^|\\s)' + needle + '(\\s|$)');

	while (i--)
	{
		e = s[i];
		if (e.className && re.test(e.className)) r.push(e);
	}

	return r;
}

function getChildrenByClassName(parent, needle)
{
	var s = first_child(parent), e, r = [];
	var re = new RegExp('(^|\\s)' + needle + '(\\s|$)');

	while (s)
	{
		if (s.className && re.test(s.className)) r.push(s);
		s = node_after(s);
	}

	return r;
}


function getDocumentProperty(prop)
{
	return document.documentElement && document.compatMode != 'BackCompat' ? document.documentElement[prop] : document.body[prop];
}