/*
 * jQuery Comment Plugin 
 * Version: 1.0 (March 30 2009)
 * Requires: jQuery v1.3.1
 *
 */

(function($){
$.fn.comment_form = function(options) {
	var form = this;
	var post = $(this).find(".comment_post").click(function(){
		var comment_id = $(form).find("input.comment_id").attr("value");
		var comment_type = $(form).find("input.comment_type").attr("value");
		var comment_text = $(form).find("textarea.user_comment").attr("value");

		$('.comment_form .button').toggle();
		$('#comment_post_rsp').html('Please wait one moment while your comment is submitted...');

		$.post("/ajax/comments/post/?id="+comment_id+"&t="+comment_type, { user_comment:comment_text }, function(data) {
			if(data.status == "pass") {
				var foo = $(data.html).appendTo("#comments .comments");
				$(foo).comments();
				$(form).find("textarea.user_comment").attr("value", "");
				$('#comment_post_rsp').html('');

				if(typeof options.callback === "function") {
					options.callback(comment_text);
				}
			} else {
                if (data.redirect) {
                    //ajax processor has requested that another page should handle the error condition,
                    //e.g. user is not logged in so forward to /login
                    try {
                        var redirectUrl = window.location.pathname + window.location.search;
                        var passReturnUrl = 'url=' + encodeURIComponent(redirectUrl + '#last_comment');
                        var identifyMiniSite = '';
                        var querySeparator = '?';
                        if (data.redirect.indexOf('?') != -1) {
                            querySeparator = '&';
                        }
                        if (window.location.pathname.indexOf('/teamradioshack') == 0) {
                           identifyMiniSite = '&trs=true';
                        }
                        window.location = data.redirect +
                            querySeparator + passReturnUrl + identifyMiniSite;
                        return false;
                    } catch (e) {
                    }
                } else {
				    $('#comment_post_rsp').html('<div id="errorBox"><ul><li>' + data.error + '</li></ul></div>');
                }
			}
			$('.comment_form .button').toggle();
		}, "json");

		return false;
	});
};

$.fn.comments = function(options) {
	$(this).each(function(index) {
		temp = this.id.split("_");
		comment_id = temp[1];

		// Add the comment rating (thumbs up, thumbs down) functionality
		var rate = $(this).find(".rate").click(function(){
			var comment_id = this.comment_id;
			// Send the comment rating request.
			$.get("/ajax/comment_rate/?a="+this.alt+"&id="+comment_id, function(data) {
				if(data > 0) { data = "+" + data; } // Show a plus sign if positive.
				$("#comment_"+comment_id+" .rating span").html(data);
			});
			return false;
		});

		var reply = $(this).find(".action_reply:first").click(function(){
			var comment_id = this.comment_id;

			// Make sure the reply box is only triggered once.
			if($("#new_comment_reply_"+comment_id).length > 0) {
				return false;
			}

			// Note if the HTML for the comments.tpl changes, it will affect this script.
			// Cloning a current comment.
			var comment_reply = $("#comment_"+comment_id).clone().attr({
				id: "new_comment_reply_"+comment_id,
				className: "comment comment_reply"
			});

			comment_reply.find(".rating, .actions").css("display", "none");
			comment_reply.find(".avatar").attr("src", user_avatar_48);
			comment_reply.find(".avatar").parent().get(0).href = user_profile_url;

			var dateNow = dateFormat(new Date(), "mmmm d, yyyy 'at' h:MM TT");
			// var dateNow = $.datepicker.formatDate("MM d, yy 'at' ", new Date()); // unable to use JQuery UI for this because it doesn't support time.
			comment_reply.find(".meta").html('by <a href="'+user_profile_url+'" rel="nofollow">'+user_username+'</a> on '+dateNow);
			comment_reply.find(".comment_reply").remove();

			var textarea = $('<textarea name="user_comment"></textarea>');
			comment_reply.find(".text").html(textarea);

			$('<input class="button button_2" type="submit" value="Reply" name="submit_button" />').appendTo(comment_reply.find(".text")).click(function(){
				var comment_type = $("input.comment_type").attr("value");

				$(this).after("Please wait one moment while your comment is submitted...");
				$(this).toggle();

				$.post('/ajax/comments/post/', { id: content_id, t: comment_type, user_comment: textarea.val(), pci: comment_id}, function(data){
					if(data.status == "pass") {
						comment_reply.attr("id", data.comment_id);
						comment_reply.find(".text").html(textarea.val());
					} else {
						// Add the container for notices here so not to keep making a new one each time.
						if($("#new_comment_reply_"+comment_id+" .message_error").length == 0) {

							$("#new_comment_reply_"+comment_id).append('<div class="message_error"></div>');
						}
						$("#new_comment_reply_"+comment_id+" .message_error").html(data.error);
					}
				}, "json");
			});

			// Close and destroy the reply box.
			$('<input class="button button_2" type="button" value="Cancel" name="cancel_button"/>')
			.appendTo(comment_reply.find(".text")).click(function(){
				$("#new_comment_reply_"+comment_id).remove();
			});

			$("#comment_"+comment_id).append(comment_reply);

			return false;
		});

		var flag = $(this).find(".action_flag:first").click(function(){
			var comment_id = this.comment_id;
			if (confirm("Do you really want to flag this comment?")) {
				$.get('/ajax/flag/?t=comment&id=' + comment_id, function(data){
					// Add the container for notices here so not to keep making a new one each time.
					if($("#comment_"+comment_id+" .message_notice").length == 0) {
						$("#comment_"+comment_id).append('<div class="message_notice"></div>');
					}
					$("#comment_"+comment_id+" .message_notice").html(data);
				});	
			}

			return false;
		});

		var del = $(this).find(".action_delete:first").click(function(){
			var comment_id = this.comment_id;
			if (confirm('Are you sure you want to delete this comment? All replies will also be deleted')) {
				$.get('/ajax/comments/delete/?t=comment&id=' + comment_id, function(data){
					$("#comment_"+comment_id).html("");
				});
			}
			return false;
		});

		for(var i=0; i<rate.length; i++) {
			rate[i].comment_id = comment_id;
		}

		for(var i=0; i<reply.length; i++) {
			reply[i].comment_id = comment_id;
		}

		for(var i=0; i<flag.length; i++) {
			flag[i].comment_id = comment_id;
		}

		for(var i=0; i<del.length; i++) {
			del[i].comment_id = comment_id;
		}
	});
}
})(jQuery);