
var recommendAry = new Array(); // array to hold the recommend count for the article
var commentsAry = new Array();  // array to hold the comment count for the article
var recommendedAry = new Array();
var recommendCommentsAry = new Array();  // array to hold the recommend count for the comments.
var titleAry = new Array();

// Enable or disable comment button and text.
function initCommentForm()
{
    var commentHeader = document.getElementById("commentHeader");
    var commentButton = document.getElementById("commentButton");
    
    var uid;
    if(uid == "" || uid == null)
    {
	cookieStr = document.cookie;
	cookieArr = cookieStr.split(";");
	for(var i=0; i < cookieArr.length; i++)
	{ 
	    var tempArr;
	    temp = cookieArr[i].replace(/^\s+/, '').replace(/\s+$/, '');
	    tempArr = temp.split("=");

	    if(tempArr[0] == "HD")
	    {
		 var tempArr2;
		 tempArr2 = tempArr[1].split("|");
		 uid = tempArr2[0];
	    }
	}
    }

    if(uid == "" || uid == null)
    {
	commentButton.disabled = true;
	commentHeader.innerHTML = '&nbsp; You must be logged in to leave a comment. <a href="/cgi-bin/login.pl?redirect_url=' + document.location + '">Login</a> | <a href="/global/registration.php?redirect_url=' + document.location + '">Register</a><br />';
    }
    else
    {
	commentButton.disabled = false;
	commentHeader.innerHTML = '<div style="float: left;"><b>Add your comment</b></div><div style="float: right;"><b>You are logged in as <span style="color: #9F001F;">' + uid + '</span></b><br><span style="font-size: 12px;">(Your User ID will be displayed with your comment.)</span></div>';
    }
}


        
// Callback function to handle article recommend and comment count
function renderArticle(responseBatch) 
{   
    if (responseBatch.Responses.length != 0) 
    {    
		for(var i = 0; i < responseBatch.Responses.length; i++)
        {
            // get article from response   
            var article = responseBatch.Responses[i].Article; 
                    
            // update recommend and comments array
			recommendedAry[article.ArticleKey.Key] = article.Recommendations.CurrentUserHasRecommended;
            recommendAry[article.ArticleKey.Key] = article.Recommendations.NumberOfRecommendations;
            commentsAry[article.ArticleKey.Key] = article.Comments.NumberOfComments;
			titleAry[article.ArticleKey.Key] = article.PageTitle;
        }                
    }   
   
    // Loop through each key and update html.
    for(var key in recommendAry)
    {
		var recommendSpan = document.getElementById("R-" + key);
		if(recommendSpan)
        {
             recommendSpan.innerHTML = recommendAry[key];
        }

		// Check Cookies to see if current key has already been recommended
		// If so disable Recommend link for article.
		//var recommended = Get_Cookie("Recommended");


		//alert(recommendedAry[key]);
		
		if(recommendedAry[key] == "True")
		{
			var pluckSpan = document.getElementById("pluck-" + key);
			var pluckSpanInnerHTML = pluckSpan.innerHTML;


				
		   
			var pluckArray = pluckSpanInnerHTML.split("|");
			var pluckStr = pluckArray[0] + " | ";
			
			
			//var startIdx = pluckArray[1].indexOf('Recommend');
		   
			
			//For IE7
			//var endIdx = pluckArray[1].indexOf('</A>');

			//For Firefox
	    
			//if(endIdx < 0)
			//{
			//	endIdx = pluckArray[1].indexOf('</a>');
			//}
				
			//if(startIdx > 0)
			//{
			//var temp = pluckArray[1].substr(startIdx, endIdx);
			var temp = pluckArray[1];	

			// For firefox
			temp = temp.replace("<a href=\"javascript: recommendReview('" + key + "')\">", "");
			temp = temp.replace("</a>", "");
			
			// For IE7
			temp = temp.replace("<A href=\"javascript: recommendReview('" + key + "')\">", "");
			temp = temp.replace("</A>", "");
			
			if(temp.indexOf('pluck_recommended') < 0)
			{
				temp = temp.replace('class=pluck_recommend', 'class=pluck_recommended');
			}
			
			pluckStr += " " + temp;
			//}
			//else
			//{
			//startIdx = pluckArray[1].indexOf('<span class=');
			//var temp = pluckArray[1].substr(startIdx, endIdx);
			
			// For Firefox
			//temp = temp.replace('class="pluck_recommend"', 'class="pluck_recommended"');
			
			// For IE7
			//temp = temp.replace('class=pluck_recommend', 'class=pluck_recommended');
			//pluckStr += " " + temp;
			//}
				
			pluckSpan.innerHTML = pluckStr;
		 
		}
    }
     
    // Update comment count

    for(var key in commentsAry)
    {
		var commentsSpan = document.getElementById("C-" + key);
		if(commentsSpan)
		{
			commentsSpan.innerHTML = commentsAry[key];
		}
	}

}
        
