/// ajax comment posting and other stuff

function confirmdelete()
{
	return confirm('Are you sure you want to permanently delete this post?');
}
function confirmabuse()
{
	return confirm('Are you sure you want to flag this post for abuse?');
}
function confirmkick()
{
	return confirm('Are you sure you want to kick this user off?');
}

function addtoolbar(owner) {
	// Though we only call this once, there's a Firefox oddity
	// (view selection source) that can make it get called again.  So check
	// if we already did it. 
	if (!$('bbcode_toolbar')) {
		bbcode_toolbar = new Control.TextArea.ToolBar.BBCode(owner+'-body');
		bbcode_toolbar.toolbar.container.className = "bbcode_toolbar";
	}
}

function show_hide(show,hide) {
	if (show) {
		if (show=$(show)) {
			show.style.visibility="visible";
			show.style.display=""; // 7/3/9
		}
	}
	if (hide) {
		if (hide=$(hide)) {
			hide.style.visibility="hidden";
			hide.style.display="none";
		}
	}
	return false;
}


function show_admin_controls(blog) {
	show_hide('admin_controls_'+blog,false);
	//if (controls=$("admin_controls_"+blog)) {
	//	controls.style.visibility="visible";
	//	controls.style.display="block";
	//}
	return false;
}
function hide_admin_controls(blog) {
	show_hide(false,'admin_controls_'+blog);
	//if (controls=$("admin_controls_"+blog)) {
	//	controls.style.visibility="hidden";
	//	controls.style.display="none";
	//}
	return false;
}

function show_comment_form(owner) {
	if (form=$("formdiv"+owner)) {
		form.style.visibility="visible";
		form.style.display="block";
	}
	if (clickything=$("show_submit_form_"+owner)) {
		clickything.style.visibility="hidden";
		clickything.style.display="none";
	}
	if (form_head=$(owner+'-headline')) {
		form_head.focus();
	}
	return false;
}

// Now I want to change this to just scan the page for all discussion info that needs to be
// updated, instead of manually starting it for each discussion.

function auto_refresh_comments(owner) {
	period=0;
	if (commentlist=$(owner+'-comments')) {
		period=Number(commentlist.getAttribute('x-poll-period'));
	}
	if (!period)
		period=90;
	setTimeout('refresh_comments("'+owner+'","auto_refresh_comments(\''+owner+'\')")',period*1000);
}

function comment_set_error(owner,errmsg) {
	err=$(owner+'-error');
	err.innerHTML=errmsg;
	err.style.display='block';
	err.style.visibility='visible';
	new Effect.Highlight(err,{duration:1.0, startcolor: "#ffff00", endcolor: "#ff0000" });
}
function comment_clear_error(owner) {
	err=$(owner+'-error');
	err.innerHTML='';
	err.style.display='none';
	err.style.visibility='hidden';
}

function comment_form_disable(owner) {
	if (txt=$(owner+'-body')) {
		txt.disabled=1;
		txt.style.cursor='wait';
	}
	if (button=$(owner+'-button')) {
		button.disabled=1;
		button.style.cursor='wait';
	}
	if (preview=$(owner+'-preview')) {
		preview.innerHTML='';
	}
}
function comment_form_enable(owner) {
	if (txt=$(owner+'-body')) {
		txt.disabled=0;
		txt.style.cursor='';
	}
	if (button=$(owner+'-button')) {
		button.disabled=0;
		button.style.cursor='';
	}
}

function runglobal(code) {
	// some info about this at
	//  http://ajaxian.com/archives/evaling-with-ies-windowexecscript
	//  http://verens.com/archives/2006/03/31/dynamically-loading-external-scripts-in-safari/

	if (window.execScript) { // msie
		window.execScript(code); // eval in global scope for IE
	} else { // everyone else
		setTimeout(code,0);
	}
}

function runscripts(node) {
	// 9/10/8 eval scripts (for the flickr bbcode thingie) in newly-fetched comments
	while (node) {
		if (node.nodeName.toLowerCase()=='script') { // 11/17/8 to lower case, saf3 needs this
		
			// 11/18/8 fascinating FF3 oddity.  Apparently the child of the <script> tag (i.e.
			// the text of the script itself) can sometimes be chopped up.  Only FF3 does this.
			//alert(node.childNodes.length);  // should say "1" but FF3 sometimes says a bigger number
		
			// the old code. works for everything but ff3.
			// script=node.firstChild.nodeValue;
			// the new code. reassemble the fragmented script:
			script='';
			subscript=node.firstChild;
			while (subscript) {
				script=script+subscript.nodeValue;
				subscript=subscript.nextSibling;
			}
			runglobal(script);
		} else {
			runscripts(node.firstChild);
		}
		node=node.nextSibling;
	}
}

