var last_comment = -1;
var timeout = 20;
// javascript interval ids
var update_request;
var posturl = "/comments/post/json";
var geturl = "/comments/get/json";
var newCommentFlasher = NewCommentFlasher();
var firstLoad = 1;
var reply_author = "";
var reply_id = "";

function showCommentersPage(e) {
	var pageTitle = e.data.commentdata.author + "'s " + e.data.commentdata.third_party;
	largeThickBox(pageTitle,e.data.commentdata.author_profile_url);
}
function showTwitterTag(tag) {
	//tb_show("title","http://search.twitter.com/search?q=%23ATT" + '?keepThis=true&TB_iframe=true&height=225&width=375');
	largeThickBox("Twitter","http://search.twitter.com/search?q=%23" + tag.substring(1),true);
}
function twitterTagClick(e) {
	showTwitterTag(e.target.innerHTML);
}
function largeThickBox(title,url,useAmp) {
	// twitter doesnt work with ?querystring so use &querystring
	var glue = useAmp ? '&' : '?';
	//alert(url + " " + glue + 'keepThis=true&TB_iframe=true&height=' + ($(window).height()-100) + '&width=' + ($(window).width()-100));
	tb_show(title, url + glue + 'keepThis=true&TB_iframe=true&height=' + ($(window).height()-100) + '&width=' + ($(window).width()-100));
}
function charsLeft() {
	var txt = (get('post_text').value == defaultInputText) ? messageLen : (messageLen - get('post_text').value.length);
	$("#charsleft").text(txt);
}

function toggleStatus(action) {
	var display = 'inline';
	if(action == 'wait') {
		$("#qawait").css('display',display);
		$("#charsleft").css('display','none');
	} else {
		$("#qawait").css('display','none');
		$("#charsleft").css('display',display);
	}
}

// sends ajax post req
function postComment() {
	if(postEnable) {
		if(get('post_text').value != defaultInputText && trim(get('post_text').value).length > 0) {
			postEnable = false;
			toggleStatus('wait');
			
			var postdata = 	"data[Comment][post_text]=" + encodeURIComponent(get('post_text').value) + 
							"&data[Comment][meet_id]=" + meet_id;
			if(twitterChecked())
				postdata += "&data[Comment][post_twitter]=true";
			
			if (reply_author != "" && reply_id != "") {
				postdata += "&data[Comment][reply_author]=" + reply_author;
				postdata += "&data[Comment][reply_id]=" + reply_id;
				reply_author = "";
				reply_id = "";
			}
			// send post
			ajaxPost(posturl,postdata,completeComment, ajaxPostTimeout, timeout);
			
			setTimeout('postEnable = true',2000);
			updateMessage("posting comment...");
		}
	}
}
// post ajax complete handler
function completeComment(msg) {
	if(msg.redirect) {
		showLogin(msg.redirect);
	} else {
		//growl();
		if(twitterChecked() && get('post_text').value.indexOf(getTag()) === 0) {
			get('post_text').value = getTag();
		} else {
			get('post_text').value = '';		
		}
	}	
	updateMessage("");
	toggleStatus('type');
}

function showLogin(url) {
	tb_show('Login in post comment', url + '?keepThis=true&TB_iframe=true&height=90&width=400');
}

// start the comment listener
function startCommentsListener(id) {
	Comets.stop()
	Comets.add('Meet', {channel_id: id, last_id: -1, callback: completeUpdate, url: '/comments/get/json/'});
	Comets.add('CommentRemoved', {channel_id: id, last_id: -1, callback: removeComments, url: '/comments/removedids/'});
	Comets.add('CommentVote', {channel_id: meet_id + '/-1', last_id: -1, callback: updateFlages, url: '/comments/getvotes/'});
	Comets.start();
}

function updateFlages(votes_json, votes_comet) {
	votes_comet.last_id = votes_json.last_id;
	
	// add flags to each comment
	jQuery.each(votes_json.votes, function(index, vote) {
		var id_str = "#comment-" + vote.comment_id;
		var comment = $(id_str);
		if(comment.length == 1) {
			var totalflags = parseInt(comment.children('.flag').html());	
			totalflags += vote.votes;
			comment.children('.flag').html(totalflags);
			loadFlag(totalflags, comment);		
		}
	});
}

function ajaxUpdateTimeout() {
	updateMessage("connection problems...");
}

function ajaxPostTimeout(request) {
	updateMessage("Timeout occured when posting comment");
}

function lastComment() {
	var commentsPane = get('commentsPane');
	var index = commentsPane.childNodes.length-1;
	while(index >= 0) {
		var id = commentsPane.childNodes[index].id;		
		if(id && id.match && id.match(/^comment\-/)) {
			return commentsPane.childNodes[index];
		}
		index--;
	}
	return false;
}

