
function poke(get, actions) {
	var rand=Math.floor(Math.random()*100000000000);
	url = "http://log.newsvine.com/poke.gif?get=" + get + "&x=" + actions + "&rand=" + rand;
	document.getElementById('poke').src = url;
}

var img = new Image();
img.src = 'http://www.newsvine.com/_vine/images/_/icon_uparrow_animated.gif';
var voteSpan = null;
var killForm = false;
var trackerMode;
//var wrangler = new Wrangler();

function doVote(linkObj, contentId) {
	sendVote(contentId);
	var spanObj = linkObj.getElementsByTagName("span")[0];
	//alert(spanObj.id);
	if(spanObj.id) {
		// update top vote
		var voteSpan = getElement('voteCount_top_of_page');
		var doAnimate = spanObj.id == 'voteCount_top_of_page' ? true : false;
		if(voteSpan) incrementVote(voteSpan.parentNode, contentId, doAnimate);
		// update bottom vote
		voteSpan = getElement('voteCount_bottom_of_page');
		var doAnimate = spanObj.id == 'voteCount_bottom_of_page' ? true : false;
		if(voteSpan) incrementVote(voteSpan.parentNode, contentId, doAnimate);
	} else {
		incrementVote(linkObj, contentId, true);
	}
}

function doVoteToolbar(linkObj, contentId) {
	sendVote(contentId);
	var spanObj = linkObj.getElementsByTagName("span")[1];
	if(spanObj.id) {	
		// update top vote
		var voteSpan = getElement('voteCount_top_of_page');
		if(voteSpan) incrementVoteToolbar(voteSpan.parentNode.parentNode, contentId);
		// update bottom vote
		voteSpan = getElement('voteCount_bottom_of_page');
		if(voteSpan) incrementVoteToolbar(voteSpan.parentNode.parentNode, contentId);
		//remove vote checkbox
		if (getElement('alsoVote'))
			getElement('alsoVote').style.display = 'none';
	} else {
		incrementVoteToolbar(linkObj, contentId);
	}
}


function incrementVote(linkObj, contentId, doAnimate) {
	var divObj = linkObj.parentNode;
	divObj.style.backgroundColor = '#e7e7e7';
	divObj.innerHTML = '<span>'+(linkObj.getElementsByTagName("span")[0].innerHTML*1.0+1)+'</span>';
	var img = document.createElement("img");
	divObj.appendChild(img);
	img.src = 'http://www.newsvine.com/_vine/images/_/icon_check.gif';
	img.style.width = '16px';
	img.style.height = '12px';
	if(doAnimate) animateVote(divObj);
}

function sendVote(contentId) {
	poke("c" + contentId, "5");
	doAjax("/_action/user/doVote", null, 'contentId='+contentId);
}
 
function incrementVoteToolbar(linkObj, contentId) {
	var increm = linkObj.getElementsByTagName("span")[1].innerHTML*1.0+1;
	var incremText = increm == 1 ? 'Vote' : 'Votes';	
	linkObj.parentNode.className = 'b_darkgrey noborder';
	linkObj.innerHTML = '<span class="b_darkgrey_right"><img src="http://www.newsvine.com/_vine/images/_/icon_b_check.gif"/> '+increm+' '+incremText+'</span>';
	//animate
	getElement('vote_anim').style.top = '-60px';
	getElement('vote_anim').style.display = 'block';		
	getElement('vote_anim').childNodes[0].src = 'http://www.newsvine.com/_vine/images/_/icon_b_vote_anim.gif';
	setTimeout("document.getElementById('vote_anim').style.display = 'none';", 2000);
} 


function doCommentVote(linkObj, contentId, commentId) {
	var divObj = linkObj.parentNode;
	divObj.style.backgroundColor = '#e7e7e7';
	var newInput = (linkObj.getElementsByTagName("span")[0].innerHTML*1.0+1)+'';
	if(newInput == 'NaN') newInput = '&nbsp;';
	divObj.innerHTML = '<span>'+newInput+'</span>';
	var img = document.createElement("img");
	divObj.appendChild(img);
	img.src = 'http://www.newsvine.com/_vine/images/_/icon_check.gif';
	img.style.width = '16px';
	img.style.height = '12px';
	animateVote(divObj);
	doAjax("/_action/user/doCommentVote", null, 'contentId='+contentId+'&commentId='+commentId);
	poke("c" + contentId, "24&d="+commentId);
}


function animateVote(divObj) {
	var img = document.createElement("img");
	if (detect.browser == 'safari') {
		divObj.appendChild(img);	
	}
	img.src = 'http://www.newsvine.com/_vine/images/_/icon_uparrow_animated.gif';
	img.style.position = 'absolute';
	img.style.bottom = '0px';
	img.style.left = '0px';
	img.style.height = '60px';
	img.style.width = '16px';
	if (detect.browser != 'safari') {
		divObj.appendChild(img);	
	}
	voteDiv = divObj;
	setTimeout("endVoteAnimation();", 1000);
}

function getFirstChildNode(node, key) {
	var elements = node.getElementsByTagName(key);
	if (elements.length > 0) {
		if (elements[0].firstChild != null) {
			return elements[0].firstChild.nodeValue;
		}
	}
	return '';
}

function endVoteAnimation() {
	divObj = voteDiv;
	divObj.removeChild(divObj.getElementsByTagName("img")[1]);
	voteDiv = null;
}


function voteInPoll(form) {
	var pollAnswer = -1;
	var items = form.elements;
	for(var i=0; i < items.length; i++) {
		if(items[i].name == 'pollAnswer' && items[i].checked) {
			pollAnswer = items[i].value;
			break;
		}
	}
	if(pollAnswer == -1) {
		alert('Please select an option before voting.');
		return false;
	}
	pollId = items.pollId.value;
	items.doVote.disabled = true;
	items.doVote.value = 'Voting ...';
	poke("c" + items.contentId.value, "6&d="+pollId);
	var data = 'doVote=1&pollId='+pollId+'&pollAnswer='+pollAnswer+'&contentId='+items.contentId.value;
	doAjax('/_tools/manage/polls', function(ajax) {
		getElement('pollFormDiv_'+pollId).innerHTML = ajax.responseText;
	}, data);
}


function togglePollForm(pollId) {
	if(getElement('pollResultsDiv_'+pollId).style.display == 'block') {
		getElement('pollFormDiv_'+pollId).style.display = 'block';
		getElement('pollResultsDiv_'+pollId).style.display = 'none';
	} else {
		getElement('pollFormDiv_'+pollId).style.display = 'none';
		getElement('pollResultsDiv_'+pollId).style.display = 'block';
	}
}



function showSubNav(item) {
	items = item.parentNode.getElementsByTagName('UL');
	if(items.length > 0) {
		items[0].style.display = 'block';
		items[0].style.top = item.offsetHeight+'px';
		items[0].style.left = item.offsetLeft+'px';
	}
}


function hideSubNav(item) {
	items = item.parentNode.getElementsByTagName('UL');
	if(items.length > 0) items[0].style.display = 'none';
}


function getLoginWidgetMsg(mode) {
	if(mode == 'convTracker') msg = 'You must have a free Newsvine account to use the Conversation Tracker.';
	else if(mode == 'topNav') msg = 'Existing users log in below. New users please register for a new account.';
	else if(mode == 'watchlistPageLink') msg = 'You must have a free Newsvine account to use the personalized Watchlist.';
	else if(mode == 'watchButton') msg = 'You must have a free Newsvine account to watch tags or authors.';
	else if(mode == 'contentVote') msg = 'You must have a free Newsvine account to cast votes for articles.';
	else if(mode == 'reportContent') msg = 'You must have a free Newsvine account to report content.';
	else if(mode == 'commentVote') msg = 'You must have a free Newsvine account to cast votes for comments.';
	else if(mode == 'reportComment') msg = 'You must have a free Newsvine account to report comments.';
	else msg = 'Existing users log in below. New users please register for a new account.';
	return msg;
}


function loginWidget(mode) {
	var iHTML = '';
	iHTML += '<a href="javascript:void(0);" onclick="this.parentNode.parentNode.removeChild(this.parentNode);return false;"><img src="http://www.newsvine.com/_vine/images/_/b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
	iHTML += '<div style="margin: 15px"><p style="font-weight: normal">'+getLoginWidgetMsg(mode)+'</p>';
	iHTML += '<div class="loginWidget_left"><h3>New Users:</h3><div style="zoom:1"><a href="http://www.newsvine.com/_tools/new/user" class="noborder"><img src="http://www.newsvine.com/_vine/images/_/b_register.gif" /></a></div></div>';
	iHTML += '<div class="loginWidget_right"><h3>Existing Users:</h3><form method="post" action="https://www.newsvine.com/_tools/user/login">';
	iHTML += '<input type="hidden" name="m" value="login" /><span class="loginWidget_message"></span>';
	iHTML += '<div>E-Mail: <input type="text" name="email" style="width: 130px; margin-bottom: 5px" /></div>';
	iHTML += '<div>Password: <input type="password" name="pass" style="width: 130px; margin-bottom: 5px" /></div>';
	iHTML += '<div><a href="javascript:void(0);" onclick="toggleForgotPass(this, true, \''+mode+'\');" style="color: #fff; font-size: 9px">Forgot Password?</a></div>';
	iHTML += '<div style="zoom:1"><input type="image" src="http://www.newsvine.com/_vine/images/_/b_login.gif" style="margin-top: 8px;" /></div>';
	iHTML += '</form></div><div style="clear: both"></div></div>';
	return iHTML;
}

function forgotPassWidget(mode) {
	var iHTML = '';
	iHTML += '<a href="javascript:void(0);" onclick="this.parentNode.parentNode.removeChild(this.parentNode);return false;"><img src="http://www.newsvine.com/_vine/images/_/b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
	iHTML += '<div style="margin: 15px"><p style="font-weight: normal">'+getLoginWidgetMsg(mode)+'</p>';
	iHTML += '<div class="loginWidget_left"><h3>New Users:</h3><div style="zoom:1"><a href="http://www.newsvine.com/_tools/new/user" class="noborder"><img src="http://www.newsvine.com/_vine/images/_/b_register.gif" /></a></div></div>';
	iHTML += '<div class="loginWidget_right"><p id="forgotPassEmailMessage">Please enter the e-mail address or domain name you registered with:</p><form method="post" action="http://www.newsvine.com/_tools/user/login">';
	iHTML += '<input type="hidden" name="m" value="forgot" /><span class="loginWidget_message"></span>';
	iHTML += '<div id="forgotPassEmailDiv">E-Mail/Domain:&nbsp;&nbsp;<input type="text" name="email" style="width: 130px; margin-bottom: 5px" /></div>';
	iHTML += '<div id="backToLoginDiv"><a href="javascript:void(0);" onclick="toggleForgotPass(this, false, \''+mode+'\');" style="color: #fff; font-size: 9px">Back to Login</a></div>';
	iHTML += '<div id="forgotPassButton" style="zoom:1"><input type="image" src="http://www.newsvine.com/_vine/images/_/b_submit.gif" style="margin-top: 8px;" /></div>';
	iHTML += '</form></div><div style="clear: both"></div></div>';
	return iHTML;
}




