var zappIds = new Array();
var arrayIndex = 0;
var proto =  location.protocol;
var host = location.host;
var url = proto + '//' + host;
var commentsFlag = true;
var addCommentOpen = false;
var comments = true;
var currentCommentedZapp=0;
/* This will be activated only after the DOM is ready */

$(document).ready(function() {
	addCommentsSection();
});

function refreshCommentsEvents(){
    $('li.comments').each(function(i){
	    $(this).unbind('click');
    });
    addCommentsSection();
}

function addCommentsSection() {
	$('li.comments').each(function(i){
		var zappId = $('.rowId').get(i).value;
		var title = $('.zappQuestion').get(i).value;
		var commentor, replyto;
		commentsFlag = false;
		if(commentor == null){
			commentor = "You";
		}
		if(replyto == null){
			replyto = "-1";
		}
        $(this).unbind("click");
		$(this).click(function() {
            openForComment(zappId);
		});
    }
    );
}

function submitComment(zappId, commentId, commentor, replyto) {
    $('#addbtn'+zappId).hide();
    $('#addcmtstatus'+zappId).show();
    var comment = $("#" + zappId + "Comment").val();
    var postData;
    if (commentId > -1) {
        postData = {"zappId":zappId,"replyToCommentId":commentId,"comment":comment};
    } else {
        postData = {"zappId":zappId,"comment":comment};
    }
    $.post(url + "/public/addComments.action",
            postData,
            function(data) {
                $('#addcmtstatus'+zappId).hide();
                $('#addbtn'+zappId).show();
                var error = data.error;
                if (error == "true") {
                    alert(data.message);
                } else {
                    alert('Your comment has been submitted for moderation. It will be live once approved.')
                    $("#" + zappId + "Comment").val('');
                }
            }, "JSON");
}




function openForComment(zappId) {
    lastCommentId = -1;
    if (addCommentOpen) {
        $("div#comment" + currentCommentedZapp).hide("slow");
        $("div#comment" + currentCommentedZapp).empty();
        arrayIndex = 0;
        addCommentOpen = false;
    }
    if (arrayIndex == 0) {

        var dialogHtml = "<div id='comment" + zappId +
                "'class='commentsDiv'><div class='lblComment' id='addComment'>Add Comment</div>" +
                "<div id='pbComments'>" +
                "<span style='float:left'>Comments</span>" +
                "<span style='float:right'><a href='#' onclick='listComments();'>Refresh</a></span>" +
                "<div class='comment_smallbox'>" +
                "</div>" +
                "</div>" +
                "<img id='close' align='right' src='styles/images/espnstar/close.gif' border='0'></img>" +
                "</div>";
        $("div#" + zappId).after(dialogHtml);
        zappIds[arrayIndex++] = zappId;
        listCommentsForZapp(zappId);

    }

    $("img#close").click(function () {
        $("div#comment" + zappId).hide("slow");
        $("div#comment" + zappId).empty();
//        stopPolling();
        arrayIndex = 0;
        addCommentOpen = false;
    });

    currentCommentedZapp = zappId;
    var commentBox = "<div class='flora' id='box" + zappId +
            "'>" +
            "<table>" +
            "<tr><td><span class='lblComment'>Add Comment</span></td></tr>" +
            "<tr><td><span id='cmterror' style='display:none;font-size:10px'>Please enter a comment</span></td></tr>" +
            "<tr><td><textarea name='comment' id='" + zappId +
            "Comment'/><td></tr>" +
            "<tr><td colspan='2'>" +
            "<span id='addbtn" + zappId + "'> <img id='submit' style='cursor: pointer;' src='styles/images/espnstar/add_button.jpg' border='0' align='left'></img></span>" +
            "<span style='display:none' id='addcmtstatus" + zappId +"'><img src='/styles/images/espnstar/loading.gif'/></span>" +
            "</td>" +
            "</tr>" +
            "</table>" +
            "</div>";
    $("div#addComment").hide();
    $("div#addComment").before(commentBox);

    $("img#submit").click(function () {
        if ($("#" + zappId + "Comment").val().length > 0) {
            $('#cmterror').hide();
            submitComment(zappId, "-1",'You',-1);
        } else {
            $('#cmterror').show();
        }
    });
    addCommentOpen = true;
}

function addOwnCommentForZapp(zappId, comment, commentId,commentor,replyTo,commentMode) {
	addReplyForZapp(zappId, comment, commentId, null, '-1', commentMode);
}

