function ka_checkInputLogic(event) {
	var input = $("ka_profileNewCommentSubject");
	var keyCode = event.keyCode;
	if ((keyCode == 13 && input.value != "") || keyCode == 9 || keyCode == 40 || keyCode == 3) {
		if (typeof tinyMCE !== "undefined") {
			try {
				tinyMCE.execCommand("mceFocus", false, "mce_editor_0");
			}
			catch (err) {
			}
		}
		return false;
	} else {
		if ($j.browser.safari && (keyCode == 13 || keyCode == 3)) {
			return false;
		}
	}
	return true;
}
$j(document).ready(function () {
	if (Ka.Info.USERID != "") {
		$j("#ka_profileAddCommentButtonTop, #ka_profileAddCommentButtonBot").show();
	} else {
		$j(".ka_LoginLink").toggle();
	}
	$j("#ka_profileNewCommentSubject").keypress(function (event) {
		return ka_checkInputLogic(event);
	});
	$j("#ka_profileAboutToggleShow a").click(function () {
		return toggleAboutMe();
	});
});
Ka.Settings.tinyMCE.defaultHeight = 150;
descMaxLimit = 600;
var profileCollapsed = true;
function toggleAboutMe() {
	$j("#ka_profileAboutMeExt").toggle();
	if (profileCollapsed == true) {
		profileCollapsed = false;
		$j("#ka_profileAboutToggleShow a").html(Ka.Messages.HIDE);
	} else {
		profileCollapsed = true;
		$j("#ka_profileAboutToggleShow a").html(Ka.Messages.READMORE);
	}
	return false;
}
var linksCollapsed = true;
function getCommentCount() {
	if ($("ka_profileCommentsList")) {
		return $("ka_profileCommentsList").getElementsByTagName("li").length;
	} else {
		return 0;
	}
}
function toggleMoreLinks() {
	var ka_profileLinksToggleShow = $("ka_profileLinksToggleShow");
	var ka_profileLinksLong = $("ka_profileLinksLong");
	var ka_profileLinksShort = $("ka_profileLinksShort");
	if (linksCollapsed == true) {
		linksCollapsed = false;
		ka_profileLinksShort.style.display = "none";
		ka_profileLinksLong.style.display = "block";
		ka_profileLinksToggleShow.getElementsByTagName("a")[0].style.background = "transparent url(/images/bullet_arrow_down.png) no-repeat scroll 0 50%";
		ka_profileLinksToggleShow.getElementsByTagName("a")[0].getElementsByTagName("span")[0].innerHTML = "hide";
	} else {
		linksCollapsed = true;
		ka_profileLinksShort.style.display = "block";
		ka_profileLinksLong.style.display = "none";
		ka_profileLinksToggleShow.getElementsByTagName("a")[0].style.background = "transparent url(/images/bullet_arrow_right.png) no-repeat 0 50%";
		ka_profileLinksToggleShow.getElementsByTagName("a")[0].getElementsByTagName("span")[0].innerHTML = "show all";
	}
}
var tagsCollapsed = true;
function toggleMoreTags() {
	var ka_profileTagsToggleShow = $("ka_profileTagsToggleShow");
	var ka_profileTagsLong = $("ka_profileTagsLong");
	var ka_profileTagsShort = $("ka_profileTagsShort");
	if (tagsCollapsed == true) {
		tagsCollapsed = false;
		ka_profileTagsShort.style.display = "none";
		ka_profileTagsLong.style.display = "block";
		ka_profileTagsToggleShow.getElementsByTagName("a")[0].style.background = "transparent url(/images/bullet_arrow_down.png) no-repeat scroll 0 50%";
		ka_profileTagsToggleShow.getElementsByTagName("a")[0].getElementsByTagName("span")[0].innerHTML = "hide";
	} else {
		tagsCollapsed = true;
		ka_profileTagsShort.style.display = "block";
		ka_profileTagsLong.style.display = "none";
		ka_profileTagsToggleShow.getElementsByTagName("a")[0].style.background = "transparent url(/images/bullet_arrow_right.png) no-repeat 0 50%";
		ka_profileTagsToggleShow.getElementsByTagName("a")[0].getElementsByTagName("span")[0].innerHTML = "show all";
	}
}
function flaggedcomment(ret) {
	var defaultUrl = "/service/displayKickPlace.kickAction?u=" + Ka.Info.USERID + "&as=" + Ka.Info.AFFILIATESITEID;
	document.location.href = defaultUrl;
}

