(function($) {
    $.fn.ng_comments = function(settings) {
        settings = $.extend({
            serverURL: process_url,
            commentsPerPage: 5,
            wordCount: 600,
            order: 'TimeStampDescending',
            countCallbacks: []
        },
        settings);
       
        var loggedIn = false;
        var baseURL = window.location.hostname;
        var pathURL = window.location.pathname;
        
        var commentContainer = $('#ng_comments');
        getUser();
        
        function getUser() {
			var requestBatch = new RequestBatch();
			
			//requesting a UserKey() with no parameter returns a User object for the current user
			// -- if the user is unauthenticated, the User object is our generic anonymous user
			requestBatch.AddToRequest(new UserKey());
			requestBatch.BeginRequest(settings.serverURL, getUserCallback);
		}
		
        function getUserCallback(responseBatch) {
            var anonUser = responseBatch.Responses[0].User.UserKey.Key;
            var dispName = responseBatch.Responses[0].User.DisplayName;
            var personaURL = responseBatch.Responses[0].User.PersonaUrl;
            var tempPersonaURL = personaURL.split(".com");
            personaURL = 'http://www.nationalgeographic.com'+tempPersonaURL[1];
            var qString = window.location.search.substring(1);
            if (qString) {
             pathURL = pathURL+'?'+qString;   
            }
            
            if (anonUser == 'anonymous') {
                $('#ssoauth').prepend('<p class="action"><a class="rpxnow" href="https://'+rpxNowRealm+'/openid/v2/signin?token_url=http://' + baseURL + '/rest/sso/rpx_response/?next=' + pathURL + '">Sign In</a></p>');
			    $('.post_comment_body').html('<h4>You must be logged in to post a comment</h4><p><a href="' + $('#account a.rpxnow').attr('href') + '" class="rpxnow">Sign in here</a></p>');
            } else {
				loggedIn = true;
                $('#ssoauth').prepend('<p class="welcome_msg">Hi,&nbsp;<a href="' + personaURL + '" title="Go to your profile">' + dispName + '</a></p><p class="action"><a class="logout" href="/rest/sso/rpx_logout/">Sign Out</a></p>');
                $('.post_comment_body').html('<h4>Post a Comment</h4>' +
                '<form>' +
                '<div>' +
                '<label for="comment" class="hidden">Comment</label>' +
                '<textarea id="comment" name="comment" rows="5" cols="40"></textarea>' +
                '</div>' +
                '<div class="comment_submitted">' +
                '<h4>Your comment has been posted.</h4>' +
                '</div>' +
                '<button href="#" class="submit_btn">Submit Comment &raquo;</button>' +
                '</form>');
            }
            
            
            $(commentContainer).each(function() {
                var c = $(this);
                var articleKey = ((typeof(ArticleKey) != "undefined") ? new ArticleKey(django_page_id) : null);
                var adata;
                var paginator = ((typeof(Paginator) != "undefined") ? new Paginator('#ng_comments .pager', fetchPage) : null);
                init();

                $(c).find('.post_comment_body .submit_btn').live('click',
                    function(event) {
    					var tempString = $(c).find('.post_comment_body form textarea').val();
    					var commentString = tempString.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    					var requestBatch = new RequestBatch();
                        requestBatch.AddToRequest(new CommentAction(articleKey, window.location.href, document.title, commentString));
                        var categories = new Array();
                        requestBatch.AddToRequest(new UpdateArticleAction(articleKey, window.location.href, document.title, new Section("news"),categories));
                        requestBatch.BeginRequest(settings.serverURL, postCommentCallback);                        
                        event.preventDefault();
                });

                $(c).find('.post_toggle_btn').bind('click',
                function(event) {
                    if ($(this).text().substr(0, 1) == '+') {
                        $(this).html('&#8211; Post a Comment');
                        $(c).find('.post_comment_body').show(1000);
                    }
                    else {
                        $(this).text('+ Post a Comment');
                        $(c).find('.post_comment_body').hide(1000);
                    }
                    event.preventDefault();
                });

                function init() {
                    var requestBatch = new RequestBatch();
                    requestBatch.AddToRequest(articleKey);
                    requestBatch.BeginRequest(settings.serverURL, articleCallback);
                }

                function fetchPage() {
    				var requestBatch = new RequestBatch();
                    requestBatch.AddToRequest(new CommentPage(articleKey, settings.commentsPerPage, paginator.currentPage, settings.order));
                    requestBatch.BeginRequest(settings.serverURL, commentPageCallback(1));
                }

                function postCommentCallback(response) {
                    if (response.Messages[0].Message != "ok") {
                        $(c).find('.comment_submitted').text("An error occurred while trying to post your comment. Please refresh the page to try again.");
                        $(c).find('.comment_submitted').addClass('error').show(1000);
                        $(c).find('textarea').addClass('error');
                    }
                    
                    else {
						$(c).find('textarea').val('').removeClass('error');
                        $(c).find('.comment_submitted').removeClass('error').show(1000);
                        fetchPage();
						
						totalComments++;
						
						$(c).find('h3 .count').html('(' + totalComments + ')');
						$('.social_stats .comments').text('Comments (' + totalComments + ')');
						$('#share_buttons .pluck .comments').html('Comments (' + totalComments + ')');
						
                    }
                }

                var totalComments;
                function articleCallback(response) {
                    if (response.Messages[0].Message != "ok") {
                        $(c).find('div.comments_body').text("There are no comments yet. Be the first to leave a comment.");
						totalComments = 0;
                    }
                    else {
                        adata = response.Responses[0].Article;
                        totalComments = adata.Comments.NumberOfComments;

    					$(c).find('h3 span').text('(' + totalComments + ')');
    					if (adata.Comments.NumberOfComments * 1 > settings.commentsPerPage) {
    						paginator.populate(Math.ceil(adata.Comments.NumberOfComments / settings.commentsPerPage), 1, 1);
    					}

    					var requestBatch = new RequestBatch();
    					requestBatch.AddToRequest(new CommentPage(articleKey, settings.commentsPerPage, 0, settings.order));
    					requestBatch.BeginRequest(settings.serverURL, commentPageCallback(1));

    					for (var i=0; i < settings.countCallbacks.length; i++) {
    						settings.countCallbacks[i](adata.Comments.NumberOfComments, adata.Recommendations.NumberOfRecommendations);
    					}
    				}
    			}

    			function commentPageCallback(pageNum) {
    				return function(response) {
    					var keys = {};
    					if (response.Messages[0].Message != "ok") {
    						$(c).find('div.comments_body').text("Comments are unavailable at this time. Please check back later.");
    					} else {
    						var comments = response.Responses[0].CommentPage.Comments;
    						var commentBody = '';
    						var comCount = 0;

    						for (var i=0; i < comments.length; i++) {
    						    var comment = comments[i];
    							var flagged = (comment.ContentBlockingState == 'BlockedByAdmin');
    							// check abuse count
    							if(comment.AbuseReportCount >= 3){
    								flagged = true;
    							    comment.CommentBody = 'This comment was flagged as inappropriate and has been removed.';
    							}
    							
    							var tempPersonaURL = comment.Author.PersonaUrl.split(".com");
                                personaURL = 'http://www.nationalgeographic.com'+tempPersonaURL[1];

    							var commentKey = comment.CommentKey.Key;
    							keys['comment' + comCount] = commentKey;

    							if(comCount == 0){
    								commentBody += '<div class="item first">';
    							} else {
    								commentBody += '<div class="item">';
    							}

    							// Avatar
    							if(comment.Author.AvatarPhotoUrl.indexOf("no-user-image.gif") == -1){
    								commentBody += '<div class="user_img"><img class="avatar" src="'+comment.Author.AvatarPhotoUrl+'" width="50px">';
    							} else {
    								commentBody += '<div class="user_img">';
    							}

    							// Staff Logo
    							if(comment.Author.UserTier == "Editor"||comment.Author.UserTier == "Staff"){
    								commentBody += '<div class="ngstaff"></div>';
    							}

    							commentBody += '</div>';
    							commentBody += '<div class="comment_block"><h5><a href="'+personaURL+'">' + comment.Author.DisplayName + '</a></h5>';

    							// Reported abuse on this comment
    							if(!flagged){
    								if(comment.CurrentUserHasReportedAbuse == 'True'){
    									commentBody += '<div class="reported">REPORT ABUSE</div>';
    								} else {
    									commentBody += '<div class="abuse"><a href="JavaScript:void(0);" id="comment' + comCount + '">REPORT ABUSE</a></div>';
    								}
    							}

    							// if not logged in, must login to report abuse
    							if(!loggedIn){
    							    commentBody += '<div class="abuse_login_box"><p class="abuse_login">You must <a href="'+$('#account a.rpxnow').attr('href')+'" class="rpxnow">Sign In</a> to report abuse.</p></div>';
    							}
    							
    							commentBody +='<p class="timestamp">' + (formatTime(comment.PostedAtTime)) + '</p>';
    							
                                // if the comment has been reported as abusive, set a class for styling
    							if (flagged) {
    							    commentBody += '<p class="comment flagged">';
    							} else {
    							    commentBody += '<p class="comment">';
    							}
    							
    							commentBody += comment.CommentBody + '</p></div></div>';


    							comCount++;
    						}

    						$(c).find('h3 .count').html('(' + totalComments + ')');
    						$('.social_stats .comments').text('Comments (' + totalComments + ')');
    						$('#share_buttons .pluck .comments').html('Comments (' + totalComments + ')');
    						$('#share_buttons .pluck').removeClass('hidden');
    						$(c).find('div.comments_body').html(commentBody);

    						// add click functionality
    						$('.item .abuse a').live('click',
    						function(event) {
    							clearLoginBox();
    							var commentID = keys[$(this)[0].id];
    							abuseClicked = $(this)[0];
    							reportAbuse(commentID);
    						});
    					}
    				};
    			}


    			function formatTime(timestamp) {
    				var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    				var parts = timestamp.split(' ');
    				var dates = parts[0].split('/');

    				return months[dates[0] - 1] + ' ' + dates[1] + ', ' + dates[2] + ', ' + parts[1].slice(0,-3) + ' ' + parts[2].toLowerCase().replace('am', 'a.m.').replace('pm', 'p.m.') + ' ET';
    			}

                var abuseClicked;
    			var loginBox;
                function reportAbuse(key) {
    				var requestBatch = new RequestBatch();
                    var reason = 'test value';
                    var desc = 'test value';
                    var commentKey = new CommentKey(key);
    				if (loggedIn){
    					requestBatch.AddToRequest(new ReportAbuseAction(commentKey, reason, desc));
                    	requestBatch.BeginRequest(settings.serverURL, reportAbuseCallback);
    				} else {
    					loginBox = $(abuseClicked).parent().parent().find(".abuse_login_box");
    					$(abuseClicked).parent().parent().find(".abuse_login_box").css('visibility','visible');
    					$('#container').bind('click', clearLoginBox);
    				}
                }

    			function clearLoginBox(){
    				$("#container").unbind('click', clearLoginBox);
    				if(typeof(loginBox) !== "undefined" && loginBox != undefined){
    				    $(loginBox).css('visibility','hidden');
    			    }
    			}

                function reportAbuseCallback(responseBatch) {
                    if (responseBatch.Messages[0].Message == "ok") {
                        $(abuseClicked).parent().removeClass('abuse').addClass('reported').html('REPORT ABUSE');
                    }
                }


                function Paginator(navClass, callback) {
                    this.navClass = navClass;
                    this.callback = callback;
                    this.currentPage = 1;
                    this.currentID = "";
                    this.totalPages = "";

                    this.populate = function(totalpages, page) {
                        var t = this;

                        this.totalPages = totalpages;
                        this.currentPage = page;
                        if (totalpages <= 1) {
                            $(this.navClass).html('');
                        }
                        else {
                            var max = 3;
                            var startPage = 1;

                            $(this.navClass).html('<ul class="nav"></ul>');
                            var pagerUL = $(this.navClass + ' ul');

                            if (totalpages < 3) max = totalpages;
                            pagerUL.append("<li><a href='#'>&laquo; Previous</a></li>");
                            if (page > 2 && totalpages > 4) {
                                pagerUL.append("<li><a href='#1' name='1'>1</a></li>");

                                pagerUL.append("<li>...</li>");
                                startPage = page - 1;
                                max = page + 1;
                            }
                            if (page >= totalpages - 1 && totalpages > 3) {
                                startPage = totalpages - 2;
                                max = totalpages;
                            }
                            for (var i = startPage; i <= max; i++) {
                                pagerUL.append("<li><a href='#" + i + "' name='" + i + "'>" + i + "</a></li>");
                            }
                            if (totalpages > 3 && page < totalpages - 1) {
                                pagerUL.append("<li>...</li>");
                                pagerUL.append("<li><a href='#" + totalpages + " name='" + totalpages + "'>" + totalpages + "</a></li>");
                            }

                            $(this.navClass + ' li:first a').bind('click',
                            function(event) {
                                t.previous();
                                event.preventDefault();
                            });

                            $(this.navClass + ' li:gt(0) a').bind('click',
                            function(event) {
                                t.goToPage($(this).text());
                                event.preventDefault();
                            });

                            $(this.navClass + " a[name='" + page + "']").addClass('selected');
                            pagerUL.append("<li><a href='#'>Next &raquo;</a></li>");
                            $(this.navClass + ' li:last a').bind('click',
                            function(event) {
                                t.next();
                                event.preventDefault();
                            });
                        }
                    };
                    this.previous = function() {
                        if (this.currentPage == 1) this.currentPage = this.totalPages;
                        else this.currentPage--;
                        this.goToPage(this.currentPage);
                    };
                    this.next = function() {
                        if (this.currentPage == this.totalPages) this.currentPage = 1;
                        else this.currentPage++;
                        this.goToPage(this.currentPage);
                    };
                    this.goToPage = function(num) {
                        this.currentPage = num * 1;
                        this.populate(this.totalPages, this.currentPage);
                        this.callback();
                    };
                }

                return this;
            });

            
        }
    };
    
})(jQuery);

