var browser = navigator.appName;

Event.observe( window, 'load', function() {
	var cnnCommentsClosed = false;

	if (typeof cnnFirstPub != "undefined") {
		var cnnTimeDiff = cnnCurrTime.getTime() - cnnFirstPub.getTime();
		var hoursDifference = Math.floor(cnnTimeDiff / 1000 / 60 / 60);
		if (hoursDifference > 23) {
			cnnCommentsClosed = true;
		}
	}
	if (typeof cnnExtendCommenting != "undefined" && cnnExtendCommenting) {
		cnnCommentsClosed = false;
	}
	if (typeof cnnCommentsClosed != "undefined" && cnnCommentsClosed) {
		if ($('cnnCommentFooter')) {
			$('cnnCommentFooter').remove();
		}
		if ($('cnnROCFrm')) {
			$('cnnROCFrm').remove();
		}
		if ($('cnnROCFrmComplete')) {
			$('cnnROCFrmComplete').innerHTML = "<br>This story is no longer available for comments, though you may read comments that were posted previously. Browse other stories for new opportunities to comment on the latest news.";
			$('cnnROCFrmComplete').show();
		}
	}
	if ($('cnnROCFrm')) {
		$('cnnROCFrm').show();
	}
});

function showCommentForm() {
	if ( !$('cnnROCFrm').visible() ) {
		new Effect.ScrollTo('cnnExpandComments', {
			duration: 0.5,
			beforeStart : function() { 
				CNN_toggleSubmissionForm('cnnROCFrm', 'cnnROCFrmComplete'); 
			}
		});
	} else {
		new Effect.ScrollTo('cnnExpandComments', { duration: 0.5 }	);
	}
}

var QaComments = {
	name			: null,
	initCnt 		: 5,
	moreCnt 		: 25,
	apiUrl		: '',
	pagingEl 	: null,
	commentEl	: null,
	errDivId		: 'commentErrors',
	init	 		: function( name, apiUrl, commentEl, pagingEl, initCnt, moreCnt ) {
		this.name 		= name;
		this.apiUrl		= apiUrl;
		this.pagingEl	= pagingEl;
		this.commentEl	= commentEl;
		this.initCnt	= (initCnt?initCnt:5);
		this.moreCnt	= (moreCnt?moreCnt:25);
	},
	genMoreLinks : function( topLnk, nextLnk, linkSep ) {
		this.pagingEl.update( [
			'<span id="',topLnk,'" style="display:none;">',
			'<a href="javascript:void(0)" onclick="',this.name,'.showOnlyTop();">',
			'Last ',this.initCnt,' comments only</a></span>',
			'<span id="',linkSep,'" style="display:none"> | </span>',
			'<span id="',nextLnk,'" style="display:none;">',
			'<a href="javascript:void(0)" onclick="',this.name,'.loadNextComments();">',
			'Next ',this.moreCnt,' comments &raquo;</a></span>'
		].join('') );
	},
	genCommentsHtml : function(commentsId) {
		this.commentEl.hide();
		this.commentEl.update( [
			'<div id="',this.errDivId,'" style="display:none;"></div>',
			'<h4 class="cnnQAComAhead">Community Answers</h4>',
			'<div id="',commentsId,'"></div>'
		].join('') );	
	},
	genCommentDiv : function(clObject) {
		var CNN_comment =	null; 
		var moreLnk = ' ...<a href="javascript:void(0);" onclick="cnnShowMore(this);return false">more</a>';
		var lessLnk = '<a href="javascript:void(0);" onclick="cnnShowLess(this);return false;">&nbsp;less</a>';
		var loc = '';
	
		if(clObject['jf:location']) {
			loc = clObject['jf:location'];
		}	
	
		CNN_comment = [
			'<div class="cnnQAEAbox3">',
			'	<div class="cnnQAEAc1">',
			'		<p><strong>' , clObject['jf:author'] , '</strong><br/>',
			loc,
			'		</p>',
			'	</div>',
			'	<div class="cnnQAEAc2">',
			'		<p class="cnnQAtimestamp">' , cnnRenderTimeStamp(clObject.pubDate) , '</p>',
			'		<p class="cnnQABCAp">',
			clObject.description.truncate(300, moreLnk),
			'		</p>',
			'		<div class="cnnExtended" style="display:none;">',
			clObject.description,
			lessLnk,
			'		</div>',
			'	</div>',
			'	<div class="clear"></div>',
			'</div>'
		];
	
		return CNN_comment.join('');
	}
};

