/**
 * neat stuff
 */

function fDate(dt){
	//Jan 12 at 9:27 AM
	var m = Array('Jan.','Feb.','March','April','May','June','July','Aug.','Sept.','Oct.','Nov.','Dec.');
	var dt = new Date(dt);
	var hour = dt.getHours();
	if( hour > 12 ){
		hour = hour - 12;
		var ampm = 'PM';
	}else{
		var ampm = 'AM';
	}
	//return (m[dt.getMonth()] +' '+ dt.getDate() +' at '+hour+':'+dt.getMinutes() + ' ' + ampm);
	return '';
}

String.prototype.trunc = function(n){
                          return this.substr(0,n-1)+(this.length>n?'...':'');
                         };
/**
 * Pluckness.
 */

var a2p = {
	debug:false,
	comments:{
		_aIds_commentCount : Object(),
		_aIds_getComments : Object(),
		_aIds_getCommentsById : Object(),
		_responseHasErrors : function(responses){
			for(x=0;x<responses.length;x++){
				for (var exIdx = 0; exIdx < responses[x].ResponseStatus.Exceptions.length; exIdx++) {
					if (responses[x].ResponseStatus.Exceptions[exIdx].ExceptionLevel === PluckSDK.ResponseExceptionLevel.Error) {
						a2p.comments._debug("Error occurred getting this article");
						return true;
					}
				}
			}
			return false;
		},
		_debug : function(message){
			if (window.console && window.console.dir && window.console.log && a2p.debug == true){
				if(typeof(message) == 'object' || typeof(message) == 'array'){
					window.console.dir(message);
				}else{
					window.console.log(message);
				}
			}
		},
		queueCommentCount : function(id, key){
			if(typeof(this._aIds_commentCount[key]) == 'undefined'){ this._aIds_commentCount[key] = Array();}
			this._aIds_commentCount[key].push(id);
		},
		queueGetComments : function(id, key){
			if(typeof(this._aIds_getComments[key]) == 'undefined'){this._aIds_getComments[key] = Array();}
			this._aIds_getComments[key].push(id);
		},
		queueGetCommentsById : function(id, key){
			if(typeof(this._aIds_getCommentsById[key]) == 'undefined'){this._aIds_getCommentsById[key] = Array();}
			this._aIds_getCommentsById[key].push(id);
		},
		pluckDiscovery : function(callback){
			var searchRequest = new PluckSDK.DiscoverContentActionRequest(),
				localMaxEntries = 6,
				localMaxAge = 1,
				requests = [];
			// accessing global variables: maxEntires, maxAge
			if (typeof maxEntries !== 'undefined') { localMaxEntries = maxEntries; }
			if (typeof maxAge !== 'undefined') { localMaxAge = maxAge; }
			if (typeof callback === 'undefined') {
				callback = function () { a2p.comments._debug('invalid callback'); };
			}

			searchRequest.Type = PluckSDK.ContentType.Article;
			searchRequest.Activity = PluckSDK.DiscoveryActivity.Commented;
			searchRequest.MaximumNumberOfDiscoveries = localMaxEntries;
			searchRequest.Age = localMaxAge;
			requests.push(searchRequest);
			PluckSDK.SendRequests(requests, callback);
		},
		pluckArticles : function(callBack, key) {
			var typeofCallback = typeof callBack,
				typeofThis_aIds_commentCount_key = typeof this._aIds_commentCount[key];
			if(typeof(callBack) != 'function'){callBack = function(){ a2p.comments._debug('invalid callback');}}
			if(typeof(this._aIds_commentCount[key]) != 'undefined'){
				var requests = Array();
				for(x=0;x<this._aIds_commentCount[key].length;x++){
					requests[x] = new PluckSDK.ArticleRequest({"ArticleKey": new PluckSDK.ExternalResourceKey({'Key': this._aIds_commentCount[key][x]})});
				}
				PluckSDK.SendRequests(requests, callBack);
			}
		},
		getCommentsById: function(callBack, key){
			if(typeof(callBack) != 'function'){callBack = function(){a2p.comments._debug('invalid callback');}}
			if(typeof(this._aIds_getCommentsById[key]) == 'undefined'){this._aIds_getCommentsById[key] = Array();}

			var requests = Array();
			for(x=0;x<this._aIds_getCommentsById[key].length;x++){
				requests[x] = new PluckSDK.CommentRequest({"CommentKey": new PluckSDK.CommentKey({"Key":this._aIds_getCommentsById[key][x]})});
			}
		
			PluckSDK.SendRequests(requests, callBack);
			
		},
		getComments : function(callBack, key, ItemsPerPage, OneBasedOnPage, sortType, sortOrder){
			if(typeof(callBack) != 'function'){callBack = function(){a2p.comments._debug('invalid callback');}}
			if(typeof(this._aIds_getComments[key]) == 'undefined'){this._aIds_getComments[key] = Array();}
			if(typeof(ItemsPerPage) == 'undefined'){ItemsPerPage = 10;}
			if(typeof(OneBasedOnPage) == 'undefined'){OneBasedOnPage = 1;}
			if(typeof(sortType) == 'undefined'){sortType = new PluckSDK.TimestampSort();}
			if(typeof(sortOrder) == 'undefined'){sortOrder = PluckSDK.SortOrder.Descending;} // PluckSDK.SortOrder.Ascending

			var requests = Array();
			//var sortType = new PluckSDK.TimestampSort();
			//var sortType = new PluckSDK.ReviewRatingSort();
			sortType.SortOrder = sortOrder;
			for(x=0;x<this._aIds_getComments[key].length;x++){
				requests[x] = new PluckSDK.CommentsPageRequest({"ItemsPerPage":ItemsPerPage,"OneBasedOnPage":OneBasedOnPage,"SortType":sortType,"CommentedOnKey":new PluckSDK.ExternalResourceKey({"Key":this._aIds_getComments[key][x]})});
			}
		
			PluckSDK.SendRequests(requests, callBack);
		}
	}
};