function toggleForgotPass(thisItem, showForgotPassWidget, mode) {
	if(showForgotPassWidget) {
		thisItem.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML = forgotPassWidget(mode);
	} else {
		thisItem.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML = loginWidget(mode);
	}
}


function setLoginWidgetPosition(thisItem, newDiv, mode) {
	if(mode == 'topNav') {
		topItem = thisItem.parentNode;
		newDiv.style.top = (topItem.offsetTop+topItem.offsetHeight-1)+'px';
		newDiv.style.right = '0px';
	} else if(mode == 'watchlistPageLink') {
		newDiv.style.top = (getElement('header').offsetHeight+thisItem.offsetHeight-1)+'px';
		newDiv.style.left = '0px';
	} else if(mode == 'watchButton') {
		newDiv.style.top = (getElement('header').offsetHeight+getElement('main_nav').offsetHeight+getElement('sub_nav').offsetHeight+thisItem.parentNode.offsetHeight+10)+'px';
		newDiv.style.left = thisItem.parentNode.offsetLeft+'px';
	} else if(mode == 'commentVote') {
		topItem = thisItem.parentNode.parentNode.parentNode.parentNode;
		newDiv.style.top = (topItem.offsetTop+topItem.offsetHeight-21)+'px';
		newDiv.style.right = '71px';
	} else if(mode == 'reportComment') {
		topItem = thisItem.parentNode.parentNode.parentNode.parentNode;
		newDiv.style.top = getElement('commentsDiv').offsetTop + (topItem.offsetTop+topItem.offsetHeight-21)+'px';
		newDiv.style.right = '46px';
	} else {
		newDiv.style.top = (thisItem.offsetTop+thisItem.offsetHeight)+'px';
		newDiv.style.left = (thisItem.offsetLeft)+'px';
	}
}


function collapseComment(commentId) {
	var commentDiv = getElement('commentText_'+commentId);
	if(commentDiv && commentDiv.style.display == 'block') {
		commentDiv.style.display = 'none';
	} else if(commentDiv) {
		commentDiv.style.display = 'block';
	}
}

function setUserBG() {
	if(getCookie('assumedUser')) {
		document.body.style.backgroundColor = 'red';
	}
}

function toggleLogin(thisItem, mode, id) {

	var divId = 'loginWidget_'+mode+(id ? '_'+id : '');
	if(getElement(divId)) {
		getElement(divId).parentNode.removeChild(getElement(divId));
	} else {
		var newDiv = document.createElement('DIV');
		newDiv.id = divId;
		newDiv.className = 'loginWidget';
		newDiv.innerHTML = loginWidget(mode);
		newDiv.style.zIndex = 99999;
		setLoginWidgetPosition(thisItem, newDiv, mode);
		getElement('master').appendChild(newDiv);
		if(newDiv.getElementsByTagName('form').length > 0) {
			newDiv.getElementsByTagName('form')[0].elements.email.focus();
		}
	}
	
}

function doWidgetForgotPass(thisItem) {
	items = thisItem.form.elements;
	msgDiv = thisItem.parentNode.parentNode.getElementsByTagName('SPAN')[0];
	if(!items.email.value.trim()) {
		msgDiv.innerHTML = 'Please enter a e-mail address<br>or domain name.';
	} else {
		var domain = '';
		var email = items.email.value.trim();
		if(email.indexOf('@') == -1) {
			domain = '&domain='+encodeURIComponent(email);
			email = '@';
		}
		var url = '/_login/proxy?path=/servista/reset&t=cp&email='+encodeURIComponent(email)+domain+'&rd=http://www.newsvine.com/_vine/images/_/blank.gif';
		doAjax(url);
		getElement('forgotPassEmailMessage').innerHTML = 'An e-mail has been sent to your Inbox. Please follow the instructions in the email to reset your password.';
		getElement('forgotPassButton').innerHTML = '<a href="javascript:void(0);" class="noborder" onclick="this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode.parentNode.parentNode);return false;"><img src="http://www.newsvine.com/_vine/images/_/b_closewindow.gif" /></a>';
		getElement('backToLoginDiv').style.display = 'none';
		getElement('forgotPassEmailDiv').style.display = 'none';
	}
}


function doWidgetLogin(thisItem) {
	items = thisItem.form.elements;
	msgDiv = thisItem.parentNode.parentNode.getElementsByTagName('SPAN')[0];
	if(!items.email.value.trim() || !items.pass.value.trim()) {
		msgDiv.innerHTML = 'No match. Please try again.';
	} else {
		msgDiv.innerHTML = 'Checking ...';
		var data = '';
		var email = items.email.value.trim();
		if(email.indexOf('@') == -1) {
			data = 'domain='+encodeURIComponent(email);
		} else {
			data = 'email='+encodeURIComponent(email);
		}
		data += '&pass='+encodeURIComponent(items.pass.value.trim());
		doAjax("/_action/user/doLogin", function(AJAX) {
			if(AJAX.responseText == 1) {
				msgDiv.innerHTML = 'Logging in ...';
				location.href = location.href;
			} else {
				msgDiv.innerHTML = 'No match. Please try again.';
			}
		}, data);
	}
	return false;
}


function doEmailThis(thisItem) {
	items = thisItem.form.elements;
	if(!items.emails.value.trim()) {
		alert('Please enter an email address.');
		return false;
	}
	var data = 'contentId='+items.emailThisContentId.value.trim()+'&emails='+encodeURIComponent(items.emails.value.trim())+'&message='+encodeURIComponent(items.message.value.trim());
	doAjax("/_action/article/emailThis", function(AJAX) {}, data);
	poke('c'+items.emailThisContentId.value.trim(), 25);
	var msgDiv = thisItem.parentNode.parentNode.parentNode;
	msgDiv.innerHTML = 'An email has been sent.';
	emailThisCloseDiv = msgDiv.parentNode.parentNode;
	setTimeout('emailThisCloseDiv.parentNode.removeChild(emailThisCloseDiv);', 1000);
	return false;
}

function checkEmailThisCount(thisItem, contentId) {
	if(!thisItem.value.trim()) {
		getElement('emailsRemaining_'+contentId).innerHTML = '';
	} else {
		thisItem.value = thisItem.value.replace(';', ',');
		var emails = thisItem.value.split(',');
		var emailCount = 20 - emails.length + 1;
		if(emailCount != 20) {
			getElement('emailsRemaining_'+contentId).innerHTML = ' '+emailCount+' remaining,';
		}
	}
}

function emailThisWidget(contentId, headline) {
	var iHTML = '';
	iHTML += '<a href="javascript:void(0);" onclick="this.parentNode.parentNode.removeChild(this.parentNode);return false;"><img src="http://www.newsvine.com/_vine/images/_/b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
	iHTML += '<div style="margin: 15px"><p>E-mailing: <strong>'+headline+'</strong></p>';
	iHTML += '<div><form method="post">';
	iHTML += '<input type="hidden" name="emailThisContentId" value="'+contentId+'" />';
	iHTML += '<div>Recipient E-Mails (20 max,<span id="emailsRemaining_'+contentId+'"></span> separate with commas):</div>';
	iHTML += '<div><textarea name="emails" style="width: 100%; height: 40px; margin: 5px 0 5px 0" onkeyup="return checkEmailThisCount(this, '+contentId+');"></textarea></div>';
	iHTML += '<div>Your Message (Optional):</div>';
	iHTML += '<div><textarea name="message" style="width: 100%; height: 40px; margin: 5px 0 5px 0"></textarea></div>';
	iHTML += '<div style="zoom:1"><input type="image" src="http://www.newsvine.com/_vine/images/_/b_send.gif" style="margin-top: 8px" onclick="doEmailThis(this); return false;" /></div>';
	iHTML += '</form></div></div><div style="clear: both"></div></div>';
	return iHTML;
}


function emailThis(thisItem, contentId, headline) {
	var divId = 'emailThisWidget_'+contentId;
	if(getElement(divId)) {
		getElement(divId).parentNode.removeChild(getElement(divId));
	} else {
		var newDiv = document.createElement('DIV');
		newDiv.id = divId;
		newDiv.className = 'loginWidget';
		newDiv.innerHTML = emailThisWidget(contentId, headline);
		newDiv.style.zIndex = 99999;
		//alert(thisItem.className);
		if (thisItem.id == 'toolbar_buttons') {
			newDiv.style.top = (thisItem.childNodes[2].offsetTop+thisItem.childNodes[2].offsetHeight)+'px';
			newDiv.style.left = (thisItem.childNodes[2].offsetLeft)+'px';
		} else {
			newDiv.style.top = (thisItem.offsetTop+thisItem.offsetHeight)+'px';
			newDiv.style.left = (thisItem.offsetLeft)+'px';		
		}
		getElement('master').appendChild(newDiv);
		if(newDiv.getElementsByTagName('textarea')[0]) newDiv.getElementsByTagName('textarea')[0].focus();
	}
}



