﻿//
// Setting up a common Blog object for ajaxing purposes; with all the defaults
//
var httpBlogPost           = HttpObj();
var httpBlogCategory       = HttpObj();
var httpBlogRecentComments = HttpObj();

var BlogObjAjax =
{ 
    IsReady:false,
    Post:     { Active:false, 
                SetActive:function(b) { this.Active=b; },
                LastResponse:'',
                Timer: { Load:false, ReLoad:function() { clearTimeout(this.Load); BlogObjAjax.Post.Active=false; this.Load=arguments[0]; Blog.ScrollPageToFocus = false },
                         Kill:function() { BlogObjAjax.Post.Timer.ReLoad(null); } },
                CurrentView: { Args: { Type: 'All', Page: 1, Id:0, Month:getDate().getMonth+1, Year:getDate().getFullYear() },
                               Reset:function() { this.Args.Type='All'; this.Args.Page=1;
                                                  this.Args.Month=getDate().getMonth+1; this.Args.Year=getDate().getFullYear(); } } },
    Category: { Active:false, 
                LastResponse:'',
                SetActive:function(b) { this.Active=b; }, 
                Timer: { Load:false, ReLoad:function() { clearTimeout(this.Load); BlogObjAjax.Category.Active=false; this.Load=arguments[0]; },
                         Kill:function() { BlogObjAjax.Category.Timer.ReLoad(null); } } },
    RecentComments: { Active:false, 
                      LastResponse:'',
                      SetActive:function(b) { this.Active=b; }, 
                      Timer: { Load:false, ReLoad:function() { clearTimeout(this.Load); BlogObjAjax.RecentComments.Active=false; this.Load=arguments[0]; },
                               Kill:function() { BlogObjAjax.RecentComments.Timer.ReLoad(null); } } },
    Archive: { SwapStaticLinks: function(arA) {
                                  for (var i=0; i < arA.length; i++) { var my = arA[i].id.split(/\./g); arA[i].href = "javascript:doBlogPostMethod('"+my[0]+"',1,"+my[1]+","+my[2]+");"; }
                                } },
    Kill : function() {
                this.Post.Timer.ReLoad(null); this.Category.Timer.ReLoad(null); this.RecentComments.Timer.ReLoad(null);
                BlogObjAjax.IsReady = false;
            }
};

//
// Setting up a the Blog object for some javascriptin'
//