// Function to submit article recommend. This one is for the longer link.
function recommendReview(key) 
{   
    var requestBatch = new RequestBatch();   
    var articleKey = new ArticleKey(key);   
    var recommendAction = new RecommendAction(articleKey);   
    requestBatch.AddToRequest(recommendAction);    
    requestBatch.BeginRequest(serverUrl, recommendationComplete);   
    var recommendCount = parseInt(recommendAry[key]) + 1;
    pluckSpan = document.getElementById("pluck-" + key);
    pluckStr = pluckSpan.innerHTML;            

    // Swap the two lines when comments go live.
    pluckSpan.innerHTML = pluckStr.split("|")[0] + " | " + "Recommend <span class=\"pluck_recommended\">" + recommendCount + "</span>"; 
    //pluckSpan.innerHTML = "Recommend <span class=\"pluck_recommended\">" + recommendCount + "</span>"; 

    
    var recommended = Get_Cookie("Recommended");
    var cookieStr = '';
    if(recommended)
    {
	if(recommended.indexOf(key) < 0)
	{
	    var cookieStr = recommended + "+" + key;
        }
    }
    else
    {
	cookieStr = key;
    }
    Set_Cookie("Recommended", cookieStr, 90, "/", "", "");
    

}
        
// Alternative function to submit article recommends. This one is for the shorter link.
function recommendReview2(key) 
{   
    var requestBatch = new RequestBatch();   
    var articleKey = new ArticleKey(key);   
    var recommendAction = new RecommendAction(articleKey);   
    requestBatch.AddToRequest(recommendAction);    
    requestBatch.BeginRequest(serverUrl, recommendationComplete);   
    var recommendCount = parseInt(recommendAry[key]) + 1;
    pluckSpan = document.getElementById("pluck-" + key);
    pluckStr = pluckSpan.innerHTML;

    // Swap the two lines when comments go live.
    pluckSpan.innerHTML = pluckStr.split("|")[0] + " | <span class=\"pluck_recommended\">" + recommendCount + "</span>";
    //pluckSpan.innerHTML = " | <span class=\"pluck_recommended\">" + recommendCount + "</span>"; 

    
    // Check Cookies to see if current key has already been recommended
    // If so disable Recommend link for article.
    var recommended = Get_Cookie("Recommended");
    var cookieStr = '';
    if(recommended)
    {
	if(recommended.indexOf(key) < 0)
	{
	    var cookieStr = recommended + "+" + key;
        }
    }
    else
    {
	cookieStr = key;
    }
    Set_Cookie("Recommended", cookieStr, 90, "/", "", "");
}   
        
