function addComment() {
	thought_id	= $j('#CommentThoughtId').attr('value');
	title		= $j('#CommentTitle').attr('value');
	comment		= $j('#CommentComment').attr('value');
	published	= $j('#CommentPublished').attr('value');
	user_id		= $j('#CommentUserId').attr('value');
	flagged		= $j('#CommentFlagged').attr('value');
	
	udate = {'data[comment]':comment,'data[flagged]':flagged,'data[published]':published,'data[thought_id]':thought_id,'data[title]':title,'data[user_id]':user_id};
	cont = true;
	org = $j('#enterComments').html();
	
	if(title == "") {
		//alert("check title");
		cont = false;
		$j('#enterComments').addClass('ui-state-highlight ui-corner-all');
		$j('#enterComments').html('<span class="ui-icon ui-icon-info" style="float:left;margin-right:0.3em;" />Please add a title to your comment.');
	}
	
	if(comment == "") {
		//alert("check comment");
		$j('#enterComments').addClass('ui-state-highlight ui-corner-all');
		if(cont == false) {
			$j('#enterComments').append('<br /><span class="ui-icon ui-icon-info" style="float:left;margin-right:0.3em;" />Please add a comment before posting.');
		} else {
			$j('#enterComments').html('<span class="ui-icon ui-icon-info" style="float:left;margin-right:0.3em;" />Please add a comment before posting.');		
		}
		cont = false;
	}
	
	if(cont == false) {
		window.setTimeout(function() {
			$j('#enterComments').hide();
			$j('#enterComments').removeClass('ui-state-highlight ui-corner-all');
			$j('#enterComments').html(org);
			$j('#CommentCount').html('');
			$j('#enterComments').show('slow');
			$j('#submitComment').bind('click', addComment);
		}, 5000);
	}
	
	if(cont == true ) {
		$j.ajax({
			type: "POST",
			url: '/comments/ajaxadd',
			//contentType: 'X-Requested-Header',
			dataType: 'html',
			data: udate,
			success: function(msg) {
				org = $j('#enterComments').html();
				$j('#enterComments').addClass('ui-state-highlight ui-corner-all');
				$j('#enterComments').html('<span class="ui-icon ui-icon-info" style="float:left;margin-right:0.3em;" />Thank you for your comment.');
				fillComments($j('#hiddenThoughtId').html());
				window.setTimeout(function() {
					$j('#enterComments').hide();
					$j('#enterComments').removeClass('ui-state-highlight ui-corner-all');
					$j('#enterComments').html(org);
					$j('#CommentCount').html('');
					$j('#enterComments').show('slow');
					$j('#submitComment').bind('click', addComment);
				}, 5000);
			},
			failure: function(msg) {
				$j('#enterComments').html('Comment did not save');
			}
		});
	}
	return false;
}

function flagComment(id) {
	$j.ajax({
		type: "POST",
		url: '/comments/flag/'+id,
		//contentType: 'X-Requested-Header',
		dataType: 'html',
		success: function(msg) {
			org = $j('#enterComments').html();
			$j('#enterComments').addClass('ui-state-highlight ui-corner-all');
			$j('#enterComments').html('<span class="ui-icon ui-icon-info" style="float:left;margin-right:0.3em;" />Thank you for flagging a comment.');
			fillComments($j('#hiddenThoughtId').html());
			window.setTimeout(function() {
				$j('#enterComments').hide();
				$j('#enterComments').removeClass('ui-state-highlight ui-corner-all');
				$j('#enterComments').html(org);
				$j('#CommentCount').html('');
				$j('#enterComments').show('slow');
				$j('#submitComment').bind('click', addComment);
			}, 5000);
			},
			failure: function(msg) {
				$j('#enterComments').html('Comment did not save');
			}
		});
}

