var sItemName1='';
var sItemName2='';

function addComment(nItemId, nUserId)
{	
	// get comment
	sComment = $("textarea[name='Comment']").val();
		
 	// are we logged in?
 	if (nUserId.length > 0)
 	{
 		if (sComment.length == 0 || sComment == 'Write a comment')
 		{	
			// set dialog content
			$("#dialogInfoBody").html('You must enter a comment!');
		
			// pop dialog notice box
        	$("#dialogInfo").dialog(
		    {
		    	title: 'Clipstar',
	            resizable: false,
	            close: function() { $(this).dialog('destroy'); },
	            buttons: { "OK": function() { $(this).dialog('destroy'); }}  					    
		    });		
 		}
 		else
 		{		
         	// add comment
            $.ajax({
                url: '/ajax/addcomment/' + sItemName2 + '/' + nItemId + '/',
                type: 'POST',
                data: sComment,
                error: function () {
    				$("#dialogInfoBody").html('We are sorry, there seems to have been a problem. Please try again.');
    	        	$("#dialogInfo").dialog(
    			    {
    			    	title: 'Clipstar',
    		            resizable: false,
    		            close: function() { $(this).dialog('destroy'); },
    		            buttons: { "OK": function() { $(this).dialog('destroy'); }}  					    
    			    });	
            	},
                success: function()
                { 
                	// clear out comments and rebuild
                	$("#commentsOutput").html('');
                	getComments(nItemId, nUserId, 1);
                	
                	// set comment box back to default
                	$("textarea[name='Comment']").val('Write a comment');
                }
            });
 		}
 	}
 	else
 	{
 		window.location = "/login/";
 	}
};

/*
 * Delete a comment!
 */
function deleteComment(nCommentId, nItemId, nUserId)
{
    $.ajax({
        url: '/ajax/deletecomment/' + sItemName2 + '/' + nItemId + '/' + nCommentId + '/',
        type: 'GET',
        error: function () {
			$("#dialogInfoBody").html('We are sorry, there seems to have been a problem. Please try again.');
        	$("#dialogInfo").dialog(
		    {
		    	title: 'Clipstar',
	            resizable: false,
	            close: function() { $(this).dialog('destroy'); },
	            buttons: { "OK": function() { $(this).dialog('destroy'); }}  					    
		    });	
    	},
        success: function()
        {                         	
        	// clear out comments and rebuild
        	$("#commentsOutput").html('');
        	getComments(nItemId, nUserId, 1);
        	// set comment box back to default
        	$("textarea[name='Comment']").val('Write a comment');
        }
    });	
};

/*
 *  Reply to a comment
 */
function replyComment(nItemId, nUserId)
{
	 if (nUserId.length > 0)
	 {
		 // popup dialog
		 $(document).ready(function()
		 {
        $("#dialog").dialog(
        {
            resizable: false,
            close: function() { $(this).dialog('destroy'); },
            buttons: 
            {
                "Submit": function() 
                {
            		// get comment id i'm replying to
            		nReplyId = $("input[name='replyId']").val();
            		sComment = $("textarea[name='replyCommentBody']").val();
                 		
                 	// add comment
                    $.ajax({
                    	url: '/ajax/addcomment/' + sItemName2 + '/' + nItemId + '/' + nReplyId +'/',
                        type: 'POST',
                        data: sComment,
                        error: function () {
        				$("#dialogInfoBody").html('We are sorry, there seems to have been a problem. Please try again.');
        	        	$("#dialogInfo").dialog(
        			    {
        			    	title: 'Clipstar',
        		            resizable: false,
        		            close: function() { $(this).dialog('destroy'); },
        		            buttons: { "OK": function() { $(this).dialog('destroy'); }}  					    
        			    });	
	                	},
	                    success: function()
	                    { 
	                    	// clear out comments and rebuild
	                    	$("#commentsOutput").html('');
	                    	getComments(nItemId, nUserId, 1);
	                    	
	                    	// set comment box back to default
	                    	$("textarea[name='Comment']").val('Write a comment');
	                    }
                    });
                 	
                	$(this).dialog('destroy');
            	},
                "Cancel": function() { $(this).dialog('destroy'); }
            }           
        });
    });
	 }
};

var pageLoaded=false;

/*
 * Ajax'd video comments
 */
