var TALKS_PER_PAGE = 12;	// note that the div holder is set to the proper hieght to hold this many talks

// callback function when response is successfully received from the service
function onSuccess(oRequest, oResponse, oPayload){
	talks = oResponse.results;
	numberOfPages = Math.ceil(talks.length/TALKS_PER_PAGE);
	// alert('there are ' + talks.length + ' talks and ' + numberOfPages + ' pages');
	gotoPage(1);
}

// callback function when call to service fails
function onFailure(oRequest,oResponse,oPayload) {
		alert("Sorry, we could not find any talks for this theme.");
}

/*
 * 
 * trigger an animation to fade out the current page of talks on a page navigation.
 * Once the animation is complete, its subscriber will actually do the page change
 * 
 */
function gotoPage(n) {
	currentPage = n;
	pageNavCode = YAHOO.Tools.printf('<p>Showing page {0} of {1} &nbsp;&nbsp({2} total talks)</p><ul>',currentPage,numberOfPages, talks.length);
	// generate each page link
	var pageLink; 	
	for (var i=1; i<=numberOfPages; i++) {
		if (i == currentPage) {
			pageLink = '<li><a class="selected">' + currentPage + '</a></li>';
		}
		else {
			pageLink = YAHOO.Tools.printf('<li><a href="javascript:gotoPage({0});">{0}</a></li>',i);
		}
		var separator = (i != 1) ? ' | ' : '';
		pageNavCode += separator + pageLink;
	}
	var nextPageLink = '&nbsp;&nbsp;<li><a class="selected">Next &rsaquo;</a></li>';
	if (currentPage != numberOfPages) {
		nextPageLink = YAHOO.Tools.printf('&nbsp;&nbsp;<li><a href="javascript:gotoPage({0});">Next &rsaquo;</a></li>',currentPage + 1); 
	}
	pageNavCode += nextPageLink + '</ul>'; 
	document.getElementById('pageNavigator').innerHTML = pageNavCode;
	fadeOut.animate();
}

/*
 * 
 * This method is a subscriber to the fadeOut animation and will 
 * paint the talks for the currentpage and fade it in.
 * 
 */
function onFadeOutComplete() {
	var output = document.getElementById('talkList');
	output.innerHTML = '';
	var start = (currentPage-1) * TALKS_PER_PAGE;
	var end = Math.min(start + TALKS_PER_PAGE,talks.length);
	for (var i=start; i<end; i++) {
		var talk = talks[i];
		output.innerHTML += talk.markup;
	}
	fadeIn.animate();
}

var dsTalks = new YAHOO.util.DataSource("/themes/talksRPC/id/"); 
dsTalks.responseType = YAHOO.util.DataSource.TYPE_JSON; 
dsTalks.responseSchema = {
	resultsList: "resultSet.result",
	fields: ['talkId','talkURL','photoURL','title','duration','datePosted']
};
var talks = new Array();
var currentPage = 0;
var numberOfPages = 0;
// register the callbacks for the service
var oCallback = {success: onSuccess, failure: onFailure, scope: this};
// animations to be used when changing pages
var fadeOut = new YAHOO.util.Anim('talkList', {opacity:{from:1,to:0}}, .25); 
fadeOut.onComplete.subscribe(onFadeOutComplete);
var fadeIn = new YAHOO.util.Anim('talkList', {opacity:{from:0,to:1}}, .25);