var totalPagesNumber, currentPageNumber, oCurrentPage;
var PREV = 'prev';
var NEXT = 'next';
var NON_CLICKABLE = false;
var CLICKABLE = true;
var SOUNDOFF_ANCHOR = '#soundoff';
//var jsonURL = 'http://srch8dev2.turner.com/cnnrelaunch/definitions.jsp';
//var jsonURL = 'http://search.cnn.com/definitions.jsp';
var jsonURL = 'http://searchapp.cnn.com/cnn-healthsearch/query.jsp';


//triggers loading sequence with nifty animation
function triggerLoading(displayPageid, paginationID) {
	oCurrentPage = new getObj(displayPageid);
	currentPageNumber = 1;
	var csiObj = CSIManager.getInstance();

	csiObj.setConfigForId(
		displayPageid, 
		{"pageNumber": currentPageNumber});
	
	csiObj.call(
		jsonURL,
		cnnSearchQueryString+currentPageNumber,
		[paginationID,displayPageid],
		[loadPaginationHandler, loadSearchResultsHandler], 
		true);
}

function loadSearchResultsHandler(json,id,config){
	var listingHTML = cnnGetListing(json);
	copy2WorkArea(listingHTML, 'Page'+config.pageNumber);
	if(config.setPagination){
		cnnSetPagination(config.pageNumber);
	}
	return listingHTML;
}

function loadPaginationHandler(json,id,config){
	var cnnNumArticlesFound = (typeof(json.articlesFound) == "number")?json.articlesFound:0;
	var paginationHTML = cnnInitPagination(cnnNumArticlesFound, cnnItemsPerPage);
	return paginationHTML;
}

function cnnGetListing(json){
	try{
		var returnString = '';
		var returnStringArr = new Array();
		returnStringArr.push('<div class="cnnLatestTopics"><div class="cnnLatestBox"><h3 class="cnnh3title">Latest from CNN<\/h3><\/div><div class="clear"><\/div><\/div>');
		if(isArray(json.contentItems)){
			for( var i = 0; i < json.contentItems.length; i++ ){
				var ciObj = new SearchItem(json.contentItems[i]);
				returnStringArr.push(ciObj.listHTML());
			}
		}
	} catch(e) {
		return 'Could not retrieve Latest News '+e.message;
	}
	return returnStringArr.join('');
}

function isArray(obj){
	return (typeof(obj)=="undefined" || typeof(obj.length)=="undefined")?false:true;
}

function copy2WorkArea(theHTML, pageID){
	if($('cnnWorkArea')){
		if(!$(pageID)){
			var workDiv = document.createElement('div');
			var idAttr = document.createAttribute("id");
			idAttr.nodeValue = pageID;
			workDiv.setAttributeNode(idAttr);
			workDiv.innerHTML = theHTML;
			$('cnnWorkArea').appendChild(workDiv);
		}
	}
}

function SearchItem(obj){
	this.headline = obj.headline;
	this.url = obj.url;
	this.summary = obj.summary;
	this.wool = obj.wool;
	this.ts = obj.ts*1000;
	this.timestampHTML = cnnRenderMTTimeStamp(obj.ts*1000);
	this.hasComments = obj.hasComments;
	this.commentCount = obj.commentCount;
	if(isArray(obj.videos)){
		this.videoURL = obj.videos.length > 0? obj.videos[0].url:'';
	}
	if(isArray(obj.galleries)){
		this.galleryURL = obj.galleries.length > 0? obj.galleries[0].url:'';
	}
	if(isArray(obj.otherTabs)){
		this.otherTabURL = obj.otherTabs.length > 0? obj.otherTabs[0].url:'';
	}
}

SearchItem.prototype = {
	listHTML:function()
	{
		var html = [];
		html.push('<div class="cnnRelatedArticle">');
		html.push(this.timestampHTML);
		html.push('<h3>');
		if(this.wool){
			html.push('<span class="cnnWOOL">'+this.wool+': </span>');
		}
		html.push('<a href="'+this.url+'">'+this.headline+'</a></h3>');
		html.push('<p>'+this.summary+'</p>');
		if(this.videoURL || this.galleryURL || this.otherTabURL ){
			html.push('<div class="cnnRelatedItems">');
			if(this.videoURL){
				html.push('<a href="'+this.videoURL+'"><img src="http://i.cdn.turner.com//cnn/.element/img/2.0/mosaic/tabs/icn_videos.gif">Video</a>');
			}
			if(this.galleryURL){
				html.push('<a href="'+this.galleryURL+'"><img src="http://i.cdn.turner.com//cnn/.element/img/2.0/mosaic/tabs/icn_photos.gif">Photos</a>');
			}
			if(this.otherTabURL){
				html.push('<a href="'+this.otherTabURL+'"><img src="http://i.cdn.turner.com//cnn/.element/img/2.0/mosaic/tabs/interactive.gif">More</a>');
			}
			html.push('</div>');
		}
		if(this.hasComments && typeof(this.commentCount) == "number"){
			html.push('<span class="cnnLatestComments">'+this.commentCount+' comments</span>');
		}
		html.push('</div>');
		return ( html.join('') );
	}
};

// ----------------------------------------------------------------------------

