/**
 * @author sweston
 */
var maxCommentLength = 4000;
var orig_offset = -1;
var comment_count = 0;

var push_timeout = 10000;
var pull_timeout = 5000;
var push_timer = null;
var pull_timer = null;

var pull_last_offset = null;

var pull_id = 0;

function InitComment(){
	
	if (orig_offset == -1)
		orig_offset = parseInt($("#orig-offset").val());
	
	comment_count = parseInt($("#comment-count").val());
	
	$("#comment-text").val("");
	$("#comment-text").bind("keydown keyup", function(e){
	
	
		var charCount = $("#comment-text").val().length;
		
		if (charCount > maxCommentLength) {
		
			$("#comment-text").css("opacity", 0.50);
			$("#character-count").css("color", "#ff0000");
			$("#comment-submit").attr("disabled", "disabled");
			$("#comment-submit").attr("src", "/images/submit-disabled.gif");
			
		}
		else {
		
			if ($("#comment-text").css("opacity") < 1) {
			
				$("#character-count").css("color", "#b9b9b9");
				$("#comment-text").css("opacity", 1);
				$("#comment-submit").removeAttr("disabled");
				$("#comment-submit").attr("src", "/images/submit.gif");
			}
			
		}
		
		$("#character-count").html(charCount + ' / ' + maxCommentLength);
		
	});
	
	
	
	$(".replay").click(function(e) {
		
		e.preventDefault();
		
		var params = $(this).attr("id").split("-");
		var comment_id = params[0];
		var username = params[1];
		
		$.scrollTo("#comment-form", 800, {easing:"swing"});
		
		$("#reply-username").val(username);
		$("#reply-comment-id").val(comment_id);
		
		$("#comment-text").val("@" + username + " ");
		$("#comment-text").focus();
		
		var input = document.getElementById("comment-text");
		var cursor_pos = input.value.length;
		
		// Set the cursor to the end of @username
		if (input.createTextRange) {
			// Internet Explorer
			var range = input.createTextRange();
		 	range.collapse(true);
			range.move('character', cursor_pos);
			range.select();
		
		} else {
			// Browsers that follow standards
			if (
				input.setSelectionRange) { 
				input.focus();
				input.setSelectionRange(cursor_pos, cursor_pos);
			
			} else {
				input.focus();
			}
		}
		
	});

	bind_view_replies();
	
	bind_in_reply_to_links();
	
	if (orig_offset != -1)
		$("#offset").val(orig_offset);
			
	
	$("#comment-submit").click(function(){
		submitComment($("#item-type").val());
		$("#submission-indicator").removeClass("hide");
	});
	
	
	if($("#top-comment-id").val())
	{
		push_timer = setTimeout(loadTopComments, push_timeout);
	}
	
	// load more comments...
	if (parseInt($("#offset").val()) < comment_count){
		$("#loading-more-comments").fadeIn("fast");
		pull_timer = setTimeout(loadMoreComments, pull_timeout);
	}
}

function bind_view_replies(id){
	
	if (id == undefined)
		id = ".view-replies";
	
	$(id).unbind();
	
	$(id).click(function(e){
		var params = $(this).attr("id").split("-");
		var comment_id = params[1];
		
		if ($("#replies-" + comment_id).length == 0) {
			// Load the replies
			load_replies(comment_id);
		} else {
			// Remove the previously loaded replies
			$("#replies-" + comment_id).slideUp("fast", function() {
				$("#replies-" + comment_id).remove();
			});
		}
		
		e.preventDefault();
	});
}

function bind_reply(id){
	
	$(id).click(function(e) {
		
		e.preventDefault();
		
		var params = $(this).attr("id").split("-");
		var comment_id = params[0];
		var username = params[1];
		
		$.scrollTo("#comment-form", 800, {easing:"swing"});
		
		$("#reply-username").val(username);
		$("#reply-comment-id").val(comment_id);
		
		$("#comment-text").val("@" + username + " ");
		$("#comment-text").focus();
		
		var input = document.getElementById("comment-text");
		var cursor_pos = input.value.length;
		
		// Set the cursor to the end of @username
		if (input.createTextRange) {
			// Internet Explorer
			var range = input.createTextRange();
		 	range.collapse(true);
			range.move('character', cursor_pos);
			range.select();
		
		} else {
			// Browsers that follow standards
			if (
				input.setSelectionRange) { 
				input.focus();
				input.setSelectionRange(cursor_pos, cursor_pos);
			
			} else {
				input.focus();
			}
		}
		
	});
}