function getComments(nItemId, nUserId, page)
{
	
	$(document).ready(function() {
	
		//$("#commentsOutput").parent().css('height', $("#commentsOutput").height()+'px');
		$("#commentsOutput").empty();
	
		$("#commentsOutput").append('<div style="padding: 50px; text-align: center; font-color: #AAAAAA; font-size: 1.2em;"><img src="/images/loading.gif" /><br />Loading Comments...</div>');
		
		// get comments for the video
	    $.ajax({
	        url: '/ajax/comments/' + sItemName2 + '/' + nItemId + '/' + page + '/',
	        type: 'GET',
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
        	    if (XMLHttpRequest.status==404) {
        	    	$("#commentsOutput").empty();
        			$("#commentsOutput").append('<div style="padding: 0 20px 20px 20px; text-align: center; font-color: #AAAAAA; font-size: 1.2em;">There are currently no comments</div>');
        	    } else {
        	    	$("#commentsOutput").empty();
        			$("#commentsOutput").append('<div style="padding: 0 20px 20px 20px; text-align: center; font-color: #AAAAAA; font-size: 1.2em;">There has been an error with the comments, please try again later.</div>');
        	    }
    	    	$("#commentsOutput").parent().css('height', 'auto');
        	},
	        success: function(xml)
	        {
	    		// loop through all the comments
	    		$("#commentsOutput").empty();
	    		
    			var commentsList=$(xml).find("commentsList");
	    		
	    		var pages=Math.ceil($(commentsList).attr('total')/$(commentsList).attr('size'));
	    		
	    		pagesHtml='';
	    		for(i=1;i<=pages;i++) {
	    			if (i==page || page==undefined) {
	    				pagesHtml=pagesHtml+"&nbsp;&nbsp;<em>"+i+'</em>';
	    			} else {
	    				pagesHtml=pagesHtml+"&nbsp;&nbsp;<a href=\"javascript:getComments('"+nItemId+"', '"+nUserId+"', '"+i+"')\">"+i+'</a>';
	    			}
	    		}	
	    		
    			$("#commentsOutput").append('<li>Pages: '+pagesHtml+'</li>');
	    		
	    		$(xml).find("comments").each(function()
	    		{
	    			
    				// save comment id for matching replies
    				nCommentId = $(this).attr(sItemName1.toLowerCase()+"CommentId");
    				
    				// calculate folder structure
    				nFolder1 = Math.ceil($(this).find("user").attr("userId") / 100000);
    				nFolder2 = Math.ceil(($(this).find("user").attr("userId") % 100000) / 1000);
    				tDate = new Date($(this).find("timestamp").text() * 1000);
    				sDate = tDate.toLocaleString();
    				
    				// sort out profile pic html
    				if ($(this).find("profilePic").text() == '1')
    				{
    					sProfile = '<a href="/' + $(this).find("user").find("url").text() + '/" class="pic"><img src="http://images' + $(this).find("clusterId").text() + '.clipstar.com/users/'+nFolder1+'/'+nFolder2+'/'+$(this).find("user").attr("userIdEncoded")+'/profile-45x60.jpg" width="45" height="60" alt="" /></a>';
    				}
    				else
    				{
    					sProfile = '<a href="/' + $(this).find("user").find("url").text() + '/" class="pic"><img src="http://images' + $(this).find("clusterId").text() + '.clipstar.com/users/profile-45x60.png" width="45" height="60" alt="" /></a>';
    				}
    				
    				// reply or delete button
    				if (nUserId!=0) {
	    				if (nUserId == $(this).find("user").attr("userId"))
	    				{
	    					sButton = '<a href="javascript:deleteComment(' + nCommentId + ',' + nItemId + ',' + nUserId + ')" class="btn-delete"><span>Delete</span></a>';
	    				}
	    				else // we are replying
	    				{
	    					sButton = '<a href="javascript:document.replyCommentForm.replyId.value=' + nCommentId + ';javascript:replyComment(\''+nItemId+'\',\''+nUserId+'\');" class="btn-reply"><span>Reply</span></a>'
	    				}
    				} else {
    					sButton = '';
    				}
    				
    				// build output
    				if (nCommentId != $(this).find("parentCommentId").text())
					{
    					if (nUserId == $(this).find("user").attr("userId"))
	    				{
	    					sDelete = '<a href="javascript:deleteComment(' + nCommentId + ',' + nItemId + ',' + nUserId + ')" class="aqua-link-blue"><span>Delete</span></a>'
	    				}
	    				else
	    				{
	    					sDelete = ' ';
	    				}
    					
						$("#commentsOutput").append('<li style="margin-left: 50px;">' + sProfile + '<h4><a href="/' + $(this).find("user").find("url").text() + '/">' + $(this).find("user").find("url").text() + '</a> - ' + sDate + '</h4><p>' + $(this).find("body").text() + '</p>' + sDelete + '</li>');
					} else {
						$("#commentsOutput").append('<li>' + sProfile + '<h4><a href="/' + $(this).find("user").find("url").text() + '/">' + $(this).find("user").find("url").text() + '</a> - ' + sDate + '</h4><p>' + $(this).find("body").text() + '</p>' + sButton + '</li>');
					}
						
	    		});
	    		
	    		$("#commentsOutput").append('<li style="border: none;">Pages: '+pagesHtml+'</li>');
	    		
	    		//$("#commentsOutput").parent().animate({height: $("#commentsOutput").height()+'px'});
	    		
	    		if (pageLoaded==true) $.scrollTo("#comments", '500');
	    		pageLoaded=true;
	    		
	        }
	   	});
	});
};	