//Allow us to template
/*
Use case:
var str="The {adjective} {color} {animal} jumps";
str.template({adjective: 'quick',
color: 'brown', animal: 'fox'}) */
String.prototype.replaceTemplate = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ?
r : a;
        }
    );

};

topicList=new Object();
topicList.cursors={
	'wireUp':function(){
		$('.prev').click(function(e) {
			e.preventDefault();
			topicList.entries.load(topicList.payload['previous_url']+"&json=1");
		})		
		$('.next').click(function(e) {
			e.preventDefault();
			topicList.entries.load(topicList.payload['next_url']+"&json=1");
		})		
	}
}


// items per page
// need to simplify and unify with backend
topicList.pagination={
	'wireUp':function(){	
		if(topicList.payload['base_pp_url'] != undefined){
			var strShow = 'Show ';
			$('#itemsdrop').show();
			$('#itemsdrop .headlink .item_count').text(strShow + topicList.payload['items_per_page']);
			$('.pp_10').click(function(e) {
				e.preventDefault();
				topicList.entries.load(topicList.payload['base_pp_url']+"&items=10&json=1");
				$('#itemsdrop .headlink .item_count').text(strShow + '10');
			});
			$('.pp_20').click(function(e) {
				e.preventDefault();
				topicList.entries.load(topicList.payload['base_pp_url']+"&items=20&json=1");
				$('#itemsdrop .headlink .item_count').text(strShow + '20');
			});
			$('.pp_50').click(function(e) {
				e.preventDefault();
				topicList.entries.load(topicList.payload['base_pp_url']+"&items=50&json=1");
				$('#itemsdrop .headlink .item_count').text(strShow + '50');
			});	
			$('.pp_all').click(function(e) {
				e.preventDefault();
				topicList.entries.load(topicList.payload['base_pp_url']+"&items=all&json=1");
				$('#itemsdrop .headlink .item_count').text(strShow + 'All');
			});
		}else{
			$('#itemsdrop').hide();
		}
	}
}

