// General functions
var _commentAdded = false;
var _commentModerated = false;

function cancelDefault(evt)
{
	if( typeof(evt.preventDefault) == "function" )
		evt.preventDefault();
	else
		evt.returnValue = false;
}

function createHtmlElement(name)
{
	if( typeof(document.createElementNS) == "function" )
		return document.createElementNS("http://www.w3.org/1999/xhtml", name);
	else
		return document.createElement(name);
}

function createHtmlElementWithText(name, text)
{
	var elt = createHtmlElement(name);
	elt.appendChild(document.createTextNode(text));
	return elt;
}

function clearElement(elt)
{
	while( elt.childNodes.length > 0 )
		elt.removeChild(elt.childNodes[0]);
}

// Comment loading
function callGetComments(refid)
{
    var types = new Array();
    types.push("Comment");
    var m = new WebMethod("/CommentService.asmx", "http://www.ookii.org/CommentService", "GetComments", types, commentDownloadComplete, commentDownloadError);
    m.refid = refid;
    var params = new CompoundObject();
    params.refid = refid;
    m.call(params);
    
    return m;
}

function getComments(refid)
{
	var comments = document.getElementById("comments" + refid);
	clearElement(comments);
	comments.appendChild(createHtmlElementWithText("h4", "Comments"));
	comments.appendChild(createHtmlElementWithText("p", "Loading comments..."));
	
	comments.request = callGetComments(refid);
}

function showComments(refid, sender, evt, originalText)
{
	var comments = document.getElementById("comments" + refid);
	if( comments.style.display == "none" )
	{
		sender.oldText = sender.firstChild.nodeValue;
		sender.firstChild.nodeValue = "Hide comments";
		comments.style.display = "block";
		getComments(refid);
	}
	else
	{
	    if( comments.request )
	        comments.request.abort();
		sender.firstChild.nodeValue = originalText ? originalText : sender.oldText;
		clearElement(comments);
		comments.style.display = "none";
	}
	cancelDefault(evt);
}

function createComment(list, c)
{
	var item = createHtmlElement("li");
	if( c.AuthorComment == "true" )
	    item.className = "authorComment";
	var comment = createHtmlElement("p");
	comment.innerHTML = c.Comment
	item.appendChild(comment);
	var author = createHtmlElement("p");
	author.className = "author";
	author.appendChild(document.createTextNode("Posted by "));
	if( !c.Link || c.Link.length == 0 )
		author.appendChild(document.createTextNode(c.Name));
	else
	{
		var anchor = createHtmlElement("a");
		anchor.href = c.Link;
		if (c.AutorComment != "true")
		    anchor.rel = "nofollow";
		anchor.appendChild(document.createTextNode(c.Name));
		author.appendChild(anchor);
	}
	var date = c.DateAdded;
	var parts = date.split("T");
	var index = parts[1].indexOf(".");
	if( index != -1 )
	    parts[1] = parts[1].substr(0, index);
	author.appendChild(document.createTextNode(" on " + parts[0] + " " + parts[1] + " UTC"));
	item.appendChild(author);
	
	list.appendChild(item);
}

function commentDownloadError(msg)
{
    var comments = document.getElementById("comments" + this.refid);
    clearElement(comments);
    comments.request = null;
	comments.appendChild(createHtmlElementWithText("h4", "Comments"));
	comments.appendChild(createHtmlElementWithText("p", "Could not load comments: " + msg));
}

function commentDownloadComplete(result)
{
    var comments = document.getElementById("comments" + this.refid);
    clearElement(comments);
    comments.request = null;
	comments.appendChild(createHtmlElementWithText("h4", "Comments"));
	if( result != null && result.Comments != null && result.Comments.length > 0 )
	{
		var list = createHtmlElement("ul");
		comments.appendChild(list);
		for( var x = 0; x < result.Comments.length; ++x )
		{
			createComment(list, result.Comments[x]);
		}
	}
	else
	{
		comments.appendChild(createHtmlElementWithText("p", "There are no comments."));
	}

    if( _commentAdded )	
    {
        if( _commentModerated )
            comments.appendChild(createHtmlElementWithText("p", "Your comment has been added. It may not be visible immediately due to caching or moderation."));
        else        
	        comments.appendChild(createHtmlElementWithText("p", "Your comment has been added. It may not be visible immediately due to caching."));
	    _commentAdded = false;
	}
	
    if( result.AllowNewComments == "true" )
    {
	    var addcommentlink = createHtmlElement("p");
	    addcommentlink.id = "addcommentlink" + this.refid;
	    var anchor = createHtmlElement("a");
	    anchor.href = "javascript:showAddComment(" + this.refid + ")";
	    anchor.appendChild(document.createTextNode("Add comment"));
	    addcommentlink.appendChild(anchor);
	    comments.appendChild(addcommentlink);
    }
    else
    {
        comments.appendChild(createHtmlElementWithText("p", "Adding comments is disabled for this post."));
    }
}

