﻿
/* make a JSON date look like .Net's ToString() */
function formatJSONDate(jsonDate) {
    return new Date(parseInt(jsonDate.replace(/\/Date[(](.*)[)]\//gi, "$1"))).format("m/d/yyyy h:M:ss TT");
}

/* take a comment structure and slap it into a container element.  
    typically the result of an AJAX based comment addition */
function showComment(container, comment) {
	var linkStart = '';
	var linkEnd = '';
	var userName = "";
	
	if (comment.display_url ) {
		linkStart = '<a href="' + comment.display_url + '">';
		linkEnd = '</a>';
	}

	userName = comment.display_username ? comment.display_username : "Anonymous";  

	container.html(container.html() +
		"<div><pre class=\"codeview_blog\">" + comment.display_content + "</pre></div>" +
		"<div>by " +  linkStart + userName+ linkEnd +" on " + comment.created.toString() +
		"</div><div class=\"spacer\"></div>");
} 

/* basic function through which all web service calls execute */
function callService(url, method, contentType, dataType, parameters, callback) {
    $.ajax(
        {
            "url": url,
            "type": method,
            "contentType": contentType,
            "dataType": dataType,
            "data": JSON.stringify(parameters),
            success:
                    function(res) {
                        callback(res);
                    },
            error:
                    function(xhr)
                    { alert(xhr.responseText); }
        }
    );
}

/* blog entry constructor */
function BlogEntry(blogEntryID) {
    var blogEntry = {
        /* primary key */
        id: blogEntryID,

        /* add a comment to the blog entry */
        addComment: function(body, creatorNickname, url, email_addy, callback) {
	
            var comment =
                {
                    "url": url,
                    "content": body,
                    "creator_nickname": creatorNickname,
		    "email_addy" : email_addy
                };

            callService("/api/article/" + this.id.toString() + "/comment", "POST", "application/json", "json", comment, callback);
        },

        /* get all the comments for the blog entry */
        getComments: function(callback) {
            callService("/api/article/" + this.id.toString() + "/comments", "GET", "application/json", "json", null, callback);

            return blogEntry;
        }
    };
    
    return blogEntry;
}