function comment_update(response) {
	commentblock=response.firstChild;
	while (commentblock) {
		if (commentblock.nodeName=='comments') {
			if (owner=commentblock.getAttribute('owner')) {
				// we're processing a <comments owner="thread-54"> type thing

				commentlist=$(owner+'-comments');
				cell_color_counter=commentlist.childNodes.length;
				
				if (commentlist) {
					last=Number(commentlist.getAttribute('x-last'));

					comment=commentblock.firstChild;
					while (comment) {
						if (comment.nodeName=='comment') {
							commentid=Number(comment.getAttribute('id'));
							if (commentid > last) {
								
								newitem=document.createElement('li');
								
								if (document.importNode) {
									// Firefox and Safari go this way:
									cmt=document.importNode(comment.firstChild,true);
									newitem.appendChild(cmt);
									newitem.innerHTML=newitem.innerHTML; // ridiculous hack to fix the 'type' of nodes
								} else {
									// MSIE 6&7 go this way
									// (though this method also works for Firefox (but not Safari!!)
									cmt=comment.firstChild.xml;
									newitem.innerHTML=cmt;
								}

								new Effect.Highlight(newitem.firstChild,{duration:2.0});

								commentlist.appendChild(newitem);

								runscripts(comment); // 9/10/8

								cell_color_counter++;
								if ((cell_color_counter % 2)>0) {
									newitem.firstChild.className='comment';
								} else {
									newitem.firstChild.className='altcomment';
								}

								last=commentid;
								commentlist.setAttribute('x-last',last);
							}
						}
						comment=comment.nextSibling;
					}
				}
			}
		} else if (commentblock.nodeName=='submit') {
			if (owner=commentblock.getAttribute('owner')) {
				comment_form_enable(owner);
				if (stat=Number(commentblock.getAttribute('success'))) {
					// clear the form
					$(owner+'-headline').setValue('');
					$(owner+'-body').setValue('');
					comment_clear_error(owner);
				} else {
					comment_set_error(owner,commentblock.getAttribute('error'));
				}
			}
		} else if (commentblock.nodeName=='deleted') {
			if (id=commentblock.getAttribute('id')) {
				if (comment=$(id)) {
					comment=comment.parentNode; // the <li> element above it
					par=comment.parentNode; // the <ul> element
					par.removeChild(comment);
					// Swell, it's deleted.  But now you have to change the class of every
					// comment after the one we just deleted.  Easiest to just start at the top.
					comment=par.firstChild;
					cell_color_counter=0;
					while (comment) {
						cell_color_counter++;
						if ((cell_color_counter % 2)>0) {
							comment.firstChild.className='comment';
						} else {
							comment.firstChild.className='altcomment';
						}
						comment=comment.nextSibling;
					}
				} else alert('did not find comment '+id);
			} else alert('no id?');
		} else if (commentblock.nodeName=='preview') {
			if (owner=commentblock.getAttribute('owner')) {
				comment_form_enable(owner);
				if (prevdiv=$(owner+'-preview')) {
					if (document.importNode) {
						// Firefox and Safari go this way:
						cmt=document.importNode(commentblock.firstChild,true);
						prevdiv.appendChild(cmt);
						prevdiv.innerHTML=prevdiv.innerHTML; // ridiculous hack to fix the 'type' of nodes
					} else {
						// MSIE 6&7 go this way
						// (though this method also works for Firefox (but not Safari!!)
						cmt=commentblock.firstChild.xml;
						prevdiv.innerHTML=cmt;
					}
					runscripts(prevdiv.firstChild);
				}
			}
		}
		commentblock=commentblock.nextSibling;
	}
}

function refresh_comments(owner,cb) {
	// ask for all comments newer than the last one that we have
	commentlist=$(owner+'-comments');
	if (commentlist) {
		last=Number(commentlist.getAttribute('x-last'))
	} else
		last=0;
	
	new Ajax.Request('/',
	{
		method: 'get',
		parameters: new Hash( { ajax_function: 'get_comments',
								owner: owner,
								later_than: last,
								detail: 1
							   } ),
		onComplete: function(transport) {
			comment_update(transport.responseXML.documentElement);
		}
	});
	
	if (cb) {
		setTimeout(cb,0);
	}

	return false;
}

function submit_comment(owner,sessiontoken) {
	// called by submit button's onclick
	// weirdness note: returns true on failure, false on success
	if (form=$(owner+'-form')) {	
	
		head=$(owner+'-headline').getValue();
		body=$(owner+'-body').getValue();

		// we're not _just_ submitting a comment; we're also going to get an update, so send the # of the
		// latest comment we have
		commentlist=$(owner+'-comments');
		if (commentlist) {
			last=Number(commentlist.getAttribute('x-last'))
		} else
			last=0;

		new Ajax.Request('/',
		{
			method: 'get',
			parameters: new Hash( { ajax_function: 'post_comment',
									owner: owner,
									later_than: last,
									detail: 1,
									submitted_blog_head: head,
									submitted_blog_text: body,
									token: sessiontoken
								   } ),
			onComplete: function(transport) {
				//alert(transport.responseText);
				comment_update(transport.responseXML.documentElement);
			}
		});
		comment_form_disable(owner);
		return false;
	} else
		return true;
}