function addTag (element, contentId) {

	if(getElement('addtagdiv_'+contentId)) {
		getElement('master').removeChild(getElement('addtagdiv_'+contentId));
	} else {
	
		var windowWidth,windowHeight;
	
		if (self.innerHeight) {
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	
		var formbox,top,left;
		top = element.offsetTop+element.offsetHeight;
		if (windowWidth - 420 > element.offsetLeft+document.getElementById('master').offsetLeft) {
			left = element.offsetLeft;
		} else {
			left = element.offsetLeft - 420 + element.offsetWidth;
		}
	
		formbox = '<div class="addtag_form" style="position: absolute; top:'+top+'px; left:'+left+'px"><a href="#" onclick="this.parentNode.parentNode.removeChild(this.parentNode);return false"><img src="http://www.newsvine.com/_vine/images/_/b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
		formbox += '<form method=POST action="/_action/user/addTags"><input type=hidden name=redirect value="' + location.href + '">';
		formbox += '<input type=hidden name=c value=' + contentId + '>';
		formbox += '<p>Enter more tags into the box below to help further classify this story:</p>';
		formbox += '<input type="text" name="tags" value="" class="flat" style="width: 300px" /><input type="submit" name="Add" value="Add" /></form></div>';
		var newDiv = document.createElement("div");
		document.getElementById('master').appendChild(newDiv);
		newDiv.innerHTML = formbox;
		newDiv.id = 'addtagdiv_'+contentId;
		newDiv.getElementsByTagName('input')[2].focus();
		
	}
}

function reportThis (element, contentId, authorid) {

	if(getElement('reportthisDiv_'+contentId)) {
		getElement('master').removeChild(getElement('reportthisDiv_'+contentId));
	} else {
	
		var windowWidth,windowHeight;
	
		if (self.innerHeight) {
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	
		var formbox,top,left;
		
		if (element.id == 'toolbar_buttons') {
			top = document.getElementById('report_button').offsetTop+document.getElementById('report_button').offsetHeight;
			left = document.getElementById('report_button').offsetLeft;
		} else {
			top = element.offsetTop+element.offsetHeight;
			if (windowWidth - 146 > element.offsetLeft+document.getElementById('master').offsetLeft) {
				left = element.offsetLeft;
			} else {
				left = element.offsetLeft - 146 + element.offsetWidth;
			}	
		}
		
		formbox = '<div class="reportthis_form" style="position: absolute; top:'+top+'px; left:'+left+'px"><a href="#" onclick="this.parentNode.parentNode.removeChild(this.parentNode);return false"><img src="http://www.newsvine.com/_vine/images/_/b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
		formbox += '<p>Report This Item As:</p>';
		formbox += '<ul><li><a href="#" onclick="thisReported(this, '+contentId+', 16, \''+location.href+'\'); return false;">Duplicate Story</a></li><li><a href="#" onclick="thisReported(this, '+contentId+', 12, \''+location.href+'\'); return false;">Miscategorized/Off-Topic</a></li><li><a href="#" onclick="thisReported(this, '+contentId+', 20, \''+location.href+'\'); return false;">Broken or Pay Link</a></li><li><a href="#" onclick="thisReported(this, '+contentId+', 18, \''+location.href+'\'); return false;">Inaccurate</a></li><li><a href="#" onclick="thisReported(this, '+contentId+', 17, \''+location.href+'\'); return false;">Advertising</a></li><li><a href="#" onclick="thisReported(this, '+contentId+', 19, \''+location.href+'\'); return false;">Misconduct/Unlawful</a></li><li><a style="background-color:#333" href="#" onClick="ignoreThisUser(this, '+authorid+');return false;">Ignore This Author</a></li>';
		formbox += '</ul>';
		formbox += '</div>';
		var newDiv = document.createElement("div");
		document.getElementById('master').appendChild(newDiv);
		newDiv.id = 'reportthisDiv_'+contentId;
		newDiv.innerHTML = formbox;
	
	}
}

function ignoreThisUser(thisItem, user) {
	var data = 'user='+user+'&ignoreState=1';
	if (confirm("Ignoring this author will collapse their comments and keep them from appearing on your front page. To unignore this author, please visit your friends page. Are you sure you want to ignore this Author?")) {
		doAjax('/_action/user/ignoreUser', null, data);
		if (getElement('ignoreUserDiv')) getElement('ignoreUserDiv').style.display = 'none';
		
		if(thisItem && thisItem.parentNode && thisItem.parentNode.parentNode) {
			reportedChild = thisItem.parentNode.parentNode;
			reportedParent = reportedChild.parentNode;
			reportedGrandio = reportedParent.parentNode;
			var text = reportedParent.getElementsByTagName('p')[0];
			text.innerHTML = 'Thank you!';
			reportedParent.removeChild(reportedChild);
			setTimeout('reportedGrandio.removeChild(reportedParent);', 750);
		}
	}
}

function unignoreUser(item, user) {
	var data = 'user='+user+'&ignoreState=0';
	changeFriendCount('ignoredCountDiv', -1);
	removeFriendNode(item);
	doAjax('/_action/user/ignoreUser', null, data);
}

function thisReported(thisItem, contentId, type, referer) {
	poke("c" + contentId, type);
	reportedChild = thisItem.parentNode.parentNode;
	reportedParent = reportedChild.parentNode;
	reportedGrandio = reportedParent.parentNode;
	var text = reportedParent.getElementsByTagName('p')[0];
	text.innerHTML = 'Thank you!';
	reportedParent.removeChild(reportedChild);
	setTimeout('reportedGrandio.removeChild(reportedParent);', 750);
}


function reportComment(element, contentId, commentId, authorid) {

	if(getElement('reportCommentDiv_'+commentId)) {
		getElement('master').removeChild(getElement('reportCommentDiv_'+commentId));
	} else {
	
		var windowWidth,windowHeight;
	
		if (self.innerHeight) {
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	
		var formbox,top,left;
		
		// CHECKS TO SEE IF ITS A CHILD COMMENT
		if (!getElement('c'+commentId).parentNode.parentNode.id.match(/c[0-9]+/))	 {
			top = getElement('commentsDiv').offsetTop + getElement('c'+commentId).offsetTop + element.offsetTop + 20;
			left = getElement('commentsDiv').offsetLeft + getElement('c'+commentId).offsetLeft + element.offsetLeft - 146;
		} else {
			top = getElement('commentsDiv').offsetTop + getElement('c'+commentId).offsetTop + getElement('c'+commentId).parentNode.parentNode.offsetTop + element.offsetTop + 20;
			left = getElement('commentsDiv').offsetLeft + getElement('c'+commentId).offsetLeft + getElement('c'+commentId).parentNode.parentNode.offsetLeft + element.offsetLeft - 146;			
		}
	
		formbox = '<div class="reportthis_form" style="z-index: 5000;position: absolute; top:'+top+'px; left:'+left+'px"><a href="#" onclick="this.parentNode.parentNode.removeChild(this.parentNode);return false"><img src="http://www.newsvine.com/_vine/images/_/b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
		formbox += '<p>Report This Item As:</p>';
	formbox += '<ul><li><a href="#" onclick="commentReported(this, '+contentId+', '+commentId+', 22, \''+location.href+'\'); return false;">No Value</a></li><li><a href="#" onclick="commentReported(this, '+contentId+', '+commentId+', 23, \''+location.href+'\'); return false;">Inflammatory</a></li><li><a href="#" onclick="commentReported(this, '+contentId+', '+commentId+', 21, \''+location.href+'\'); return false;">Advertising</a></li><li><a style="background-color:#333" href="javascript: void(0)" onClick="ignoreThisUser('+authorid+');return false;">Ignore This Author</a></li>';
		formbox += '</ul>';
		formbox += '</div>';
		var newDiv = document.createElement("div");
		document.getElementById('master').appendChild(newDiv);
		newDiv.id = 'reportCommentDiv_'+commentId;
		newDiv.innerHTML = formbox;
	
	}
}

function commentReported(thisItem, contentId, commentId, type, referer) {
	type += '&d='+commentId;
	poke("c" + contentId, type);
	reportedChild = thisItem.parentNode.parentNode;
	reportedParent = reportedChild.parentNode;
	reportedGrandio = reportedParent.parentNode;
	var text = reportedParent.getElementsByTagName('p')[0];
	text.innerHTML = 'Thank you!';
	reportedParent.removeChild(reportedChild);
	setTimeout('reportedGrandio.removeChild(reportedParent);', 750);
}


function deleteComment(thisItem, contentId, commentId) {
	if(confirm('By clicking "OK", this comment will be deleted and the author of the comment will be notified by e-mail.\n\nPlease use this feature only to delete spam or content which violates the Code of Honor.')) {
		var data = 'contentId='+contentId+'&commentId='+commentId;
		doAjax("/_action/admin/article/deleteComment", function() {}, data);
		var comment = thisItem.parentNode.parentNode.parentNode.parentNode.parentNode;
		comment.className += ' faded';
		thisItem.parentNode.innerHTML = '<a href="javascript:void(0);" onclick="restoreComment(this, '+contentId+', '+commentId+');return false;" title="Restore Comment"><img src="http://www.newsvine.com/_vine/images/_/icon_add_mini.gif"></a>';
		if(getElement('commentStatus_'+commentId)) getElement('commentStatus_'+commentId).innerHTML = 'Deleted';	
	}
}


function restoreComment(thisItem, contentId, commentId) {
	var data = 'contentId='+contentId+'&commentId='+commentId;
	doAjax("/_action/admin/article/restoreComment", function() {}, data);
	var comment = thisItem.parentNode.parentNode.parentNode.parentNode.parentNode;
	comment.className = comment.className.replace(' faded', '');
	thisItem.parentNode.innerHTML = '<a href="javascript:void(0);" onclick="deleteComment(this, '+contentId+', '+commentId+');return false;" title="Delete Comment"><img src="http://www.newsvine.com/_vine/images/_/icon_trash_mini.gif"></a>';
	if(getElement('commentStatus_'+commentId)) getElement('commentStatus_'+commentId).innerHTML = 'Restored';
}


function whatsThis (element, cmsId) {
	if(getElement('cms_'+cmsId)) {
		getElement('cms_'+cmsId).parentNode.parentNode.removeChild(getElement('cms_'+cmsId).parentNode);
	} else {

		doAjax('/_cms/help/tooltip?tipId='+cmsId, function(ajax) {
			getElement('cms_'+cmsId).innerHTML = ajax.responseText;
		});
	
		var windowWidth,windowHeight;
	
		if (self.innerHeight) {
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	
		var formbox,top,left;
		top = element.offsetTop+element.offsetHeight;
		var masterDiv = getElement('master');
		if(!masterDiv) { // try wineHeader master div
			masterDiv = getElement('master_miniwin');
		}

		if (windowWidth - 420 > element.offsetLeft+masterDiv.offsetLeft) {
			left = element.offsetLeft;
		} else {
			left = element.offsetLeft - 420 + element.offsetWidth;
		}
		var newDiv = document.createElement("div");
		masterDiv.appendChild(newDiv);
		newDiv.innerHTML = '<div class="whatsThis_div" id="cms_'+cmsId+'" style="position: absolute; top:'+top+'px; left:'+left+'px"></div>';
		
	}

}

/*******************************************************************************
THREADS, GROUPS, FRIEND LISTS
*******************************************************************************/

function toggleNewFriendList() {
	if(getElement('newFriendList')) {
		if(getElement('newFriendList').style.display == 'block') {
			getElement('newFriendList').style.display = 'none';
		} else {
			getElement('newFriendList').style.display = 'block';
		}
	}
}


var activeNewFriendDivId = '';
function toggleFriendTab(divId) {
	getElement('newFriend_tab_'+activeNewFriendDivId).className = '';
	getElement('newFriend_tool_'+activeNewFriendDivId).style.display = 'none';
	activeNewFriendDivId = divId;
	getElement('newFriend_tab_'+activeNewFriendDivId).className = 'active';
	getElement('newFriend_tool_'+activeNewFriendDivId).style.display = 'block';
}



function add2FriendList(item) {
	var newItem = document.createElement('li');
	newItem.id = item.id;
	newItem.innerHTML = '&nbsp;<a href="javascript:void(0);" onclick="removeFromFriendList(this.parentNode);"><img src="/_vine/images/_/b_minus.gif"></a>';
	newItem.innerHTML += '<a href="javascript:void(0);" onclick="removeFromFriendList(this.parentNode);">'+item.childNodes[item.childNodes.length-1].innerHTML+'</a>';
	newItem.removeChild(newItem.childNodes[0]);
	item.parentNode.removeChild(item);
	getElement('newFriendListMembers').appendChild(newItem);
}


function removeFromFriendList(item) {
	var newItem = document.createElement('li');
	newItem.id = item.id;
	newItem.innerHTML = '&nbsp;<a href="javascript:void(0);" onclick="add2FriendList(this.parentNode);"><img src="/_vine/images/_/b_plus.gif"></a>';
	newItem.innerHTML += '<a href="javascript:void(0);" onclick="add2FriendList(this.parentNode);">'+item.childNodes[item.childNodes.length-1].innerHTML+'</a>';
	newItem.removeChild(newItem.childNodes[0]);
	item.parentNode.removeChild(item);
	getElement('allMyFriendsList').appendChild(newItem);
}


function Friend(domainName, displayName) {

	this.domainName = domainName;
	this.displayName = displayName;
	this.divId = 'friend_'+domainName;

	this.add2MasterList = function() {
		var li = document.createElement('li');
		li.id = this.divId;
		li.innerHTML = '&nbsp;<a href="javascript:void(0);" onclick="add2NewFriendList(this.parentNode);"><img src="/_vine/images/_/b_plus.gif"></a>';
		li.innerHTML += '<a href="javascript:void(0);" onclick="add2NewFriendList(this.parentNode);">'+this.displayName+'</a>';
		getElement('allMyFriendsList').appendChild(li);
	}

}

var activeFriendListMembers = '';
function showFriendListMembers(listId) {
	if(activeFriendListMembers) {
		getElement(activeFriendListMembers).style.display = 'none';
	}
	activeFriendListMembers = 'friendList_participants_'+listId;
	if(getElement(activeFriendListMembers)) getElement(activeFriendListMembers).style.display = 'block';
	if(getElement('sendNotificationDiv')) {
		if(listId*0 == 0) {
			getElement('sendNotification').checked = false;
			getElement('sendNotification').disabled = false;
		} else {
			getElement('sendNotification').checked = true;
			getElement('sendNotification').disabled = true;
		}
	}
}

var createFriendResponse = false;
function waitingForFriendResponse(count) {
	if(count > 10000) {
		var button = getElement('saveListButton');
		button.disabled = false;
		button.value = 'Cancelled. Please try again.';
	} else if(!createFriendResponse) {
		count = count + 500;
		var button = getElement('saveListButton');
		if(button.value == 'Saving ... ') button.value = 'Saving .   ';
		else if(button.value == 'Saving ..  ') button.value = 'Saving ... ';
		else if(button.value == 'Saving .   ') button.value = 'Saving ..  ';
		setTimeout('waitingForFriendResponse('+count+');', 500);
	}
}
	
function friendListAdded(listId, label) {
	var lists = getElement('friendLists');
	lists.innerHTML += '<input type="radio" name="friendListId" value="'+listId+'" checked="checked" onclick="showFriendListMembers('+listId+');" /> '+label;
	getElement('participantDiv').innerHTML += '<span id="friendList_participants_'+listId+'" style="display:none;">friends ... </span>';
	showFriendListMembers(listId);
	toggleNewFriendList();
	resetNewFriendListForm();	
}

function resetNewFriendListForm() {
	getElement('friendListName').value = '';
	getElement('allMyFriendsList').innerHTML = masterFriendList;
	getElement('newFriendListMembers').innerHTML = '';
	getElement('saveListButton').disabled = false;
	getElement('saveListButton').value = 'Save List';
}

function showMoreParticipants(item) {
	item.style.display = 'none';
	item.nextSibling.style.display = 'inline';
}

function saveFriendList() {
	getElement('saveListButton').disabled = true;
	getElement('saveListButton').value = 'Saving ... ';
	waitingForFriendResponse(500);
	var items = getElement('newFriendListMembers').childNodes;
	var data = 'doAction=createList&label='+encodeURIComponent(getElement('friendListName').value);
	for(var i=0; i < items.length; i++) {
		data += '&friends[]='+items[i].id;
	}
	doAjax('/_tools/manage/friendList', function(ajax) {
		createFriendResponse = true;
		if(ajax.responseText*1 > 0) {
			friendListAdded(ajax.responseText, getElement('friendListName').value);
		} else {
			getElement('saveListButton').disabled = false;
			getElement('saveListButton').value = 'Save List';
		}
	}, data);
}

function toggleArticlePublishTo(item) {
	if(item.value == 'friends') {
		getElement('publishToFriends').style.display = 'block';
		getElement('publishToGroups').style.display = 'none';
		if(getElement('sendNotificationDiv')) getElement('sendNotificationDiv').style.display = 'block';
	} else if(item.value == 'groups') {
		getElement('publishToFriends').style.display = 'none';
		getElement('publishToGroups').style.display = 'block';
		if(hideGroupNotification && getElement('sendNotificationDiv')) getElement('sendNotificationDiv').style.display = 'none';
	}
}

function toggleArticlePublishTo2(item) {
	if(item.value == 'groups') {
		getElement('publishToMode').innerHTML = 'Groups:';	
		getElement('publishToFriends').style.display = 'none';
		getElement('publishToGroups').style.display = 'block';

		getElement('participantsLabel').style.display = 'none';
		getElement('notificationsLabel').style.display = 'none';
		getElement('participantsRow').style.display = 'none';
		getElement('publishOptions').style.display = 'none';

	} else if(item.value =='friends') {
		getElement('publishToMode').innerHTML = 'Friends:';	
		getElement('publishToFriends').style.display = 'block';
		getElement('publishToGroups').style.display = 'none';

		getElement('participantsLabel').style.display = 'block';
		getElement('notificationsLabel').style.display = 'block';
		getElement('participantsRow').style.display = 'block';
		getElement('publishOptions').style.display = 'block';
	}
}
	

function sendSemiPrivateFriendRequest(item, contentId) {
	doAjax(vine.toolRoot+'/authors/friends?doAction=sendSemiPrivateFriendRequest&contentId='+contentId);
	item.parentNode.innerHTML = 'A request has been sent. You will be sent an email if your request is accepted.';
}


function acceptSemiPrivateFriendRequest(item, contentId, domainName) {
	doAjax(vine.toolRoot+'/authors/friends?doAction=acceptSemiPrivateFriendRequest&contentId='+contentId+'&domainName='+encodeURIComponent(domainName));
	item.parentNode.parentNode.removeChild(item.parentNode);
}


function declineSemiPrivateFriendRequest(item, contentId, domainName) {
	doAjax(vine.toolRoot+'/authors/friends?doAction=declineSemiPrivateRequest&contentId='+contentId+'&domainName='+encodeURIComponent(domainName));
	item.parentNode.parentNode.removeChild(item.parentNode);
}



/*******************************************************************************
FRIEND LIST
*******************************************************************************/

function Friend(domainName, displayName) {
	this.domainName = domainName;
	this.displayName = displayName;
}


function FriendList(divId) {
	this.divId = divId;
	this.listId = -1;
	this.label = '';
	this.isSaved = false;
	this.activeTab = 'emails';
	this.friends = new Array();
	this.allFriends = new Array();
	this.pendingFriendCount = 0;
}


FriendList.prototype.toggle = function(mode) {
	var div = getElement(this.divId);
	if(mode == 'off') {
		div.style.display = 'none';
	} else if(mode == 'on') {
		div.style.display = 'block';
	} else if(div.style.display == 'block') {
		div.style.display = 'none';
	} else if(div.style.display == 'none') {
		div.style.display = 'block';
	}
}


FriendList.prototype.buildModule = function() {
	vine.loadFriends();

	var iHTML = '';

	iHTML += '<div class="newFriendAdmin" class="clearfix" style="display:block; top: 0">';
	iHTML += '<a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].toggle();"><img src="'+vine.imgRoot+'b_close.gif" width="10" height="10" style="position: absolute; top: -1px; right: -1px; border: none" /></a>';
	iHTML += '<div style="width: 285px; float: left;">';
	
	iHTML += '<div class="minitabs"><ul class="tabnav">';
	iHTML += '<li><a href="javascript:void(0);" id="'+this.divId+'_tab_emails" class="active" onclick="vine.friendLists[\''+this.divId+'\'].toggleTab(\'emails\');">Emails</a></li>';
	iHTML += '<li><a href="javascript:void(0);" id="'+this.divId+'_tab_friends" onclick="vine.friendLists[\''+this.divId+'\'].toggleTab(\'friends\');">Friends</a></li>';
	iHTML += '<li><a href="javascript:void(0);" id="'+this.divId+'_tab_users" onclick="vine.friendLists[\''+this.divId+'\'].toggleTab(\'users\');">Users</a></li>';
	iHTML += '</ul></div>';

	iHTML += '<div class="newFriendTools">';
	iHTML += '<div id="'+this.divId+'_div_emails"><p style="font-size:10px;">Enter as many email addresses as you\'d like, separated by commas:</p><textarea style="height:120px; width:100%;" class="flat"></textarea><div style="text-align:center; margin-top:1em;"><input type="button" value="Add &gt;" onclick="vine.friendLists[\''+this.divId+'\'].addEmails(this);" /></div></div>';
	iHTML += '<div id="'+this.divId+'_div_friends" style="display:none;"><p style="font-size:10px;">Add your friends below:</p><div style="border: 1px solid #ccc; height: 170px; margin-top: 10px; overflow:auto;"><ul id="'+this.divId+'_allFriends" class="friendList"></ul></div></div>';
	iHTML += '<div id="'+this.divId+'_div_users" style="display:none;"><p style="font-size:10px;">Type in all or part of user\'s Display Name or Domain Name:</p><input style="width:100%;" class="flat" onkeydown="vine.friendLists[\''+this.divId+'\'].lookupUsers(this);" /><div style="border:1px solid #ccc; height:130px; margin-top:10px; overflow:auto;"><ul id="'+this.divId+'_users" class="friendList"></ul></div></div>';
	iHTML += '</div>';

	iHTML += '</div>';
	iHTML += '<div style="width: 180px; float: right">';
	iHTML += '<p style="font-size: 10px; margin-bottom: 5px">Current Participants:</p>';
	iHTML += '<div style="height: 180px; background-color: #ebebeb; overflow:auto;" class="flat"><ul id="'+this.divId+'_members" class="friendList">';
	for(var i=0; i < this.friends.length; i++) {
		friend = this.friends[i];
		iHTML += '<li><a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].moveMember(this.parentNode, \''+friend.domainName+'\');"><img src="'+vine.imgRoot+'b_minus.gif"></a><a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].moveMember(this.parentNode, \''+friend.domainName+'\');">'+friend.displayName+'</a></li>';
	}
	if(this.pendingFriendCount > 0) {
		iHTML += '<li>'+(this.friends.length > 0 ? 'and ' : '')+this.pendingFriendCount+' pending friend'+(this.pendingFriendCount != 1 ? 's' : '')+'</a></li>';
	}		
	iHTML += '</ul></div>';
	iHTML += '<div style="margin: 10px 0 4px 0">Friend List Name (e.g. "My Family"):</div>';
	iHTML += '<div><input type="text" id="'+this.divId+'_label" name="'+this.divId+'_label" value="'+this.label+'" style="width:100px;" /><input type="button" name="Save" value="Save List" onclick="vine.friendLists[\''+this.divId+'\'].saveList(this);" /></div>';
	iHTML += '</div>';
	iHTML += '</div>';
	
	div = getElement(this.divId);
	div.innerHTML = iHTML;	
	div.style.display = 'block';
	this.loadFriends(0);
}


FriendList.prototype.clear = function() {
	getElement(this.divId).innerHTML = '';
	vine.friendLists[this.divId] = null;
}


FriendList.prototype.loadFriends = function(count) {
	if(vine.friends.length == 0) {
		if(count == 0) getElement(this.divId+'_allFriends').innerHTML = '<li><img src="'+vine.imgRoot+'waiting.gif"></li>';
		if(count < 15000) {
			setTimeout('vine.friendLists["'+this.divId+'"].loadFriends('+(count+100)+');', 100);
		} else {
			getElement(this.divId+'_allFriends').innerHTML = '<li>You have not added any friends. Click on the "Emails" tab above to invite your friends to Newsvine, or click on the "Users" tab to search for your friends on Newsvine.</li>';
		}
	} else {
		var iHTML=''; var friend=null;
		for(var i=0; i < vine.friends.length; i++) {
			friend = vine.friends[i];
			this.allFriends[friend.domainName] = friend;
			iHTML += '<li><a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].moveMember(this.parentNode, \''+friend.domainName+'\');"><img src="'+vine.imgRoot+'b_plus.gif"></a><a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].moveMember(this.parentNode, \''+friend.domainName+'\');">'+friend.displayName+'</a></li>';
		}
		getElement(this.divId+'_allFriends').innerHTML = iHTML;
	}
}


FriendList.prototype.toggleTab = function(tabId) {
	getElement(this.divId+'_tab_'+this.activeTab).className = '';
	getElement(this.divId+'_div_'+this.activeTab).style.display = 'none';
	this.activeTab = tabId;
	getElement(this.divId+'_tab_'+this.activeTab).className = 'active';
	getElement(this.divId+'_div_'+this.activeTab).style.display = 'block';
}


FriendList.prototype.moveMember = function(item, domainName,displayName) {
	var img = item.getElementsByTagName('img')[0];
	var newItem = document.createElement('li');
	if(img.src.endsWith('b_plus.gif')) { // move to members; remove from allFriends
		img.src = vine.imgRoot+'b_minus.gif';
		newItem.innerHTML = item.innerHTML;
		getElement(this.divId+'_members').appendChild(newItem);
		item.parentNode.removeChild(item);
		if(!displayName) {
			this.friends[this.friends.length] = this.allFriends[domainName];
		} else {
			this.friends[this.friends.length] = new Friend(domainName, displayName);
		}
	} else if(img.src.endsWith('b_minus.gif')) { // move to all Friends; remove from members
		img.src = vine.imgRoot+'b_plus.gif';
		newItem.innerHTML = item.innerHTML;
		getElement(this.divId+'_allFriends').appendChild(newItem);
		item.parentNode.removeChild(item);
		for(var i=0; i < this.friends.length; i++) {
			if(this.friends[i] && this.friends[i].domainName == domainName) {
				this.friends[i] = null;
				this.friends.splice(i, 1);
				break;
			}
		}
	}
}


FriendList.prototype.saveList = function(item) {
	var label = getElement(this.divId+'_label');
	if(!label || !label.value.trim()) {
		alert('Please give your Friend List a name. This can be any arbitrary name and only you will see the name.');
		label.focus();
		return false;
	}
	this.label = label.value.trim();
	var noMembers = true;
	for(var i=0; i < this.friends.length; i++) {
		if(this.friends[i]) {
			noMembers = false;
			break;
		}
	}
	if(noMembers && this.pendingFriendCount == 0) {
		alert('A Friend List must contain at least one friend.');
		return false;
	}
	this.toggle('off');
	if(document[this.divId+'_saveList']) document[this.divId+'_saveList'](this, item); // call custom saveList function
	else if(document['editFriendListDiv_editList']) document['editFriendListDiv_editList'](this, item); // call custom editList function
	this.isSaved = true;
	return true;
}


FriendList.prototype.lookupUsers = function(item) {
	ul = getElement(this.divId+'_users');
	if(item.value.trim().length < 1) {
		ul.innerHTML = '';
	} else if(item.value.trim().length > 1) {
		doAjax(vine.toolRoot+'/authors/friends', function(ajax) {
			ul.innerHTML = ajax.responseText;
		}, 'doAction=findUser&type=list&divId='+this.divId+'&query='+item.value.trim());
	}
}


FriendList.prototype.addEmails = function(item) {
	var text = item.parentNode.previousSibling;
	var emails = text.value.trim().split(',');
	var iHTML=''; var friend=null; var email='';
	for(var i=0; i < emails.length; i++) {
		email = emails[i].trim();
		if(email) {
			var newItem = document.createElement('li');
			var friend = new Friend(email, email);
			newItem.innerHTML = '<a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].moveMember(this.parentNode, \''+friend.domainName+'\');"><img src="'+vine.imgRoot+'b_minus.gif"></a><a href="javascript:void(0);" onclick="vine.friendLists[\''+this.divId+'\'].moveMember(this.parentNode, \''+friend.domainName+'\');">'+friend.displayName+'</a>';
			getElement(this.divId+'_members').appendChild(newItem);
			this.friends[this.friends.length] = friend;
		}
	}
	text.value = '';
}



/*******************************************************************************
THE VINE
*******************************************************************************/

var vine = new function() {

	// SITE SETTINGS
	this.protocol = location.href.substr(0, location.href.indexOf('//')+2);
	this.url = location.href.replace(this.protocol, '');
	this.fullDomain = this.url.substr(0, this.url.indexOf('/'));
	this.path = this.url.substr(this.url.indexOf('/'));
	
	var nodes = this.fullDomain.split('.');
	if(nodes.length > 3) {
		this.domain = ''; this.subDomain='';
		for(var i=nodes.length-3; i < nodes.length; i++) {
			this.domain += nodes[i]+(i != nodes.length-1 ? '.' : '');
		}
		for(var i=0; i < nodes.length-3; i++) {
			this.subDomain += nodes[i]+(i!=nodes.length-4 ? '.' : '');
		}
	} else {
		this.subDomain = nodes[0];
		this.domain = 'newsvine.com';
	}

	this.webRoot = 'http://www.'+this.domain;
	this.cmsRoot = this.webRoot+'/_cms';
	this.toolRoot = this.subDomain == 'www' ? this.webRoot+'/_tools' : 'http://'+this.subDomain+'.'+this.domain+'/_tools';
	this.vineRoot = this.subDomain == 'www' ? this.webRoot+'/_vine' : 'http://'+this.subDomain+'.'+this.domain+'/_vine';
	this.actionRoot = this.subDomain == 'www' ? this.webRoot+'/_action' : 'http://'+this.subDomain+'.'+this.domain+'/_action';
	this.imgRoot = this.webRoot+'/_vine/images/_/';

	// FRIENDS and FRIEND LISTS
	this.activeFriendListId = '';
	this.friends = new Array();
	this.friendLists = new Array();


	this.loadFriendListModule = function(divId) {
		if(!this.friendLists[divId]) {
			this.friendLists[divId] = new FriendList(divId);
			this.friendLists[divId].buildModule();
		} else if(getElement(divId).innerHTML) {
			this.friendLists[divId].toggle();
		} else {
			this.friendLists[divId].buildModule();
		}
		
		// hide the active friend list module
		if(divId != this.activeFriendListId && getElement(this.activeFriendListId) && getElement(this.activeFriendListId).style.display != 'none') {
			getElement(this.activeFriendListId).style.display = 'none';
		}
		this.activeFriendListId = divId;
	}


	this.loadFriends = function(doFunction) {
		if(this.friends.length == 0 || doFunction) {
			doAjax(this.toolRoot+'/manage/friendList', function(ajax) {
				eval(ajax.responseText);
				if(doFunction) doFunction(ajax);
			}, 'doStream=getAllFriends');
		}
	}


	// MODULES
	this.modules = new function() {}
	this.modules.content = new function() {}
	this.modules.content.comments = new function() {}
	this.modules.content.comments.commentForm = new function() {}


	// COMMENT FORM MODULE
	this.modules.content.comments.commentForm.retries = 0;
	this.modules.content.comments.commentForm.showWordCount = false;
	this.modules.content.comments.commentForm.wordCountLimit = 0;


	// comment bomb debugging only
	this.commentPokeNum = 1;
	this.commentPoke = function(lineNum, msg) {

		var debugPokeActionId = 42;
		var domainName = '';
		var form = document.getElementById('commentsForm');

		var data = '&cb-ln='+lineNum+';';
		data += 'cb-msg='+encodeURIComponent(msg);
		data += '&cb-cid='+form.contentId.value+';';
		data += 'cb-dn='+encodeURIComponent(domainName);
		data += '&cb-mth='+form.method+';';
		data += 'cb-act='+encodeURIComponent(form.action);
		data += '&cb-rdr='+encodeURIComponent(form.redirect.value);
		
		var hasComment = 'false'; value='';
		for(var i=0; i < form.elements.length; i++) {
			if(form.elements[i].name.startsWith('commentsText') && form.elements[i].value.trim()) {
				hasComment = 'true';
				value = encodeURIComponent(form.elements[i].value.substr(0, 10));
			}
		}
		
		data += '&cb-has='+hasComment+'&cb-cmt='+value;

		// do poke ( instead of calling poke() )
		var rand = Math.floor(Math.random()*100000000000);
		var url = "http://log.newsvine.com/poke.gif?x=" + debugPokeActionId + "&rand=" + rand + data;
		document.getElementById('poke'+this.commentPokeNum).src = url;
		this.commentPokeNum++;


	}
	
	
	// FEEDS
	this.modules.feeds = new function() {}
	this.modules.feeds.search = function(inputId, containerId, messageId) {
		var input = getElement(inputId);
		var container = getElement(containerId);
		var message = getElement(messageId);
		if(input && container && message) {
			if(input.value.trim().length > 3) {
				message.innerHTML = 'Searching ... ';
				setTimeout('vine.modules.feeds.doSearch("'+inputId+'","'+containerId+'","'+messageId+'");', 500);
			} else {
				message.innerHTML = '';
				container.innerHTML = '';
			}
		}
	}
	this.modules.feeds.doSearch = function(inputId, containerId, messageId) {
		var input = getElement(inputId);
		var container = getElement(containerId);
		var message = getElement(messageId);
		if(input && container && message) {
			doAjax('/_action/tools/searchFeeds?format=userlist&query='+encodeURIComponent(input.value.trim()), function(ajax) {
				message.innerHTML = '';
				container.innerHTML = ajax.responseText;
				container.style.display = 'block';
			});
		}
	}

	this.modules.feeds.loadSidebarFeed = function(feedId, feedName) {
		var item = getElement('sidebarFeed');
		item.innerHTML = '<h4>'+feedName+'</h4><div id="feed'+feedId+'"></div>';
		vine.modules.feeds.loadFeed(feedId, 7, false);
	}

	this.modules.feeds.loadFeed = function(feedId, count, showHeader) {

		var url = '/_static/feeds/' + feedId + '.xml';
		doAjax(url, function(ajax) {
			if(ajax && ajax.responseXML && ajax.responseXML.firstChild) {
				var rootNode;
				for (var i = 0; i < ajax.responseXML.childNodes.length; i++) {
					rootNode = ajax.responseXML.childNodes[i];
					if (rootNode.nodeName != 'xml-stylesheet' && rootNode.nodeName != 'xml' && rootNode.nodeType != 10 && rootNode.nodeType != 8) {
						break;
					}
				}
				var html = '';
				var lookup = 'item';
				var channels = rootNode.getElementsByTagName("channel");
				var channelNode = channels[0]; //we'll only use the first channel
				if (channels.length == 0) { //atom garbage
					channelNode = rootNode;
					lookup = 'entry';
				} else if (channelNode.getElementsByTagName(lookup).length == 0) {
					 
					channelNode = rootNode;
				}
				if(showHeader) {
					var images = channelNode.getElementsByTagName("image");
					for (var j = 0; j < images.length; j++) {
						if (getNodeValue(images[j], "link")) {
							var logo = getFirstChildNode(images[j], "url");
							var ref = getFirstChildNode(images[j], "link");
							var alt = getFirstChildNode(images[j], "title");
							html += '<a href="' + ref + '"><img border="0" src="' + logo + '" alt="' + alt + '"></a><ul>';
							break;
						}
					}
				}
				var items = channelNode.getElementsByTagName(lookup);
				for (var j = 0; j < items.length && j < count; j++) {
					var headline = getFirstChildNode(items[j], "title");
					var link = items[j].getElementsByTagName('link')[0].getAttribute('href');
					if (link == null) {
						link = getFirstChildNode(items[j], "link");
					}
					var guid = getFirstChildNode(items[j], "guid");
					if (guid.length == 0) {
						guid = link;
					}
					// html += '<li><a href="/_action/article/import?f=' + feedId + '&fi=' + encodeURIComponent(link) + '">';
					html += '<li><a href="' + link + '">';
					html += headline + '</a>';
				}
				html += '</ul>';
				document.getElementById('feed' + feedId).innerHTML = html;
			}
		}, 'a=b');
	}

}



/*******************************************************************************
COMMENTS
*******************************************************************************/

vine.comments = new function() {

}


vine.comments.alert = function() {
	alert('garbage');
}




/*******************************************************************************
WRANGLER
*******************************************************************************/

function Wrangler() {
	
	this.URL = '/_login/proxy?path=/servista/ads';
	this.divRoot = 'wrangler_';
	this.frameId = 'wranglerFrame';

	this.root = null;
	this.log = null;
	this.collection = null;
	this.divs = new Array();
	
	this.add = function(divId) {
		this.divs[this.divs.length] = divId;
		document.write('<div id="'+this.divRoot+divId+'"></div>');
	};

	this.run = function() {
		if(this.divs.length > 0) {
			document.body.appendChild(this.createFrame());
			var query = '';
			for(var i=0; i < this.divs.length; i++) query += 'type='+this.divs[i]+'&';
			query += '&url='+location.href;
			doAjax(this.URL, function(ajax) {
				if(ajax && ajax.responseXML && ajax.responseXML.firstChild) {
					wrangler.root = ajax.responseXML.firstChild;
					if(wrangler.root.nodeName != 'AdCollection') { // for PCIE garbage
						wrangler.root = wrangler.root.nextSibling;
					}
					wrangler.doPoke();
					wrangler.collection = getChildNode(wrangler.root, 'ads');
					wrangler.loadDivs();
					wrangler.fixHistory();
				}
			}, query);
		}
	};

	this.doPoke = function() {
		this.log = getNodeValue(this.root, 'logData');
		poke('&ad='+this.log, 26);
	}

	this.loadDivs = function() {
		for(var i=0; i < this.divs.length; i++) {
			this.loadDiv(this.divs[i]);
		}
	}

	this.loadDiv = function(divId) {
		var node = getChildNode(this.collection, divId);
		if(node) {
			var htmlBody = getNodeValue(node, 'body');
			var htmlHead = getNodeValue(node, 'head');
			if(htmlBody || htmlHead) {
				var fNode = getChildNode(node, 'frame');

				// Create a new iFrame to write to, and append the iFrame to the divId
				if(fNode) {
					var width = getNodeValue(fNode, 'width');
					var height = getNodeValue(fNode, 'height');
					if(width && height) {
						var divFrame = this.createFrame(this.divRoot+divId+'_frame', width, height);
						getElement(this.divRoot+divId).appendChild(divFrame);
						divFrame = frames[divFrame.id];
						this.writeToFrame(divFrame, htmlHead, htmlBody);
					}

				// Write to the Wrangler iFrame, then insert the results into the divId
				} else {
					var wFrame = frames[this.frameId];
					this.writeToFrame(wFrame, htmlHead, htmlBody);
					getElement(this.divRoot+divId).innerHTML = wFrame.document.body.innerHTML;
					wFrame.document.body.innerHTML = '';
				}
			}
		}
	}

	this.createFrame = function(namedId, width, height) {
		if(!namedId) namedId = this.frameId;
		if(!width) width = 0;
		if(!height) height = 0;
		var frame = document.createElement('iframe');
		frame.id = namedId;
		frame.name = frame.id;
		frame.frameBorder = 0;
		frame.scrolling = 'no';
		frame.width = width;
		frame.height = height;
		frame.src = '/_util/blank.html';
		return frame;
	}

	this.writeToFrame = function(frame, htmlHead, htmlBody) {
		if(detect.browser == 'ie') {
			frame.document.open();
			frame.document.write('<html><head>');
			if(htmlHead) frame.document.write(htmlHead);
			frame.document.write('</head><body>');
			if(htmlBody) frame.document.write(htmlBody);
			frame.document.write('</body></html>');
		} else {
			frame.document.open();
			var src = '<html><head></head><body>';
			if(htmlHead) src += htmlHead;
			if(htmlBody) src += htmlBody;
			src += '</body></html>';
			frame.document.write(src);
			frame.document.close();
		}
	}
	
	this.fixHistory = function() {

		/************

		if (IFrameObj.contentDocument) { // For NS6
			IFrameDoc = IFrameObj.contentDocument; 
		} else if (IFrameObj.contentWindow) { // For IE5.5 and IE6
			IFrameDoc = IFrameObj.contentWindow.document;
		} else if (IFrameObj.document) { // For IE5
			IFrameDoc = IFrameObj.document;
		} else {
			return true;
		}
  
		IFrameDoc.location.replace(URL);
		return false;

		*************/


	}





// END WRANGLER
}


function clearWatchlist(thisItem) {
	doAjax("/_action/user/clearWatchlist", function() {}, null);
	thisItem.parentNode.parentNode.removeChild(thisItem.parentNode);
	clearWatchlistGroup('watchlistTags', 'watchlistTagHeader');
	clearWatchlistGroup('watchlistAuthors', 'watchlistAuthorHeader');
	clearWatchlistGroup('watchlistGroups', 'watchlistGroupHeader');
}


function clearWatchlistGroup(group, gHeader) {
	if(getElement(group)) {
		var items = getElement(group).getElementsByTagName('LI');
		if(getCookie('watchlistFilter') == 1) {
			var className = 'hideStaleWatchlistItem';
			watchlistHeader(getElement(gHeader), false);
		} else {
			var className = 'showStaleWatchlistItem';
		}
		for(var i=0; i < items.length; i++) {
			items[i].className = className;
			items[i].innerHTML = items[i].innerHTML.split('(')[0].trim();
		}
	}
}


function addToWatchList(contentSetId, isTag, label) {
	getElement('addtowatchlist').style.display = 'none';
	var item = document.createElement("LI");
	if(getCookie('watchlistFilter') == 1) item.className = 'hideStaleWatchlistItem';
	else item.className = 'showStaleWatchlistItem';
	var removeImg = '<img src="http://www.newsvine.com/_vine/images/_/icon_remove.gif" width="7" height="7" alt="Remove" title="Remove" style="margin-left: 4px" onclick="removeFromWatchlist(this, '+contentSetId+', \''+escape(label)+'\', '+contentSetId+'); return false" />';
	item.innerHTML = '<a href="'+location.href+'">'+label+removeImg+'</a>';
	if(isTag && getElement('watchlistTags')) getElement('watchlistTags').appendChild(item);
	else if(!isTag && getElement('watchlistAuthors')) ulObj = getElement('watchlistAuthors').appendChild(item);
	else if(!isTag && getElement('watchlistGroups')) ulObj = getElement('watchlistGroups').appendChild(item);
	doAjax('/_action/user/addToWatchlist?cs='+contentSetId);
}


function removeFromWatchlist(imgItem, contentSetId, label, pageContentSetId) {
	if(confirm("Delete '"+unescape(label)+"' from your Watchlist?")) {
		removed = imgItem.parentNode.parentNode.parentNode.removeChild(imgItem.parentNode.parentNode);
		if(pageContentSetId == contentSetId) {
			getElement('addtowatchlist').style.display = 'inline';
		}
		doAjax('/_action/user/removeFromWatchlist?cs='+contentSetId);
	}
}


function getCookie(name) {
	if(document.cookie.length>0) {
		var start=document.cookie.indexOf(name+"=");
		if(start!=-1) {
			start=start+name.length+1;
			var end=document.cookie.indexOf(";",start);
		    if(end==-1) end=document.cookie.length;
    		return unescape(document.cookie.substring(start,end));
		} 
	}
	return null;
}

function setCookie (name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function filterWatchlist(thisCheckbox) {
    var now = new Date();
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);

	if(thisCheckbox.checked) {
		setCookie('watchlistFilter', 1, now, '/', '.newsvine.com', false);
	} else {
		setCookie('watchlistFilter', 0, now, '/', '.newsvine.com', false);
	}
	
	if(getElement('watchlistAuthors')) {
		var authorItems = getElement('watchlistAuthors').getElementsByTagName('LI');
		if(thisCheckbox.checked) {
			authorHasItems = doWatchlistFilter(authorItems, 'hideStaleWatchlistItem');
			watchlistHeader(getElement('watchlistAuthorHeader'), authorHasItems);
		} else {
			hasItems = doWatchlistFilter(authorItems, 'showStaleWatchlistItem');
			watchlistHeader(getElement('watchlistAuthorHeader'), true);
		}
	}
	
	if(getElement('watchlistGroups')) {
		var groupItems = getElement('watchlistGroups').getElementsByTagName('LI');
		if(thisCheckbox.checked) {
			groupHasItems = doWatchlistFilter(groupItems, 'hideStaleWatchlistItem');
			watchlistHeader(getElement('watchlistGroupHeader'), groupHasItems);
		} else {
			hasItems = doWatchlistFilter(groupItems, 'showStaleWatchlistItem');
			watchlistHeader(getElement('watchlistGroupHeader'), true);
		}
	}
	
	if(getElement('watchlistTags')) {
		var tagItems = getElement('watchlistTags').getElementsByTagName('LI');
		if(thisCheckbox.checked) {
			tagHasItems = doWatchlistFilter(tagItems, 'hideStaleWatchlistItem');
			watchlistHeader(getElement('watchlistTagHeader'), tagHasItems);
		} else {
			hasItems = doWatchlistFilter(tagItems, 'showStaleWatchlistItem');
			watchlistHeader(getElement('watchlistTagHeader'), true);
		}
	}

}

function watchlistHeader(item, status) {
	if(status) {
		item.style.display = 'block';
	} else {
		item.style.display = 'none';
	}
	
}

function doWatchlistFilter(items, className) {
	var hasWatchlistItems = false;
	for(var i=0; i < items.length; i++) {
		if(items[i].className) {
			items[i].className = className;
		} else {
			hasWatchlistItems = true;
		}
	}
	return hasWatchlistItems;
}


function clipThis(contentId, placement) {
	doAjax('/_action/user/clip?contentId='+contentId);
	var divId = placement ? 'clipThis_'+placement+'_'+contentId : 'clipThis_'+contentId;
	getElement(divId).innerHTML = 'Clipped';
	setTimeout('clipThisOff("'+divId+'");', 1000);
}

function removeItem(contentId, title, from, sectionId) {
	if(confirm("Are you sure you want to remove '"+(title)+"' from '"+(from)+"'? This article will not be deleted.")) {
		doAjax('/_action/tools/remove?contentId='+contentId);
		var divId = 'a'+contentId;
		div = document.getElementById(divId);
		div.parentNode.removeChild(div);
	}
}

function clipThisToolbar(contentId, placement) {
	doAjax('/_action/user/clip?contentId='+contentId);
	var divId = placement ? 'clipThis_'+placement+'_'+contentId : 'clipThis_'+contentId;
	getElement(divId).innerHTML = 'Clipped';
}

function clipThisOff(divId) {
	getElement(divId).innerHTML = '';
}	



function doFilterCS(mode, url, category) {
	var now = new Date();
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookie('rawFilter', mode, now, '/', '.newsvine.com', false);
	if(mode || category) url += '?';
	if(category) url += category;
	if(mode && category) url += '&raw';
	else if(mode) url += 'raw';
	location.href = url;
}

function smoothColumns () {
	if (getElement('index_mostactive')) {
		var ulArray = getElement('index_mostactive').getElementsByTagName('ul');
		var index_middle = getElement('index_middle').offsetHeight;
		var index_right = getElement('index_right').offsetHeight;
		if (index_middle - 25 > index_right) {	
			liArray = new Array();
			for (i=0; i < ulArray.length; i++) {
				liArray[i] = ulArray[i].getElementsByTagName('li').length;
			}
			var topvalue = -1, topindex = -1; 
			for (x = 0; x < liArray.length; x++) {
			    if (liArray[x] > topvalue) {
			         topvalue = liArray[x];
			         topindex = x;
			    }
			}
			if (ulArray[topindex].lastChild && ulArray[topindex].getElementsByTagName('li').length > 3) {
				ulArray[topindex].removeChild(ulArray[topindex].lastChild);
				if (!ulArray[topindex].lastChild) {
					document.getElementById('index_mostactive').style.display = 'none';
					return;
				}
			} else {
				return;
			}
			smoothColumns();
		}
	}	
}


function mostActiveToggle(id) {
	if(id == 'comments') {
		getElement('mostActiveVotes').style.display = 'none';
		getElement('mostActiveComments').style.display = 'block';
	} else if(id == 'votes') {
		getElement('mostActiveComments').style.display = 'none';
		getElement('mostActiveVotes').style.display = 'block';
	}
}

function showXPerPage(thisItem, url) {
	var show = thisItem.options[thisItem.selectedIndex].value;
	location.href = url+'&c='+show;
}


function showTracker(mode, contentId, threadId) {
	
	if(!getElement('convTrackerDiv').innerHTML) {

		var url = '/_wine/user/commentTracker?r='+(Math.floor(Math.random()*10000000))+(contentId ? '&contentId='+contentId : '')+(threadId ? '&threadId='+threadId : '');
		doAjax(url, function(ajax) {
			getElement('convTrackerDiv').innerHTML = ajax.responseText;
			toggleConvTracker(mode);
		});

	} else {
		toggleConvTracker(mode);
	}

	if(getElement('convTrackerDiv').style.display == 'block' && mode == trackerMode) {
		getElement('convColumnDiv').style.display = 'none';
		getElement('convCommentsDiv').style.display = 'none';
		getElement('convTrackerDiv').style.display = 'none';
	} else {
		getElement('convTrackerDiv').style.display = 'block';
	}

	trackerMode = mode;

}

function toggleConvTracker(mode) {

	if(mode == 'column') {
		getElement('convCommentsDiv').style.display = 'none';
		getElement('convFriendsDiv').style.display = 'none';
		setTimeout("setConvHeight('convColumnDiv')", 10);
	} else if(mode == 'comments') {
		getElement('convColumnDiv').style.display = 'none';
		getElement('convFriendsDiv').style.display = 'none';
		setTimeout("setConvHeight('convCommentsDiv')", 10);
	} else if(mode == 'friends') {
		getElement('convColumnDiv').style.display = 'none';
		getElement('convCommentsDiv').style.display = 'none';
		setTimeout("setConvHeight('convFriendsDiv')", 10);
	}

}

function setConvHeight(parentId) {
	var parent = getElement(parentId);
	parent.style.display = 'block';
	if(parent && parent.childNodes.length > 0 && parent.childNodes[0].childNodes.length > 0) {
		var child = parent.childNodes[0].childNodes[0];
		if(child.offsetHeight > 320) {
			child.style.height = '320px';
		}
	}
}


function removeConversations(divId) {
	var table = getElement(divId).getElementsByTagName('table')[0];
	for(var i=table.rows.length-1; i > 1; i--) {
		table.deleteRow(i);
	}
	var row = table.insertRow(2);
	row.className = 'conv_items';
	var cell = row.insertCell(row.cells.length);
	cell.colSpan = 6;
	cell.innerHTML = '&nbsp;';
	getElement(divId).childNodes[0].childNodes[0].style.height = 'auto';
	return cell;
}
	

function convDiv2trackType(divId) {
	if(divId == 'convColumnDiv') return 1;
	else if(divId == 'convCommentsDiv') return 3;
	else if(divId == 'convFriendsDiv') return 4;
}

convContentIds = new Array();
function updateConvCount(divId, update, contentId) {
	if(update == 'all') {
		getElement(divId+'_count').innerHTML = '0';
	} else if(contentId && !convContentIds.in_array(contentId)) {
		update = (getElement(divId+'_count').innerHTML)*1 - update;
		if(update < 0) update = 0;
		getElement(divId+'_count').innerHTML = update;
		convContentIds.push(contentId);
	}
	
}


function clearTrackAll(divId) {
	updateConvCount(divId, 'all');
	doAjax('/_action/user/startTracking?clear=true&typeId='+convDiv2trackType(divId));
	var cell = removeConversations(divId);
	cell.innerHTML = '<div style="padding-bottom: 6px; padding-left: 6px">Your conversations have been cleared. Items will reappear here as more comments are posted to the conversations.</div>';
}


function stopTrackAll(divId) {
	updateConvCount(divId, 'all');
	doAjax('/_action/user/stopTracking?typeId='+convDiv2trackType(divId));
	var cell = removeConversations(divId);
	cell.innerHTML = '<div style="padding-bottom: 6px; padding-left: 6px">Your conversations have been removed. You will no longer be notified when new comments are posted to the conversations.</div>';
}


function stopTracking(thisItem, contentId, threadId, newCount, divId) {
	updateConvCount(divId, newCount, contentId);
	var row = thisItem.parentNode.parentNode;
	row.parentNode.removeChild(row);
	doAjax('/_action/user/stopTracking?r='+(Math.floor(Math.random()*10000000))+'&contentId='+contentId+'&threadId='+threadId);
}

function stopTrackingMe(thisItem, contentId, threadId) {
	if(confirm('Clicking OK will remove this article from your conversation tracker. You will no longer be notified when a comment is left on this article.')) {
		doAjax('/_action/user/stopTracking?r='+(Math.floor(Math.random()*10000000))+'&contentId='+contentId+'&threadId='+threadId);
		getElement('stopTrackingButton').style.display = 'none';
		getElement('startTrackingButton').style.display = 'block';
	}
}

function clearTrackCount(thisItem, contentId, newCount, divId) {
	updateConvCount(divId, newCount, contentId);
	var row = thisItem.parentNode.parentNode;
	var newCount = row.getElementsByTagName('span')[0];
	newCount.innerHTML = 0;
	doAjax('/_action/user/startTracking?r='+(Math.floor(Math.random()*10000000))+'&clear=true&contentId='+contentId);
}

function startTracking(contentId, threadId) {
	if (confirm('Clicking OK will add this article to your conversation tracker. Whenever a new comment comes in, you will be notified in the green header area at the top of the screen.')) {
		doAjax('/_action/user/startTracking?r='+(Math.floor(Math.random()*10000000))+'&contentId='+contentId+'&threadId='+threadId);
		getElement('startTrackingButton').style.display = 'none';
		getElement('stopTrackingButton').style.display = 'block';
	}
}

function threadReplyActivate (element) {
	element.className += ' threadhighlight';
}

function threadReplyReset (element) {
	element.className = element.className.replace(" threadhighlight", "");
}


function moveIndexScores(direction) {
	var curPointer = indexScoresPointer;
	var scores = getElement('scores_module').childNodes;
	if(direction == -1 && indexScoresPointer == 0) {
		indexScoresPointer = scores.length-1;
	} else if(direction == 1 && indexScoresPointer == scores.length-1) {
		indexScoresPointer = 0;
	} else {
		indexScoresPointer += direction;
	}
	getElement('indexScores_'+curPointer).style.display = 'none';
	getElement('indexScores_'+indexScoresPointer).style.display = 'block';
}

function launchChatRoom(name, topic) {
	//var topic = encodeURIComponent(topic);
	topic = '';
	var num = Math.floor(Math.random() * 8196);
	window.open('http://www.newsvine.com/_wine/kewlchat?isPrivate&name='+name+'&topic='+topic, 'kewlchat_' + num, 'toolbar=no,scrollbars=no,width=680,height=370');
}

function chatRequestResponse(item, response, toDomain, roomName) {
	if(response == 1 && roomName) {
		launchChatRoom(roomName, '');
	}
	var data = 'domainName='+encodeURIComponent(toDomain)+'&doCancel=1';
	doAjax('/_action/user/sendChatRequest', null, data);
	var pNode = item.parentNode.parentNode;
	pNode.removeChild(item.parentNode);
	var spans = pNode.getElementsByTagName('span');
	if(spans.length == 0) {
		pNode.parentNode.removeChild(pNode);
	}
	if(response == 1) {
		poke(roomName, 31);
	} else {
		poke(roomName, 32);
	}
	
}

//-------------------- displayName checking-------------------------

function suggestDisplayName(suggestion, field, msgField) {
	var next = 0;
	var url = '/_action/user/checkDisplayName?suggestion='+escape(suggestion.trim());
	doAjax(url, function(AJAX) {
		next = parseInt(AJAX.responseText);
		var url = '/_action/user/checkDomain?suggestion='+escape(suggestion.trim());
		doAjax(url, function(AJAX) {
			next = parseInt(AJAX.responseText) > next ? parseInt(AJAX.responseText) : next;
			if (getElement(field).value == '') getElement(field).value = next > 0 ? suggestion+'-'+next : suggestion;
			checkDisplayNameUsage(getElement(field).value, msgField);
		});
	});
}

//input:
//displayName: the form element which current holds the value for the name to be checked
//msgField (optional): the form element which will display the result of the check
//isValidDisplayName = the global boolean js var which holds the result of this check
function checkDisplayNameUsage(displayName, msgField) {
	var errorMsg;
	if(getElement(displayName)) displayName = getElement(displayName).value;
	if(displayNameTimerSet) displayNameTimerSet = false;
	if (msgField) msgField = getElement(msgField);
	if(displayName.trim()) {
		errorMsg = checkDisplayNameRules(displayName);
		if(errorMsg) {
			if (msgField) msgField.innerHTML = errorMsg;
			isValidDisplayName = false;
		} else {
			if (msgField) msgField.innerHTML = 'Checking ... ';
			var url = '/_action/user/checkDisplayName?displayName='+escape(displayName);
			doAjax(url, function(AJAX) {
				if(AJAX.responseText == 1) {
					errorMsg = '<span style="font-weight:bold;font-style:italic;color:green;">Available!</span>';
					isValidDisplayName = true;
				} else if(AJAX.responseText == 2) {
					errorMsg = '<span style="font-weight:bold;font-style:italic;">Your Current Display Name</span>';
					isValidDisplayName = true;
				} else {
					errorMsg = '<span class="invalidMsg">Not Available</span>';
					isValidDisplayName = false;
				}
				if (msgField) msgField.innerHTML = errorMsg;
			});
		}
	} else {
		if (msgField) msgField.innerHTML = '';
		isValidDisplayName = false;
	}
}
	
function checkDisplayNameRules(str) {
	str = str.toLowerCase();
	var validAlpha = 'abcdefghijklmnopqrstuvwxyz';
	if(str.length > 30) {
		return '<span class="invalidMsg">Display names must be less than 30 characters.</span>';
	} else {
		var foundAlpha = false;
		for(var i=0; i < str.length; i++) {
			if (validAlpha.indexOf(str.charAt(i)) > -1)
				foundAlpha = true;
		}
		if (!foundAlpha)
			return '<span class="invalidMsg">Display names need at least one alpha character.</span>';
	}
}

//------------------------ domainName checking ---------------------------

function suggestDomainName(suggestion, field, msgField) {
	var next = 0;
	var url = '/_action/user/checkDomain?suggestion='+escape(suggestion.trim());
	doAjax(url, function(AJAX) {
		next = parseInt(AJAX.responseText);
		var url = '/_action/user/checkDisplayName?suggestion='+escape(suggestion.trim());
		doAjax(url, function(AJAX) {
			next = parseInt(AJAX.responseText) > next ? parseInt(AJAX.responseText) : next;
			if (getElement(field).value == '') getElement(field).value = next > 0 ? suggestion+'-'+next : suggestion;
			checkDomainUsage(getElement(field).value, msgField);	
		});
	});
}

//input: 
//domain = the text value for the domain name to be checked
//msgField (optional) = the form element to display the result of the check
//isValidDomain = the global boolean js var which holds the result of this check
function checkDomainUsage(domain, msgField) {
	var errorMsg;
	if(getElement(domain)) domain = getElement(domain).value;
	if (domainTimerSet) domainTimerSet = false;
	if (msgField) msgField = getElement(msgField);
	if(domain.trim()) {
		errorMsg = checkDomainRules(domain);
		if(errorMsg) {
			if (msgField) msgField.innerHTML = errorMsg;
			isValidDomain = false;			
		} else {
			if (msgField) msgField.innerHTML = 'Checking ... ';
			var url = '/_action/user/checkDomain?domain='+escape(domain);
			doAjax(url, function(AJAX) {
				if(AJAX.responseText == 1) {
					errorMsg = '<span style="font-weight:bold;font-style:italic;color:green;">Available!</span>';
					isValidDomain = true;
				} else if(AJAX.responseText == 2) {
					errorMsg = '<span style="font-weight:bold;font-style:italic;">Your Current Display Name</span>';
					isValidDomain = true;
				} else {
					errorMsg = '<span class="invalidMsg">Not Available</span>';
					isValidDomain = false;
				}
				if (msgField) msgField.innerHTML = errorMsg;
			});
		}
	} else {
		if (msgField) msgField.innerHTML = '';
		isValidDomain = false;
	}
}

function suggestionFilter(str) {
	var valid = '-1234567890abcdefghijklmnopqrstuvwxyz';
	for(var i=0; i < str.length; i++) {
		if(valid.indexOf(str.charAt(i)) == -1) {
			str = str.replace(str.charAt(i), '-');
		}
	}
	return str;
}

function checkDomainRules(str) {
	str = str.toLowerCase();
	var valid = '-1234567890abcdefghijklmnopqrstuvwxyz';
	var validAlpha = 'abcdefghijklmnopqrstuvwxyz';
	if(str.length > 60) {
		return '<span class="invalidMsg">Domain names must be less than 60 characters.</span>';
	} else if (str.charAt(0) == '-' || str.charAt(str.length-1) == '-') {
		return '<span class="invalidMsg">Domain names cannot start or end with a hyphen.</span>';
	} else {
		var foundAlpha = false;
		for(var i=0; i < str.length; i++) {
			if(valid.indexOf(str.charAt(i)) == -1) {
				return '<span class="invalidMsg">Only letters, numbers, and - are valid.</span>';
			}
			if (validAlpha.indexOf(str.charAt(i)) > -1)
				foundAlpha = true;
		}
		if (!foundAlpha)
			return '<span class="invalidMsg">Domain names need at least one alpha character.</span>';
	}
}