$(document).ready(function() {
    $.getScript(
    (("https:" == document.location.protocol) ? "https://": "http://static.") + "rpxnow.com/js/lib/rpx.js",
    function() {
        RPXNOW.overlay = true;
        RPXNOW.language_preference = 'en';
    });
    
    if ((window.location.hostname).endsWith('.com')) {

        if ($('body').hasClass('news') || $('body').hasClass('livetest')) {
            if ($('#ng_comments').length < 1) {
                $('.article_text').after(
                '<a name="comments"></a><div id="ng_comments">' +
                '<h3 class="title">Comments&nbsp;<span class="count"></span></h3>' +
                '<div class="comments_body"></div>' +
                '<div class="comments_footer clearfix">' +
                // '<div class="item"><a href="#" class="post_toggle_btn">+ Post a comment</a></div>' +
                '<div class="pager"></div>' +
                '</div>' +
                '<div class="post_comment_body">' +
                '</div>' +
                '</div>'
                );
            }
        }        
        
        var comments = $('#content').ng_comments({
            countCallbacks: [setSocialNumbers]
        });
        
    }
    
    function setSocialNumbers(ccount, rcount) {
        if ($('.social_stats').length < 1) {
            // Uncomment once recommendations are implemented
            // $('.article_text').append('<div class="social_stats clearfix"><p class="comments"></p><p class="recommendations"><a href="#" title="Click to recommend this page"></a></p></div>');
        }
        $('.social_stats .comments').text('Comments (' + ccount + ')');
        $('.social_stats .recommendations a').text('Recommendations (' + rcount + ')');
    }
    
}); 

String.prototype.endsWith = function(str){
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex != -1) && (lastIndex + str.length == this.length);
}
