jQuery Help: Variables Outside of Function

<script type="text/javascript">
var forum_id = '1521804';

if (location.href.indexOf('/profile/') !== -1) {
$.get(main_url + 'forum/' + forum_id + '', function (data) {

var nav_text = $('#nav span:last', data).text();

$('td.c_cat-starter a', data).each(function () {
var profile_id =  $(this).attr('href').split('profile/')[1].split('/')[0];

$('td.c_cat-starter:has(a[href*="' + profile_id + '"])', data).prev('td.c_cat-title').find('a').each (function() {
var topic_id = $(this).attr('href').split('topic/')[1].split('/')[0];
var topic_name = $(this).text();

if (location.href.indexOf('/profile/' + profile_id + '') !== -1) {
$('table.profile:eq(2) tbody tr:has(th)').before('<tr><td class="c_desc">My ' + nav_text + ' Topics</td><td id="my_topics"></td></tr>');
$('#my_topics').append('<a href="' + main_url + 'topic/' + topic_id + '/">' + topic_name + '</a>');
}
});
});
});
}
</script>

Being used here: http://s1.zetaboards.com/Cory/forum/1521804/ (Click on one of the profile URLs from the Topic Starter column and check where it says ‘My Development Discussions Topics’)

If you click on ‘Cory’, you will notice how the data duplicates, which I assume is caused by putting it inside the each() functions, which I had to do because Firebug read the variables as undefined when the inner if statement was placed outside of the each() functions. How would I fix this issue?

Note: I am a beginner at JavaScript and intermediate at jQuery, so don’t be surprised if my code is a mess.