/**
 * Pluck callbacks
 */

var featuredDomId = 'featured_comments';
function _checkFeatured(responses){
	var minComment = 12;
	if ( !a2p.comments._responseHasErrors(responses) ) {
		if( responses[0].Article.Comments.NumberOfComments >= minComment ){
			a2p.comments.queueGetComments(responses[0].Article.ArticleKey.Key, '_checkFeatured');
			a2p.comments.getComments(_displayFeatured, '_checkFeatured', 1,1, new PluckSDK.ScoreSort({'ScoreSortColumn':PluckSDK.ScoreSortColumn.PositiveCount, 'ScoreId':'Thumbs'}));
		}
	}
	$("#"+featuredDomId).css("display","none");
}

function _displayFeatured(responses){
	var minCommentScore = 6;
	if (responses[0].Items[0].Score >= minCommentScore){
		$("#"+featuredDomId).css("display","block");	
	}else{
		$("#"+featuredDomId).css("display","none");
	}
}

function _displayCommentCounts(responses){
	var domStyle = 'comment_count';
	for(var x=0;x<responses.length;x++){
		if( a2p.comments._responseHasErrors(Array(responses[x])) ){
			cc = 0;
			dn = $("."+domStyle+"_"+responses[x].ResponseStatus.Exceptions[0].Value);
		}else{
			dn = $("."+domStyle+"_"+responses[x].Article.ArticleKey.Key);
			cc = responses[x].Article.Comments.NumberOfComments;
		}
		if( cc > 0 ){
			if( cc == 1 ){
				cchtml = '<span>'+cc+'<span class="comments-words"> Comment</span></span>';
			}else{
				cchtml = '<span>'+cc+'<span class="comments-words"> Comments</span></span>';
			}
			for(var y=0;y<dn.length;y++){
				dn[y].innerHTML = cchtml;
			}
		}
	}
}

var discoveryItems = Array();
function _discoveryParse(responses){
	var i, libname = 'discovery';
	if (typeof featured_comments !== 'undefined') {
		for (i = 0; i < featured_comments.length; i += 1) {
			a2p.comments.queueGetCommentsById(featured_comments[i], libname);
		}

		if (!a2p.comments._responseHasErrors(responses)) {
			for (i = 0; i < responses[0].DiscoveredContent.length; i += 1) {
				discoveryItems[i] = Object();
				discoveryItems[i].key = responses[0].DiscoveredContent[i].ArticleKey.Key;
				discoveryItems[i].title = responses[0].DiscoveredContent[i].Title;
				discoveryItems[i].entryUrl = responses[0].DiscoveredContent[i].Url;
				discoveryItems[i].commentCount = responses[0].DiscoveredContent[i].Comments.NumberOfComments;
			}
			a2p.comments.getCommentsById(_populateDiscovery, libname);
		}
	}
}

function _populateDiscovery(responses){
	if (!a2p.comments._responseHasErrors(responses)) {
		var active_discussions = '',
			pop_comments = '',
			i;
		for (i = 0; i < responses.length; i += 1) {
			pop_comments +=
				'<div class="comment">' +
					'<div class="photo">' +
						'<img src="' + responses[i].Comment.Owner.AvatarPhotoUrl + '" alt="" />' +
					'</div>' +
					'<div class="body">' + 
						responses[i].Comment.Body.trunc(150) + '<br />' +
						'<a href="' + responses[i].Comment.Url + '">Read the full comment</a>' +
					'</div>' +
					'<div class="source">' +
						'<div class="commenter">by ' +
							'<a href="' + responses[i].Comment.Owner.PersonaUrl + '">' +
								responses[i].Comment.Owner.DisplayName +
							'</a>' +
							'<span class="timestamp">' + fDate(responses[i].Comment.PostedAtTime) + '</span>' +
						'</div>' +
					'<div class="article">on ' +
						'<a href="' + responses[i].Comment.Url + '">' +
							responses[i].Comment.Parent.Title +
						'</a>' +
					'</div>' +
				'</div>';
		}
		
		discoveryItems.sort(function (a, b) {
			return b.commentCount - a.commentCount;
		})
		for (i = 0; i < discoveryItems.length; i += 1) {
			active_discussions += 
				'<div class="article clearfix">' +
					'<div class="count">' + 
						discoveryItems[i].commentCount + 
					'</div>' +
					'<div class="headline">' +
						'<a href="' + discoveryItems[i].entryUrl + '" class="scTrackLink:headline">' +
							discoveryItems[i].title + 
						'</a>' +
					'</div>' +
				'</div>';
		}
		$("#pop_comments").html(pop_comments);
		$("#active_discussions").html(active_discussions);
	}
}

