AARP.Comments = {
	__version__: ''
	, defaultText: ""
	, textUnset: function( obj )
	{
		defaultText.unset( obj, this.defaultText );
	}
	, textSet: function( obj )
	{
		defaultText.set( obj, this.defaultText );
	}
}

var AARPComments = {
	host: ''
};

AARPComments.host = location.hostname;
//alert(location.hostname);

function bgffffcc(obj) {
	obj.style.backgroundColor = '#ffffcc';
}

function bgfff(obj) {
	obj.style.backgroundColor = '#fff';
}

function checkNumberOfCharacters(textArea, numLeft){
    var maxChrs = 2000;
    var openChrs = maxChrs - $(textArea).value.length;
   
	if (openChrs <= 0) {
		openChrs = 0;
		$(textArea).value = $(textArea).value.substr(0, maxChrs);
	}
	
	$(numLeft).update(openChrs);
}

function submitDeleteProfile(commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		var formValues = $('deleteFormTestimonial' + commentId).serialize();
		var loginRequest = new Ajax.Request( '/community/profile/deleteProfileTestimonial.bt', {method: 'post', parameters: formValues, onSuccess: showTestimonialResponse} );
	}
}

function submitDeleteAll(commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		var formValues = $('deleteFormTestimonial' + commentId).serialize();
		// since we can have more than one page here, we need to find out what page number we are on and pass it on. 
		var pageNum = getPageNumber();
		if (pageNum != null){ 
			formValues = formValues + "&pageNum="+pageNum;
		} 
		var loginRequest = new Ajax.Request( '/community/profile/deleteFromAllTestimonial.bt', {method: 'post', parameters: formValues, onSuccess: showTestimonialResponse} );
	}
}

function submitNewTestimonial(commentType, commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		
		if (commentType == "new") {
			var formValues = $('testimonialForm').serialize();
		} else if (commentType == "reply") {
			var formValues = $('testimonialReplyForm' + commentId).serialize(); 
		}
		
		var pageNum = getPageNumber();
		if (pageNum != null){ 
			formValues = formValues + "&pageNum="+pageNum;
		} 
		
		var loginRequest = new Ajax.Request( '/community/profile/submitTestimonial.bt', {method: 'post', parameters: formValues, onSuccess: showTestimonialResponse} );
	
	}
}

function showTestimonialResponse(originalRequest) {
	var gotBack = originalRequest.responseText;
	//this line fails locally and doesn't refresh the page properly
	
	if (gotBack.match(/ERROR/)) {
		return false;
	} else {
		$('memberTestimonials').update(gotBack);
	}
}

function submitDeleteComment(commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		var formValues = $('deleteFormComment' + commentId).serialize();
		// since we can have more than one page here, we need to find out what page number we are on and pass it on. 
		var pageNum = getPageNumber();
		if (pageNum != null){ 
			formValues = formValues + "&pageNum="+pageNum;
		} 
		var loginRequest = new Ajax.Request( '/community/content/comment/delete.bt', {method: 'post', parameters: formValues, onSuccess: showCommentResponse} );
	}
}

function showCommentResponse(originalRequest) {
	var gotBack = originalRequest.responseText;
	if (gotBack.match(/ERROR/)) {
		return false;
	} else {
		$('commentDiv').update(gotBack);
	}
}

function getPageNumber() {
	var currLocation = (window.location).toString();
	page_num_object = currLocation.toQueryParams();
	if (page_num_object.pageNum) {
		return page_num_object.pageNum;
	} else {
		return null;
	}
}

function checkLoginStatus(cookieName) {

	if (document.cookie.length > 0) {
	 
		headerStart = document.cookie.indexOf(cookieName+"="); 
	
		if (headerStart != -1) 
			{ 
			headerStart += cookieName.length+1; 
			headerEnd = document.cookie.indexOf(";", headerStart);
	
			if (headerEnd == -1) {
				headerEnd = document.cookie.length;
                                 }
			return unescape(document.cookie.substring(headerStart, headerEnd)); 
				} 
			
		return null; 
		}
		return null; 
	}