var Blog =
{
    Post: { ID:0, // ID & Comments only used when this object is used in single form
            Items:[],
            Count:function() { return this.Items.length; },
            Comments: { Items:[],
                        Count:function() { return this.Items.length; } } },
    Category: { Items:[],
                Count:function() { return this.Items.length; } },
    RecentComments: { Items:[],
                      Count:function() { return this.Items.length; } },
    ScrollPageToFocus: true,
    UseAccordianScroll: false
};

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//
// METHODS: Gathering Blog Post Data
//
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function getBlogPostAll(page)
{
    var AjaxParams = "InjectionFree=true&AjaxAction=Load_BlogPost&Type=All";
    loadBlogPost(AjaxParams);
}
function getBlogPostPageByCategory(page, id)
{
    var AjaxParams = "InjectionFree=true&AjaxAction=Load_BlogPost&Type=Category&Id="+id
    loadBlogPost(AjaxParams);
}
function getBlogPostPageByArchive(page, month, year)
{
    var AjaxParams  = "InjectionFree=true&AjaxAction=Load_BlogPost&Type=Archive&Month="+month+"&Year="+year;
    loadBlogPost(AjaxParams);
}
function getBlogPostPageById(page, id, focus)
{
    var AjaxParams  = "InjectionFree=true&AjaxAction=Load_BlogPostWithComments&Type=Post&Id="+id;    
    loadBlogPostWithComments(AjaxParams, focus);
}
function doBlogPostMethod()
{ 
    var args = doBlogPostMethod.arguments;
    var type, page, id, month, year, focus;
    var prevType = BlogObjAjax.Post.CurrentView.Args.Type;
    
    type = (args.length > 0 ? args[0] : BlogObjAjax.Post.CurrentView.Args.Type);
    page = (args.length > 1 ? args[1] : BlogObjAjax.Post.CurrentView.Args.Page);
    
    BlogObjAjax.Post.CurrentView.Args.Page = page;
    BlogObjAjax.Post.CurrentView.Args.Type = type;
    
    if ('Category' == type || 'Post' == type)
    {
        id = (args.length > 2 ? args[2] : BlogObjAjax.Post.CurrentView.Args.Id);
        focus = (args.length > 3 ? args[3] : '');
        BlogObjAjax.Post.CurrentView.Args.Id = id;
    }
    else if ('Archive' == type)
    {
        month = (args.length > 2 ? args[2] : BlogObjAjax.Post.CurrentView.Args.Month);
        year  = (args.length > 3 ? args[3] : BlogObjAjax.Post.CurrentView.Args.Year);
        BlogObjAjax.Post.CurrentView.Args.Month = month;
        BlogObjAjax.Post.CurrentView.Args.Year  = year;
    }
    
    // in any case where we are loading a different view than the actual post, and the last
    // view was a post.. then we want to supress the comments/reply section for that post
    // and reset the timer... because the timer is at a stand-still when full post is in view
    if ('Post' == prevType && 'Post' != type)
    {
        hideBlogCommentsAndReply();
        BlogObjAjax.Post.Timer.ReLoad(null);	       
    }
        
    // lets reset the purple astericks (if any).  We don't want them showing from view to view
    // if it's not applicable.  We'll also reset the form.    
    ResetLastErrorState();
    
    // Clear out any initiated reply on the comment form
    ResetBlogReplyForm();
    
    // You may notice that some of these functions do not need the page for any processing,
    // however, it needs to be included with all function calls in order to make this
    // method modular like it is.  All links which come here use the type,page[,etc...]
    // argument list.
 
    switch(type)
    {
        case      'All': getBlogPostAll(page); break;
        case 'Category': getBlogPostPageByCategory(page, id); break;
        case  'Archive': getBlogPostPageByArchive(page, month, year); break;
        case     'Post': getBlogPostPageById(page, id, focus); break;
        default: getBlogPostAll(1); break;
    }
}