function delete_comment(comment_id,sessiontoken) {
	if (confirmdelete()) {
		new Ajax.Request('/',
		{
			method: 'get',
			parameters: new Hash( { ajax_function: 'delete_comment',
									comment_id: comment_id,
									token: sessiontoken
								   } ),
			onComplete: function(transport) {
				//alert(transport.responseText);
				comment_update(transport.responseXML.documentElement);
			}
		});
	}
	return false;
}


function preview_comment(owner,sessiontoken) {
	// called by preview button's onclick
	// weirdness note: returns true on failure, false on success
	if (form=$(owner+'-form')) {	
	
		head=$(owner+'-headline').getValue();
		body=$(owner+'-body').getValue();


		new Ajax.Request('/',
		{
			method: 'get',
			parameters: new Hash( { ajax_function: 'preview_comment',
									owner: owner,
									submitted_blog_head: head,
									submitted_blog_text: body,
									token: sessiontoken
								   } ),
			onComplete: function(transport) {
				//alert(transport.responseText);
				comment_update(transport.responseXML.documentElement);
			}
		});
		comment_form_disable(owner);
		comment_clear_error(owner);
		return false;
	} else
		return true;
}

function postcomment(form) {
	// for when AJAX failed.  Send the form with HTTP POST
	if (form) {
		form.submit();
	}
}

function reply_to(blog,owner) {
	reply_to_body=$('blog_text_'+blog);
	form_body=$(owner+'-body');
	if (reply_to_body && form_body) {
		form_body.value = form_body.value+'[quote]'+dom_to_bbcode(reply_to_body.firstChild)+'[/quote]';
		form_body.focus();
	}
	return false;
}

function dom_to_bbcode(element) {
	// return bbcode for a dom tree
	retval='';
	if (element) {
		switch (element.nodeType) {
			case 1: // element
				switch (element.nodeName) {
					case 'BLOCKQUOTE':
						retval='[quote]'+dom_to_bbcode(element.firstChild)+'[/quote]';
						break;
					case 'I':
						retval='[i]'+dom_to_bbcode(element.firstChild)+'[/i]';
						break;
					case 'B':
						retval='[b]'+dom_to_bbcode(element.firstChild)+'[/b]';
						break;
					case 'IMG':
						retval='[img]'+element.getAttribute('src')+'[/img]';
						break;
					case 'BR':
						// do nothing; the text already has as newline in it.
						//retval='\n';
						break;
					case 'SPAN':
						style=element.getAttribute('style');
						if (style=='text-decoration: line-through;')
							retval='[strike]'+dom_to_bbcode(element.firstChild)+'[/strike]';
						else if (style.substr(0,6)=='color:')
							retval='[color:'+style.substr(7)+']'+dom_to_bbcode(element.firstChild)+'[/color]';
						else
							retval=dom_to_bbcode(element.firstChild);
	
						break;
					case 'A':
						href=element.getAttribute('href');
						if (href.substr(0,7)=='mailto:')
							retval='[email]'+href.substr(7)+'[/email]';
						else
							retval='[url='+href+']'+dom_to_bbcode(element.firstChild)+'[/url]';
						break;
					case 'EMBED':
						// transform the embed version back into URL version
						//         http://www.youtube.com/v/j30JEyXzldo&amp;hl=en
						// becomes http://www.youtube.com/watch?v=j30JEyXzldo
						src=element.getAttribute('src');
						matcher=/(?:^.*)(?:\/v\/)(.*)(?:&.*$)/;
						video=matcher.exec(src)[1];
						retval='[youtube]http://www.youtube.com/watch?v='+video+'[/youtube]';
						break;
					default:
						retval=dom_to_bbcode(element.firstChild);
						break;
				}
				break;
			case 3: // text
				retval=element.nodeValue;
				break;
		}
		next=element.nextSibling;
		if (next)
			retval=retval+dom_to_bbcode(next);
	}
	return retval;
}

// poor msie6 isn't very clueful about :hover
function msie6_userpop_mouseover(li) {
	node=li.firstChild;
	while (node) {
		//alert(node.nodeName);
		if (node.nodeName == 'UL')
			node.style.display='block';
		node=node.nextSibling;
	}
}
function msie6_userpop_mouseout(li) {
	node=li.firstChild;
	while (node) {
		if (node.nodeName == 'UL')
			node.style.display='none';
		node=node.nextSibling;
	}
}