function generateArticleCommentSubmitArea() {
	//temporarily turning this off so we can see a comment box on beta-d
	//if ( AARP.page.is_authoring ) return;
	
	// first let's find out if they are logged in
	var loginStatus = checkLoginStatus("header");

	if (loginStatus != null) {
		
		// lets see who this is, since we need to know for the form. 
		var userName = loginStatus.split('|')[2];
	
		document.write("<div class='commentTitle'>Add Your Comments:</div>");
		document.write("<form action='#' id='articleCommentForm' method='post' onSubmit='return false;'>");
		document.write("<input type='hidden' name='membername' value='" + userName +"'>");
		document.write("<input type='hidden' name='articleUrl' value='" + AARP.page.url +"'>"); // checkArticleUrl()
		document.write("<input type='hidden' name='method' value='submitNewArticleComment'>");
		document.write("<textarea name='comment' id='comment' class='articleCommentFormInput' rows='4' onfocus='bgffffcc(this);' onblur='bgfff(this);' onkeyup='checkNumberOfCharacters(\"comment\", \"remainChars\")';></textarea>");
		document.write("<div class='commentChars'>You can enter <span id='remainChars'>2000</span> more characters.</div>");
		/*
		document.write("<a href=\"javascript:submitNewArticleComment();\"><img id=\"content_submit\" class=\"button\" src=\"http://assets.aarp.org/aarp.org_/build/topics/images/buttons/btn24_submit.gif\" onmouseover=\"this.src='http://assets.aarp.org/aarp.org_/build/topics/images/buttons/btn24_submit_over.gif';\" onmouseout=\"this.src='http://assets.aarp.org/aarp.org_/build/topics/images/buttons/btn24_submit.gif';\"/></a>&nbsp;");
		document.write("<div id='commentResponse' class='generalStatus' style='display: none;'></div>");
		*/
		
		//USING SPRITE (not working for some reason)
		document.write("<a href='#' onclick='submitNewArticleComment(); return false;' class='btn24Blue'>");
		document.write("<span class='left'>&nbsp;</span>");
		document.write("<span class='middle'>Submit</span>");
		document.write("<span class='right'>&nbsp;</span>");
		document.write("</a>");
		document.write("<div class='clearer'></div>");
	
	} else {
		
		document.write("<p>Please log in to leave a comment. <a href='#' onclick='jumpToLogin();'>Log In</a> | <a href='https://login.aarp.org/community/register/index.bt'>Sign Up</a></p>");

		// return the notloggedin form.
		document.write("<textarea name='comment' id='comment' class='articleCommentFormInput' rows=4 disabled></textarea><BR>");
		/*
		document.write("<img src='http://assets.aarp.org/aarp.org_/build/topics/images/buttons/btn24_submit_off.gif' alt='Submit'>");
		*/
		
		//USING SPRITE (not working for some reason)
		document.write("<a href='#' onclick='return false;' class='btn24Inactive'>");
		document.write("<span class='left'>&nbsp;</span>");
		document.write("<span class='middle'>Submit</span>");
		document.write("<span class='right'>&nbsp;</span>");
		document.write("</a>");
		document.write("<div class='clearer'></div>");
	
	}
}

function grabRecentComments() {
	//temporarily turning this off so we can see a comment box on beta-d
	//if ( AARP.page.is_authoring ) return;
	
    params = 'method=viewArticleComments&articleID=' + AARPAds.pgid;
    AJAXUrl = 'http://' + AARPComments.host + '/community/articleComments/comments.bt';
	var grabCommentsRequest = new Ajax.Request( AJAXUrl, {method: 'post', parameters: params, onSuccess: showArticleComments, onFailure: showError} );
}