function showAddComment(refid)
{
	var addcommentlink = document.getElementById("addcommentlink" + refid);
	addcommentlink.parentNode.removeChild(addcommentlink);
	var comments = document.getElementById("comments" + refid);
	var header = createHtmlElement("h4");
	header.appendChild(document.createTextNode("Add comment"));
	comments.appendChild(header);
	
	var form = createHtmlElement("form");
	form.onsubmit = postComment;
	form.action = "postcomment.aspx";
	form.method = "post";
	var div = createHtmlElement("div");
	var hiddenInput = createHtmlElement("input");
	hiddenInput.type = "hidden";
	hiddenInput.name = "refid";
	hiddenInput.id = "comment" + refid + "_refid";
	hiddenInput.value = refid;
	div.appendChild(hiddenInput);
	form.appendChild(div);
	
	var dl = createHtmlElement("dl");
	
	var idBase = "comment" + refid;
	
	var nameInput = addFormElementToDL(dl, "Name:", "input", "name", idBase);	
	nameInput.type = "text";
	nameInput.size = 50;
	nameInput.maxLength = 50;
	
	var linkInput = addFormElementToDL(dl, "E-mail or web address (optional):", "input", "link", idBase);
	linkInput.type = "text";
	linkInput.size = 50;
	linkInput.maxLength = 256;

	var commentArea = addFormElementToDL(dl, "Comment:", "textarea", "comment", idBase);
	commentArea.cols = 50;
	commentArea.rows = 5;
	
	form.appendChild(dl);
	
	div = createHtmlElement("div");
	var input = createHtmlElement("input");
	input.type = "submit";
	input.name = "commentSubmit";
	input.id = idBase + "_commentSubmit"
	input.value = "Post comment";
	div.appendChild(input);
	form.appendChild(div);
	
	comments.appendChild(form);
	comments.style.display = "block";	
}

function addFormElementToDL(dl, text, tagName, eltName, eltIDBase)
{
	dt = createHtmlElement("dt");
	label = createHtmlElement("label");
	var id = eltIDBase + "_" + eltName;
	label.htmlFor = id;
	label.appendChild(document.createTextNode(text));
	dt.appendChild(label);
	dl.appendChild(dt);

	dd = createHtmlElement("dd");
	var formElt = createHtmlElement(tagName);
	formElt.id = id
	formElt.name = eltName;
	dd.appendChild(formElt);
	dl.appendChild(dd);

	return formElt;
}

// Posting related functions
function callPostComment(refid, name, link, comment)
{
    var m = new WebMethod("/CommentService.asmx", "http://www.ookii.org/CommentService", "PostComment", null, postComplete, postComplete);
    m.refid = refid;
    var params = new CompoundObject();
    params.refid = refid;
    params.name = name;
    if( link )
        params.link = link;
    params.comment = comment;
    m.call(params);
}

function postComment(evt)
{
	if( evt == null )
		evt = event;
	
	postCommentForm(this, evt);
}

function postCommentForm(form, evt)
{
	var refid = form.elements[0].value;
	_postrefid = refid;
	var name = form.elements[1].value;
	var link = form.elements[2].value;
	var comment = form.elements[3].value;	
	if( checkInput(name, link, comment) )
	{
		var comments = form.parentNode;
		clearElement(comments);
		var commentslink = document.getElementById("commentsLink" + refid);
		commentslink.style.display = "none";

		comments.appendChild(createHtmlElementWithText("h4", "Comments"));
		comments.appendChild(createHtmlElementWithText("p", "Posting comment..."));
		callPostComment(refid, name, link, comment);		
	}
	cancelDefault(evt);
}

function postComplete(result)
{
    if( result == "moderated" )
    {
        _commentAdded = true;
        _commentModerated = true;
    }
    else if( result != null )
		alert("Could not post your comment: " + result);
	else
	{
	    _commentAdded = true;
	    _commentModerated = false;
	}
	
	var commentslink = document.getElementById("commentsLink" + this.refid);
	commentslink.style.display = "";
	getComments(this.refid);
}

function checkInput(name, link, comment)
{
	if( name.length == 0 )
		alert("You must enter a name.");
	else if( name.length > 50 )
		alert("Your name is too long");
	else if( comment.length == 0 )
		alert("You must enter a comment.");
	else if( link.length != 0 )
	{
		var re = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
		if( !(re.test(link) || (link.substring(0,7).toLowerCase() == "http://" && link.length > 7)) )
			alert("You must provide either a valid e-mail address or a link starting with http://");
		else
			return true;
	}
	else
		return true;
	
	return false;
}