function kap_profileCommentSaveCallback() {
	if (tinyMCE) {tinyMCE.triggerSave();}
	if (Ka.Info.AUTOAPPROVALCOMMENTS == "false") {
		alert(Ka.Messages.YOURCOMMENTSHASBEENSUBMITTED);
	}

	Ka.formValidation.actions.enableSubmit($('ka_profileCommentForm'));
	
	// Ka.formValidation.actions.enableSubmit($('ka_profileCommentForm'));
	var newCommentLI = document.createElement("li");
	$j(newCommentLI).addClass('ka_profComment');
	var newCommentSubject = document.createElement("div");
	newCommentSubject.className = "ka_profileCommentSubject ka_profileHeadline";
	newCommentSubject.appendChild(document.createTextNode($("ka_profileNewCommentSubject").value));
	var newCommentDate = document.createElement("div");
	newCommentDate.className = "ka_profileCommentDate";
	var newCommentUserLink = document.createElement("a");
	newCommentUserLink.href = "/service/displayKickPlace.kickAction?u=" + Ka.Info.USERID + "&as=" + Ka.Info.AFFILIATESITEID;
	newCommentUserLink.title = Ka.Info.USERNAME;
	var newCommentUserImgLink = document.createElement("a");
	newCommentUserImgLink.href = "/service/displayKickPlace.kickAction?u=" + Ka.Info.USERID + "&as=" + Ka.Info.AFFILIATESITEID;
	newCommentUserImgLink.title = Ka.Info.USERNAME;
	var newCommentUserImgDiv = document.createElement("div");
	newCommentUserImgDiv.className = "ka_profileCommentImg";
	var newCommentUserImg = document.createElement("span");
	var userImage = new Image();
	userImage.src = Ka.Info.AUDIOPHOTOSERVERPATH + Ka.Info.AFFILIATESITEID + "/users/" + Ka.Info.USERNAME + "_" + Ka.Info.AFFILIATESITEID + "_portrait48X48.jpg";
	if (!userImage.complete) {
		userImage.src = Ka.Info.AUDIOPHOTOSERVERPATH + Ka.Info.PATHTOPHOTO;
	}
	newCommentUserImg.style.backgroundImage = "url(\"" + userImage.src + "\")";
	newCommentUserImg.innerHTML = "&nbsp;";
	var newCommentContent = document.createElement("div");
	newCommentContent.className = "ka_profileCommentContent";
	newCommentContent.innerHTML = $("ka_profileNewCommentTextarea").value + '<span class="ka_flag ka_flag_comment ka_emptyFlag"></span>';
	
	if (!$("ka_profileCommentsList")) {
		var commentsList = document.createElement("ul");
		commentsList.id = "ka_profileCommentsList";
		$("ka_profileCommentsEmptyCont").innerHTML = "";
		$("ka_profileCommentsEmptyCont").appendChild(commentsList);
	}
	newCommentDate.appendChild(document.createTextNode(Ka.Messages.SECONDS.replace('($count)',0)+" | "));
	newCommentUserLink.appendChild(document.createTextNode(Ka.Info.USERNAME));
	newCommentDate.appendChild(newCommentUserLink);
	newCommentUserImgLink.appendChild(newCommentUserImg);
	newCommentUserImgDiv.appendChild(newCommentUserImgLink);
	newCommentLI.appendChild(newCommentSubject);
	newCommentLI.appendChild(newCommentDate);
	newCommentLI.appendChild(newCommentUserImgDiv);
	newCommentLI.appendChild(newCommentContent);
	if ($("ka_profileCommentsList").getElementsByTagName("li")[0]) {
		$("ka_profileCommentsList").insertBefore(newCommentLI, $("ka_profileCommentsList").getElementsByTagName("li")[0]);
	} else {
		$("ka_profileCommentsList").appendChild(newCommentLI);
	}

	Ka.show("#ka_profileCommentControlTop", "#ka_profileAddCommentButtonTop", "#ka_profileCommentPosted");
	if (getCommentCount() > 1) {
		Ka.show("#ka_profileCommentControlBot", "#ka_profileAddCommentButtonBot");
	}
	if ($("ka_profileCommentBotLink")) {
		Ka.hide("#ka_profileCommentForm", "#ka_profileCommentBotLink");
	} else {
		Ka.hide("#ka_profileCommentForm");
	}
	$("ka_profileNewCommentSubject").value = "";
	$("ka_profileNewCommentTextarea").value = "";
	//clear fields
	$("ka_profileNewCommentTextarea").value = "";
	if ($("ka_profileNewCommentTextarea_ifr")) {
		tinyMCE.getInstanceById("ka_profileNewCommentTextarea").setContent("");
	}
	// tinyMCE.updateContent("ka_profileNewCommentTextarea");
	$('ka_profileNewCommentSubmit').value = Ka.formValidation.containers.submitButtonMessage;
		// pagination code
	if ($('ka_showMoreCommentsOutter')){
		$j('#ka_commentPageEndTotal').html(Number($j('#ka_commentPageEndTotal').html())+1);
	}
	// hide no comments div
	$j('#ka_profileCommentsEmptyCont').hide();
	
	$('ka_profileNewCommentSubmit').value = ka_submitFormText;

}