function bind_view_original(comment_id) {
	$("#replies-" + comment_id + " .a-link").click(function(e) {
		
		e.preventDefault();
		
		var comment_id = $(this).attr("id").split('-');
		
		comment_id = 'comment' + '-' + comment_id[2];
		
		$.scrollTo('#' + comment_id, 800, {easing:"swing", offset:{top: -200}, onAfter: highlight(comment_id)});
		
	});
}

function bind_in_reply_to_links() {
	$(".discussion-post").each(function(e) {
		var comment = $(this).attr("id").split('-');
		var comment_id = comment[1];
		bind_in_reply_to(comment_id);
	});
}

function bind_in_reply_to(comment_id) {
	$("#comment-" + comment_id + " .a-link").click(function(e) {
		
		e.preventDefault();

		var comment = $(this).attr("id").split('-');

		comment_id = comment[1] + '-' + comment[2];
		
		var found_obj = $("#" + comment_id).attr('id');
		
		if (found_obj == undefined)
			window.location = base_url + comment[2] + '/' + meta;
		else
			$.scrollTo('#' + comment_id, 800, {easing:"swing", offset:{top: -200}, onAfter: highlight(comment_id)});

	});
}

function submitComment(){
	
	$('#comment-text').css("opacity", 0.50);
	$('#comment-submit').attr("disabled", "disabled");
	
	clearTimeout(push_timer);
	
	$.ajax({
			type: "POST", 
			url: siteUrl() + $('#item-type').val() + "/comment", 
			data: {member_id: $("#member-id").val(),
				   comment: $("#comment-text").val().substr(0, maxCommentLength),
			       item_type: $('#item-type').val(),
			       item_id: $("#item-id").val(),
				   reply_username: $("#reply-username").val(),
				   reply_comment_id: $("#reply-comment-id").val()
				  },
			cache: false,
			dataType: "json", 
			success: function(data) {
				
			
				$('#comment-text').html('');
				
				$("#reply-username").val('');
				$("#reply-comment-id").val('');
				
				$('#character-count').html('0/' + maxCommentLength);
				$('#comment-submit').removeAttr("disabled");
				$('#comment-text').css("opacity", 1);
				$('#comment-text').val('');
				
				loadTopComments(true);
				push_timer = setTimeout(loadTopComments, push_timeout);
					
			},
			error: function() {
				
				$('#comment-text').html('');
				
				$("#reply-username").val('');
				$("#reply-comment-id").val('');
				
				$('#character-count').html('0 / ' + maxCommentLength);
				$('#comment-submit').removeAttr("disabled");
				$('#comment-text').css("opacity", 1);
				$('#comment-text').val('');
				
				// remove submit message when comment is added to UI
				$('#submission-indicator').fadeOut(500, function() {
					$(this).addClass("hide").removeAttr("style");
				});
	
				push_timer = setTimeout(loadTopComments, push_timeout);
			}
	}); 	

	
}


function loadTopComments(from_submit){

		var top_comment_id = $("#top-comment-id").val();
		var item_id = $("#item-id").val();
		$.ajax({
			type: "POST",
			url: siteUrl() + $("#item-type").val() + "/ajax_top_comments",
			data: {
				top_comment_id: top_comment_id,
				item_id: item_id
			},
			cache: false,
			timeout: 5000,
			dataType: "json",
			success: function(data){
			
			// remove submit message when comment is added to UI
			$('#submission-indicator').fadeOut(500, function() {
				$(this).addClass("hide").removeAttr("style");
			});
				
				if (data.top_comment_id != null && data.top_comment_id != undefined && data.top_comment_id != $("#top-comment-id").val()) {	
					
					$("#top-comment-id").val(data.top_comment_id);
					
					$.each(data.top_comments, function(i, comment){
						
						var injection = get_injection(data, comment);
						$("#comment-container").prepend(injection);
						
						if (comment.is_author) {
							bind_team_hover("#comment-" + comment.comment_id);
						}
						bind_flag("#comment-flag-" + comment.comment_id);
						bind_reply("#comment-" + comment.comment_id + " .replay");
						bind_favor("#comment-favor-" + comment.comment_id);
						
						$("#comment-" + comment.comment_id).fadeIn(500);
						
						bind_in_reply_to(comment.comment_id);
	
					});
					

					$("#offset").val(parseInt($("#offset").val()) + parseInt(data.comment_count));
					
					
				}
				// If the comment is being submitted, don't fire another event
				if (!from_submit) {
					push_timer = setTimeout(loadTopComments, push_timeout);
				}
				
			},
			error: function(e1, e2, e3){
				push_timer = setTimeout(loadTopComments, push_timeout);
			}
		});
		
	
		
}