// Callback function to handle article recommend request
// Currently does nothing. Just a dummy function. 
function recommendationComplete(responseBatch) 
{   
               
    var message = responseBatch.Messages[0];   
               
    if (message.Message == 'ok') 
    {   
	//alert('Review successfully recommended');
	//submitRequest();   
    }        
    /* 
    else 
    {   
        var errorBlock = document.getElementById('errors');   
	var errorHtml = "";   
	errorHtml += "(" + message.MessageTime + ")<br/>";   
	errorHtml += message.Message;   
	errorBlock.innerHTML = errorHtml;   
    }
    */   
}

// Function to submit request for comments.
function submitRequest2(articleKey, pageNum) 
{   
	//alert(articleKey);
    var requestBatch = new RequestBatch();   
    var articleKey = new ArticleKey(articleKey);   
    var commentPage = new CommentPage(articleKey, 10, pageNum, "TimeStampDescending");           
    requestBatch.AddToRequest(commentPage);    
    requestBatch.BeginRequest(serverUrl, renderCommentPage);    
}        

// Callback function to render comments
function renderCommentPage(responseBatch) 
{   
    if (responseBatch.Responses.length == 0) 
    {   
		//alert('Article Not Found.');   
    } 
    else 
    {   
		var commentBlock = document.getElementById('commentBlock');   
		var commentBlockHtml = "<table width='100%'>";   
		var commentPage = responseBatch.Responses[0].CommentPage;   
	
		//alert(commentPage.Comments.length);
		for(var i=0; i < commentPage.Comments.length; i++) 
		{   
			commentBlockHtml += getCommentHtml(commentPage.Comments[i], i);
			recommendCommentsAry[commentPage.Comments[i].CommentKey.Key] = commentPage.Comments[i].NumberOfRecommendations;
		}   

		// Add Pagination Code
		var numOfPages = Math.ceil(commentPage.NumberOfComments / 10);		
		if(numOfPages > 1)
		{
			commentBlockHtml += "<tr><td colspan=\"2\">";
			var onPage = parseInt(commentPage.OnPage);
			if(onPage > 1)
			{
				commentBlockHtml += "<a href=\"#Comments\" onClick=\"submitRequest2('" + commentPage.ArticleKey.Key + "'," + (onPage - 1) + ");\">&laquo;</a> ";
			}
			
			for(var i=0; i < numOfPages; i++)
			{
				if(commentPage.OnPage == (i + 1))
				{
					commentBlockHtml += "" + (i + 1) + " ";
				}
				else
				{
					commentBlockHtml += "<a href=\"#Comments\" onClick=\"submitRequest2('" + commentPage.ArticleKey.Key + "'," + (i + 1) + ");\">" + (i + 1) + "</a> ";
				}	
			}		
			
			if(onPage < numOfPages)
			{
				commentBlockHtml += "<a href=\"#Comments\" onClick=\"submitRequest2('" + commentPage.ArticleKey.Key + "'," + (onPage + 1) + ");\">&raquo;</a> ";
			}
			
			commentBlockHtml += "</td></tr>";
		}
		// End Pagination Code
		
		
		
		commentBlockHtml += "</table>"; 
		
		commentBlock.innerHTML = commentBlockHtml;   
    }   
}   
        