function completeUpdate(json, comet) {
	$(".loadingimg").remove();

	// remove extra comments at the bottom
	var commentsPane = get('commentsPane');
	while((commentsPane.childNodes.length + json.comments.length > 40) && lastComment()) {
		commentsPane.removeChild(lastComment());
	}
	// put new comments in
	var initHeight = get('commentsPane').clientHeight;
	if(json.comments) {
		$("#nocomments").css("display","none");
		for(var i = json.comments.length -1;i>=0;i--) {
			addComment(json.comments[i].Comment);
		}
		if(panelInitialized) {
			newCommentFlasher.start();
		}
	}
	
	panelInitialized = true;

	var heightDiff = get('commentsPane').clientHeight - initHeight;
	
	reinitializeScroll(heightDiff);
	if(json.last_comment) {
		comet.last_id = json.last_comment;
	}
	
	updateMessage("");
	if (firstLoad == 1) {
		refreshClicks();
		firstLoad = 0;
	}
}

function reinitializeScroll(heightDiff) {
	scrollPane = $("#commentsPane").jScrollPane({scrollbarWidth: 14});
	$(".jScrollPaneContainer").css("width","100%");
	$(".jScrollPaneContainer").css("height","100%");
	$("#commentsPane").css("width","100%");
	if(IE) {
		adjustMiddleColumn();
	}	
	
	if(heightDiff && scrollPane.position().top != 0 ) {
		scrollPane[0].scrollTo(-scrollPane.position().top + heightDiff, true);
	}
}

// updates status message
function updateMessage(str) {
	//get('message').innerHTML = str;
}

function replyClick(e) {
	var comment_id = getID(e.target.id);
	var search_str = '#author-'+comment_id;
	var author = $(search_str).text();
	if(get('post_text').value == defaultInputText || get('post_text').value == "") {
		if (defaultInputText == getTag()) {
			get('post_text').value = '@' + author + ' ' + get('post_text').value;
		} else {
			get('post_text').value = '@' + author;
		}
	} else {
		get('post_text').value = '@' + author + ' ' + get('post_text').value;
	}
	reply_id = comment_id;
	reply_author = author;
}

function commentClick(e) {
	var url;
	var target = '#' + e.target.id;
	if($(target).hasClass("commentauthor")) {
		// show author bio
	} else {
		url = '/comments/vote/' + getID(e.target.id) + '/';
		var txt;
		//vote($cid,$vote,$output_format)
		if($(target).hasClass("commentvote")) {
			// vote up
			url += '1';
			vals = '1';
		} else {
			// vote down
			url += '-1';
			vals = '-1';			
		}
		url += '/json';
		ajax(url);
		
		var cid = getID(e.target.id);		
		showClicks(cid, vals);

		if (vals == '1') {
			var voteup = readCookie("votes");
			if (voteup == null) voteup = "";
			eraseCookie("votes")
			createCookie("votes", voteup + " " +cid);
		} else {
			var votedown = readCookie("flags");
			if (votedown == null) votedown == "";
			eraseCookie("flags")
			createCookie("flags", votedown + " " +cid);
		}
	}
}

function showClicks(cid, up) {
	$("#comment-" + cid).find("img.commentclick").addClass("commentclicked");
	$("#comment-" + cid).find("img.commentclick").unbind("click");
	$("#comment-" + cid).find("img.commentclick").removeClass("commentclick");
	if (up == 1) {
		$("#vote-" + cid).attr('src','/images/portal/voteupClicked.png');
	} else {
		$("#flag-" + cid).attr('src','/images/portal/reportClicked.png');
	}
}

function refreshClicks() {
	var i;
	var len;
	var voteup = readCookie("votes");
	if (voteup != null) {
		ups = voteup.split(" ");
		len = ups.length;
		for(i = 0; i<len; i++) {
			 showClicks(ups[i], 1);
		}
	}
	var votedown = readCookie("flags");
	if (votedown != null) {
		downs = votedown.split(" ");
		len = downs.length;
		for(i = 0; i<len; i++) {
			 showClicks(downs[i], -1);
		}
	}
}

function twitterChecked() {
	if($('#twitterCheckBox:checked').val()) { return 1;	} else { return 0; }
}

function getTag() {
	return '#' + sessions.sessions[0].Conference.subdomain + ' ';
}