function loadMoreComments(){
		
		var limit = 40;
	
		var offset = parseInt($("#offset").attr('value'));
		var item_type = $('#item-type').attr('value');
		var item_id = $("#item-id").attr('value');
		var top_comment_id = $("#top-comment-id").val();
	
		$.ajax({
			type: "POST",
			url: siteUrl() + item_type + "/ajax_more_comments",
			data: {
				offset: offset,
				limit: limit,
				item_type: item_type,
				item_id: item_id
			},
			cache: false,
			dataType: "json",
			success: function(data){
		
			
			if (data.bottom_comments != null && data.bottom_comments != undefined) {
			
				$.each(data.bottom_comments, function(i, comment){
				
					var injection = get_injection(data, comment);
					
					$("#comment-container").append(injection);
					
					if (comment.is_author) {
						bind_team_hover("#comment-" + comment.comment_id);
					}
					
					bind_flag("#comment-flag-" + comment.comment_id);
					bind_favor("#comment-favor-" + comment.comment_id);
					bind_reply("#comment-" + comment.comment_id + " .replay");
					bind_view_replies("#comment-" + comment.comment_id + " .view-replies");
						
					$("#comment-" + comment.comment_id).fadeIn(500);
					bind_in_reply_to(comment.comment_id);
					
				});				
			}
			
			pullTimer = setTimeout(loadMoreComments, pull_timeout);

			$("#offset").val(parseInt(data.offset) + parseInt(data.comment_count));
			
			pull_last_offset = parseInt(data.offset) + parseInt(data.comment_count);
		},
		error: function(e1, e2, e3){
			
			clearInterval(pull_timer);
			$("#loading-more-comments").fadeOut("fast");
			
		}
	});
	
	
}

function get_injection(data, comment) {
	injection = '<div id="comment-' + comment.comment_id + '" class="discussion-post" style="display:none;" >';
	
	if (parseInt(data.logged_in) == 1)
		injection += '<a href="#" id="' + comment.comment_id + '-' + comment.username + '" onclick="return false;" class="replay">reply</a>';
	
	injection += '<span class="image ' + ((comment.is_author) ? 'team' : '') + '" ><a href="' + siteUrl("people/") + comment.username + '"><img class="' + ((comment.is_author) ? 'team' : '') + '" src="' + comment.path + '" alt="' + comment.username + '" width="48" height="48" /></a><span class=""><a href="' + siteUrl("people/") + comment.username + '"></a></span></span>';
	injection += '<div class="txt">';
	injection += '<div class="title">';
	

	if (comment.to_username != undefined || comment.to_username != null)
		injection += '<h3><a href="' + siteUrl("people/") + comment.username + '">' + comment.username + '</a></h3> <strong>- <a href="' + base_url + comment.comment_id + '/' + meta + '" class="fuzzy-date" alt="' + comment.timestamp +'">' + comment.fuzzy + '</a></strong> <a href="#" id="to-comment-' + comment.to_comment_id + '" onclick="return false;" class="a-link">in reply to ' + comment.to_username + '</a>';
	else
		injection += '<h3><a href="' + siteUrl("people/") + comment.username + '">' + comment.username + '</a></h3> <strong>- <a href="' + base_url + comment.comment_id + '/' + meta + '" class="fuzzy-date" alt="' + comment.timestamp +'">' + comment.fuzzy + '</a></strong> ';
	
	injection += '<ul class="right">';
		
	if (comment.reply_count > 0) {
		injection += '<li><a href="#" id="repliesbtn-' + comment.comment_id + '" onclick="return false;" class="view-replies">View ' + comment.reply_count + (comment.reply_count == 1 ? " @reply" : " @replies") + '</a></li>';
	}
	if (parseInt(data.logged_in) == 1 && comment.is_edited == 0) {
		injection += '<li><a id="comment-favor-' + comment.comment_id + '" href="' + siteUrl("favorite/comment/") + comment.comment_id + '" onclick="return false;" class="favbtn ';
		
		if (parseInt(comment.is_favorite) == 1) 
			injection += 'favor">Unfavorite</a></li>';
		else 
			injection += 'disfavor">Favorite</a></li>';
		
		injection += '<li class="report-flag"><a id="comment-flag-' + comment.comment_id + '" href="' + siteUrl("flag/comment/") + comment.comment_id + '" onclick="return false;" class="flagbtn ';
		
		if (parseInt(comment.is_flagged) == 1) 
			injection += 'flagged">Unflag</a></li></ul>';
		else 
			injection += 'not-flagged">Flag</a></li></ul>';
	}
	
 	injection += "</div>";
	injection += '<div class="discussion-post-box">';
	injection += '<div>';
	injection += '<h4>'; 
	injection += comment.value + '</h4>';
	injection += '</div></div></div></div>';
	
	return injection;
}