function grabRecentCommentsShort() {
     params = 'method=viewArticleCommentsShort&articleID=' + AARPAds.pgid;
     AARPAds.version = 'less';
     AJAXUrl = 'http://' + AARPComments.host + '/community/articleComments/shortComments.bt';
  
  var grabCommentsRequest = new Ajax.Request( AJAXUrl, {method: 'post', parameters: params, onSuccess: showArticleComments, onFailure: showError} );
}
 
function grabPagedCommentsForArticle(url, sortOrder) {
    AJAXUrl = 'http://' + AARPComments.host + url +'&sOr=' + sortOrder;
	var grabCommentsRequest = new Ajax.Request( AJAXUrl, {method: 'post', onSuccess: showArticleComments, onFailure: showError} );
}

function showError(originalRequest) {
   alert('Error ' + originalRequest.status + ' -- ' + originalRequest.statusText);
}

function showArticleComments(originalRequest) {

    var gotBack = originalRequest.responseText;
    $('recentCommentsSlot').update(gotBack);
    var commentCount = readCookie('articleCommentCount');
    if (commentCount == null) {
        commentCount = 0;
    }
    if (AARPAds.version == 'less' && (parseInt(commentCount)) > 3) {
        $('moreCommentsDiv').show();
    }
}

function readCookie(n) {
    var cookiecontent = null;
    if (document.cookie.length > 0) {
        var cookiename = n + '=';
        var cookiebegin = document.cookie.indexOf(cookiename);
        var cookieend = 0;
        if (cookiebegin > -1) {
            cookiebegin += cookiename.length;
            cookieend = document.cookie.indexOf(";", cookiebegin);
            if (cookieend < cookiebegin) {
                cookieend = document.cookie.length;
            }
            cookiecontent = document.cookie.substring(cookiebegin, cookieend);
        }
    }
    return cookiecontent;
}

 
 
 function successfulCommentAddition(originalRequest) {
	var pageVersion = AARPAds.version;
	if (pageVersion != null && pageVersion == 'less') {
		location.reload(true);
	} else {
		showArticleComments(originalRequest);
	}
}
 
 function successfulCommentDeletion(originalRequest) {
	var pageVersion = AARPAds.version;
	if (pageVersion != null && pageVersion == 'less') {
		location.reload(true);
	} else {
		showArticleComments(originalRequest);
		$('comment').value = "";
		$('commentResponse').update("<div class='systemError'>The comment has been deleted.</div>");
	}
}
 
var debug_url = '';

function submitNewArticleComment() {
	// NEW (2007-12-13): issues with serialize() on Safari 2.x and other WebKit browsers
	//var formValues = $('articleCommentForm').serialize() + '&articleID=' + AARPAds.pgid;
	var formValues = Form.serialize( 'articleCommentForm', null ) + '&articleID=' + AARPAds.pgid + '&version=' + AARPAds.version + '&articleTitle=' + escape( document.title.substring(0, 30) );
	AJAXUrl = 'http://' + AARPComments.host + '/community/articleComments/comment/submit.bt';
	// alert(AJAXUrl + "\n" + formValues);
	debug_url = AJAXUrl + '?' + formValues;
	
	var submitNewArticleCommentRequest = new Ajax.Request( 
		AJAXUrl, { method: 'post'
		, parameters: formValues
		, onSuccess: successfulCommentAddition
		//, onComplete: function( o ) { alert( 'complete: ' + o ); }
		, onFailure: function( o )
			{
				if ( document.location.toString().match( /debugNow/ ) )
				{
					$( 'comment' ).value = debug_url + "\n\n" + o.responseText;
				}
			} 
		, onException: function( o, e )
			{
				if ( document.location.toString().match( /debugNow/ ) )
				{
					alert( 'submit new comment exception: ' + e.message ); 
				}
			}
		} 
	);
	
	// debugging
	//$('previewArea').style.display = 'block';
	//$('previewArea').innerHTML = 'Debug:<br />' + AJAXUrl + '?' + formValues;
	$('previewArea').style.display="none";
}

