/**
 * @author ezdermam
 */

if(typeof NICK == "undefined" || !NICK) var NICK = {};

NICK.namespace("comments");

NICK.comments.arrayCID = {"game":"383", "video":"384", "troopgrid":"394"};
//NICK.comments.arrayCType = {"game":"nickGameComment", "video":"nickVideoComment"};
NICK.comments.MSG_NO_COMMENT = "Please enter a comment";
NICK.comments.MSG_NO_ID = "No Item ID";
NICK.comments.ERROR_STORY_SUBMISSION = "There were errors in your story submission.";
NICK.comments.MSG_ERROR = "Error";
NICK.comments.ERROR_SERVER_LOGIN_KEY = "membername";
NICK.comments.date = Date;

NICK.comments.doPost=function(form){
	NICK.comments.date = new Date();
	
	var data = NICK.comments.getComment();
	
	if (NICK.comments.isValid(data)) {
		NICK.comments.enabledSubmission(false);
		// gdc is performing a redirect after success -- convert it to an xml blob and pass by "xml" param...
		data = {cid:data.cid, xml:NICK.utils.getGdcXml(data.cid, data)};
		try { // Catch browser security exceptions.
			$.ajax({
				type: "GET",
				url: NICK.config.URL_COMMENT_POST,
				data: data,
				dataType:"jsonp",
				success:NICK.comments.handleCommentPost,
				error:NICK.comments.handleSubmitDataErrors
			});
		} catch(error) {
			NICK.comments.handleSubmitDataErrors(error);
		}
	}
	return false;
}

NICK.comments.handleCommentPost=function(json) {
	NICK.utils.doLog("comment posted");
	if(json == null) {
		NICK.comments.handleCommentPostErrors(NICK.comments.ERROR_STORY_SUBMISSION);
	} else if(json.code == "ok") {
		$("#comment-input").val("");
		NICK.comments.thankyou();
		
	} else if(json.code == "error") {
		var errors = "";
		var isLoggedOut = false;

		for(var key in json.errors) {
			errors += json.errors[key]+"\n";
		}
	}
}


NICK.comments.thankyou=function(){
	
	NICK.comments.enabledSubmission(true);
	$("#comment-thankyou").show();
}

NICK.comments.handleSubmitDataErrors=function(request, error, exception) {
	NICK.utils.doLog("handleSubmitDataErrors: "+error);
}

NICK.comments.handleCommentPostErrors=function(error){
	NICK.utils.doLog(error);
	NICK.comments.enabledSubmission(true);
}

NICK.comments.getMemberName = function(){
	var membername ="";
	NICK.utils.doLog("screenName:"+NICK.userData.screenName+"   nickName:"+NICK.userData.nickName);
	if (NICK.userData.screenName == "undefined"||NICK.userData.screenName == "") {
		membername = NICK.userData.nickName;
	}
	else {
		
		membername = NICK.userData.screenName;
	}
	NICK.utils.doLog("membername:"+membername)
	return membername;
	
}


NICK.comments.getComment=function(){

	return {
		cid: NICK.comments.arrayCID[$("#comment-post-form input[name='pageType']").val()],
		type: $("#comment-post-form input[name='type']").val(),
		itemid: $("#comment-post-form input[name='cmsID']").val(),
		comment: $("#comment-post-form #comment-input").val(),
		workflow_stages:$("#comment-post-form #workflow_stages").val(),
		workflow_name:$("#comment-post-form #workflow_name").val(),
		status_url:$("#comment-post-form #status_url").val(),
		suspend_url:$("#comment-post-form #suspend_url").val(),
		resume_url:$("#comment-post-form #resume_url").val(),
		publish_url:$("#comment-post-form #publish_url").val(),
		membername:NICK.comments.getMemberName()
		
	}
	
}



NICK.comments.getCType = function(type){
	return NICK.comments.arrayCType[type];
}


NICK.comments.isValid=function(_data){
	var valid = true;
	var errorMsg = "";
	
	if (_data.comment == "") {
		errorMsg += NICK.comments.MSG_NO_COMMENT + "\n";
		valid = false;
	}
	
	if (_data.itemid == "") {
		NICK.utils.doLog("comments post: "+NICK.comments.MSG_NO_ID)
		valid = false;
	}
	
	if(!valid){
		//todo: error message
		$("#errorMsg").append(errorMsg);
	}
	
	return valid;
}

NICK.comments.enabledSubmission=function(bool){
	switch (bool) {
		case false:
			$("#comment-post-form .icon-post" ).attr("onclick", "");
			break;
		case true:
			$("#comment-post-form .icon-post" ).attr("onclick", "javascript:NICK.comments.doPost(this)");
			break;
	}
}

NICK.comments.initCommentPost=function() {
	//NICK.utils.doLog("initCommentPost");
	$(".comment-post #comment-thankyou").hide();
}

$(document).ready(NICK.comments.initCommentPost);


NICK.comments.loadComments = function(type,mn,url,start,stop,sort) {
	NICK.comments.urlAlias = url;
	
	var mn 		= mn ? mn : null;
	var url 	= url ? url : null;
	var start 	= start ? start : null;
	var stop 	= stop ? stop : null;
	var sort 	= sort ? sort : null;
	var comments = null;
	
	var commentCall = NICK.comments.buildComURL(mn,url,start,stop,sort);
	
	$.ajax({
		type:"get",
		url:commentCall,
		dataType:"html",
		success: function(c){ NICK.comments.displayComments(type,c,stop);},
		error: function(m) {return 'no comments'}
	})
	
	if (comments) return comments;
}

