// the comment textarea
var comment = document.getElementById('comment_field');

// if JS is available, show "preview" link
var previewnote = document.createElement('SPAN');
previewnote.className = 'textile';
previewnote.innerHTML = '<a href="#" onclick="return textile_preview()">Click to preview.</a>';
comment.parentNode.insertBefore(previewnote,comment);

// Textile help div
var helpvisible = false;
var help = document.createElement('DIV');
function textile_help() {
	if(helpvisible==true) {
		// if help has already been shown, allow link click to go through to Textile site
		return true;
	} else {
		// otherwise, set up help content and show it
		helpvisible = true;
		help.id = 'textilehelp';
		help.innerHTML = '<p><b>Textile:</b> Format your comment using the following conventions.</p><p>"A link":http://...</p><p>_<i>emphasis</i>_<br />*<b>strong</b>*<br />@<code>code</code>@</p><p># Numbered list<br />* Bulleted list<br />bq. Blockquote<br />bc. Block of code</p><p><a href="http://textile.thresholdstate.com/">More...</a></p>';
		document.getElementById('comments').appendChild(help);
		slide(540);
		return false;
	}
}
// slide out the help div
function slide(pos) {
	if(pos<680) {
		pos += 4;
		help.style.right = pos+'px';
		setTimeout('slide('+pos+')',10);
	} else {
		pos = 680;
		help.style.right = pos+'px';
	}
}

// show preview of Textile comment
var preview = document.createElement('DIV');
preview.id = 'commentpreview';
function textile_preview() {
	// get current form values
	var url = document.getElementById('website_field').value;
	var name = document.getElementById('name_field').value;
	// set up preview HTML
	var html = '<a href="#" onclick="close_preview(); return false" id="closepreview">close preview</a><h3>Preview your comment</h3><article class="comment"><header><p>';
	if(url.length>3) html += '<a href="'+url+'">'+name+'</a>';
	else html += name;
	html += '</p></header><div id="previewtext"><p>Loading preview...</p></div></article>';
	preview.innerHTML = html;
	// append preview
	document.getElementById('addcomment').appendChild(preview);
	// get preview from server
	if (window.XMLHttpRequest) {
		var previewtext = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		var previewtext = new ActiveXObject("Microsoft.XMLHTTP");
	}
	previewtext.onreadystatechange=function() {
		if(this.readyState==4) {
			document.getElementById("previewtext").innerHTML = this.responseText;
		}
	}
	previewtext.open("POST","http://www.insteadofthebox.com/.library/fly/textile_preview.php",true);
	previewtext.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	previewtext.send('text='+encodeURIComponent(comment.value));
	return false;
}

// close preview
function close_preview() {
	document.getElementById('addcomment').removeChild(preview);
}