// Helper function for renderCommentPage()
function getCommentHtml(comment, count) 
{   
    var html = "";

    if(count % 2 == 0)
    {
	html = "<tr class='commentRowEven'><td class='commentTD1'>\n";   
    }
    else 
    {
	html = "<tr><td class = 'commentTD1'>\n";
    }

	html += "\t<a href=\"" + comment.Author.PersonaUrl + "\">"
    html += "\t<img class='commentImg' src='" + comment.Author.AvatarPhotoUrl + "' />\n";
	html += "\t</a>";
    html += "\t</td><td class='commentTD2'>";
    html += "\t<div class='commentRight'>\n";
    html += "\t<div class='commentByLineContainer'><span class='commentByLine'><b>" +  comment.Author.UserKey.Key + "</b></span> <span class='commentBody'> wrote:</span></div>\n";   
    html += "\t<div class='commentBody'>" + comment.CommentBody + "</div>\n";   
    //if (comment.SiteOfOrigin != null) {   
    //    html += "\t<div class='commentBody'>" + comment.SiteOfOrigin + "</div>\n";   
    //}   
    html += "</div>\n";
    html += "<div class='commentTimestamp'>" + FormatDate(comment.PostedAtTime) + "</div>";
    html += "<div class='commentRecommend'><span class=\"pluck\" id=\"pluck-" + comment.CommentKey.Key + "\">";

    // Check Cookies to see if current key has already been recommended
    // If so disable Recommend link for article.
    var recommended = Get_Cookie(comment.CommentKey.Key);
    if(recommended)
    {
	html += "Recommend <span class=\"pluck_recommended\" id=\"" + comment.CommentKey.Key + "\">" + comment.NumberOfRecommendations + "</span> ";
    }
    else
    {
	html += "<a href=\"#none\" onclick=\"recommendComment('" + comment.CommentKey.Key + "'); return false;\">Recommend <span class=\"pluck_recommend\" id=\"" + comment.CommentKey.Key + "\">" + comment.NumberOfRecommendations + "</span></a> ";
    }

    html += "</span></div><div id='rpt_" + comment.CommentKey.Key + "' class=\"pluck commentReportAbuse\"><span><a href=\"#none\" onclick=\"ShowReportAbuse(event, document.URL, gSiteLife.__baseUrl + '/AbuseReport/ReportAbuse?plckElementId=rpt_" + comment.CommentKey.Key + "&plckTargetKey=" + comment.CommentKey.Key + "&plckTargetKeyType=Comment'); return false;\"><span class=\"pluck_abuse\">&nbsp;</span>Report Abuse</a></span></div>";
    html += "</td></tr>\n";

    return html;   
}   


// Function to send post comment request.
function postComment(key) 
{   

	//alert(key);
    // get form elements and page info      
    var articleKey = new ArticleKey(key); 
    var pageUrl = "";
    if (document.getElementById("pluckurl"))
    {
        pageUrl = "http://www.workforce.com" + document.getElementById("pluckurl").value;
    }
    else
    {
        pageUrl = document.location.href;
    }
	//alert(pageUrl);
    var pageTitle = document.title;   
	//alert(pageTitle);
    var commentBody = document.getElementById('commentBody').value;   	
  
	
	
    // create and send request   
    var requestBatch = new RequestBatch();               
	
	// check if we need to update the ArticleKey (ie. see if it has a title)
	//alert(titleAry[key]);
	//if(titleAry[key] == "" || titleAry[key] == null)
	//{
		//alert("updating articlekey");
		var updateAction = new UpdateArticleAction(articleKey, pageUrl, pageTitle, new Section(""), new Array());
		requestBatch.AddToRequest(updateAction);
	//}	
	
    var commentAction = new CommentAction(articleKey, pageUrl, pageTitle, commentBody);   	
    requestBatch.AddToRequest(commentAction);    
    requestBatch.BeginRequest(serverUrl, commentSubmitted);    
} 
        

// Function to send a recommend for a comment
function recommendComment(key)
{
    var requestBatch = new RequestBatch();   
    var commentKey = new CommentKey(key);   
    var recommendAction = new RecommendAction(commentKey);   
    requestBatch.AddToRequest(recommendAction);    
    requestBatch.BeginRequest(serverUrl, recommendationComplete);   
    var recommendCount = parseInt(recommendCommentsAry[key]) + 1;
    pluckSpan = document.getElementById("pluck-" + key);
    //pluckHTML = pluckSpan.innerHTML;
    //pluckAry = pluckHTML.split("|");
    pluckSpan.innerHTML = "Recommend <span class=\"pluck_recommended\">" + recommendCount + "</span>"; 	    

    Set_Cookie( key, "true", 90, "/", "", "");
}
        