function twitterBoxClick(e) {
	var tag = getTag();
	if(twitterChecked()) {
		if(get('post_text').value == '' || get('post_text').value == defaultInputText)
			get('post_text').value = tag;
		else
			get('post_text').value = tag + get('post_text').value;
		defaultInputText = tag;	
	} else {
		defaultInputText = 'Type your message, press enter';
		if(get('post_text').value == '' || get('post_text').value == tag) 
			get('post_text').value = defaultInputText;
		else
			get('post_text').value = get('post_text').value.replace(tag,'');
	}	
}
// adds comment to list
function addComment(comment) {
	var dom_id = '#comment-' + comment.id;
	var html = genCommentHTML(comment, "");

	html += '<div class="flag" style="display:none">0</div>';
	html += '<div class="commentactions">';
	html += '<img class="commentvote commentclick" src="/images/portal/voteup.png" id="vote-' + comment.id + '" title="Vote question up" />';
	html += '<img class="commentflag commentclick" src="/images/portal/report.png" id="flag-' + comment.id + '" title="Report as inappropriate"/>';
	html += '<div class="replydiv"><a class="replyclick" id="reply-' + comment.id + '" title="Reply to Message">Reply</a></div>';
	html += '</div>';
	if (comment.parent_id) {
		var childrenHTML = genCommentHTML(comment.parent_id.Comment, "child-");
		html += '<div class="childcomment">' + childrenHTML + '</div>';
	}
	html += '<div class="commentborder"></div>';
	html += '</div>';
	
	$('#commentsPane').prepend(html);
	$("#comment-" + comment.id).find("img.commentclick").bind("click", {}, commentClick);
	$("#comment-" + comment.id).find("a.replyclick").bind("click", {}, replyClick);
	$("#comment-" + comment.id).find("span.twitterTag").bind("click", {}, twitterTagClick);
	$("#comment-" + comment.id).find("img.commentimg").error(function() { this.src = "/images/portal/default_profile_normal.png"; });
	if(comment.third_party == 'facebook') {
		$(dom_id + ' .commentauthor, ' + dom_id + ' .commentimg').bind("click", { commentdata: comment }, showCommentersPage);
	}
	
	
	if(last_comment > -1)
		$("#comment-" + comment.id).effect("highlight", {}, 5000);

}

function genCommentHTML(comment, post_id) {
	var html = '';
	if(!comment.author_image_url) {
		comment.author_image_url = '/images/portal/default_profile_normal.png';	
	}
	html += '<div id="comment-' + post_id + comment.id + '" class="comment';
	if(comment.third_party == 'twitterimport') {
		html += ' twitterimport';
	} 
	html += '" >';	
	
	if(comment.third_party == 'twitter' || comment.third_party == 'twitterimport') {
		html += '<a href="' + comment.author_profile_url + '" target="_blank"><img src="' + comment.author_image_url + '" class="commentimg" /></a>';
	} else if (comment.third_party == 'facebook') {
		html += '<img src="' + comment.author_image_url + '" class="commentimg" />';
	}
	
	html += '<div class="commenttext">';
	
	if(comment.third_party == 'twitter' || comment.third_party == 'twitterimport') {
		html += '<span class="commentsmall"><a href="' + comment.author_profile_url + '" target="_blank"><span class="commentauthor" id="author-' + post_id + comment.id + '" >' + comment.author + '</span></a> ';
	} else if(comment.third_party == 'facebook') {
		html += '<span class="commentsmall"><span class="commentauthor" id="author-' + post_id + comment.id + '" >' + comment.author + '</span> ';
	}
	
	html += comment.created_formatted + '</span><br />';
	html += linkify(HTMLescape(comment.post_text)) + '</div>';
	return html;
}

function removeComments(json, comet) {
	if(json.last_comment) {
		comet.last_id = json.last_comment;
	}
	
	jQuery.each(json.comments, function(i, comment) {
		$('#comment-' + comment.removed_comments.comment_id).remove();
	});
}

function NewCommentFlasher() {
	var self = {
		start: function() {
			var active = (self.cycles > 0);
			self.cycles = 5;
			if(!active) {
				self.loopCycle();
			}
		},
		cycles: 0,
		defaultTitle: document.title,
		loopCycle: function() {
			if(document.title == self.defaultTitle) {
				document.title = 'New comment';
			} else {
				document.title = self.defaultTitle;
				self.cycles -= 1;
			}
			
			if(self.cycles > 0) {
				setTimeout(self.loopCycle, 1000);
			}
		}
	}
	
	return self;
}

function loginSuccessful(name, type) {
	defaultInputText = 'Type your message, press enter';
	tb_remove();
	get('post_text').value = defaultInputText;
	$('#username').html(name);
	identifiedType = type;
	if(type == 'twitter') {
		$("#post-to-twitter").css("display","block");
	}
	$('#logindiv').css('display','none');
	refreshList();
}