function load_replies(comment_id) {
	
	var item_type = $('#item-type').attr('value');

	var loading_injection = get_replies_loading_injection(comment_id);
	$("#comment-" + comment_id).after(loading_injection);
	$("#replies-loader-" + comment_id).slideDown("fast");
	
	$.ajax({
		type: "POST",
		url: siteUrl() + item_type + "/ajax_replies",
		data: {
			comment_id : comment_id
		},
		cache: false,
		dataType: "json",
		success: function(data){
			var injection = get_replies_injection(comment_id, data);
			// Replace loader with content
			$("#replies-loader-" + comment_id).after(injection).remove();
			bind_view_original(comment_id);
		},
		error: function(e1, e2, e3) {
		}
	});
}


function get_replies_injection(comment_id, replies) {
	var injection = "";
	if (replies != undefined){
		injection += '<div id="replies-' + comment_id + '" class="comment-replies">';
		
		$.each(replies, function(i, reply){
		
			injection += '<div class="discussion-sub-post">';
			injection += '<div class="discussion-post">';
			injection += '<span class="image ' + ((reply.is_author) ? 'team' : '')  + '" ><a href="' + siteUrl('people/' + reply.username) + '"><img class="' + ((reply.is_author) ? 'team' : '') + '" src="' + reply.avatar + '" alt="' + reply.username + '" width="48" height="48" /></a></span>';
			injection += '<div class="txt">';
			injection += '<div class="title"><h3><a href="' + siteUrl('people/' + reply.username) + '">' + reply.username + '</a></h3> <strong>- <a href="' + base_url + reply.comment_id + '/' + meta + '">' + reply.fuzzy + '</a></strong>';
			injection += '</div>';
			injection += '<div class="discussion-post-box"><div>' + reply.value + '</div></div>';
			injection += '</div></div></div>';
			
		});
		injection += '	<div class="submit-reply">';
		injection += ' <input type="text" class="reply-field" placeholder="Reply..."></input>';
		injection += ' <input type="submit" class="sys-btn size-small" value="Submit Reply"></input>';
		injection += '	</div>';
		injection += '	<div class="submit-reply2">';
		injection += '<span class="image" ><a href="#"><img src="http://images.soulpancake.s3.amazonaws.com/default/avatar.png" width="48" height="48" /></a></span>';
		
		injection += ' <textarea type="text" class="reply-field2" placeholder="Reply..."></textarea>';
		injection += ' <input type="submit" class="sys-btn size-small" value="Submit Reply"></input>';
		injection += '	</div>';
		
		injection += '</div>';
			
						
	}
	return injection;
}



function get_replies_loading_injection(comment_id) {
	var injection = "";
	injection += '<div id="replies-loader-' + comment_id + '" class="comment-replies" style="display:none">';
	injection += '<div id="loading-replies" style="width:100%;margin:auto;padding:16px 0 16px 0;text-align:center;"><img src="' + siteUrl() + 'images/ajax_loader.gif"></img></div>';
	injection += '</div>';
	return injection;
}

function highlight(comment_id)
{
	$("*").removeClass('comment-highlight');
	$('#' + comment_id).addClass('comment-highlight').css({
	 	"background-color": "#ebfcfc",
		"border-color": "#9ed5d5"
	});	;	
	$(".comment-highlight").delay(2000).animate({
		"background-color": "#fff",
		"borderTopColor": "#B2E5E5",
		"borderBottomColor": "#B2E5E5",
		"borderLeftColor": "#B2E5E5",
		"borderRightColor": "#B2E5E5"
	}, 1000, function(){
		$(".comment-highlight").removeClass("comment-highlight");
	});
}
	

$(function(){ InitComment();});