// Report Abuse Functions pulled from the Sitelife widget
function ShowReportAbuse(evt, url, command) 
{
    var doc = document;
    doc.getElementById("ReportAbuse_Url").value = url; 
    doc.getElementById("ReportAbuse_Command").value = command;
    doc.getElementById("ReportAbuse_CommentText").value = "";
    doc.getElementById("ReportAbuse_Reason").selectedIndex = 0;
    ShowDivAtMouse(evt, "ReportAbuse_Menu");
    doc.getElementById('ReportAbuse_CommentText').focus();
}

function ShowDivAtMouse(evt, id) 
{
    posx = mouseX(evt) - 170;    
    posy = mouseY(evt);
    //normalize to make sure we at least appear on the screen
    if(posx < 0) posx = 10;
    if(posy < 0) posy = 10;
    
    document.getElementById(id).style.left = posx + "px";
    document.getElementById(id).style.top = posy + "px";
    document.getElementById(id).style.display = "block";
}

function mouseX(evt) 
{
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX)
	return evt.clientX + (document.documentElement.scrollLeft ?
			      document.documentElement.scrollLeft :
			      document.body.scrollLeft);
    else return null;
}

function mouseY(evt) 
{
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY)
	return evt.clientY + (document.documentElement.scrollTop ?
			      document.documentElement.scrollTop :
			      document.body.scrollTop);
    else return null;
}

function HideDiv(id)
{
    document.getElementById(id).style.display = "none";
}

function ReportAbuse() 
{
    var url = document.getElementById("ReportAbuse_Url").value; 
    var command = document.getElementById("ReportAbuse_Command").value;
    var text = document.getElementById("ReportAbuse_CommentText").value;
    var reason = document.getElementById("ReportAbuse_Reason").value;
    document.getElementById("ReportAbuse_Menu").style.display='none';
    var sendUrl = command+'&plckReason='+gSiteLife.EscapeValue(reason)+'&plckURL=' + gSiteLife.EscapeValue(url)
	if(text) sendUrl += "&plckAbuseDetail=" + gSiteLife.EscapeValue(text);
    gSiteLife.__Send(sendUrl);
}
// End Report Abuse functions pulled from Sitelife Widget.


// Helper function used to render Comments HTML.
function FormatDate(date)
{
    var dateObj = new Date(date.split(" ")[0]);
    var dateStr = "";
    var dayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    var monthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    dateStr = dayArray[dateObj.getDay()];
    dateStr += ", " + monthArray[dateObj.getMonth()];
    dateStr += " " + dateObj.getDate();
    dateStr += ", " + dateObj.getYear();

    dateStr += " " + date.split(" ")[1] + " " + date.split(" ")[2];

    return dateStr;
}



// Cookie Functions
function Set_Cookie( name, value, expires, path, domain, secure ) 
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
      if the expires variable is set, make the correct 
      expires time, the current script below will set 
      it for x number of days, to make it for hours, 
      delete * 24, for minutes, delete * 60 * 24
    */

    if ( expires )
	{
	    expires = expires * 1000 * 60 * 60 * 24;
	}

    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
	

function Get_Cookie( check_name ) 
{
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
	
    for ( i = 0; i < a_all_cookies.length; i++ )
	{
	    // now we'll split apart each name=value pair
	    a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
	    // and trim left/right whitespace while we're at it
	    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
	    // if the extracted name matches passed check_name
	    if ( cookie_name == check_name )
		{
		    b_cookie_found = true;

		    // we need to handle case where cookie has no value but exists (no = sign, that is):
		    if ( a_temp_cookie.length > 1 )
			{
			    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}

		    // note that in cases where cookie is initialized but no value, null is returned
		    return cookie_value;
		    break;
		}

	    a_temp_cookie = null;
	    cookie_name = '';
	}
    
    if ( !b_cookie_found )
	{
	    return null;
	}
}

//Uncomment when comments go live
initCommentForm();
submitRequest();