/*
 * jQuery plugins for Convio TeamRaiser[TM]
 * Version 1.1 (02/08/2011)
 * @author Brian P. Mucha (bmucha@childrensmemorial.org)
 */
 
/*
 * The getParticipantRoster() method provides a simple way of showing a list
 * of TeamRaiser participants with links to their personal fundraising pages.
 *
 * getParticipantRoster() takes the following arguments:
 *
 * proxyURL (required)
 * nonsecureConvioPath (required)
 * secureConvioPath (required)
 * apiKey (required)
 * fr_id (required)
 * loadingImage (optional)
 * loadingText (optional)
 * list_sort_column( optional)
 * list_ascending (optional)
 * list_page_size (optional)
 * list_page_offset (optional)
 *
 *
 * Example: 
 * 
 * <script type="text/javascript">
 * 
 * $(document).ready(function() {
 * 	$('#rosterList').getParticipantRoster({
 * 		'proxyURL':'AjaxProxy?auth=[[S86:true]]&cnv_url=',
 * 		'nonsecureConvioPath':'http://[[S29:DOMAIN]][[S29:PATH]]',
 * 		'secureConvioPath':'https://'+'[[S29:SECURE_DOMAIN]][[S29:SECURE_PATH]]',
 * 		'apiKey':'[[S0:CONVIO_API_KEY]]',
 * 		'fr_id':'[[S334:fr_id]]',
 * 		'loadingText': 'Loading...',
 * 		'showTeams': 'true',
 * 		'list_page_size': '40',
 * 		'list_page_offset': '0'
 * 	})
 * });
 *  	function getPrev()
 * 	{
 * 		$('#rosterList').getParticipantRoster('prev');
 * 	}
 * 	function getNext()
 * 	{
 * 		$('#rosterList').getParticipantRoster('next');
 * 	}
 * </script>
 */
 
 (function( $ ){

	var methods = 
	{
		init : function( options ) 
		{
			settings = $.extend( {}, defaults, options );
			markLoading( this, settings );
			this.data('settings', settings);	// Store the state for pagination.
			updateElement( this, settings );
		},
		
		prev : function( ) 
		{
			settings = $.extend( {}, defaults, this.data('settings') );	// Use stored state.
			markLoading( this, settings );
			var oldOffset = parseInt(settings['list_page_offset']) ;
			if (oldOffset > 0) 
			{
				settings['list_page_offset'] = (--oldOffset).toString();
			} else {
				settings['list_page_offset'] = '0';
			}
				this.data('settings', settings);	// Store the state for pagination.
				updateElement( this, settings );
		},
		
		next : function( ) 
		{
			settings = $.extend( {}, defaults, this.data('settings') );	// Use stored state.
			markLoading( this, settings );
			var oldOffset = parseInt(settings['list_page_offset']) ;
			settings['list_page_offset'] = (++oldOffset).toString();
			this.data('settings', settings);	// Store the state for pagination.
			updateElement( this, settings );
		}
	};

	var defaults =
	{
		'proxyURL'				: null,
		'nonsecureConvioPath'	: null,
		'secureConvioPath'		: null,
		'apiKey'					: null,
		'fr_id'					: null,
		'loadingImage'			: null,
		'loadingText'				: null,
		'list_sort_column'		: 'last_name',
		'list_ascending'			: 'true',
		'list_page_size'			: '25',
		'list_page_offset'			: '0',
		'personalPageDelimiter'	: ', ',
		'teamPageDelimiter'		: ' - '
	};

	// Public Functions
	
	$.fn.getParticipantRoster = function( method ) 
	{
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +	method + ' does not exist on jQuery.getParticipantRoster' );
		}
	};
	
	// Private Functions
	
	function markLoading( element, settings )
	{
			$('.rosterentry').remove();
			if(settings.loadingImage&&settings.loadingText)
				element.append('<p id="rosterloading""><img alt="' + settings.loadingText + '" src="' + settings.loadingImage + '" />' + settings.loadingText + '</p>');
			else if(settings.loadingImage)
				element.append('<p id="rosterloading"><img alt="' + settings.loadingText + '" src="' + settings.loadingImage + '" /></p>');
			else if(settings.loadingText)
				element.append('<p id="rosterloading">' + settings.loadingText + '</p>');
	}

	function updateElement( element, settings )
	{
		var dataString =
			'method=getParticipants' +
			'&v=1.0' +
			'&api_key=' + settings.apiKey +
			'&response_format=json' +
			'&suppress_response_codes=true' +
			'&fr_id=' + settings.fr_id +
			'&list_sort_column=' + settings.list_sort_column +
			'&list_ascending=' + settings.list_ascending +
			'&list_page_size=' + settings.list_page_size +
			'&list_page_offset=' + settings.list_page_offset +
			'&first_name=%%%';

		var requestURL = settings.proxyURL + escape(settings.secureConvioPath + 'CRTeamraiserAPI?' + dataString);

		$.getJSON(requestURL, function(data)
		{
			if( data.errorResponse )
			{
				element.html("<p>(" + data.errorResponse.message + ")</p>");
			} else {
				$('#rosterloading').remove();
				var trObject=data.getParticipantsResponse.participant;
				if ($(trObject).size()==1)
				{
					// TODO: trObject is a participant, not a collection.
				} else if ($(trObject).size()>1) {
					$.each(trObject,function()
					{
						var newEntry = $('<p />').attr('class', 'rosterentry' );
						newEntry.append(this.name.first + " " + this.name.last);
						newEntry.append(settings.personalPageDelimiter);
						newEntry.append("<a href=\"" + this.personalPageUrl + "\">Personal Page</a>");
						if(this.teamName ) { 
							newEntry.append(settings.teamPageDelimiter);
							newEntry.append("<a href=\"" + this.teamPageUrl + "\">" + this.teamName + "</a>");
							if(this.aTeamCaptain=="true") { newEntry.append(" (Captain)"); }
						}
						element.append(newEntry);
					});
				} else {
					var newEntry = $('<p />').attr('class', 'rosterentry' );
					newEntry.append('(end of list)');
					element.append(newEntry);
				}
			}
		});
	};

})( jQuery );