function submitNewContentComment() {
	var commentValue = $('postCommentForm').comment.value;
	if(commentValue == '') {
		alert("You cannot post a blank comment.  Please try again!");
		return false;
	} else {
		var formValues = $('postCommentForm').serialize();
		AJAXUrl = 'http://'+AARPComments.host+'/community/content/comment/submit.bt';
		var submitNewContentComment = new Ajax.Request(AJAXUrl, {method:'post', parameters: formValues, onSuccess: showCommentResponse});
	}
}

function previewNewArticleComment() {
	var previewComment = $('comment').value.replace(/\n/g, "<br />");
	$('previewArea').style.display="block";
	$('previewComment').update(previewComment);
}

function checkArticleUrl() {
	var tmpArticleUrl = location.href.match(new RegExp('(.*\.html)(.*)'));
	var articleUrl = tmpArticleUrl[1];
	return articleUrl.replace( ':4402/author/home', '' );
}

function jumpToLogin() {
	openLogin();
}

function submitDeleteArticleComment(commentId) {
	var params = "method=deleteArticleComment&commentId=" + commentId + "&articleID=" + AARPAds.pgid + '&version=' + AARPAds.version;
	// since we can have more than one page here, we need to find out what page number we are on and pass it on. 
	// var pageNum = getPageNumber();
	//if (pageNum != null){ 
	//formValues = formValues + "&pageNum="+pageNum;
	// } 
	var loginRequest = new Ajax.Request( '/community/articleComments/comment/delete.bt', {method: 'post', parameters: params, onSuccess: successfulCommentDeletion} );
}

function showArticleCommentDeleteConfirmation(commentId) {
	document.getElementById("deleteButton" + commentId).style.display = 'none';
	document.getElementById("deleteConfirmationFormDiv" + commentId).style.display = 'block';
}

function showArticleCommentDeleteForm(commentId) {
    document.getElementById("deleteConfirmationFormDiv" + commentId).style.display = 'none';
    document.getElementById("deleteButton" + commentId).style.display = '';
}

function showFlagConfirmation(commentId) {
    document.getElementById("flagButton" + commentId).style.display = 'none';
    document.getElementById("flagConfirmationFormDiv" + commentId).style.display = 'block';
}

function showFlagForm(commentId) {
    document.getElementById("flagConfirmationFormDiv" + commentId).style.display = 'none';
    document.getElementById("flagButton" + commentId).style.display = '';
}

function submitFlagProfile(commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		var formValues = $('flagFormTestimonial' + commentId).serialize();
		formValues = formValues + "&itemTypeId=3";
		
		var loginRequest = new Ajax.Request( '/community/profile/flagProfileTestimonial.bt', {method: 'post', parameters: formValues, onSuccess: showTestimonialResponse} );
	}
}

function submitFlagAll(commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		var formValues = $('flagFormTestimonial' + commentId).serialize();
		// since we can have more than one page here, we need to find out what page number we are on and pass it on. 
		var pageNum = getPageNumber();
		if (pageNum != null){ 
			formValues = formValues + "&pageNum="+pageNum;
		}
		formValues = formValues + "&itemTypeId=3";
		var loginRequest = new Ajax.Request( '/community/profile/flagFromAllTestimonial.bt', {method: 'post', parameters: formValues, onSuccess: showTestimonialResponse} );
	}
}

function submitFlagComment(commentId) {
	var errorFlag = 0;
	
	if (errorFlag == 0) {
		var formValues = $('flagFormComment' + commentId).serialize();
		// since we can have more than one page here, we need to find out what page number we are on and pass it on. 
		var pageNum = getPageNumber();
		if (pageNum != null){ 
			formValues = formValues + "&pageNum="+pageNum;
		}
		formValues = formValues + "&itemTypeId=2";
		var loginRequest = new Ajax.Request( '/community/content/comment/flag.bt', {method: 'post', parameters: formValues, onSuccess: showCommentResponse} );
	}
}