var ka_submitFormText;
function kap_profileCommentSave(thisForm) {
	Ka.formValidation.actions.disableSubmit(thisForm);
	var kap_subject = thisForm.ka_profileNewCommentSubject.value;
	var kap_body;
	if ($("ka_profileNewCommentTextarea_ifr")) {
		kap_body = tinyMCE.getInstanceById("ka_profileNewCommentTextarea").getContent();
	} else {
		kap_body = thisForm.ka_profileNewCommentTextarea.value;
	}
	thisForm.ka_profileNewCommentTextarea.value = kap_body;
	var kap_target = $("kap_profileNewCommentTargetId").value;
	KickAppsBizComponent.addGuestbookEntry(kap_target, Ka.Info.USERID, kap_subject, kap_body, Ka.Info.AFFILIATESITEID, kap_profileCommentSaveCallback);
	return false;
}
var kap_commentSourceLogin = false;
function loginFromSearch(loggedIn) {
	if (loggedIn != null) {
		Ka.hide("#ka_profileCommentTopLink");
		if (getCommentCount() > 1) {
			if ($("ka_profileCommentBotLink")) {
				Ka.hide("#ka_profileCommentBotLink");
			}
		}
		Ka.show("#ka_profileAddCommentButtonTop");
		if (getCommentCount() > 1) {
			Ka.show("#ka_profileAddCommentButtonBot");
		}
		if (kap_commentSourceLogin) {
			Ka.show("#ka_profileCommentForm");
			if ($("ka_profileCommentBotLink")) {
				Ka.hide("#ka_profileCommentBotLink", "#ka_profileAddCommentButtonTop");
			} else {
				Ka.hide("#ka_profileAddCommentButtonTop");
			}
			if (getCommentCount() > 1) {
				Ka.hide("#ka_profileCommentControlBot");
			}
			Ka.$("#ka_profileNewCommentSubject").focus();
		}
		if (Ka.Info.USERID == loggedIn.userId) {
			Ka.toggle("#ka_profileEditLink");
		} else {
			Ka.toggle("#ka_profileMessageLink");
		}
		if (Ka.Info.USERID != loggedIn.userId) {
			Ka.toggle("#ka_profileAddRSSLink");
		} else {
			if (false) {
				Ka.toggle("#ka_profileAddedRSSLink");
			}
		}
		KickAppsBizComponent.getFavoriteUsers(function (obj) {
			var kap_areFriends = false;
			for (var x = 0; x < obj.length; x++) {
				if (obj[x][2] == Ka.Info.USERID || loggedIn.userId == Ka.Info.USERID) {
					kap_areFriends = true;
					break;
				}
			}
			if (!kap_areFriends) {
				$("ka_profileFriendLink").style.display = "inline";
			}
		}, 1, 1);
	}
}
function kap_addFriend() {
	KickAppsBizComponent.addFavoriteUserAsFriend(Ka.Info.USERID, Ka.Info.PROFILEID, Ka.Info.AFFILIATESITEID, function () {
		if ($("ka_profileFriendLink")) {
			$("ka_profileFriendLink").style.display = "none";
			$("ka_profileFriendAlready").style.display = "inline";
		}
	});
}
function ka_sendMessage(id) {
	var url = Ka.Info.SERVERROOT + "/view/displayNewMessage.kickAction?as=" + Ka.Info.AFFILIATESITEID + "&name=" + Ka.Info.PROFILENAME;
	$("redirectURL").value = url;
	Ka.popup(id);
}
function ka_addFriendsAndRss(id, uId) {
	var url = Ka.Info.SERVERROOT + "/update/addWatchMe.kickAction?as=" + Ka.Info.AFFILIATESITEID + "&u=" + uId;
	$("redirectURL").value = url;
	Ka.popup(id);
}
function toggleCommentForm() {
	Ka.toggle("#ka_profileCommentForm", "#ka_profileCommentControlTop");
	$("ka_profileNewCommentSubject").value = "";
	if (getCommentCount() > 1) {
		Ka.toggle("#ka_profileCommentControlBot");
	}
	Ka.hide("#ka_profileCommentPosted");
	if ($("ka_profileNewCommentSubject").style.display != "none") {
		$("ka_profileNewCommentSubject").focus();
	}
}
function showCommentButtons() {
	Ka.show("#ka_profileCommentControlTop", "#ka_profileAddCommentButtonTop");
	if (getCommentCount() > 1) {
		Ka.show("#ka_profileCommentControlBot", "#ka_profileAddCommentButtonBot");
	}
	Ka.hide("#ka_profileCommentPosted", "#ka_profileCommentForm");
}
function ka_flagComment(thisLink, dataObj) {
	var tosHrf='/service/displayTOS.kickAction?as='+Ka.Info.AFFILIATESITEID;
	Ka.prompt(Ka.Messages.flagCommentAsInappropriate.replace('($siteName)',Ka.Info.SITENAME).replace('($tosHref)',tosHrf), function (reason) {
		var thisUserOr0 = (Ka.Info.USERID == "") ? 0 : Ka.Info.USERID;
		KickAppsBizComponent.flagCommentAsInappropriate(dataObj.messageId, thisUserOr0, dataObj.commenterId, dataObj.commenterName, reason, Ka.Info.AFFILIATESITEID, function (response) {
			if (response) {
				$j(thisLink).parent().append("<span class=\"red\">"+Ka.Messages.PROFILEPAGEFLAGGED+"</span>");
				$j(thisLink).remove();
			}
		});
	});
}