topicList.topButtons={
	'container':'.topOptions',
	'wireUp':function(){
		var that=this;
		that.container=$(that.container);
		$('followDefault');
		//followDefault
	}
}
//Once you clicked Customize your Klist this object controls functionality
topicList.myList={
	'wireUp':function(){
		var that=this;

		//Initialize data container for twitter IDs in my list
		$('#mylist').data('twitterIds',new Array());
		
		// Enable the remove from list links
		$('#list a').live('click', function() {
			//Remove from data
			var twitterId=$(this).parent().data('twitterId');
			$li = $(this).closest('li');
			$entry = $li.data('entry')

			that.removePerson(twitterId,$entry);
			topicList.people.unselect(twitterId,$entry);
			return false;
		})

		//Wire up add user link
		var $addUser=$('#mylist .console input.add').click(function(e){
			topicList.entries.mode = 'edit';
			var screenName=$(this).siblings('input.text').val();
			screenName=$.trim(screenName);
			var url='/profile/lists/getUser/'+screenName+'/';
			//var params={'screen_name':screenName};
			$.getJSON(url,null,function(data,textStatus){
				//Error checking here
				var user=data;
				$entry=topicList.people.addInfluencer(user); //Add to data and people view
				topicList.people.select(user.id,$entry); //User is now clicked
				that.addPerson(user.id,$entry);  //Add to my list
			});
		});

		//Make enter key work as well
		$('#mylist .console input.text').keyup(function(e){
			if(e.which==13){
				e.preventDefault();
				$addUser.trigger('click');
			}
		});

		//that.wireEdit();

		//Save button for list
		$('#rightbox .listMaker .save').click(function(e){
			e.preventDefault();
			e.stopPropagation();

			//User has not added any people to their list yet
			if ( $('#mylist').data('twitterIds').length==0 ){
				$('.emptyListDialog').dialog({
					beforeclose: function(e){ $(this).dialog('destroy') },
					dialogClass: 'dialog',
					draggable:false,
					modal:true,
					resizable:false
				});
				return false;
			}

			$(this).css('opacity',.3);

			var twitterIds=$('#mylist').data('twitterIds');
			var twitterIds=$.toJSON(twitterIds);

			//Check if list name already has the word "Customized" in it
			if( $('.followKlistDialog input.listName').attr('value').indexOf('Customized') == -1 ) {
				//Rename the list name in the dialog to "Customized + <<ORIGINAL STRING>>"
				var currName='Customized '+$('.followKlistDialog input.listName').attr('value');
				$('.followKlistDialog input.listName').attr('value',currName);
			}
			//Popup dialog to prompt for name of list
			$('.followKlistDialog').dialog({
				//Hide the close button (X) in top right
				open:function(){
					var $dialog=$(this);
					//Wire up save button
					$(this).find('.save').click(function(e){
						$dialog.dialog('destroy');
						var name=$(this).siblings('input.listName').val();
						var slug = name.toLowerCase();
						slug = slug.replace(/ /gi, "-");
						var description=$(this).siblings('textarea.listDescription').val();
						//Make ajax call to save the list
						params={'name':name,
								'type':topicList.payload.type,
								'custom_list':'1',
								'topic': topicList.payload.topic,
								'description': description,
								'twitterIds':twitterIds};

						that.saveList(params,{
							'onSuccess':
							   function(data){
								//Replace the tweet url with the appropriate link to this list
								var tweetUrl=data.tweet_url;
								$('.successDialog a.tweetThis').attr('href',tweetUrl);
								$('.successDialog a.tweetThis').attr('target','_blank');
								$('.successDialog a.createEmailAlert').attr("onClick","listimonkey('"+topicList.payload.list_creator+"/"+slug+"','"+topicList.payload.topic+"','"+topicList.payload.email+"');return false;");
							   },
							'onNameTaken':
								function(){$('#rightbox .listMaker .save').css('opacity',1); return true;},
							'onError':
							//Make the "save list" button visible again
								function(){$('#rightbox .listMaker .save').css('opacity',1); return true;}
						});
					});
				},
				beforeclose: function(e){
				  $(this).dialog('destroy');
				  $('#rightbox .listMaker .save').css('opacity',1); //Make save button visible again
				},
				dialogClass: 'dialog',
				draggable:false,
				modal:true,
				resizable:false
			});
		});

		$('.addAll').click(function(e){
			topicList.entries.mode = 'edit';
			// Enable the add to list links
			$('a.add').each(function(){
				$entry = $(this).closest('.entry');
				var twitterId=$.trim( $entry.find('.twitterId').html() );
				//Already selected
				if( !$entry.hasClass('selected') ){
					topicList.people.select(twitterId,$entry);
					topicList.myList.addPerson(twitterId, $entry); //Pass along entry so that we have a handle to it later
				}
			});
		});
		$('.removeAll').click(function(e){
			$('a.add').each(function(){
				$entry = $(this).closest('.entry');
				var twitterId=$.trim( $entry.find('.twitterId').html() );
				//Already selected
				if( $entry.hasClass('selected') ){
					topicList.people.unselect(twitterId,$entry);
					topicList.myList.removePerson(twitterId);
				}
			});
		});

	    //Wire up tweet this button
		$('.successDialog a.tweetThis').click(function(e){
		  //e.preventDefault();
		  //Close the dialogue after the tweetThis has been executed
		  //Find the dialog box, then find the close button and trigger it
		  $(this).closest('.ui-dialog').find('.ui-icon-closethick').trigger('click');
		  $('#rightbox .listMaker .save').css('opacity',1); //Make save button visible again
		});
	},
	'saveList':function(params,callbacks){//Params is an object of params that will be sent to try and save the list
		var callbackTypes=new Array('onSuccess','onNameTaken','onError');
		if(typeof(callbacks)=='undefined'){
			callbacks=new Object();
		}
		for(var i in callbackTypes){
			if(!callbacks.hasOwnProperty(callbackTypes[i])){
				callbacks[ callbackTypes[i] ]=function(){return true;};
			}
		}
		var url='/listmaker.process.php';

		//Display loading screen
		$('.savingDialog').dialog({
			//Hide the close button (X) in top right
			open:function(){
				$(this).parents(".ui-dialog:first")
						.find(".ui-dialog-titlebar-close")
						.css('display','none')
						.end();
			},
			beforeclose: function(e){ $(this).dialog('destroy') },
			dialogClass: 'dialog',
			draggable:false,
			modal:true,
			resizable:false
		});

		$.post(url,params,function(data,textStatus){
			data = eval("(" + data + ")" );
			//Remove the dialog with the loading bar
			$('.savingDialog').dialog('destroy');
			var status=(!data.status)?'error':data.status;
			if(status=='success'){
				callbacks.onSuccess(data);
				topicList.entries.mode = 'view';
				$('.successDialog').dialog({
					beforeclose: function(e){
						$(this).dialog('destroy');
						$('#rightbox .listMaker .save').css('opacity',1); //Make save button visible again
					},
					dialogClass: 'dialog',
					draggable:false,
					modal:true,
					resizable:false
				});
			}
			else if(status=='nameTaken'){
				$('.nameTakenDialog').dialog({
					beforeclose: function(e){ $(this).dialog('destroy') },
					dialogClass: 'dialog',
					draggable:false,
					modal:true,
					resizable:false,
					buttons: { "Ok": function() { $(this).dialog("close"); } }
				});
				//Make the "save list" button visible again
				callbacks.onNameTaken();
				$('#rightbox .listMaker .bottom a.save').css('opacity',1);
			}
			else if (status=='invalid'){
				if(typeof(data.message)!='invalid'){ $('.invalidErrorDialog').html(data.message) }
				$('.invalidErrorDialog').dialog({
					beforeclose: function(e){ $(this).dialog('destroy') },
					dialogClass: 'dialog',
					draggable:false,
					modal:true,
					resizable:false,
					buttons: { "Ok": function() { $(this).dialog("close"); } }
				});
				callbacks.onError();
				$('#rightbox .listMaker .bottom a.save').css('opacity',1);
			}
			else if (status=='oauth'){
				if(typeof(data.message)!='oauth'){ $('.oauthErrorDialog').html(data.message) }
				$('.oauthErrorDialog').dialog({
					beforeclose: function(e){ $(this).dialog('destroy') },
					dialogClass: 'dialog',
					draggable:false,
					modal:true,
					resizable:false,
					buttons: { "Ok": function() { $(this).dialog("close"); } }
				});
				callbacks.onError();
				$('#rightbox .listMaker .bottom a.save').css('opacity',1);
			}
			else {
				if(typeof(data.message)!='undefined'){ $('.unknownErrorDialog').html(data.message) }
				$('.unknownErrorDialog').dialog({
					beforeclose: function(e){ $(this).dialog('destroy') },
					dialogClass: 'dialog',
					draggable:false,
					modal:true,
					resizable:false,
					buttons: { "Ok": function() { $(this).dialog("close"); } }
				});
				callbacks.onError();
				$('#rightbox .listMaker .bottom a.save').css('opacity',1);
			}
		});
	},
	/*
	 //Make the name of the list clickable and editable
	'wireEdit':function(){
		//Wire up edit title button
		$editButton=$('.editButton');
		var editing=false;
		$('.console span.name').click(function(e){
			editing=true;
			e.preventDefault();
			$a=$(this);
			$a.css('display','none');
			var val=$a.html();
			var height=$a.height()+5;
			var lineHeight=$a.css('line-height');
			$('<textarea class="edit"></textarea>')
				.insertAfter($a)
				.css('height',height)
				.attr('value',val) //.autogrow()
				.blur(function(e){
					editing=false;
					$textarea=$(this);
					var val=$textarea.remove().attr('value');
					$a.html(val).css('display','inline');//Set to div and reveal
				})
				.focus();
		});
		$editButton.click(function(e){
			switch(editing){
				case true:
					$('.console textarea.edit').trigger('blur');
					break;
				case false:
					$('.console span.name').trigger('click');
					break;
			}
		});
	},//*/
	'removePerson':function(twitterId,$entry){
		//Remove from hidden data
		var newList=new Array();
		var currList=$('#mylist').data('twitterIds');
		//Have to loop through array to remove this value (no array search in JS)
		for(var i in currList){
			var currId=currList[i];
			if(currId==twitterId){
				continue;
			}
			newList.push(currId);
		}
		$('#mylist').data('twitterIds',newList);

		//Remove image
		$('#list').find('li .'+twitterId).remove();

		// Show the instructions if required
		if (!$('#list').children().length) $('#mylist .instruct').show()
	},
	//entry is a handle to the LI in the people list
	'addPerson':function(twitterId, $entry){
		//Check if person already exists
		var existingTwitterIds=$('#mylist').data('twitterIds');

		//Check to see if the user has already been added
		for(var i in existingTwitterIds){
			if(existingTwitterIds[i]==twitterId){
				return false;
			}
		}

		// Hide the instructions
		$('#mylist .instruct').hide()

		var person=topicList.people.findById(twitterId);

		//Add to hidden data
		$('#mylist').data('twitterIds').push( person['id'] );

		// Locate the img source
		var src = person.profile_image_url;
		
		// Make the new list item
		var $li = $('<li><a href="#" class="' + person['id'] + '" title="Remove ' + person['screen_name'] + '"><img src="' + src + '" height="50" width="50" /><div>remove</div></a></li>')
				//.addClass(person['id']) //Add this class to make it jQuery searchable
				.data('twitterId',person['id'])
				.data('entry',$entry) //entry is a handle to the LI in the people list so that it can be toggled
				.appendTo($('#list'));


	}
};
//The people available (influencers) to choose from for your list
topicList.people={
	'entries':'#entries',//Container for people to choose from

	//Finds a twitter user by their twitter ID
	'findById':function(twitId){
		var that=this;
		for(var i in topicList.payload['influencers']){
			var influencer=topicList.payload['influencers'][i];
			if(influencer['id']==twitId){
				return influencer;
			}
		}
		return false;
	},

	//If you manually add an influencer
	'addInfluencer':function(user){
		var that=this;

		topicList.entries.mode = 'edit';

		//if the user already exists in our data object
		if( that.findById(user['id']) !== false ){
			$entry=false;
			//Find the entry DIV and return it, rather than creating a new one (duplicate)
			$('div.entry').each(function(e){
				if( $(this).find('div.twitterId').html() == user['id'] ){
					$entry=$(this);
				}
			});
			return $entry;
		}

		//Store user data to hidden datastore
		topicList.payload['influencers'].push(user);

		//Use this as a template
		var $entry=$('div.entry').eq(1).clone()
		//Now replace with the new users attributes
			.find('div.avatar a').attr('href','/profile/summary/'+user.screen_name).end() //Replace link
			.find('div.avatar img').attr('src',user.profile_image_url).end() //Replace image
			.find('div.data .name').html('<a href="http://twitter.com/'+user.screen_name+'" target="_blank">'+user.screen_name+'</a>').end()
			.find('div.data .kscore .text').html(user.kscore).end()
			.find('div.data .bio').html(user.description).end()
			.find('div.data .location').html(user.location).end()
			.find('div.data .topics').html('&nbsp;').end()
			.find('div.twitterId').html(user['id']).end()
			.prependTo(that.entries);
		return $entry;		
	},

	'wireUp':function(){
		var that=this;
		that.entries=$(that.entries);

		// Add a div to make sure the container sets height
		that.entries.append('<div class="clear"></div>');

		// Enable the add to list links
		$('a.add').live('click', function() {
			topicList.entries.mode = 'edit';

			$entry = $(this).closest('.entry');
			var twitterId=$.trim( $entry.find('.twitterId').html() );

			//Already selected
			if( $entry.hasClass('selected') ){
				that.unselect(twitterId,$entry);
				topicList.myList.removePerson(twitterId);
			}
			else{
				that.select(twitterId,$entry);
				topicList.myList.addPerson(twitterId, $entry); //Pass along entry so that we have a handle to it later
			}
			return false;
		});

		// Make switch link works (little icons at top)
		$('.switches a').click( function() {
			if(this.id != 'tiles_view' && this.id != 'entries_view'){
				return false;
			}
			// Reset the styles for the buttons
			$('.switches a').removeClass('active');
			this.className = 'active';

			// Change the entries class
			$('#entries').attr('class', this.id.split('_')[0]);

			return false;
		})

	},
	'select':function(twitterId,$entry){
		$entry.find('a.add').html( 'Remove' );
		$entry.addClass('selected')
	},
	'unselect':function(twitterId,$entry){
		// Change the button text
		$entry.find('a.add').html( 'Add to List' );
		$entry.removeClass('selected');
	}
}
topicList.rightBox={
	'wireUp':function(){
		var that=this;
		//Wire up buttons on right
		$('#rightbox .listOptions')
			.find('.makeOwn').unbind().end()
			.find('.followKlist').unbind().end()
			.find('.deleteKlist').unbind().end()
			//Make your own list
			.find('.makeOwn.allGood').click(function(e){
				e.preventDefault();
				//Fade out the list options
				$('#rightbox .listOptions').fadeOut('fast',function(){
					$('#rightbox .listMaker').css('display','block');
				});
				$('.actions .badge').fadeOut('fast',function(){
					$('.actions .add').css('display','block');
				});

				//Fade in buttons to Add all users/remove all users from your custom list
				$('.addAllContainer').css('visibility','visible');//.css('opacity',.3).fadeIn('slow');

			}).end()
			
			//Wire up tweet this button
			$('.successFollowDialog a.tweetThis').click(function(e){
			  //e.preventDefault();
			  //Close the dialogue after the tweetThis has been executed
			  //Find the dialog box, then find the close button and trigger it
			  $(this).closest('.ui-dialog').find('.ui-icon-closethick').trigger('click');
			}).end()
			
			//Follow this Klist (default list) button
			.find('.followKlist.allGood').click(function(e){
				e.preventDefault();
				
				// If we have a twitter list, follow that list
				if (topicList.payload.slug != undefined) {
					me = this;
					
					// Update the text to indicate we're busy
					this.innerHTML = 'Following List...';
					
					// Contact the server to follow
					var url='/listmaker.process.php';
					$.post(url,{ 'list_slug':topicList.payload.slug, 'owner_screen_name':topicList.payload.owner_screen_name, 'list_topic':topicList.payload.topic }, function(data,textStatus) {
						data = eval("(" + data + ")" );
						var status=(!data.status)?'error':data.status;
						if(status=='success'){	
							me.innerHTML = 'You\'re Now Following This List';
							var tweetUrl=data.tweet_url;
							$('.successFollowDialog a').attr('href',tweetUrl);
							$('.successFollowDialog a').attr('target','_blank');
							$('.successFollowDialog').dialog({
								beforeclose: function(e){ $(this).dialog('destroy') },
								dialogClass: 'dialog',
								draggable:false,
								modal:true,
								resizable:false
							});
						}
						else if (status=='oauth'){
							me.innerHTML = 'Follow This List On Twitter';
							if(typeof(data.message)!='oauth'){ $('.oauthErrorDialog').html(data.message) }
							$('.oauthErrorDialog').dialog({
								beforeclose: function(e){ $(this).dialog('destroy') },
								dialogClass: 'dialog',
								draggable:false,
								modal:true,
								resizable:false,
								buttons: { "Ok": function() { $(this).dialog("close"); } }
							});
						}
						else {
							me.innerHTML = 'Follow This List On Twitter';
							if(typeof(data.message)!='undefined'){ $('.unknownErrorDialog').html(data.message) }
							$('.unknownErrorDialog').dialog({
								beforeclose: function(e){ $(this).dialog('destroy') },
								dialogClass: 'dialog',
								draggable:false,
								modal:true,
								resizable:false,
								buttons: { "Ok": function() { $(this).dialog("close"); } }
							});
						}
					});
					
				// This is not a Twitter List, so follow it our way	
				} else {
					$('.followKlistDialog').dialog({
						//Hide the close button (X) in top right
						open:function(){
							var $dialog=$(this);
							//Wire up save button
							$(this).find('.save').click(function(e){
								$dialog.dialog('destroy');
								var name=$(this).siblings('input.listName').val();
								var slug = name.toLowerCase();
								slug = slug.replace(/ /gi, "-");
								var description=$(this).siblings('textarea.listDescription').val();
								params={'name': name,
										'type':topicList.payload.type,
										'topic': topicList.payload.topic,
										'description': description};
										
								topicList.myList.saveList(params,{
										'onSuccess':function(data){
											var tweetUrl=data.tweet_url;
											$('.successDialog a.tweetThis').attr('href',tweetUrl);
											$('.successDialog a.tweetThis').attr('target','_blank');
											$('.successDialog a.createEmailAlert').attr("onClick","listimonkey('"+topicList.payload.list_creator+"/"+slug+"','"+topicList.payload.topic+"','"+topicList.payload.email+"');return false;");
										},
										'onNameTaken':
											function(){$('#rightbox .listMaker .finished').css('opacity',1); return true;},
										'onError':
										//Make the "save list" button visible again
											function(){$('#rightbox .listMaker .bottom a.save').css('opacity',1); return true;}						
									});
							});
						},
						beforeclose: function(e){ $(this).dialog('destroy') },
						dialogClass: 'dialog',
						draggable:false,
						modal:true,
						resizable:false
					});
				}
			//});
			}).end()
			
			//Delete this Klist
			/*.find('.deleteKlist.allGood').click(function(e){
				e.preventDefault();
				
				// If we have a twitter list, delete that list
				if (topicList.payload.slug != undefined) {
					me = this;
					
					// Update the text to indicate we're busy
					this.innerHTML = 'Deleting List...';
					
					// Contact the server to delete
					var url='/listmaker.process.php';
					$.post(url,{ 'delete_list':'1', 'slug':topicList.payload.slug, 'owner_user_name':topicList.payload.owner_screen_name }, function(data,textStatus) {
						data = eval("(" + data + ")" );
						var status=(!data.status)?'error':data.status;
						if(status=='success'){
							me.innerHTML = 'List deleted successfully';
							document.location = '/';
						}
						else if (status=='oauth'){
							me.innerHTML = 'Delete This List On Twitter';
							if(typeof(data.message)!='oauth'){ $('.oauthErrorDialog').html(data.message) }
							$('.oauthErrorDialog').dialog({
								beforeclose: function(e){ $(this).dialog('destroy') },
								dialogClass: 'dialog',
								draggable:false,
								modal:true,
								resizable:false,
								buttons: { "Ok": function() { $(this).dialog("close"); } }
							});
						}
						else {
							me.innerHTML = 'Delete List';
							if(typeof(data.message)!='undefined'){ $('.unknownErrorDialog').html(data.message) }
							$('.unknownErrorDialog').dialog({
								beforeclose: function(e){ $(this).dialog('destroy') },
								dialogClass: 'dialog',
								draggable:false,
								modal:true,
								resizable:false,
								buttons: { "Ok": function() { $(this).dialog("close"); } }
							});
						}
					});
				} 
			});
			//}).end()*/
			
			// #567 - add user without kscore to queue for processing
			.find('.addUserToQueue.allGood').click(function(e){
				e.preventDefault();
				
				me = this;
				if (me.innerHTML != "Done!") {
					me.innerHTML = 'Queueing...';
					// Contact the server to queue
					var url='/listmaker.process.php';
					var users=$(this).siblings('input.userToQueue').val();
					$.post(url,{ 'add_to_queue':'1', 'users':users }, function(data,textStatus) {
						me.innerHTML = data;
					});
				}
			});
	}
}
topicList.entries = {
	'mode': 'view',
	
	'load': function(url) {
		var that = this;

		// Request the new data
		jQuery.get(url,null, function(data,status) {
			topicList.payload = data;
			// Reload the data

			that.render(data);
			
		}, 'json')
	},
	
	'render': function(payload,mode) {
		var that=this;
		var $entries  = $('#entries');
		var $template = $('#entry-template');

		// Empty the entries
		document.getElementById('entries').innerHTML = '';

		// Hide the entries
		$entries.hide();
		
		// refresh page title
		document.title = 'Klout - Twitter Analytics - ' + payload.topic;
		// set default listname
		$('.listName').val('Klout influencers-'+payload.topic);

		// set topic 
		if (payload['slug'] == undefined)
			$('.topic_placeholder').html(payload.topic);
		else
			$('.topic_placeholder').html(payload['owner_screen_name']+'/'+payload['slug']);
		// set cursors
		if (payload['previous_url'] != undefined)
		{
			$('.next').attr('href',payload['previous_url']);
			$('.prev').show();
		}
		else
			$('.prev').hide();
		
		if (payload['next_url'] != undefined)
		{
			$('.next').attr('href',payload['next_url']);
			$('.next').show();
		}
		else
			$('.next').hide();
		
		if (payload['influencers'] != undefined && payload.logged_in == true) 
		{
			$('.followKlist').addClass('allGood');
			$('.makeOwn').addClass('allGood');
			//$('.deleteKlist').addClass('allGood');
		}
		else // set the onclick for the buttons to no results
		{
			$('.followKlist').removeClass('allGood');
			$('.makeOwn').removeClass('allGood');
			//$('.deleteKlist').removeClass('allGood');
			
			if (!payload.logged_in)
				var alert_txt = 'javascript:window.alert(\'Please login first.\');';
			else
				var alert_txt = 'javascript:window.alert(\'There are no results.\');';

			$('.followKlist').attr('href',alert_txt);
			$('.makeOwn').attr('href',alert_txt);
			//$('.deleteKlist').attr('href',alert_txt);
		}

		topicList.rightBox.wireUp();
		
		// Loop over the payload
		if (payload['influencers'] != undefined) {
			var userNames = "";
			jQuery.each(payload['influencers'], function(x,i) {
				// Create the container div
				var $entry =jQuery('<div id="entry_' + i.id + '" class="entry column grid_12"></div>');
				
				// Save a reference to the data
				$entry.attr('id',i.id);
				$entry.data('influencer',i);
				
				// check kscore
				var kscore = Math.floor(i.kscore);
				if (kscore <= 0) {
					kscore = 0;
					if (userNames == "") {
						userNames = i.screen_name;
					}
					else {
						userNames = userNames + "|" + i.screen_name;
					}
				}
				
				// Make the text replacements
				$entry.html($template.html().replaceTemplate( {
					screen_name: i.screen_name,
					location: (i.location.length) ? '('+i.location+')':'',
					kscore: kscore,
					description: i.description,
					id: i.id
				}));
				
				// Secondary replacements
				$entry
					// Show the image
					.find('.photo').attr('src',i.profile_image_url).end()
					
					// Make the link adjustments
					.find('.plink').attr('href','/profile/summary/' + i.screen_name).end()
					.find('.tlink').attr('href','http://twitter.com/' + i.screen_name).end()
					.find('.tweetThis').attr('href','/tweet/tag/rank/' + i.screen_name + '/1/5/').end()
				
					// Add the topics
					.find('.topics').html(that.entryTopics(i.tags)+'&nbsp;').end();
										
				// Append the entry	
				$entries.append($entry);
			})
			
			// handle the queue thingy
			$('.listOptions input.userToQueue').attr('value',userNames);
			$('.listOptions a.addUserToQueue').text("Add users to queue");

			if (userNames == "") {
				$('.listOptions a.addUserToQueue').css('display','none');
			}
			else {
				$('.listOptions a.addUserToQueue').css('display','block');
			}
			
			// Toggle the mode
			that.toggleMode(mode);
			
			// Disable any items which are already present
			var selected = $('#mylist').data('twitterIds');
			
			jQuery.each(selected, function(x,y) {
				topicList.people.select(y,$('#' + y + '.entry'));
			})
		}
		
		// Show the entries
		$entries.show();
	},
	
	'entryTopics': function(topics) {
		var html = [];
		
		jQuery.each(topics, function(x,t) {
			html.push('<a href="/topic/lists/' + escape(t.topic) + '">' + t.topic + '</a>');
		})
		
		return html.join(', ');
	},
	
	'toggleMode': function(mode) {
		if (!mode) mode = this.mode;
		
		var b_a = $('#entries .add');
		var b_t = $('#entries div.badge');

		if (mode === 'view') {
			b_a.hide();
			b_t.show();
		} else {
			b_a.show();
			b_t.hide();
		}
	}
}