function fillComments(thought_id) {
	t = thought_id.replace(/^\s*|\s*$|%20| /,"");
	//alert('/comments/bythought/'+t+'.xml'); // for debugging
	$j.ajax({
		type: "POST",
		url: '/comments/bythought/'+t+'.xml',
		dataType: 'xml',
		success: function(msg) {
			$j(msg).find('comments').each(function() {
				t = $j(this).text().replace(/\n+|\s+|\t+/);
				if(t == '\n' || t == ''|| t == 'undefined') {
					$j('#CommentsMsg').addClass('ui-state-highlight ui-corner-all');
					$j('#CommentsMsg').html('<span class="ui-icon ui-icon-info" style="float:left;margin-right:0.3em;" />Currently there are no comments on this thought. Please leave a comment.');
					$j('#CommentsMsg').show();
				} else {
					$j('#CommentsMsg').hide();
				}
			});
			
			$j('#printComments').hide('slow');
			$j('#printComments').html('');
			$j(msg).find('user_id').each(function() {
				id 			= $j(this).prev().prev().prev().text();
				title 		= $j(this).prev().prev().text();
				text		= $j(this).prev().text();
				user_id		= $j(this).text();
				author		= $j(this).next().text();
				created		= $j(this).next().next().text();
				modified	= $j(this).next().next().next().text();
				
				chtml =  '<div class="commentTop"></div>';
				chtml += '<div class="aComment">';
				chtml += '<div class="commentTitle"><h3>'+title+'</h3></div>';
				chtml += '<div class="commentAuthor">Written By: '+author+'</div>';
				chtml += '<div class="commentBody">'+text+'</div>';
				chtml += '<div class="flagComment" rel="'+id+'" style="float:right;margin-top:2px;">';
				chtml += '<img src="/img/flagcomment.gif" border="0" alt="Flag this comment" /></div>';
				chtml += '</div>';
				chtml += '<div class="commentBtm"></div>';
				
				$j('#printComments').append(chtml);
			});
			$j('.flagComment').bind('click', function() {
				flagComment($j(this).attr('rel'));
			});
			$j('#printComments').show('slow');
		}
	});
}

function onFBConnect() {
	var changeTxt = "<span><fb:profile-pic class='fbleft' uid='loggedinuser' facebook-logo='true'></fb:profile-pic>";
	changeTxt += "Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>.";
	changeTxt += " You are signed in with your Facebook account.</span><br />";
	$j('#userConnect').html(changeTxt);
	FB.XFBML.Host.parseDomTree();
}

function onFBFailed() {
	var newTxt = '<div id="facebookStatus">';
	newTxt += '<font color="red">Failed to connect to facebook.</font>';
	newTxt += '</div>';
	$j('#userConnect').append('<br />' + newTxt);
	setInterval('hideFBError()',1000);
}

function hideFBError() {
	$j('#facebookstatus').hide('slow');
}

$j(function() {
	fillComments($j('#hiddenThoughtId').html());
	$j('#submitComment').bind('click', addComment);
	
	$j('#CommentComment').keyup(function() {
		var commentlength = $j(this).val().length;
		if(commentlength >= 255) {
			$j('#CommentCount').html('<font color="red">You have exceeded the comment length</font>');
			$j('#submitComment').hide('slow');
		} else {
			$j('#CommentCount').html(commentlength+' of 255.');
			$j('#submitComment').show('slow');
		} 
	});
	
	$j('#CommentCtrl').bind('click', function() {
		text = $j('#CommentCtrl').html();
		if(text == 'Show Comments') {
			$j('#CommentCtrl').html('Hide Comments');
		} else if(text == 'Hide Comments') {
			$j('#CommentCtrl').html('Show Comments');
		}
		$j('#commentsWrap').toggle('slow');
		
		commentAuth = $j('#CommentsAuth').html().replace(/\s+|\n+|\t+| +|%20+/,"");
		if(commentAuth == "false     	" || commentAuth == ""||commentAuth == 'false') {
			$j('#CommentsAuth').html('<span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"/>Please <a href="/users/login">login</a> to make a comment.');
			$j('#CommentsAuth').show();
		}
	});
	
	FB.init("8d8e7228d555056d749d86b201378b89", "xdr"); 
	FB.ensureInit(function(){
		FB.Connect.ifUserConnected(onFBConnect);	
	});
	
	$j('#submitComment').bind('click', function() { 
		var tdata = { 
				'sitename': 'AwakenGeneration.com',
				'siteurl': location.href,
				'template_body' : '{*actor*} just commented on ' + $j('title').text() + ' from AwakenGeneration.com.',
				'actiontext': 'commented'
			};
			
			target_ids = {};
			FB.Connect.showFeedDialog('113138851674', tdata,target_ids, '', 
					FB.FeedStorySize.oneLine, FB.RequireConnect.promptConnect);
	});
});