function CommentsObj( configObj ) {
	//// config setup
	this.configObj = configObj;
	var initCnt 	= configObj.initCnt;
	var moreCnt 	= configObj.moreCnt;
	var apiUrl		= configObj.apiUrl;
	var pagingEl 	= configObj.pagingEl;
	var commentEl	= configObj.commentEl;

	//// record keeping
	var This				= null; //used to track obj for async
	var initLnkEl		= null;
	var nextLnkEl		= null;
	var sepLnkEl		= null;
	var currentCnt		= 0;
	var currentPage	= 0;
	var loading 		= false;
	var pages			= [];
	var counts			= [];

	/**********************************
	 * Async Call Functions
	 *********************************/
	this.init = function() {
		//// loads the first n comments
		This = this;
		callCommentsApi( 
			this.initHandler, 
			initCnt + 1, 
			this.configObj.errDivId 
		);
	};

	this.loadNextComments = function() {
		//// shows the page if it is loaded, loads it if it isn't
		var currPgNum = currentPage + 1;

		if (pages.length >= currPgNum) {
			this.effects.blindDown($(pages[currentPage]));
			this.toggleLinks( true, (counts[currentPage] > ((currentPage+1)*moreCnt+initCnt)) );
			++currentPage;
		} else {
			This = this;
			callCommentsApi( 
				this.moreHandler, 
				currPgNum * moreCnt + initCnt + 1, 
				this.configObj.errDivId
			);
		}
	};

	/**********************************
	 * Async Call Handler Functions
	 *********************************/
	this.initHandler = function(obj) {
		loading = false;

		var initLnkName 	= 'topLink';
		var nextLnkName 	= 'nextLink';
		var sepLnkName		= 'linkSeperator';
		var allDivName		= 'allComments';

		try {
			if ( hasNoResults(obj) ) { return ''; }
	
			var items = obj.rss.channel.item;
			var html = new Array();

			if ( items && !items.length ) {
				currentCnt = 1;
				html.push( This.configObj.genCommentDiv(items) );			
			} else {
				currentCnt = (items.length < initCnt ? items.length : initCnt);
				for ( var i = 0 ; i < currentCnt ; ++i ) {
					html.push( This.configObj.genCommentDiv(items[i]) );
				} 
			}
	
			This.configObj.genMoreLinks( initLnkName, nextLnkName, sepLnkName );
			initLnkEl	= $(initLnkName);
			nextLnkEl 	= $(nextLnkName);
			sepLnkEl		= $(sepLnkName);

			This.configObj.genCommentsHtml(allDivName);
	
			$(allDivName).update( html.join('') );	
			$(commentEl).show();
				
			if ( items.length > initCnt ) {
				This.toggleLinks( false, true );
			}
		} catch (e) {
			return "Error getting initial set of results: ERR:" + e;
		} finally {
			This = null;
		}
		return '';
	};

	this.moreHandler = function(obj) {
		loading = false;
		
		if ( hasNoResults(obj) ) { return ''; }

		try {
			var html = ['<div id="commentsPage_', currentPage, '" style="display:none;">'];
			var items 	= obj.rss.channel.item;
			var maxCnt 	= ((currentPage+1) * moreCnt + initCnt);
			var i = ((currentPage*moreCnt)+initCnt);
			
			currentCnt = (items.length < maxCnt ? items.length : maxCnt);
			
			while (  i < currentCnt ) {
				html.push( This.configObj.genCommentDiv(items[i++]) );
			}
	
			html.push('</div>');
	
			new Insertion.Bottom(commentEl,html.join(''));
			pages[currentPage] = $('commentsPage_'+currentPage);
			counts[currentPage] = items.length;
	
			This.effects.blindDown('commentsPage_'+currentPage);
			++currentPage;
			This.toggleLinks( true, (items.length > maxCnt) );
		} catch(e) {
			return "Error getting next set of results: ERR:" + e;
		} finally {
			This = null;
		}

		return '';
	};

	/**********************************
	 * CSIManager Helper Function 
	 *********************************/
	function callCommentsApi(loadHandler, count, errDivId) {
		if(loading){ return; }
		loading=true;

		CSIManager.getInstance().call(
			apiUrl, [
				'full=true&outputType=JSON_BOXED&forumName=',
				cnnForum,
				'&threadName=',
				cnnThread,
				'&numItems=',
				count
			].join(''),
			errDivId, 
			loadHandler, 
			false, 
			'cnnComments'	
		);
	}

	function hasNoResults(obj) {
		return (
			typeof obj.rss.channel.item == 'undefined' || 
			obj.rss.channel.item == null || 
			obj.rss.channel.item.length == 0 
		); 
	}
	
	/**********************************
	 * DOM Helper Functions
	 *********************************/
	this.showOnlyTop = function() {
		pages.each(function(item, i) {
			$(item).hide();
		});

		currentPage = 0;
		
		this.toggleLinks( false, true );
		this.effects.scrollUp(commentEl);
	};

	this.effects = {
		scrollUp 	: function(el) { 
			new Effect.ScrollTo(el, { 
				duration : 0.5 
			}); 
		},
		blindDown 	: function(el) {
			new Effect.BlindDown(el, {
				beforeStart	: function() {
					pagingEl.hide();
				},
				afterFinish	: function() {
					pagingEl.show();
				}
			});
		}
	};

	this.toggleLinks = function(showOnly, showNext) {
		if ( showOnly ) {
			$(initLnkEl).show();
		} else {
			$(initLnkEl).hide();
		}

		if ( showNext ) {
			$(nextLnkEl).show();
		} else {
			$(nextLnkEl).hide();
		}

		if ( showOnly && showNext ) {
			$(sepLnkEl).show();
		} else {
			$(sepLnkEl).hide();
		}

	};
};

/**********************************
 * List Helper Functions
 *********************************/
function cnnShowMore(el) {
	var block = document.getElementsByClassName('cnnExtended',el.parentNode.parentNode);
	if (block && block.length > 0) {
		el.parentNode.hide();
		block[0].show();
	}
}

function cnnShowLess(el) {
	var block = el.parentNode;
	var blockLinks = block.parentNode.getElementsByTagName('p');
	block.hide();
	if(browser == "Microsoft Internet Explorer") {
		blockLinks[2].show();
	}
	else {
		blockLinks[1].show();
	}
}