function getCommentText(zappId,comment,commentId,commentor,replyTo,
		commentMode){
	var mode;
	if(commentMode == "HTTP"){
		mode = "web";
	}else{
		mode = "SMS";
	}
	if(commentor == null){
		commentor = "You";
	}
	if(replyTo == null){
		replyTo = "-1";
	}
	var commentText;
	if(replyTo != "-1"){
		commentText = "<div class='comment'>" +
                      "<span class='comment_who'>" + commentor +
					  " replied to " + replyTo + " through " + mode + "</span><br>" +
                      "<span class='comment_comment'>" +
                      comment +
                      "</span>&nbsp;";
	}
	else{
				commentText = "<div class='comment'>" +
                      "<span class='comment_who'>" + commentor +
					  " commented through " + mode + "</span><br>" +
                      "<span class='comment_comment'>" +
                      comment +
                      "</span>&nbsp;";
	}
	return commentText;
}

function addReplyForZapp(zappId, comment, commentId, commentor, replyTo, commentMode) {
	var commentText = getCommentText(zappId, comment, commentId, commentor, replyTo,
		commentMode);
	$("#comment" + zappId + " > #yrComments > .comment_smallbox").empty();
}

function addPublicForZapp(zappId, comment, commentId, commentor, replyTo, commentMode) {
	var commentText = getCommentText(zappId, comment, commentId, commentor, replyTo, commentMode)
	$("#comment" + zappId + " > #pbComments > .comment_smallbox").prepend(commentText);
}

function addComment(zappId, commentId, commentor, replyto) {

    var commentBox = "<div class='flora' id='box" + zappId + "'" +
                     "<span></span>" +
                     "<table>" +
                     "<tr><td><span>Your Comment</span></td></tr>" +
                     "<tr><td><textarea name='comment' id='" + zappId +
					 "Comment'/><td></tr>" +
                     "<tr><td><input type='submit' value='Add'" +
                     " onclick=submitComment('"
						+ zappId + "','" +
						commentId + "','" +
						commentor + "','" +
						replyto +
					 "')></input></td>" +
                     "<td><input type='submit' value='Cancel'" +
                     " onclick='cancelComment(" + zappId + ")'/></td></tr>" +
                     "</table>" +
                     "</div>";

    $("#comment_box").html(commentBox);
    $("#box" + zappId).dialog({resizable:false});
}

function cancelComment(zappId) {
    $("#box" + zappId).dialog("close");
    $("#box" + zappId).remove();
}

var id = null;
var lastCommentId = 0;

function listCommentsResponse(data) {
    var replies = data.replies;
    var public = data.public;

    if (replies != null) {
        for (var i = 0; i < replies.length; i++) {
            handleReply(replies[i]);
        }
    }
    if (public != null) {
        for (var i = 0; i < public.length; i++) {
            handlePublic(public[i]);
        }
    }
}

function listComments() {
    if (arrayIndex != 0) {
        for (var i = 0; i < zappIds.length; i++) {
            var zappId = zappIds[i];

            $.post(url + "/public/listComments.action",
            {"zappId":zappId,"lastCommentId":lastCommentId},
                    listCommentsResponse, "json");
        }
    }
}

function listCommentsForZapp(zappId) {
    $.post(url + "/public/listComments.action",
    {"zappId":zappId,"lastCommentId":lastCommentId},
            function(data) {
                var public = data.public;
                for (var i = 0; i < public.length; i++) {
					handlePublic(public[i]);
                }
            }
            , "json");
}

/*
replies:
    zappId:<zappId>,
    commentId:<commentId>,
    commentor:<commentor>,
    comment:<comment>,
    commentMode:<commentMode>,
    replyTo:<replyTo>
 */
function handleReply(reply) {
    var zappId = reply.zappId;
    var comment = reply.comment;
    var commentId = reply.commentId;
	var commentor = reply.commentor;
	var replyTo = reply.replyTo;
	var commentMode = reply.commentMode;
    addReplyForZapp(zappId, comment, commentId, commentor, "You", commentMode);
}

/*
public:
    zappId:<zappId>,
    commentId:<commentId>,
    commentor:<commentor>,
    comment:<comment>,
    commentMode:<commentMode>,
    replyTo:<replyTo>
 */
function handlePublic(public) {
    var zappId = public.zappId;
    var comment = public.comment;
    var commentId = public.commentId;
	var commentor = public.commentor;
	var replyTo = public.replyTo;
	var commentMode = public.commentMode;

	lastCommentId = commentId;
    addPublicForZapp(zappId, comment, commentId, commentor,replyTo, commentMode);
}

function approveComment(row, commentid) {
    var link = 'makelive.action?comment.id=' + commentid;
    callAHAH(link, row, 'Activating the comment. Please wait...', 'Error');

}

function rejectComment(row, commentid) {
    var link = 'flagcomment.action?comment.id=' + commentid;
    callAHAH(link, commentid, 'Flagging the comment. Please wait...', 'Error');
//    $('#'+row).remove();
}