$(document).ready(function() {
	if (typeof(payload) != 'undefined') {
		topicList.payload=payload;

		if (payload['empty'] != undefined) {
			$('#grid_header').html('<strong>Gathering Results</strong>');
			if (payload['slug'] == undefined)
				$('#entries').html('<div class="entry column grid_12"><div style="padding:10px;">No results found. Top influencers have not been discussing this topic in the last 14 days.</div></div>')
			else
				$('#entries').html('<div class="entry column grid_12"><div style="padding:10px;">We could not retrieve the members for this list.  It could be that this list has been marked \'private\'.</div></div>')
		}
		else if (payload['influencers'] == undefined) {
			$('#grid_header').html('<strong>Gathering Results</strong>');
			if (payload['slug'] == undefined)
				$('#entries').html('<div class="entry column grid_12"><div style="padding:10px;">Processing for this topic is still in progress.  Please refresh this page in a few seconds.</div></div>')
			else
				$('#entries').html('<div class="entry column grid_12"><div style="padding:10px;">We could not retrieve the members for this list.  It could be that this list has been marked \'private\'.</div></div>')
		}
	}
	
	topicList.topButtons.wireUp();
	topicList.myList.wireUp();
	topicList.people.wireUp();
	topicList.rightBox.wireUp();
	topicList.cursors.wireUp();
	topicList.pagination.wireUp();

	// Configure text fields
	$('input.text').focus( function() {
		if (this.value == this.defaultValue) this.value = '';
	}).blur( function() {
		if (this.value == '') {
			this.value = this.defaultValue;
			$(this).removeClass('changed');
		}
	}).change( function() {
		$(this).addClass('changed')
	})
	
	// turn off loading
	$('#loading').hide();
});