NICK.comments.loadShoutbox = function(type,start,stop,imgpath) {

	var limit=5;
	var start 	= start ? start : null;
	var stop 	= stop ? stop : limit;
	var comments = null;
	
	if(NICK.config.SITE_NAME == "nicktoons"){
		var commentCall = '/api/comments/1.0/search?parentSiteAlias=site-nicktoons&parentContentSuperType='+type+'s';
	}else{
		var commentCall = '/api/comments/1.0/search?parentContentSuperType='+type+'s';
	}
	if (start) commentCall += '&start='+start;
	if (stop) commentCall += '&rows='+stop;
	
	$.ajax({
		type:"get",
		url:commentCall,
		dataType:"json",
		success: function(c){ NICK.comments.displayShoutbox('shoutbox',c,limit);},
		error: function(m) {return 'no comments'}
	})
	
	if (comments) return comments;
}

NICK.comments.buildComURL=function(mn,u,start,stop,sort) {
	
	var url = "/api/comments/1.0/display?";
	
	if (mn!=null) 	url += "memberName="+mn;
	
	if (NICK.comments.areBothNotNull(mn,u)) 
		url += "&";
	
	if (u!=null)  url += "urlAlias="+u;
	
	if ( NICK.comments.areBothNotNull(mn,start) || 
	  	 NICK.comments.areBothNotNull(u,start) ) 
		url += "&";
	
	if (start != null) url+="start="+start;
	
	if (NICK.comments.areBothNotNull(mn, stop) ||
		NICK.comments.areBothNotNull(u, stop) ||
		NICK.comments.areBothNotNull(start, stop)) {
		if (stop > start) 
			url += "&";
	}
		
	if (stop != null && stop>start) url+="rows="+stop;
	
	return url;
}

NICK.comments.areBothNotNull=function(a,b) {
	return (a != null && b != null);
}

NICK.comments.displayComments = function(type,comments,stop){
	var comlist ='';
/*	if (json_comments.response.numFound == 0) {
		comlist='';
	} else {
		printnumber = (stop>json_comments.response.numFound)?json_comments.response.numFound:stop;
		for (q = 0; q < printnumber; q++) {
			comlist += NICK.comments.buildCommentLI(type, json_comments.response.docs[q].memberName_t, json_comments.response.docs[q].comment_t);
		}
		
	} */

	$("#commentlist").html(comments);
	return false; 
}

NICK.comments.displayShoutbox = function(type,json_comments,l,imgpath){
	var comlist ='';

	if (json_comments.response.numFound > 0) {
		for (q = 0; q < l; q++) {
			current_type = json_comments.response.docs[q].parentContentSuperType_t;
			current_com = json_comments.response.docs[q];
			thumbnail = (current_com.wideThumbnail_t) ? NICK.utils.getImage(current_com.wideThumbnail_t[0],25):'';
			comlist += NICK.comments.buildCommentLI(
							type, 
							current_com.memberName_t, 
							current_com.comment_t, 
							thumbnail,
							current_com.parentTitle_t, 
							current_com.parentUrlAlias_t,
							current_type
						);
		}
	} else {
			// if no shoutbox data, pull the shoutbox
			//$("#shoutbox-comments").hide();
			return false;
	}
	$("#shoutbox-comments").html(comlist);
	return false;
}

NICK.comments.buildCommentLI=function(type,username,usercomment,s_image,s_gametitle,s_gamelink,contenttype) {
	switch(type){
			case 'video':
			case 'game':
				
				// adds a class 'odd' every other comment, to enable zebra striping...
				var odd = '';
				var mod = q % 2;
				if ( mod != 0 ) {odd=''} else {odd=' odd'};

				var licontent='<li class="clearfix'+ odd +'">'+
							//'<img class="user-avatar" src="/assets/default_avatar.png" width="60" height="60" />'+
							'<div class="comment"><span class="username">'+username+'</span>'+
							'<p class="color-light">'+usercomment+'</p>'+
	                   		'</div></li>';break;
			case 'shoutbox':
				var shoutlink = NICK.comments.buildShoutLink(contenttype,s_gamelink);
				var licontent = '<li class="clearfix">'+
									'<div class="shoutbox-item">' +
										'<div class="shoutbox-image"><a href="'+shoutlink+'"><img src="'+s_image+'" border="0" /></a></div>'+
										'<div class="shoutbox_info">'+
											'<div class="shoutbox-username">'+username+'</div>'+
											'<div class="shoutbox-gametitle"><a href="'+shoutlink+'">'+s_gametitle+'</a></div>'+
											'<div class="shoutbox-comment">'+usercomment+'</div>'+
										'</div>'+
									'</div>'
								'</li>';
			default: '<li>No type found</li>';break;
		}

	return licontent;
}


NICK.comments.buildShoutLink= function(ctype,link) {
	var l = "";
	
	if (ctype=='video')  l = '/videos/clip/'+link+'.html'; 
	if (ctype=='game')  l = '/games/'+link+'.html'; 
	if (ctype=='playlist')  l = '/videos/playlist/'+link+'.html'; 

	return l;
}

