var loadMoreCommentsCount = 0;
var maxComments = 50;
var totalComments = 0;
var scrollToCommentId = null;
var highlightId = null;
var border_color = '#E1E1E1';
var maxCommentLength = 4000;
var xTooltipOffset = 10;
var yTooltipOffset = 100;

$(document).ready(function() {
	
	maxCommentLength = $("#max-comment-length").val();
	
	if (!maxCommentLength)
		maxCommentLength = 4000;
	
	wireUpEvents();
 }); 
 
function wireUpEvents() {
	$("#discussion-loading").css("display", "none");
	$(".add-comment-form .submit").click(function(e) {
		e.preventDefault();
		$(".submit").attr("disabled", "disabled"); 
		$("#loading").css("display", "block");
		var params = $(this).attr("id").split("-");
		var type = params[0];
		var mediaId = params[1];
		var mediaTitle= $("#media-title").val();
		
		$.ajax({
			type: "POST", 
			url: "../comment/", 
			data: {id: mediaId,
				   comment: $("#comment-text").val().substr(0, maxCommentLength),
			       mediaType: type,
			       mediaTitle: mediaTitle,
				   max: (loadMoreCommentsCount + 1) * maxComments,
				   page: $("#page-id").val(),
				   replyMessageId: $("#reply-message-id").val(),
				   replyUsername: $("#reply-username").val(),
				   tweetMessage: $("#tweet-message").val(),
				   tweetThis: $("#tweet-this").attr("checked")
				  },
			datatype: "xml", 
			success: function(data) {
				$("#comments").html(data);
				$("#comment_text").val("");
				$.scrollTo( '#comments', 800, {easing:'swing'} );
				$("#loading").css("display", "none");
				$(".submit").removeAttr("disabled");
				
		
				wireUpEvents();
			}, 
			error: function() {
				$("#loading").html("<div class='error'>Whoops. Please try again</div>");
				$(".submit").removeAttr("disabled");
			}
		});
 	 });
	
	
	$("#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");
			$(".submit").attr("disabled", "disabled");
			$(".submit").attr("src", "../images/submit-disabled.gif");
			
		} else {
			
			if ($("#comment-text").css("opacity") < 1){
				
				$("#character-count").css("color", "#b9b9b9");
				$("#comment-text").css("opacity", 1);
				$(".submit").removeAttr("disabled");
				$(".submit").attr("src", "../images/submit.gif");
			}
			
		}
		
		$("#character-count").html( charCount + '/' + maxCommentLength );
		
	});
	

	$("span[id*='fuzzy-time-']").bind("mouseover", function(e){
		
		var timeParams = $(this).attr("id").split("-");
		var replyId = $("a[name*='reply-link-" + timeParams[2] + "-']").attr("name");
		var replyParams = null;
		
		if (replyId)
			replyParams =  $("a[name='" + replyId + "']").attr("name").split("-");
		
		
		if (replyParams != null)
			$("a[name='" + replyId + "']").html(" in reply to...");
		
		$("#focused-time-" + timeParams[2]).html(" | " + $("#focused-time-" + timeParams[2] ).attr("title") + " <span style='font-size: 8pt;'>[EST]</span>");
		
		
		
	});

	$("span[id*='fuzzy-time-']").bind("mouseout", function(e){
		
		var timeParams = $(this).attr("id").split("-");
		var replyId = $("a[name*='reply-link-" + timeParams[2] + "-']").attr("name");
		var replyParams = null;
		
		if (replyId)
			replyParams = $("a[name='" + replyId + "']").attr("name").split("-");
		
		
		if (replyParams != null)
			$("a[name='" + replyId + "']").html( " in reply to " + replyParams[3]);
		
		$("#focused-time-" + timeParams[2]).html("");
		
	});
	
	
	$(".reply-link").click(function(e) {
		e.preventDefault();
		var params = $(this).attr("id").split("-");
		var id = params[0];
		var username = params[1];
		$.scrollTo(".comment", 800, {easing:"swing"});
		$("#reply-username").val(username);
		$("#reply-message-id").val(id);
		$("#comment-text").val("@" + username + " ");
		$("#comment-text").focus();
		
		var input = document.getElementById("comment-text");
		var cursorPos = 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', cursorPos);
			range.select();
		} else {
			// Browsers that follow standards
			if (input.setSelectionRange) { 
				input.focus();
				input.setSelectionRange(cursorPos, cursorPos);
			} else {
				input.focus();
			}
		}
		
	});
	
	$(".follow-reply-link").click(function(e) {
		e.preventDefault();
		$(".comment-box").css("background-color", "#FEFEFE");
		$(".comment-box").css("border-color", border_color);
		var params = $(this).attr("id").split("-");
		var type = params[0];
		var page = params[1];
		var mediaId = params[2];
		var replyMessageId = params[3];
		
		var commentBoxId = "#comment-box-" + replyMessageId;
		// If the reply-to comment has not been loaded yet, load all comments.
		if ($(commentBoxId).length == 0) {
			loadMoreComments(type, page, mediaId, totalComments);
			scrollToCommentId = commentBoxId;
		} else {
			highlightId = commentBoxId;
			$.scrollTo(commentBoxId, 800, {easing:"swing", offset:{top: -200}, onAfter: highlight});
		}
	});
	
	
	$(".load-more").click(function(e) {
		e.preventDefault();
		loadMoreCommentsCount ++;
		var params = $(this).attr("id").split("-");
		var type = params[0];
		var page = params[1];
		var mediaId = params[2];
		var commentCount = (loadMoreCommentsCount + 1) * maxComments;
		loadMoreComments(type, page, mediaId, commentCount);
	});
	
	totalComments = $("#comment-count").text();
	if ((loadMoreCommentsCount + 1) * maxComments >= totalComments) {
		$(".load-more").css("display", "none");
	}
	if (scrollToCommentId != null) {
		highlightId = scrollToCommentId;
		$.scrollTo(scrollToCommentId, 800, {easing:"swing", offset:{top: -200}, onAfter:highlight});
		$(".load-more").css("display", "none");
		scrollToCommentId = null;
	}
	
	$("#tweet-this").click(function(e){
		
		
		if ($("#tweet-this").attr("checked") == true){
			$("#tweet-label").css("color" , "#1d1d1d");
		}
		else
			$("#tweet-label").css("color", "#B9B9B9");
		
	});
	

	
	if ($("#tweet-this").attr("disabled") == true)
	{		
			
			$("#tweet-label").bind("click", function(e){
				$("#tweet-tip").trigger("click");
			});
	}
	
	
		$("a.tooltip").bind("click", function(e){
		e.preventDefault();
		this.t = $(this).attr('alt');
		var c = (this.t != "") ? "<strong class='tool-tip'>" + this.t + "</strong>" : "";
		var id = this.id;
								 
		$("body").append("<p id='tooltip'>" + c + "</p>");
		
		var pw = $("#tooltip").width();
		
		if(e.pageX <= $(window).width()/2){//flip right
			
			yTooltipOffset = 10;
			xTooltipOffset = 60;
		}
		else{ //flip left
			
			yTooltipOffset = -pw - 20;
			xTooltipOffset = 60;	
		}
		
		$("#tooltip")
		.css("top",(e.pageY - xTooltipOffset) + "px")
		.css("left",(e.pageX + yTooltipOffset) + "px")
		.fadeIn("fast");
		
		$("#tooltip").bind("click", function(e){
			$("#tooltip").remove();
		});
		
	});
	

}

function highlight() {
	$(highlightId).animate({ backgroundColor: "#E8F5FF" }, 500);
	$(highlightId).css("border-color","#22c3ff");
}

function loadMoreComments(type, page, mediaId, commentCount) {
	$("#discussion-loading").css("display", "block");
	$.ajax({
		type: "POST", 
		url: "../comment/", 
		data: {id: mediaId,
		       mediaType: type,
			   page: page,
			   max: commentCount
			  },
		datatype: "xml", 
		success: function(data) {
			$("#comments").html(data);
			$("#loading").css("display", "none");
			$(".submit").removeAttr("disabled");
			wireUpEvents();
		} 
	});
}
