// JavaScript Document

     jQuery(document).ready(function() {
     
         	jQuery.noConflict();
		
		checkCommentEnable(userObjLoginStatus);
	});
	
	function strStripHtml( text ) {
		return text.replace(/<(?:.|\s)*?>/g, "");
	}
	
	function strTrim( text ) {
		return text.replace(/^\s+|\s+$/g,"");
	}

        function escapeQuote(text){
           var result = text.replace(/'/g,"\\'");
           return result;
        }

        function txtshow( txt2show, elemId ) { 
 
 	    if( elemId == undefined )
 	    	elemId = 'txtmsg';
 	    	
            if (parseInt(navigator.appVersion) >=5) {DOM=1};           
            // Detect Browser
            if (DOM) {
		var viewer = document.getElementById(elemId);
                viewer.innerHTML=txt2show;
            }
            else if(IE)
                document.all[elemId].innerHTML=txt2show;
        }

      function keyup(what, elemId){
        var str = new String(what.value);
        var len = str.length;
        var showstr = "You have typed "+len + " characters out of " + maxKeys + " allowed.";
        if (len > maxKeys) showstr += '<br>Some information will be lost, please revise your entry';
        txtshow( showstr, elemId );
      }
    	

	function chkboxValueFlip( object ) {
		if( object.value == 1 )
			object.value = 0;
		else
			object.value = 1;
	}    	
    	
    	
    	function nextComments(objId, beginning, kind){
    	   var nextJSON = '{                                                     '+                   
                   ' "objectId":               "'+objId+'",                  '+
                   ' "kind":               "'+commentKind+'",                  '+
                   ' "begin":                "'+beginning+'"              '+
                   '}                                                         ';
                   
         fetchcomments(nextJSON);
      }
      
       function fetchcomments(json){                  
       
            var data = jQuery.evalJSON(json);
            jQuery.post("/community/viewEntertainmentComments.html", data, function(data){
            drawPage(data);},"json");
         }
         
         
         function drawPage( json ) 
         {
         	var count = 0;
         	var begin = 0;
         	var next = 0;
         	var previous = 0;
         	var display_begin = 0;
         	var display_end = 0;
         	
         	var isNextImgOn = true;
         	var isPrevImgOn = true;
         	
		if (json.count != undefined && json.count > 0 ) {
                	count = parseInt(json.count);
                	
                	if( json.begin != undefined ) {
                		begin = parseInt(json.begin);
                		next = begin + 10;
                		previous = begin - 10;
                		display_begin = begin + 1;
                		display_end = display_begin + 9;
                		
                		
                		if( begin == 0 ) 
                			isPrevImgOn = false;
                               		
                		
                		if( next >= count ) {
                			display_end = count;
                			isNextImgOn = false;
                		}
                		
                		if( previous <= 0 )
                			previous = 0;
                	}
                }
                else {
                	isNextImgOn = false;
                	isPrevImgOn = false;
                }
                
                
                var paginationStr = '';
                
                if( isPrevImgOn )
                	paginationStr += '<a href="javascript:nextComments(\''+objectId+'\','+previous+')"><img width="5" height="10" src="/community/images/icons/prev_page.png" border="0" alt="Previous Page" title="Previous Page"/></a>&nbsp;&nbsp;';
                else
                	paginationStr += '<img width="5" height="10" src="/community/images/icons/prev_page_disabled.png" border="0"/>&nbsp;&nbsp;';
                	
                paginationStr += display_begin.toString()+'-'+display_end.toString()+' of '+count.toString();
                
                if( isNextImgOn ) 
                	paginationStr += '&nbsp;&nbsp;<a href="javascript:nextComments(\''+objectId+'\','+next+')"><img width="5" height="10" src="/community/images/icons/next_page.png" border="0" alt="Next Page" title="Next Page"/></a>';
                else
                	paginationStr += '&nbsp;&nbsp;<img width="5" height="10" src="/community/images/icons/next_page_disabled.png" border="0"/>';
                
                
                document.getElementById('commentsPagination').innerHTML = paginationStr;
                document.getElementById('commentsCount').innerHTML = count.toString();
                
		items = json.items;   
		document.getElementById('communityComments').innerHTML = '';

		for ( var i in items ) {
			if (items[i].comment != undefined) {

				var commentObj = createComment( items[i] );
				var commentDiv = getCommentDiv( commentObj, false );

				jQuery('#communityComments').append(commentDiv);
			}
		}
                
         }
         

 
         function addComment(){
         
         	if( userObjLoginStatus == true ) {
         	
			var comment = strTrim(jQuery('#entertainmentCommentsForm textarea[name=comments]').val().toString());
			var cleanComment = unescape(strStripHtml( urldecode(comment))); 
			cleanComment = cleanComment.toString().replace('"','\\"');
			
			if( cleanComment != '' ) {
				
				var MyJSONObject = '{                                                                                         '+
				   ' "comments":              "'+cleanComment+'",                                                         '+
				   ' "kind":              "'+commentKind+'",                                                         '+
				   ' "objectId":               "'+objectId+'"               '+
				   '}                                                                                                     ';


				  if (facebook_enabled && facebook_uid != "") {
				  	if( jQuery('#entertainmentCommentsForm input[name=postToFB]').val() == 1 ) {  
						
						var fbCommentStreamObj = fbGetCommentStreamObj( commentKind, cleanComment );
						fbPublishCommentStream(fbCommentStreamObj);
					}
				  }

				  submitComment(MyJSONObject);  
			}
			else
				alert('Your comment appears to be empty.');
		}
		else
			alert("You must be logged in to post comments");

         }
         
         
         function fbCommentStreamBase( title, url, caption, description ) {
         
         	this.title = title;
         	this.url = url;
         	this.caption = caption;
         	this.description = description;
         
         }
         
         
         function fbCommentStreamVideo( comment ) {
         	var videoTitle = jQuery('#entertainmentCommentsForm input[name=videoTitle]').val();
         	var videoUrl = jQuery('#entertainmentCommentsForm input[name=defaultVideoUrl]').val();
         	var videoImage = jQuery('#entertainmentCommentsForm input[name=defaultVideoPhotoUrl]').val();
         	var showTitle = jQuery('#entertainmentCommentsForm input[name=showTitle]').val();
         	var serverHost = window.location.hostname;
         	
         	var fbTitle = 'Commented on CBS.com for the show \'' + showTitle + '\'';
         	var fbUrl = 'http://' + serverHost + videoUrl;
         	var fbCaption = 'Check out the video: ' + videoTitle;
         	var fbDesc = truncate('My comment: ' + comment, 200, '...');
         	
         	fbCommentStreamBase.apply( this, [fbTitle, fbUrl, fbCaption, fbDesc] );
         	
         }
         fbCommentStreamVideo.prototype = new fbCommentStreamBase;
         
 
         function fbCommentStreamBio( comment ) {
         	var biosTitle = fbActorName;
         	var biosUrl = window.location.href;
         	var showTitle = fbShowTitle;
         	
         	var fbTitle = 'Commented on CBS.com for the show \'' + showTitle + '\'';
         	var fbUrl = biosUrl.toString().split('#')[0];
         	var fbCaption = 'Check out the bio for: ' + biosTitle;
         	var fbDesc = truncate('My comment: ' + comment, 200, '...');
         	
         	fbCommentStreamBase.apply( this, [fbTitle, fbUrl, fbCaption, fbDesc] );
         	
         }
         fbCommentStreamBio.prototype = new fbCommentStreamBase; 
 
 
          function fbCommentStreamRecap( comment ) {
         	var recapTitle = fbShowTitle + ' (episode: ' + fbEpisodeTitle + ')';
         	var recapUrl = window.location.href;
         	var showTitle = fbShowTitle;
          	
          	var fbTitle = 'Commented on CBS.com for the show \'' + showTitle + '\'';
          	var fbUrl = recapUrl.toString().split('#')[0];
          	var fbCaption = 'Check out the show recap: ' + recapTitle;
          	var fbDesc = truncate('My comment: ' + comment, 200, '...');
          	
          	fbCommentStreamBase.apply( this, [fbTitle, fbUrl, fbCaption, fbDesc] );
          	
          }
         fbCommentStreamRecap.prototype = new fbCommentStreamBase; 

          function fbCommentStreamPhoto( comment ) {
         	var photoTitle = fbPhotoTitle;
         	var photoUrl = window.location.href;
          	
          	var fbTitle = 'Commented on CBS.com for the show \'' + showTitle + '\'';
          	var fbUrl = recapUrl.toString().split('#')[0];
          	var fbCaption = 'Check out the photo: ' + fbPhotoTitle;
          	var fbDesc = truncate('My comment: ' + comment, 200, '...');
          	
          	fbCommentStreamBase.apply( this, [fbTitle, fbUrl, fbCaption, fbDesc] );
          	
          }
         fbCommentStreamPhoto.prototype = new fbCommentStreamBase; 
        
         
         function fbPublishCommentStream( fbCommentStreamObj ) {
         
		 var attachment = {
			'name': fbCommentStreamObj.title,
			'href': fbCommentStreamObj.url,
			'caption': fbCommentStreamObj.caption,
			'description': fbCommentStreamObj.description
		}      
			
		facebookPublishStream(attachment);
         }
         
   
         function fbGetCommentStreamObj( commentKind, comment )
         {     
         	switch( commentKind ) {
         		case 1:
         			return new fbCommentStreamBio( comment );
         			break;
         		case 2:
         			return new fbCommentStreamRecap( comment );
         			break;     
            		case 3:
         			return new fbCommentStreamPhoto( comment );
         			break;        			
         		default:
         			return new fbCommentStreamVideo( comment );
         			break;
         	
         	}
         } 
      
         
         function truncate (text, maxlen, moreLabel) {
            if (text.length > maxlen) { return text.substring(0,maxlen) + moreLabel; }
            return text;
         }
         
         function submitComment(json){
            var data = jQuery.evalJSON(json); 
            jQuery.post("/community/addEntertainmentComment.html", data, function(data){
            postComment(data);},"json");
         }
         
         function postComment(json) {
            if (json.message == "Success" || json.message == "Success with Anonymous user!") {
                
                var commentObj = createComment( json );
		var commentDiv = getCommentDiv( commentObj, true );
                var commentForm = document.getElementById('entertainmentCommentsForm');
                
                jQuery('#communityComments').prepend(commentDiv);
		commentForm.comments.value = '';           
 
            }
            else {
		if(json.message =='? user must be logged in to make a comment') 
			alert("You must be logged in to post comments");
		else
			alert("Unable to add your comment.");
            }        
         }
         
         function removeComment(cid) {
         	if( cid != undefined ) {
			var data = { "cid": cid };
			jQuery.post("/community/removeEntertainmentComment.html", data, function(data){
            		postRemove(data, cid );},"json"); 
         	}
         	else
         		alert( 'Please specify comment Id.' );
         	
         }
               
         
         function postRemove(json, cid){
         	if( json.success == true ) {
             		var thisRemoveId = "remove_" + cid;
            		var thisRemoveSpan = document.getElementById(thisRemoveId);
            		thisRemoveSpan.innerHTML = "Deleted!";        	
         	}
         	else {
         	
         		alert('Delete failed. Error Msg: ' + json.message);
         	}

         }     
               
         function flagComment(cid){
            var json = { 
            			"commentId": cid.toString(),
            			"pageUrl": window.location.href.toString()
            		};
            		
            jQuery.post("/community/flagComment.html", json, function(json){
            finishFlag(cid);},"json");            
         }
         

         function flagPhoto(pid){
            photo_id = pid;
            flagJSON = "{ 'pid': '"+photo_id+"' }";
            submitPhotoFlag(flagJSON);
         }
         
          function submitPhotoFlag(json){
            var data = jQuery.evalJSON(json); 
            $.post("/community/flagPhoto.html", data, function(data){
            finishPhotoFlag(data);},"json");
         }
         
         function finishPhotoFlag(json){
            var thisFlagId = "flag"+photo_id;
            var thisFlagSpan = document.getElementById(thisFlagId);
            thisFlagSpan.innerHTML = "Reported!";
         }
         
         function finishFlag(comment_id){
            var thisFlagId = "flag"+comment_id;
            var thisFlagSpan = document.getElementById(thisFlagId);
            thisFlagSpan.innerHTML = "Reported!";
         }
         
         function urldecode( str ) {   
            ret = str;       
            ret = ret.replace(/\+/g, '%20');
            ret = decodeURIComponent(ret);
            ret = ret.toString(); 
            return ret;
        } 
        
        
        function checkCommentEnable(userObjLoginStatus) 
        {
        	
        	if( userObjLoginStatus == false ) {
			formObj = document.getElementById('comments');
        		formObj.disabled = true;
        		formObj.style.backgroundColor = '#AAAAAA';

        		textObj = document.getElementById('instrText');
        		textObj.innerHTML = getLoginStr();
        	}
        	else {
  			formObj = document.getElementById('comments');
        		formObj.disabled = false;      	
        	}
        		
        	
        }
     
     
     	function getReplies( parentId, begin, fromRoot ) {
     	
		if( begin == null )
			begin = 0;

		if(fromRoot == null )
			fromRoot = 0;

		var jsonTxt = '{'+                   
		   ' "cid": "' + parentId + '",' +
		   ' "begin": ' + begin + ',' +
		   ' "size": 10' +
		   '}';   

		replyLink = document.getElementById("view_replies_" + parentId );
		replyLink.href='javascript:hideReplies(' + parentId + ')';
		replyLink.innerHTML = '- hide replies';  

		var data = jQuery.evalJSON(jsonTxt); 
		jQuery.post("/community/viewEntertainmentCommentsReplies.html", data, function(data){ 
		 	showReplies(data, parentId, fromRoot);},"json");
           


     		
     	}
             
         function showReplies( jsonObj, parentId, fromRoot ) {
         	
         	if( fromRoot != 0 )
         		jQuery('#aCommentReply_' + parentId ).html('');
         	
         	var commentDiv = '<br /><br />';
         	items = jsonObj.items;
         	
         	for(var i=0;i<jsonObj.items.length;i++) {
                	
                	if (items[i].comment != undefined) {
                	
         			var commentObj = createComment( items[i] );
				commentDiv += getCommentReplyDiv( commentObj );	
         		}
         	}
         	

         	oldBegin = parseInt(jsonObj.begin) - 10;
         	nextBegin = parseInt(jsonObj.begin) + 10;

           	
         	jQuery('#moreReplies_' + parentId + '_' + oldBegin).html('');
         	
         	if( nextBegin < jsonObj.count ) 
         		commentDiv += '<div id="moreReplies_' + parentId + '_' + jsonObj.begin + '" align="right" style="font-size: 9pt"><br /><a href="javascript:getReplies(' + parentId + ',' + nextBegin + ')">more replies >></a><br /><br /><div>';
         	
         	jQuery('#aCommentReply_' + parentId ).append(commentDiv);

         }
         
         
         
         function hideReplies( parentId ) {
         
           	replyLink = document.getElementById("view_replies_" + parentId );
           	replyLink.href='javascript:unHideReplies(' + parentId + ')';
           	replyLink.innerHTML = '+ view replies';  
           	
           	
           	replyDiv = document.getElementById("aCommentReply_" + parentId );
           	replyDiv.style.display = 'none';
           	replyDiv.style.visibility = 'hidden'; 
         
         }
         
         
         function unHideReplies( parentId ) {
         
           	replyLink = document.getElementById("view_replies_" + parentId );
           	
           	if( replyLink != undefined ) {
           		replyLink.href='javascript:hideReplies(' + parentId + ')';
           		replyLink.innerHTML = '- hide replies'; 
           	}
           	
           	
           	replyDiv = document.getElementById("aCommentReply_" + parentId );
           	replyDiv.style.display = '';
           	replyDiv.style.visibility = 'visible'; 
         
         }         
         
         
         
         function showReplyInput( parentId ) {
         
         	if( userObjLoginStatus == true ) {
			var divStr = '<br /><div style="padding: 8px; margin: 0; color: #000000; font-size: 8pt"><form id="commentReplyForm_' + parentId + '">';
				divStr += '<textarea name="comments" cols="60" rows="4" style="border: 1px solid #000000;" onkeyup="keyup(this, \'reply_wordcount_' + parentId + '\')"></textarea>';
				
				if (facebook_enabled && facebook_uid != "") {
					divStr += '<p><br /><input type="checkbox" value="1" name="postToFB" checked="yes" onClick="javascript:chkboxValueFlip(this);"> Share on Facebook</p>';
				}
				
				divStr += '</form><span id="reply_wordcount_' + parentId + '">You have typed 0 out of 2000 characters</span>';
				divStr += '<br /><br /><a href="javascript:sendReply(' + parentId + ');" class="btn-site-color1-arrow"><span>Submit</span></a></div><br />';

			replyLink = document.getElementById("view_reply_input_" + parentId );
			replyLink.href='javascript:hideReplyInput(' + parentId + ')';
			replyLink.innerHTML = '- close reply';           		

			jQuery('#aCommentReplyInput_' + parentId ).append(divStr);
		}
		else {
			replyLink = document.getElementById("view_reply_input_" + parentId );
			replyLink.href='javascript:hideReplyInput(' + parentId + ')';
			replyLink.innerHTML = '- close reply';   
			
			jQuery('#aCommentReplyInput_' + parentId ).append(getLoginStr());
		}
         
         
         
         }
         
         function hideReplyInput( parentId ) {
           	replyLink = document.getElementById("view_reply_input_" + parentId );
           	replyLink.href='javascript:showReplyInput(' + parentId + ')';
           	replyLink.innerHTML = '+ post reply'; 
           	
           	jQuery('#aCommentReplyInput_' + parentId ).html('');
	 }
	 
	 
	 
         function sendReply( parentId ) {
         	
         	var message = strTrim(jQuery('#commentReplyForm_' + parentId + ' textarea[name=comments]').val().toString());
         	var cleanComment = unescape(strStripHtml( urldecode(message)));
         	cleanComment = cleanComment.toString().replace('"','\\"');
         	
         	if( cleanComment != '' ) {
			 
			var jsonTxt = '{ '+
			   ' "comments": "'+cleanComment+'", '+
			   ' "kind": "'+commentKind+'", '+
			   ' "objectId":  "'+objectId+'", '+
			   ' "parent":   "'+parentId+'" '+
			   '} ';


			  if (facebook_enabled && facebook_uid != "") {
			  	if( jQuery('#commentReplyForm_' + parentId + ' input[name=postToFB]').val() == 1) { 
					
					var fbCommentStreamObj = fbGetCommentStreamObj( commentKind, cleanComment );
					fbPublishCommentStream(fbCommentStreamObj);					
				}
			  }

			var data = jQuery.evalJSON(jsonTxt);

			jQuery.post("/community/addEntertainmentComment.html", data, function(data){
				showReplyPost(data, parentId);},"json");  
		}
		else
			alert('Your reply appears to be empty.');
       	
         }
         


         function showReplyPost( jsonObj, parentId ) {
         	var commentDiv = '';
         	if (jsonObj.message == "Success") {
         		
         		var commentObj = createComment( jsonObj );
			commentDiv += getCommentReplyDiv( commentObj );
			     	     
			hideReplyInput( parentId ); 	     
			jQuery('#aCommentReply_' + parentId ).prepend('<br />' + commentDiv);
			unHideReplies( parentId );
	          	
	         }  
         }
         
         function getLoginStr() {
         	return '<b>Please <a href="/community/login/loginform.html?desturl=' + document.location.href + '">log in</a> or <a href="/community/login/signup.html">register</a> to post a comment</b>';
         }
         
         
         function Comment( id, message, userId, userName, userPhotoUrl, hasChildren, parentId ) 
         {
         
         	this.id = id;
         	this.message = message;
         	this.userId = userId;
         	this.userName = userName;
         	this.userPhotoUrl = userPhotoUrl;
         	this.hasChildren = hasChildren;
         	this.parentId = parentId;
         
         
         }
         
         function createComment( commentItemJsonObj ) 
         {
         	var scrubbedComment = commentItemJsonObj.comment.replace(/\+/g, '%20');
         	scrubbedComment = urldecode( unescape( scrubbedComment ));
         	var commentObj = new Comment( commentItemJsonObj.cid, scrubbedComment, commentItemJsonObj.uid, commentItemJsonObj.username, commentItemJsonObj.photoURl, commentItemJsonObj.hasChildren, commentItemJsonObj.parentId );
         
         	return commentObj;
         }
         
         function getCommentDiv( comment, isNew )
         {
         	var commentDiv = '<div class="aComment">';
         	commentDiv += getCommentContent( comment, false, isNew );
         	commentDiv += '</div>';
         	
         	return commentDiv;
         
         }
        
         function getCommentReplyDiv( comment )
         {
         	var commentDiv = '<div class="aCommentReply" id="aComment_' + comment.id + '">';
         	commentDiv += getCommentContent( comment, true, false );
         	commentDiv += '</div>';
         	
         	return commentDiv;
         
         }        
        
         function getCommentContent( comment, isReply, isNewComment )
         {
             	
         	var commentContent = '<div class="aCommentPortraitContainer">'+
                             		'<div class="commentPortrait">'+
                             			'<a href="/community/manage/userProfileHome.html?u=' + comment.userId + '"><img src="/' + comment.userPhotoUrl + '" alt="" border="0" width="32" height="32"/></a>'+
                             		'</div>'+
                             		'<div class="commentUsername">'; 
                             		
						if( comment.userId != 0 )
							commentContent += '<a href="/community/manage/userProfileHome.html?u=' + comment.userId + '">' + comment.userName + '</a>';
						else
							commentContent += '<span class="anonymousComment">' + comment.userName + '</span>';
                             			
                             			
                commentContent +=       '</div><div class="clear"></div>'+
                             	      '</div>';
                             	      
	      var msgCommentContainer = '';
	      if( isReply == false )
		msgCommentContainer = 'aCommentBodyContainer';
	      else
		msgCommentContainer = 'aCommentBodyContainerReply';
                             	      	
                             	      	
                commentContent +=         '<div class="' + msgCommentContainer + '">' +
                				'<div class="aCommentBody">' + comment.message + '</div>'+
                             		'</div><div class="clear"></div>';
                             		
                        	
			if( isReply == false ) {
				commentContent += '<div align="right" style="font-size: 8pt">';

				if( comment.hasChildren == true )
					commentContent += '<a id="view_replies_' + comment.id + '" href="javascript:getReplies(' + comment.id + ',0,1);">+ view replies</a> | ';
				
				if( isNewComment == false )
					commentContent += '<a id="view_reply_input_' + comment.id + '" href="javascript:showReplyInput(' + comment.id + ');">+ post reply</a><br /><br />'; 
				
				commentContent += '</div>';
			}
				
			if( userRole > 3 )
				commentContent += '<div align="right" style="font-size: 8pt;" id="remove_' + comment.id + '"><a href="javascript:removeComment(' + comment.id + ')">(x) delete</a><br/><br /></div> ';
				
		commentContent += '<div class="aCommentFlag">'+
					'<span id="flag' + comment.id + '"><a href="javascript:flagComment(' + comment.id + ')">report</a></span>' +
				  '</div><div class="clear"></div> ';
				  
			if( isReply == false ) 
                            commentContent += '<div id="aCommentReplyInput_' + comment.id + '" align="right" style="width: 570px"></div><div id="aCommentReply_' + comment.id + '"></div>';
                  
         
         	return commentContent;
         
         }
        
        
             