var Comments = {
	
	get: function(offset, limit){
		//console.log('Comments.get',arguments);
		var totalCommentsOnPage = $j('#ka_profileCommentsList li.ka_profComment').length;
		offset = offset || totalCommentsOnPage + 1;
		limit = limit || Ka.Settings.profileCommentsLength;
		
		//console.log('retriving comments: ', offset, limit);
		
		KickAppsBizComponent.getProfileCommentsJson(Ka.Info.USERID === ''? null : Ka.Info.USERID, Ka.Info.PROFILEID, Ka.Info.AFFILIATESITEID, offset, limit,{ 
			// async: false,
			callback: function(c){
				//console.log('CALLBACK');
				r = eval('(' + c + ')');

				//console.log('WHOLE OBJECT', r);
				Comments.iterate(r);
			}
		});
	
	},
	
	// iterates through commentsObj and displays pagination if neccissary
	iterate: function(commentObj){
		//console.log('commentObj',commentObj);
		var newComments = commentObj.comments;
		
		//console.log('iterateiterate',commentObj );

		newComments = $j.grep( newComments, function(i){
		    return !this.blocked;
		});
		
		for (var i = 0, len = newComments.length; i < len; i++){
			var comment = newComments[i], userThumbnail, commenterLink, flagBlock;
				    	
			//console.log('showing!',i);
			userThumbnail = comment.commentByImg; //Ka.Info.STATICSERVERIMAGES + '/' + Ka.Info.PATHTOPHOTO;
			commenterLink = comment.formerMember != "" ?comment.formerMember:comment.commentByLink + " "+comment.username+"</a>";
			flagBlock = comment.isFlagged ? '<span id="flagcomment_' + comment.commentId + '" class="ka_flag ka_flagged_comment red">' + Ka.Messages.PROFILEPAGEFLAGGED + '</span>' : '<span class="ka_flag ka_flag_comment"><a onclick="ka_flagComment(this, {\'messageId\':\'' + comment.commentId + '\', \'commenterId\': \'' + comment.userId + '\', \'commenterName\': \'' + comment.username + '\', \'comment\': \' <p>\'}); return false;" href="#">' + Ka.Messages.FLAGASINAPPROPRIATE + '</a></span>';
			$j('<li id="c' + comment.commentId + '" class="ka_profComment"><div class="ka_profileCommentSubject ka_profileHeadline">' + comment.subject + '</div><div class="ka_profileCommentDate">' + comment.commentTimeStamp + ' | ' + commenterLink+ '</div><div class="ka_profileCommentImg">'+comment.commentByLink+'<span style="background-image: url(' + userThumbnail + ');"> </span></a></div><div><p>' + comment.commentBody + '</p></div>' + flagBlock + '</li>')
				.hide()
				.appendTo('#ka_profileCommentsList');
				//.fadeIn('slow');
		}
		
		function showNext() {
			if (Ka.Settings.profileCommentsFade){
		    	$j('#ka_profileCommentsList li.ka_profComment:hidden:eq(0)').fadeIn(function(){
		    		showNext();
		    	});
		    }else{
		    	$j('#ka_profileCommentsList li.ka_profComment:hidden').show();
		    }
		}
		 
		showNext();

		var totalComments = commentObj.totalComments;
		var totalCommentsOnPage = $j('#ka_profileCommentsList li.ka_profComment').length;
		
		var nextCommentStart = totalCommentsOnPage + 1;
		
		/*
		var nextCommentLimit = (function(){
			if ($('ka_showMoreCommentsOutter')){
				console.log('a');
				return 	(Number($j('#ka_commentLimit').html()) + Ka.Settings.profileCommentsLength) <= totalComments ? (Number($j('#ka_commentLimit').html()) + Ka.Settings.profileCommentsLength) : totalComments;
				// return 	( totalCommentsOnPage + Ka.Settings.profileCommentsLength) <= totalComments ? Ka.Settings.profileCommentsLength : totalComments - totalCommentsOnPage;
			}else{
				console.log('b');
				console.log(totalCommentsOnPage + Ka.Settings.profileCommentsLength <= totalComments);
				return (totalCommentsOnPage + Ka.Settings.profileCommentsLength <= totalComments) ? totalCommentsOnPage + Ka.Settings.profileCommentsLength : totalComments;
			}
		})();
		*/
		
		//console.log('nextCommentLimitnextCommentLimitnextCommentLimit',nextCommentLimit);
		//console.log(totalCommentsOnPage,  newComments.length, totalComments);
	

		// if pagination should be shown
		if (totalCommentsOnPage != totalComments){
			//get remaining comments
			var remainingComments = totalComments - totalCommentsOnPage;
			//console.log('remainingComments',remainingComments);
			var remainingLimit = (remainingComments > Ka.Settings.profileCommentsLength) ? Ka.Settings.profileCommentsLength : remainingComments;
			//console.log('remainingLimit',remainingLimit);
			//console.log('===========remainingLimit',remainingLimit);
			// if there is no more comments container, add it
			if (!$('ka_showMoreCommentsOutter')){
				$j('<div id="ka_showMoreCommentsOutter"><span id="ka_showMoreCommentsInner">' + Ka.Messages.PAGINATIONLINKCOMMENT  + ' <span id="ka_commentPageStartTotal">1</span> - <span id="ka_commentPageEndTotal">' + totalCommentsOnPage + '</span>  <a href="#">' + Ka.Messages.PAGINATIONLINKNEXT + ' <span id="ka_commentOffset">' + remainingLimit + '</span></a></span></div>').insertAfter('#ka_profileCommentsList');
				// $j('<div id="ka_showMoreCommentsOutter"><span id="ka_showMoreCommentsInner"><a href="#">Show <span id="ka_commentOffset">' + nextCommentStart + '</span> - <span id="ka_commentLimit">' + nextCommentLimit + '</span> of <span id="ka_commentTotal">' + totalComments + '</span> comments</a></span></div>').insertAfter('#ka_profileCommentsList');
				$j('#ka_showMoreCommentsOutter a').click(function(){
					Comments.get($j('#ka_profileCommentsList li.ka_profComment').length+1, remainingLimit);
					return false;
				});
			}else{
				// else modify it
				$j('#ka_commentOffset').text(remainingLimit);
				$j('#ka_commentPageEndTotal').html(totalCommentsOnPage);
			}
		}else{
			$j('#ka_showMoreCommentsOutter').remove();
		}
	
	}

}

/*
Still working on this new version of get comments
ka_nextComments = function(){
	var clickCount = 0;

	return function(){
		clickCount++;
		var currentCommentCount = $j('#ka_profileCommentsList li.ka_profComment:visible').length;
		
		//if this is the first click
		if(clickCount===1){
		}
		
		alert('clicked: ' + clicked);
	
		return false;
	}
}();
*/

function ka_main(){
	ka_submitFormText = $('ka_profileNewCommentSubmit').value;
	
	
	/*
	if ($j('#ka_profileCommentsList li.ka_profComment:visible').length === 5){
		ka_nextComments();
	}
	*/


	//iterate(Comments.get(5,5));
	//console.log('comments',comments);
	/*
	// Pagination.displayPage(0);	
	KickAppsBizComponent.getProfileCommentsJson(Ka.Info.USERID === ''? null : Ka.Info.USERID, Ka.Info.PROFILEID, Ka.Info.AFFILIATESITEID, offset, limit,{ 
		async:false,
		callback: function(c){
			console.log('CALLBACK');
			r = eval('(' + c + ')');
			console.log('WHOLE OBJECT', r);
		}
	});
	*/
	
	Comments.get();
}


//que up main func on dom ready
$j(ka_main);