function submitFlagArticleComment(commentId) {
	var params = "commentId=" + commentId + "&itemTypeId=4&method=flagArticleComments";
	// since we can have more than one page here, we need to find out what page number we are on and pass it on. 
	// var pageNum = getPageNumber();
	//if (pageNum != null){ 
	//formValues = formValues + "&pageNum="+pageNum;
	// } 
	var loginRequest = new Ajax.Request( '/community/flagItems/flagContent.bt', {method: 'post', parameters: params, onSuccess: overlayConfirmation('flagCommentConfirmation' + commentId)} );
}

// Start JS function for Admin Edit
// Current comment being editted
var activeEdit = null;
// Original text  being edited
var originalText = null;

/**
 * Prepare the text area for edit
 */
function prepareEditArticleComment(comment) {
	
	var editComment = 'articleCommentText'+comment;
	if (editComment != activeEdit) {
		closeEditArticleComment();
		activeEdit = editComment;
	} else {
		return false;
	}
	
	originalText = $(activeEdit).innerHTML;
	// stripTags()
	var commentText = originalText.replace(/<br>/gi, '\n').trim();
	
	var edit_area = "<table><tr><td>" +
					"<div id='editCommentTextDiv'>" + 
					"<input type='hidden' name='editComment' id='editComment' value='" + comment +"' />" +
					"<textarea name='editCommentText' id='editCommentText' class='articleCommentFormInput' rows='4' onkeyup='checkNumberOfCharacters(this, \"editRemainChars\"); return false;'>" + commentText+ "</textarea>" +
					"<div class='commentChars'>You can enter <span id='editRemainChars'>2000</span> more characters.</div>" +
					"<div id='editCommentFailed'></div>" +
					"<div class='clearer'></div>" + 
					"<a href='#' onclick='submitEditArticleComment(); return false;' class='btn24Blue'>" +
					"<span class='left'>&nbsp;</span>" +
					"<span class='middle'>Save</span>" +
					"<span class='right'>&nbsp;</span>" +
					"</a>" +
					"<a href='#' onclick='closeEditArticleComment(); return false;' class='btn24Blue'>" +
					"<span class='left'>&nbsp;</span>" + 
					"<span class='middle'>Cancel</span>" + 
					"<span class='right'>&nbsp;</span>" + 
					"</a>" + 
					"<div class='clearer'></div>" + 
					"</div>" +
					"</td></tr></table>";
					
	 $(activeEdit).innerHTML = edit_area;
	checkNumberOfCharacters('editComment', "editRemainChars");
}

/**
 * Close the comment area after edit
 */
function closeEditArticleComment() {
	if (activeEdit != null){
		if (originalText != null) {
			 $(activeEdit).innerHTML = originalText;
		}
		activeEdit = null;
		originalText = null;
	}
}

/**
 * Save the edit article comment
 */
function submitEditArticleComment() {
	
	var params = 'editComment='+$F('editComment') +'&comment=' +escape($F('editCommentText'));
	url = 'http://' + AARPComments.host + '/community/articleComments/edit.bt';
	
	var loginRequest = new Ajax.Request( url, {method: 'post', parameters: params, 
					onSuccess: function() {
						var commentText = $('editCommentText').value
						originalText = commentText.replace(/\n/gi, '<br>');
						closeEditArticleComment();
					}, onException : function() {
					    document.getElementById('editCommentFailed').innerHTML = 'Sorry, the edit failed.';
					}});
}
// End JS function for Admin Edit


/*
Don't look-- this is going to get ugly
--------------------------------------- */
function processSubSiteSearchForm() {
	AARP.SubSiteSearch.processPromoForm() ;
} ;

if( typeof console === "undefined" ) {
	console = {
		log: function() {},
		info: function() {}
	} ;
} ;