function cnnInitPagination(articlesFound, cnnItemsPerPage) {
	if(articlesFound >100) { //limit us to 10 pages. Enforcement was in the jsp before, moving to the JS.
		articlesFound = 100;
	}
	var strPagerContent = [];
	if (articlesFound==0)
	
	{
	strPagerContent.push('<span class="cnnWOOL">There are no current headlines for this topic.</span>');
	return strPagerContent.join('');
	}
	
  totalPagesNumber = Math.ceil(articlesFound / cnnItemsPerPage);
  var strPagerContent = [];
  strPagerContent.push('<table><tr><td align="center"><table class="cnnPagination" align="center"><tr>');
  strPagerContent.push('<td id="liGoToPagePrev">'+getNavigationButton(PREV, NON_CLICKABLE)+'</td>');
  for(var i=0; i<totalPagesNumber; ++i) {
    var j = i+1;
	if(j==1){
		strPagerContent.push('<td id="liGoToPage' + j + '">'+getNavigationButton(j, NON_CLICKABLE)+'</td>');
	} else {
		strPagerContent.push('<td id="liGoToPage' + j + '">'+getNavigationButton(j, CLICKABLE)+'</td>');
	}
  }
  var nextButtonHTML = (totalPagesNumber <= 1)?getNavigationButton(NEXT, NON_CLICKABLE):getNavigationButton(NEXT, CLICKABLE);
  strPagerContent.push('<td id="liGoToPageNext">'+nextButtonHTML+'</td>');
  strPagerContent.push('</tr></table></td></tr></table>');
  return strPagerContent.join('');
}

function getNavigationButton(page, isClickable){
	var buttonHTML = '';
	if(page == PREV ){
		if(isClickable) {
			buttonHTML = '<a href="#aCurrentPage" id="buttonPagePrev" class="pagerButton" onClick="goToPage(\'prev\');" onMouseOver="window.status = \'\'; return true;"><b class="cnnArrows">&laquo;</b> Previous</a>';
		} else {
			buttonHTML = '<span class="pagerButtonActive prevNextPagerButtonActive"><b class="cnnArrows">&laquo;</b> Previous</span>';
		}
	} else if(page == NEXT ){
		if(isClickable) {
			buttonHTML = '<a href="#aCurrentPage" id="buttonPageNext" class="pagerButton" onClick="goToPage(\'next\');" onMouseOver="window.status = \'\'; return true;">Next <b class="cnnArrows">&raquo;</b></a>';
		} else {
			buttonHTML = '<span class="pagerButtonActive prevNextPagerButtonActive">Next <b class="cnnArrows">&raquo;</b></span>';
		}
	} else {
		if(isClickable) {
			buttonHTML = '<a href="#aCurrentPage" id="buttonPage' + page + '" class="pagerButton" onClick="goToPage(' + page + ');">' + page + '</a>';
		} else {
			buttonHTML = '<span class="pagerButtonActive">' + page + '</span>';
		}
	}
	return buttonHTML;
}

function cnnSetPagination(page) {
	var oldPageNumber;
	// Set page, currentPageNumber and oldPageNumber
	if(page && page == 'next')
	  page = currentPageNumber + 1;
	else if(page && page == 'prev')
      page = currentPageNumber - 1;
	if(!page || isNaN(page) || page < 1)
      var page = 1;
	else if(page > totalPagesNumber)
      page = totalPagesNumber;
	if(currentPageNumber == page) return; else {
      oldPageNumber = currentPageNumber;
      currentPageNumber = page;
	}
	// Change current page number style and link
    if((o = new getObj('buttonPage' + page)) && o.obj)
      o.obj.className = 'pagerButtonActive';
    // Remove link on active element
    if((o = new getObj('liGoToPage' + oldPageNumber)) && o.obj && o.obj.innerHTML )
      o.obj.innerHTML = getNavigationButton(oldPageNumber, CLICKABLE);
    if((o = new getObj('liGoToPage' + page)) && o.obj && o.obj.innerHTML) {
      o.obj.innerHTML = getNavigationButton(page, NON_CLICKABLE);
    }

    // Change previously viewed page number style
    if((o = new getObj('buttonPage' + oldPageNumber)) && o.obj)
      o.obj.className = 'pagerButtonViewed';

    // Show/Hide prev button if on first page
    o = new getObj('liGoToPagePrev');
    if(page == 1) {
      o.obj.innerHTML = getNavigationButton(PREV, NON_CLICKABLE);
    } else if(page > 1) {
      o.obj.innerHTML = getNavigationButton(PREV, CLICKABLE);
    }
    // Show/Hide next button if on last page
    o = new getObj('liGoToPageNext');
    if(page == totalPagesNumber || totalPagesNumber == 1) {
      o.obj.innerHTML = getNavigationButton(NEXT, NON_CLICKABLE);
    } else if(totalPagesNumber != 1 && page < totalPagesNumber) {
      o.obj.innerHTML = getNavigationButton(NEXT, CLICKABLE);
    }
}

function goToPage(page) {
	if ( page == PREV ) {
		page = currentPageNumber - 1;
	} else if ( page == NEXT ) { 
		page = currentPageNumber + 1;
	}

  var o = new getObj('Page' + page);
  if(o && o.obj) {
    oCurrentPage.obj.innerHTML = o.obj.innerHTML;
	cnnSetPagination(page);
  } else {
	goToPage_Helper(page);
  }
}

function goToPage_Helper(pageNumber){
	var csiObj = CSIManager.getInstance();
	csiObj.setConfigForId(displayPageid, {"pageNumber": pageNumber,"setPagination": true});
	csiObj.call(jsonURL,cnnSearchQueryString+pageNumber,displayPageid, loadSearchResultsHandler, true);
}
// -->