function loadBlogPost(AjaxParams)
{
	if (! BlogObjAjax.Post.Active && BlogObjAjax.IsReady)
	{
	    BlogObjAjax.Post.SetActive(true);
	    
	    try
	    {		    
		    httpBlogPost.open('POST', 'controls/ajaxLib.aspx', true);
		    httpBlogPost.onreadystatechange = function() {
		    
			    if (httpResponseIsValid(httpBlogPost))
                {                    
                    var _json = httpBlogPost.responseText.replace(/\\\"/g,'"');

                    var ResultObj = eval('(' + _json + ')');
                    doBlogPostOutput(ResultObj);
			    }
			    else
			        BlogObjAjax.Post.Timer.ReLoad(setTimeout("doBlogPostMethod();", SiteSettings.Blog.Post.RefreshRate+60000)); //let's give it some time			    
			        
		    };
		    httpBlogPost.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		    httpBlogPost.send(AjaxParams);
	    }
	    catch (e)
	    {
            BlogObjAjax.Post.Timer.ReLoad(setTimeout("doBlogPostMethod();", SiteSettings.Blog.Post.RefreshRate+60000)); //let's give it some time
	    }
    }
    else
        BlogObjAjax.Post.Timer.ReLoad(setTimeout("doBlogPostMethod();", SiteSettings.Blog.Post.RefreshRate));
}

function sizePostIframe(id,c)
{
    try
    {
        c++;
        var f = docObj(id);
        
    }
    catch(e)
    {
        if (c < 10)
            setTimeout('sizePostIframe('+id,c+');',50);
    }
    
}

function doBlogPostOutput(Obj)
{
    var strOutput='';

    docObj('Blog_Posts').innerHTML = '';
    
    if (Obj.Items && Obj.Items.length) // should always be defined
    {
        Blog.Post.Items = Obj.Items;

        var countFrom = 0;
        if (BlogObjAjax.Post.CurrentView.Args.Page != 1)
            countFrom = (BlogObjAjax.Post.CurrentView.Args.Page * SiteSettings.Blog.Post.PageCount) - SiteSettings.Blog.Post.PageCount; 
        var countTo   = countFrom + SiteSettings.Blog.Post.PageCount;

        if ('Category' == BlogObjAjax.Post.CurrentView.Args.Type)
        {
            strOutput += '<h2 class="pagetitle">Archive: '+Obj.Category+'</h2>';
        }
        else if ('Archive' == BlogObjAjax.Post.CurrentView.Args.Type)
        {
            strOutput += '<h2 class="pagetitle">Archive: '+formatDate('month',BlogObjAjax.Post.CurrentView.Args.Month) + ' ' + BlogObjAjax.Post.CurrentView.Args.Year+'</h2>';
        }

        if (Blog.Post.Count() > 0)
        {
            // BEGIN: Post creation
        
            for (var i = countFrom; i < countTo; i++)
            {
                Post = Blog.Post.Items[i];
                if (Post)
                {
                    strOutput += '<table id="BlogPost.'+Post.id+'" class="postcontainer" width="485" cellpadding="0" cellspacing="0" border="0">';
                    strOutput += '<tr>';
                    strOutput +=  '<td width="20" class="postdate" valign="top">';
                    strOutput +=   '<span class="day"><strong>'+Post.Date.day+'</strong></span><strong class="month">'+Post.Date.month+'</strong>';
                    strOutput +=  '</td>';
                    strOutput +=  '<td valign="top" width="465">';
                    strOutput +=    '<div class="posthead">';
                    strOutput +=     '<h1 class="title"><a href="javascript:doBlogPostMethod(\'Post\',1,'+Post.id+');" rel="bookmark">'+Post.title+'</a></h1>';
                    strOutput +=     '<p class="postmeta">Posted by '+Post.user+' as <em>';
                    strOutput +=     '<a href="javascript:doBlogPostMethod(\'Category\',1,'+Post.Category.id+');" title="View all posts in '+Post.Category.title+'" rel="category">'+Post.Category.title+'</a></em></p>';
                    strOutput +=    '</div>';
                    strOutput +=  '</td>';
                    strOutput += '</tr>';
                    strOutput += '<tr>';
                    strOutput +=  '<td colspan="2"><div class="entry"><p>'+txt2Html(Post.post)+'</p></div></td>';               
                    strOutput += '</tr>';
                    strOutput += '<tr>';
                    strOutput +=  '<td colspan="2">';
                    strOutput +=   '<div class="postmetadata">';
                    strOutput +=    '<span class="permalink"><a href="'+Post.permalink+'">Permalink</a></span>';
                    strOutput +=    '<span class="comments"><a href="javascript:doBlogPostMethod(\'Post\',1,'+Post.id+',\'comments\');">'+Post.Comments.count+' Comment'+(Post.Comments.count!=1?'s':'')+'</a></span>';
                    //strOutput +=    '<span class="trackback'+oTheme+'">'+Post.Trackbacks.count+' Trackback'+(Post.Trackbacks.count!=1?'s':'')+'</span>';
                    strOutput +=    '<span class="comment"><a href="javascript:doBlogPostMethod(\'Post\',1,'+Post.id+',\'reply\');">Comment on this Post</a></span>';
                    strOutput +=   '</div>';
                    strOutput +=  '</td>';
                    strOutput += '</tr>';
                    strOutput += '</table>';
                }

                docObj('Blog_Posts').innerHTML += strOutput;  
                strOutput = '';
            }

            // decipher if we should throw a pagination section at the bottom
            // of the postings

            if (Blog.Post.Count() > SiteSettings.Blog.Post.PageCount && BlogObjAjax.Post.CurrentView.Args.Type != 'Post')
            {
                var blogLnkEvent, postLnk = '';
                var totalPages = Math.ceil(Blog.Post.Count()/SiteSettings.Blog.Post.PageCount);

                for (var pageIndex = 1; pageIndex <= totalPages; pageIndex++)
                {                
                    // not the prettiest, but deciphering which method to include in the pagination
                    // each one takes different arguments, so we just build based on which method the
                    // user is currently utilizin'
                    // argument[0] => PageType
                    // argument[1] => PageIndex
                    // argument[2] => Id or Month
                    // argument[4] => Year
                    
                    var args = new Array('\''+BlogObjAjax.Post.CurrentView.Args.Type+'\'');                

                    switch(BlogObjAjax.Post.CurrentView.Args.Type)
                    {
                        case      'All': args.push(pageIndex); break;
                        case 'Category': args.push(pageIndex,BlogObjAjax.Post.CurrentView.Args.Id); break;
                        case  'Archive': args.push(pageIndex,BlogObjAjax.Post.CurrentView.Args.Month,BlogObjAjax.Post.CurrentView.Args.Year); break;
                        default:         args.push(pageIndex); break;
                    }

                    postLnk += '<a onclick="doBlogPostMethod('+args.toString()+');" ';
                    postLnk += (pageIndex==BlogObjAjax.Post.CurrentView.Args.Page?'class="selected"':'')+'>'+pageIndex+'</a>';
                }

                var prevPageArgs = nextPageArgs = false;
                if (BlogObjAjax.Post.CurrentView.Args.Page > 1)
                {
                    // remember: argument[1] is the page index
                    args[1] = BlogObjAjax.Post.CurrentView.Args.Page - 1;
                    prevPageArgs = args.toString();
                }
                if (BlogObjAjax.Post.CurrentView.Args.Page < totalPages)
                {
                    args[1] = BlogObjAjax.Post.CurrentView.Args.Page + 1;
                    nextPageArgs = args.toString(); 
                }
        
                strOutput += '<div class="blog_pagination">';
                strOutput +=  '<span class="page_left">';
                strOutput +=    (prevPageArgs ? '<a onclick="doBlogPostMethod('+prevPageArgs+');">Previous</a>' : 'Previous') + '</span>';
                strOutput +=  '<span class="page_num">'+postLnk+'</span>';
                strOutput +=  '<span class="page_right">';
                strOutput +=    (nextPageArgs ? '<a onclick="doBlogPostMethod('+nextPageArgs+');">Next</a>' : 'Next') + '</span>';
                strOutput += '</div>';
            }
            
            //END: Post creation
            
        }
        else //> no posts exist
        {
            if ('Category' == BlogObjAjax.Post.CurrentView.Args.Type)
            {
                strOutput += '<div class="entry"><p>No posts are available for this category.</p></div>'; 
            }
            else if ('Archive' == BlogObjAjax.Post.CurrentView.Args.Type) // will probably never happen since it is dependent on posts to begin with.
            {
                strOutput += '<div class="entry"><p>Posts no longer exist for this archive.</p></div>';
            }
            else
                strOutput += '<div class="entry"><p>This post is no longer available.</p></div>';
        }
    }
    
    docObj('Blog_Posts').innerHTML += strOutput;
        
    
    if ('Post' != BlogObjAjax.Post.CurrentView.Args.Type)
    {
        var rightColHt = docObj('Blog_Right_Column').offsetHeight;
        var leftColHt  = docObj('Blog_Left_Column').offsetHeight;
        
        var ht2Use = leftColHt;
        if (rightColHt > ht2Use)
            ht2Use = rightColHt;
        else
            ht2Use += 30;

        if (! Blog.UseAccordianScroll)
            docObj('blogBox').style.height = ht2Use + 'px';
        else
            Blog.UseAccordianScroll = false;
        
        OmniCordion.display(2);
        BlogObjAjax.Post.Timer.ReLoad(setTimeout("doBlogPostMethod();", SiteSettings.Blog.Post.RefreshRate));
    }
    
    loadPageFocus();
}

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//
// METHODS: Gathering Blog Post Comment Data
//
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function loadBlogPostWithComments(AjaxParams, focus)
{
	// Since we are going to view the post and it's comments in full, we will kill the normal 
	// post timer as it is uneccessary at this point.
	
	BlogObjAjax.Post.Timer.Kill();	
	
	if (! BlogObjAjax.Post.Active && BlogObjAjax.IsReady)
	{
	    BlogObjAjax.Post.SetActive(true);
	    
	    try
	    {		    
		    httpBlogPost.open('POST', 'controls/ajaxLib.aspx', true);
		    httpBlogPost.onreadystatechange = function() {
		    
			    if (httpResponseIsValid(httpBlogPost))
                {                    
                    var _json = httpBlogPost.responseText.replace(/\\\"/g,'"');

                    var ResultObj = eval('(' + _json + ')');
                    doBlogPostOutputWithComments(ResultObj, focus);
			    }
			    			        
		    };
		    httpBlogPost.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		    httpBlogPost.send(AjaxParams);
	    }
	    catch (e)
	    {
            // throw some error
	    }
    }
    else
    {
        // throw some other error
    }
}

function doBlogPostOutputWithComments(Obj, focus)
{
    var strOutput='';
    var oTheme = SiteSettings.Theme.current.id;
    
    docObj('Blog_Comments').innerHTML = '';
    
    //using our method above to help us out with this single post listing
    doBlogPostOutput(Obj);

    if (Obj.Items)
    {
        Post = Obj.Items[0]; // this came back as an array because I hijacked some functions
                             // which was pre-formatted this way.
        
        Comments = Obj.Comments;     // comments are brought back as a separate array object
        Trackbacks = Obj.Trackbacks; // trackbacks are brough tback as separate array with Comments
        
        strOutput += '<h2>'+Post.Trackbacks.count+' Trackback(s) on "'+Post.title+'"</h2>';
        strOutput += '<ul class="commentlist">';
        strOutput +=  '<li>';
        strOutput +=   '<span class="trackbackintro">Listed below are links to blogs that reference this entry.<br />';
        strOutput +=     'The TrackBack URL for this entry is:<br /><div class="trackbackintrolink">' + Post.trackback + '</div>';
        strOutput +=   '</span><br />';
        
        if (Trackbacks.Items && Trackbacks.Items.length > 0)
        {
            for (var i = 0; i < Trackbacks.Items.length; i++)
            {
                Trackback = Trackbacks.Items[i];
                var lnkTitle = Trackback.url;
                if (Trackback.title != '')
                    lnkTitle = Trackback.title;
                
                strOutput += '<strong><a href="'+Trackback.url+'" target="_new">'+lnkTitle+'</a></strong><br />';
            }
        }
        else
            strOutput += '<em>No trackbacks listed.</em>';
        
        strOutput +=  '</li>';
        strOutput += '</ul>';
        
        strOutput += '<h2>'+Post.Comments.count+' Comment(s) on "'+Post.title+'"</h2>';
        strOutput += '<ul id="ulCommentList" class="commentlist">';
        
        strOutput += doBlogComment(Obj, Comments, false);
        
        strOutput += '</ul>';

        docObj('Blog_Comments').innerHTML = strOutput;

        //if (docObj('ifrmRTE').src.match(/\.htm$/g))
        //    docObj('ifrmRTE').src = FormObjAjax.BasePath + '/controls/FreeTextBox/ftb.aspx';
        
        docObj('Blog_Comment_Column').style.display = 'block';

        docObj('blogBox').style.height = (docObj('Blog_Left_Column').offsetHeight+30) + 'px';
        OmniCordion.display(2);
        loadPageFocus(focus);
    }
    else
    {
        initBlog();
        // post was deleted while user was trying to refresh that post
    }
}

function doBlogComment(BaseObj, Comments, isReply)
{
    strOutput = '';

    if (Comments.Items)
    {
        for (var i = 0; i < Comments.Items.length; i++)
        {
            Comment = Comments.Items[i];

            var rStyle = getCommentReplyStyle(isReply);           
            
            strOutput += '<li '+rStyle.li+'>';
            strOutput += '<span class="commentmetadata">';

            if (Comment.id == BaseObj.LastCommentId)
                strOutput += 'UNPOSTED: Currently awaiting approval.<br /><br />';
               
            if (Comment.User.website.length > 5)
               strOutput += '<a href="'+Comment.User.website+'" target="_new" '+rStyle.a+'>'+Comment.User.name+'</a>';
            else
               strOutput += '<span '+rStyle.span+'>' + Comment.User.name + '</span>';
            
            strOutput += ' Says:</span><br />';
            strOutput += '<span class="commentmetadata">'+formatDate('month',Comment.Date.month);
            strOutput +=    ' '+formatDate('day',Comment.Date.day,1)+', '+Comment.Date.year;
            strOutput +=     ' at '+Comment.Date.time.toLowerCase()+'</span>';
            strOutput += '<p>'+txt2Html(Comment.comment)+'</p>';
            
            if (BaseObj.OmnitechIsLoggedIn && !Comment.User.name.match(/omnitech/i))
                strOutput += '<div align="right"><a href="javascript:initOmnitechReply(\''+Comment.User.name+'\','+Comment.id+')">reply</a></div>';
            
            strOutput += '</li>';
            
            if (Comment.RelatedReplies.Items.length > 0)
            {
                strOutput += doBlogComment(BaseObj, Comment.RelatedReplies, true);            
            }
        }
    }
    
    return strOutput;
}


//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//
// METHODS: Gathering Blog Category Data
//
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function getBlogCategoryAll()
{
    var AjaxParams = "InjectionFree=true&AjaxAction=Load_BlogCategory&Type=All";

    loadBlogCategory(AjaxParams);
}

function loadBlogCategory(AjaxParams)
{
	if (! BlogObjAjax.Category.Active && BlogObjAjax.IsReady)
	{
	    BlogObjAjax.Category.SetActive(true);
	    
	    try
	    {
		    httpBlogCategory.open('POST', 'controls/ajaxLib.aspx', true);
		    httpBlogCategory.onreadystatechange = function() {
		    
			    if (httpResponseIsValid(httpBlogCategory))
                {                    
                    var _json = httpBlogCategory.responseText.replace(/\\\"/g,'"');
                    
                    // if categories are the same as our last check, then go ahead and
                    // re-write the list... otherwise, no need for the extra processing
                    if (BlogObjAjax.Category.LastResponse != _json)                    
                    {
                        BlogObjAjax.Category.LastResponse = _json;
                        
                        var ResultObj = eval('(' + _json + ')');                        
                        doBlogCategoryOutput(ResultObj);
                    }
			    }
			    else
			        BlogObjAjax.Category.Timer.ReLoad(setTimeout("getBlogCategoryAll();", SiteSettings.Blog.Category.RefreshRate+60000)); //let's give it some time
		    
		    };
		    httpBlogCategory.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		    httpBlogCategory.send(AjaxParams);

	    }
	    catch (e)
	    {
		    BlogObjAjax.Category.Timer.ReLoad(setTimeout("getBlogCategoryAll();", SiteSettings.Blog.Category.RefreshRate+60000)); //let's give it some time
	    }
    }
    else
        BlogObjAjax.Category.Timer.ReLoad(setTimeout("getBlogCategoryAll();", SiteSettings.Blog.Category.RefreshRate));
}

function doBlogCategoryOutput(Obj)
{
    var strOutput='';

    if (Obj.Items)
    {
        Blog.Category.Items = Obj.Items;
        
        strOutput += '<ul>';
        
        for (var i = 0; i < Blog.Category.Items.length; i++)
        {
            Category =  Blog.Category.Items[i];
            strOutput += '<li>';
            strOutput +=  '<a href="javascript:doBlogPostMethod(\'Category\',1,'+Category.id+');" title="View all posts filed under '+Category.title+'">'+Category.title+'</a>';
            strOutput += '</li>';
            
            //strOutput +=   '<img src="images/feedicon.gif" onmouseover="RssOver(this,true);" onmouseout="RssOver(this,false);" ';
            //strOutput +=   '    onclick="window.location=\'' + Category.rss + '\';" id="feed" />';
        }
        strOutput += '</ul>';
    }
    else
    {
        // nada
    }
    
    docObj('Blog_Category').innerHTML = strOutput;

    BlogObjAjax.Category.Timer.ReLoad(setTimeout("getBlogCategoryAll();", SiteSettings.Blog.Category.RefreshRate));
}

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//
// METHODS: Gathering Blog Most Recent Comment Data
//
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function getBlogRecentComments()
{
    var AjaxParams = "InjectionFree=true&AjaxAction=Load_BlogRecentComments&Type=All";

    loadBlogRecentComments(AjaxParams);
}

function loadBlogRecentComments(AjaxParams)
{
	if (! BlogObjAjax.RecentComments.Active && BlogObjAjax.IsReady)
	{
	    BlogObjAjax.RecentComments.SetActive(true);
	    
	    try
	    {
		    httpBlogRecentComments.open('POST', 'controls/ajaxLib.aspx', true);
		    httpBlogRecentComments.onreadystatechange = function() {
		    
			    if (httpResponseIsValid(httpBlogRecentComments))
                {                    
                    var _json = httpBlogRecentComments.responseText.replace(/\\\"/g,'"');
                    
                    // if recent comments are the same as our last check, then go ahead and
                    // re-write the list... otherwise, no need for the extra processing
                    if (BlogObjAjax.RecentComments.LastResponse != _json)                    
                    {
                        BlogObjAjax.RecentComments.LastResponse = _json;
                        
                        var ResultObj = eval('(' + _json + ')');                        
                        doBlogRecentCommentOutput(ResultObj);
                    }
			    }
			    else
			    {
			        // Let's try this again.. but let's give it some more time (+1 minute)
			        BlogObjAjax.RecentComments.Timer.ReLoad(setTimeout("getBlogRecentComments();", SiteSettings.Blog.RecentComments.RefreshRate+60000));
			    }
		    
		    };
		    httpBlogRecentComments.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		    httpBlogRecentComments.send(AjaxParams);

	    }
	    catch (e)
	    {
		    // Let's try this again.. but let's give it some more time (+1 minute)
		    BlogObjAjax.RecentComments.Timer.ReLoad(setTimeout("getBlogRecentComments();", SiteSettings.Blog.RecentComments.RefreshRate+60000));
	    }
    }
    else
        BlogObjAjax.RecentComments.Timer.ReLoad(setTimeout("getBlogRecentComments();", SiteSettings.Blog.RecentComments.RefreshRate));
}

function doBlogRecentCommentOutput(Obj)
{
    var strOutput='';
    
    if (Obj.Items && Obj.Items.length)
    {
        Blog.RecentComments.Items = Obj.Items;
        
        strOutput += '<ul class="recentcomments">';
        
        for (var i = 0; i < Blog.RecentComments.Items.length; i++)
        {
            RecentComment = Blog.RecentComments.Items[i];
            strOutput += '<li class="recentcomments">';
            
            if (RecentComment.User.website.length > 5)
                strOutput += '<a href="'+RecentComment.User.website+'" target="_new">'+RecentComment.User.name+'</a>';
            else
                strOutput += RecentComment.User.name;
            
            strOutput += ' on <a href="javascript:doBlogPostMethod(\'Post\',1,'+RecentComment.Post.id+');">'+RecentComment.Post.title+'</a></li>';
        }
        strOutput += '</ul>';
        
        docObj('Blog_RecentComments').innerHTML = strOutput;
    }
    else
        docObj('Blog_RecentComments').innerHTML = '<ul class="recentcomments"><li class="recentcomments"><em>No comments available</em></li></ul>';

    BlogObjAjax.RecentComments.Timer.ReLoad(setTimeout("getBlogRecentComments();", SiteSettings.Blog.RecentComments.RefreshRate));
}

/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
//
// METHODS: Saving Blog Comment
//
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function saveBlogReply()
{
    var returnType = true;
    var formId = 'reply';
        FormObjAjax.CurrentForm = formId; //set this right away 'cause we need this variable for url validation
        
    var arFlds = [['replyFldAuthor','name',true],['replyFldUrl','link',false],['replyFldEmail','email',true],
                  ['replyFldComment','blog_comment',true]];

    resetFldFocus(arFlds[0][0]);
    
    for (var i = 0; i < arFlds.length; i++)
    {
        if (! valFields(arFlds[i]))
            returnType = false;
    }
    
    //return false;
    
    if (returnType)
    {
        // Since this blog may also be viewed as a static object, a lot of this dynamic object instantiation never happens.
        // Luckily, we just have one blog form... and the only piece we really need is the post id.  On the ajax end this
        // is being kept track of on a click by click basis.  However, if the value is 0 at his point in the form submission
        // (btw 0 is the default) then let's grab it out of the form field   
        if (0 == BlogObjAjax.Post.CurrentView.Args.Id)
            BlogObjAjax.Post.CurrentView.Args.Id = findDotNetObjectByIdAndTag('hdnPostId','input').value;
            
        BlogReplyInfo = 
                    { "postId"  : BlogObjAjax.Post.CurrentView.Args.Id,
                      "name"    : docObj('replyFldAuthor').value,
                      "website" : ( docObj('replyFldUrl').value.length>3 ? 'http://'+docObj('replyFldUrl').value : '' ),
                      "email"   : docObj('replyFldEmail').value,
                      "comment" : docObj('replyFldComment').value,
                      "replyId" : docObj('replyFldCommentId').value };

        arFlds[arFlds.length] = ['replyFldSubmit'];
	    
    var AjaxParams  = "InjectionFree=true&AjaxAction=Save_BlogPostComment&Id="+BlogReplyInfo.postId+"&Name="+BlogReplyInfo.name;
        AjaxParams += "&Email="+BlogReplyInfo.email+"&Website="+BlogReplyInfo.website+"&Comment="+BlogReplyInfo.comment;
        AjaxParams += "&CommentReplyId="+BlogReplyInfo.replyId;
	    
        initFormProcessingAnimation(formId);
        
        FormObjAjax.CurrentForm      = formId;
        FormObjAjax.FieldCollection  = arFlds;
        FormObjAjax.AjaxParams       = AjaxParams;
        FormObjAjax.ObjectCollection = BlogReplyInfo;
        
        FormObjAjax.Timer.Load = setTimeout('doHttpFormPost();',1000);
    }
}

//////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
//
// METHODS: Miscellaneous.. which are blog related
//
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function initOmnitechReply(replyTo, replyId)
{
    docObj('replyFldCommentId').value = replyId;
    docObj('replyFldAuthor').value = 'Omnitech';
    docObj('replyFldEmail').value = 'info@omnitech-inc.com';
    docObj('replyFldAuthor').readOnly = true;
    docObj('replyFldEmail').readOnly = true;
    docObj('replyFldUrl').readOnly = true;
    
    docObj('h2Reply').innerHTML = 'Leave a Reply to ' + replyTo;
    
    loadPageFocus('reply');    
    resetFldFocus('replyFldComment');    
}

function hideBlogCommentsAndReply()
{
    docObj('Blog_Comment_Column').style.display = 'none';
    //docObj('ifrmRTE').location = FormObjAjax.BasePath + '/controls/FreeTextBox/blank.htm';
    ResetBlogReplyForm();
}

function ResetBlogReplyForm()
{
    docObj('replyFldAuthor').value = '';
    docObj('replyFldEmail').value = '';
    docObj('replyFldUrl').value = '';
    docObj('replyFldComment').value = '';
    docObj('replyFldCommentId').value = 0;
    
    docObj('replyFldAuthor').readOnly = false;
    docObj('replyFldEmail').readOnly = false;
    docObj('replyFldUrl').readOnly = false;
    
    docObj('h2Reply').innerHTML = 'Leave a Reply';
}

function loadPageFocus(focus)
{
    if (Blog.ScrollPageToFocus)
    {
        if (focus)
        {
            if ('reply' == focus)
            {        
                var pos = findPos(docObj('replyFldAuthor'));
                pos.top = pos.top-65; //offset for cbc

                window.scrollTo(0,pos.top);
                resetFldFocus('replyFldAuthor');
            }
            else if ('comments' == focus)
            {
                var pos = findPos(docObj('Blog_Comment_Column'));
                window.scrollTo(0,pos.top);
            }
            else
            {
                // do nothing
            }
        }
        else
        {
            var pos = findPos(docObj('taking_you'));
                pos.top = pos.top - 200;
            window.scrollTo(0,pos.top);
        }
    }
    else
    {
        // when this conditional is hit, it means user navigated to the blog.  Since we're here now, any navigation
        // we do we will want to always autoscroll the referenced blog post into view.
        Blog.ScrollPageToFocus = true;
    }
}

function getCommentReplyStyle(isReply)
{
    if (isReply)
        return { a:'style="color:#7964AF"', li:'style="margin-left:20px"', span:function() { return this.a; } };
    else
        return { a:'', li:'', span:'' };
}

function getDate()
{    
    var date = new Date();
    
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
  
    return date;
}
function formatDate(which,part,style)
{
    var months = ["January", "February","March", "April", "May", "June", "July", "August",
                  "September", "October", "November", "December"];
    
    if (which == 'month')
        return months[part-1];
    else if (which == 'day')
    {
        if (style == 1)
        {
            switch (parseInt(part))
            {
                case 1: 
                case 21:
                case 31:
                    return part+'st';
                case 2:
                case 22:
                    return part+'nd';
                case 3:
                case 23:
                    return part+'rd';
                default:
                    return part+'th'; break;
            }
        }
    }
}