var url = 'http://www.crazeapp.us/app/';
profileImageUrl = 'http://www.crazeapp.us/uploads/profile/';
postImageUrl = 'http://www.crazeapp.us/uploads/post/';

var loggedIn = false;
var sessionId = '';

var homePosts;
var homeOffset;
var profileOffset;
var searchOffset;
var postsPerPage = 20;

var notificationsCount = false;

var currentIndividualPost = false;



// hack to prevent double buttons on first profile view
var profileViews = 0;

$(document).ready(function() {
	$.ajaxSetup({ cache: false });
});

// load home posts on home page show
$(document).delegate('#home', 'pageshow', function() {
	if (!loggedIn) {
		showLogIn();
	} else if (!homePosts) {
		buildHomePage();
	}
});

// load individual post on individual page show
$(document).delegate('#individual_post', 'pageshow', function() {
	if (!currentIndividualPost) {
		$('div#individual_post_content').text("Sorry, couldn't find that post.");
	} else {
		buildIndividualPost();
	}
});

// empty individual post on individual page hide
$(document).delegate('#individual_post', 'pagehide', function() {
	// empty individual post to prevent flickering
	$('#individual_post_content').empty();
});

// load profile on page show
$(document).delegate('#profile', 'pageshow', function() {
	loadProfile(currentProfile);
});

// load fanned list on page show
$(document).delegate('#fanned_page', 'pageshow', function() {
	if (!loggedIn) {
		showLogIn();
	} else {
		buildListPage('fanned');
	}
});

// load fans list on page show
$(document).delegate('#fans_page', 'pageshow', function() {
	if (!loggedIn) {
		showLogIn();
	} else {
		buildListPage('fans');
	}
});

// load vips list on page show
$(document).delegate('#vips_page', 'pageshow', function() {
	if (!loggedIn) {
		showLogIn();
	} else {
		buildListPage('vips');
	}
});

$(document).delegate('#profile', 'pagehide', function() {
	$('div#profile_main').empty();
});

// fill account page with user data on page load
$(document).delegate('#account', 'pageshow', function() {
	buildAccountPage();
});

// load notifications on page show
$(document).delegate('#notifications', 'pageshow', function() {
	buildNotificationsPage();
});

// populate notifications count link on page show
$(document).delegate('#home', 'pageshow', function() {
	populateNotificationsCount();
});

// populate top hashtags and posts on page show
$(document).delegate('#top', 'pageshow', function() {
	buildTopPage();
});

// reload home posts
$(document).delegate('#refresh', 'click', function() {
	buildHomePage();
});

// close side menu
$(document).delegate('#close_menu', 'click', function() {
	$('#menu').panel('close');
});

// vote up
$(document).delegate('.vote_up', 'click', function(e) {
	var post = e.target.id;
	// vote up id is vote_up##
	post = post.substr(7, post.length);
	vote(1, post, e.target);
});

// vote down
$(document).delegate('.vote_down', 'click', function(e) {
	var post = e.target.id;
	// vote down id is vote_down##
	post = post.substr(9, post.length);
	vote(0, post, e.target);
});

// favorite a post
$(document).delegate('.favorite', 'click', function(e) {
	var post = e.target.id;
	// favorite id is favorite##
	post = post.substr(8, post.length);
	favorite(post, e.target);
});

// load an individual post by clicking a post image
$(document).delegate('img.content_image', 'click', function(e) {
	var id = $(e.target).parent().attr('id');
	// content image link id is content_image_link##
	id = id.substr(18, id.length);
	currentIndividualPost = id;
});

// load an individual post by clicking a view/add comments button
$(document).delegate('a.view_comments', 'click', function(e) {
	var id = e.target.id;
	// view comments link id is view_comments##
	id = id.substr(13, id.length);
	currentIndividualPost = id;
	$.mobile.changePage('#individual_post');
});

// load an individual post by clicking a view post button in a notification
$(document).delegate('a.view_post', 'click', function(e) {
	var id = e.target.id;
	// view comments link id is view_post##
	id = id.substr(9, id.length);
	currentIndividualPost = id;
	$.mobile.changePage('#individual_post');
});

// delete a notification by clicking a delete button in a notification
$(document).delegate('a.delete_notification', 'click', function(e) {
	var id = e.target.id;
	// view comments link id is delete_notification##
	id = id.substr(19, id.length);
	deleteNotification(id);
});

// submit a comment
$(document).delegate('span.comment_submit', 'click', function(e) {
	var id = e.target.id;
	// submit id is comment_submit##
	id = id.substr(14, id.length);
	var comment = $('textarea#comment_input' + id).val();
	if (comment.length > 0) {
		addComment(id, comment);
	} else {
		alert('Please write a comment.');
	}
});

// load a profile after clicking a user link span
$(document).delegate('a.user span', 'click', function(e) {
	var id = $(e.target).parent().attr('id');
	// user id is user##
	id = id.substr(4, id.length);
	currentProfile = id;
	$.mobile.changePage('#profile', {allowSamePageTransition: true});
});

// load a profile after clicking a user link image
$(document).delegate('a.user img', 'click', function(e) {
	var id = $(e.target).parent().attr('id');
	// user id is user##
	id = id.substr(4, id.length);
	currentProfile = id;
	$.mobile.changePage('#profile', {allowSamePageTransition: true});
});

// load a profile after clicking a user list item
$(document).delegate('a.user_link', 'click', function(e) {
	var id = $(e.target).attr('id');
	// user link id is user_link##
	id = id.substr(9, id.length);
	currentProfile = id;
	$.mobile.changePage('#profile', {allowSamePageTransition: true});
});

// run a search after clicking on a search button
$(document).delegate('a.search_button', 'click', function(e) {
	var id = $(e.target).attr("id");
	// search button id is search_xxxxx
	type = id.substr(7, id.length);
	var query = $('input#search_text').val().trim();
	if (query.length > 0) {
		search(type, query);
	}
});

// send fan request on button click
$(document).delegate('a.become_fan', 'click', function(e) {
	var id = $(e.target).attr('id');
	// become fan button id is become_fan##
	id = id.substr(10, id.length);
	requestFan(id);
});

// send vip request on button click
$(document).delegate('a.become_vip', 'click', function(e) {
	var id = $(e.target).attr('id');
	// become vip button id is become_vip##
	id = id.substr(10, id.length);
	requestVip(id);
});

// show profile fan list on button click
$(document).delegate('#fans_metrics', 'click', function(e) {
	buildProfileListPage('fans');
	$.mobile.changePage('#profile_fans');
});

// show profile vip list on button click
$(document).delegate('#vips_metrics', 'click', function(e) {
	buildProfileListPage('vips');
	$.mobile.changePage('#profile_vips');
});

// accept vip request on button click
$(document).delegate('.accept_vip', 'click', function(e) {
	var id = $(e.target).attr('id');
	// accept vip button id is accept_vip##
	id = id.substr(10, id.length);
	vipResponse('yes', id);
});

// deny vip request on button click
$(document).delegate('.deny_vip', 'click', function(e) {
	var id = $(e.target).attr('id');
	// deny vip button id is deny_vip##
	id = id.substr(8, id.length);
	vipResponse('no', id);
});

// accept fan request on button click
$(document).delegate('.accept_fan', 'click', function(e) {
	var id = $(e.target).attr('id');
	// accept fan button id is accept_fan##
	id = id.substr(10, id.length);
	fanResponse('yes', id);
});

// deny vip request on button click
$(document).delegate('.deny_fan', 'click', function(e) {
	var id = $(e.target).attr('id');
	// deny fan button id is deny_fan##
	id = id.substr(8, id.length);
	fanResponse('no', id);
});

// search hashtag on click
$(document).delegate('.hashtag_link', 'click', function(e) {
	var query = $(e.target).text().slice(1);
	search('hashtag', query);
	$.mobile.changePage('#search');
});

// search username on at mention click
$(document).delegate('.mention_link', 'click', function(e) {
	var query = $(e.target).text().slice(1);
	search('username', query);
	$.mobile.changePage('#search');
});


// log in
$(document).delegate('#log_in_submit', 'click', function() {
	var username = $('input#username').val().trim();
	var password = $('input#password').val().trim();
	if (username.length > 0 && password.length > 0) {
		logIn(username, password);
	} else {
		alert('No username or password.');
	}
});

/*
// submit a new post
$(document).delegate('#new_post_submit', 'click', function() {
	newPost();
});
*/

// submit a new post
$(document).delegate('#new_post_form', 'submit', function(e) {
	e.preventDefault();
	newPost($(this));
});

// submit profile changes
$(document).delegate('#account_form', 'submit', function(e) {
	e.preventDefault();
	editAccount($(this));
});

// show log in page
function showLogIn() {
	$.mobile.changePage('#log_in');
	// auto fill with saved username and password
	if (localStorage.getItem('username') && localStorage.getItem('password')) {
		$('input#username').val(localStorage.getItem('username'));
		$('input#password').val(localStorage.getItem('password'));
	}
}

// log in
function logIn(username, password) {
	$.mobile.loading('show');
	$.post(url + 'log_in.php', {username:username,password:password}, function(data) {
		console.log(data);
		if (data != 'no username' && data != 'no password') {
			loggedIn = true;
			$.mobile.changePage('#home');
			sessionId = data;
		} else if (data == 'no username') {
			alert('That username was not found.');
			$('input#username').val('');
			$('input#password').val('');
		} else if (data == 'no password') {
			alert('Incorrect password.');
			$('input#password').val('');
		}
		$.mobile.loading('hide');
		localStorage.setItem('username', username);
		localStorage.setItem('password', password);
		notificationsCount = false;
	});
}

// populate home page with posts
function buildHomePage() {
	$.mobile.loading('show');
	$('div#home_posts_list').empty();
	homeOffset = 0;
	$.post(url + 'get_home_posts.php', {offset:homeOffset,session_id:sessionId}, function(data) {
		if (data == 'error') {
			alert('Please log in.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
		}
		$.post(url + 'get_posts_by_id.php', {post_ids:data,session_id:(sessionId ? sessionId : false)}, function(d) {
			homePosts = JSON.parse(d);
			console.log(homePosts);
			for (i = 0; i < homePosts.length; i++) {
				var post = individualPost(homePosts[i], false);
				$('div#home_posts_list').append(post);
			}
			$('div#home_posts_list').append('<a data-role="button" data-icon="plus" class="more_home_posts">More Posts</a>');
			$('.post_metrics').controlgroup().controlgroup('refresh');
			$('.post a.view_comments').button().button('refresh');
			$('a.more_home_posts').button().button('refresh').click(function() {
				$('a.more_home_posts').parent().remove();
				loadMoreHomePosts();
			});
			$.mobile.loading('hide');
		});
	});
}

// populate individual post page
function buildIndividualPost() {
	if (!currentIndividualPost) {
		$('div#individual_post_content').text("Sorry, couldn't find that post.");
	} else {
		$.mobile.loading('show');
		
		$('div#individual_post_content').empty();
		
		// get_posts_by_id.php accepts a JSON object containing an array of post ids, so make an array
		var postIds = JSON.stringify([currentIndividualPost]);
		
		// get post
		$.post(url + 'get_posts_by_id.php', {post_ids:postIds,session_id:(sessionId ? sessionId : null)}, function(data) {
			var post = JSON.parse(data)[0];
			console.log(post);
			var postHtml = individualPost(post, true);
			$('div#individual_post_content').append(postHtml);
			$('.post_metrics').controlgroup().controlgroup('refresh');
			$('.comment_submit').button().button('refresh');
			// get comments
			$.post(url + 'get_comments.php', {post:post.id,session_id:(sessionId ? sessionId : null)}, function(d) {
				if (d == 'no data') {
					alert("Sorry, couldn't get comments for this post. Please try again.");
					return;
				} else if (d == 'no comments') {
					console.log('No comments.');
					return;
				}
				var comments = JSON.parse(d);
				var commentsListHtml = '';
				for (var i = 0; i < comments.length; i++) {
					commentsListHtml += individualComment(comments[i]);
				}
				$('div.comments').append(commentsListHtml);
			});
			$.mobile.loading('hide');
		});
	}
}

function loadMoreHomePosts() {
	$.mobile.loading('show');
	homeOffset += postsPerPage;
	$.post(url + 'get_home_posts.php', {offset:homeOffset,session_id:sessionId}, function(data) {
		$.post(url + 'get_posts_by_id.php', {post_ids:data,session_id:(sessionId ? sessionId : false)}, function(d) {
			homePosts = JSON.parse(d);
			console.log(homePosts);
			for (i = 0; i < homePosts.length; i++) {
				var post = individualPost(homePosts[i], false);
				$('div#home_posts_list').append(post);
			}
			$('div#home_posts_list').append('<a data-role="button" data-icon="plus" class="more_home_posts">More Posts</a>');
			$('.post_metrics').controlgroup().controlgroup('refresh');
			$('.post a.view_comments').button().button('refresh');
			$('a.more_home_posts').button().button('refresh').click(function() {
				$('a.more_home_posts').parent().remove();
				loadMoreHomePosts();
			});
			notificationsCount = false;
			populateNotificationsCount();
			$.mobile.loading('hide');
		});
	});
}

function vote(type, post, element) {
	if (!loggedIn) {
		showLogIn();
	}
	console.log('vote ' + type + ' ' + post);
	$.post(url + 'vote.php', {type:type,post:post,session_id:sessionId}, function(data) {
		console.log(data);
		if (data == 'error') {
			// user isn't logged in
			alert('Please log in to vote.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
		} else if (data == 'no data') {
			// post data was missing
			alert('Sorry, something went wrong. Please try again.');
		} else if (data == 'already voted') {
			// user already voted on this post
			alert('You already voted on this post.');
		} else if (data == 'own post') {
			// user's own post
			alert("You can't vote on your own posts!");
		} else {
			// successful vote
			// change metric button value
			$(element).text(data);
			if (type === 1) {
				console.log('up voted to ' + data);
			} else if (type === 0) {
				console.log('down voted to ' + data);
			}
		}
	});
}

function favorite(post, element) {
	if (!loggedIn) {
		showLogIn();
	}
	console.log('favorite ' + post);
	$.post(url + 'favorite.php', {post:post,session_id:sessionId}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to feature posts.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
		} else if (data == 'no data') {
			// post data was missing
			alert('Sorry, something went wrong. Please try again.');
		} else if (data == 'already favorited') {
			// already favorited
			alert('You already featured this post.');
		} else if (data == 'own post') {
			// user's own post
			alert("You can't feature your own posts!");
		} else {
			// successful favorite
			// change metric button value
			$(element).text(data);
			console.log(post + ' favorites now ' + data);
		}
	});
}

// submit a comment
function addComment(post, comment) {
	$.mobile.loading('show');
	$.post(url + 'comment.php', {post:post,comment:comment,session_id:sessionId}, function(data) {
		console.log(data);
		if (data == 'error') {
			// not logged in
			alert('Please log in to add comments.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
		} else if (data == 'no data') {
			// post data was missing
			alert('Sorry, something went wrong. Please try again.');
		} else if (data == 'success') {
			buildIndividualPost();
		}
	});
}

// load a user's profile
function loadProfile(id) {
	$('#profile_main').empty();
	$('#profile_side').empty();
	profileOffset = 0;
	
	// get user data
	$.post(url + 'get_user_data.php', {id:id}, function(data) {
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			return;
		}
		var userData = JSON.parse(data);
		console.log(userData);
		profileSideHtml = profileSide(userData);
		$('#profile_side').append(profileSideHtml);
		$('.become_fan').button().button('refresh');
		$('.become_vip').button().button('refresh');
	});
	
	// get metrics
	$.post(url + 'get_profile_metrics.php', {id:id}, function(data) {
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			return;
		}
		var profileMetrics = JSON.parse(data);
		console.log(profileMetrics);
		$('#fans_metrics').text(profileMetrics.fans + ' Fans');
		$('#vips_metrics').text(profileMetrics.vips + ' VIPs');
		$('#posts_metrics').text(profileMetrics.posts + ' Posts');
	});
	
	// get post ids
	$.mobile.loading('show');
	$.post(url + 'get_profile_posts.php', {id:id,offset:profileOffset,session_id:(sessionId ? sessionId : false)}, function(d) {
		console.log(d);
		if (d == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		}
		if (d == 'private') {
			$('div#profile_main').append('<p>This user is private. Become their fan or VIP to view their posts.</p>')
			$.mobile.loading('hide');	
			return;
		}
		// get post data
		$.post(url + 'get_posts_by_id.php', {post_ids:d,session_id:(sessionId ? sessionId : false)}, function(d2) {
			console.log(d2);
			profilePosts = JSON.parse(d2);
			// generate html for posts
			for (var i = 0; i < profilePosts.length; i++) {
				var post = individualPost(profilePosts[i], false);
				$('div#profile_main').append(post);
			}
			// add posts
			$('div#profile_main').append('<a data-role="button" data-icon="plus" class="more_profile_posts">More Posts</a>');
			$('.post_metrics').controlgroup().controlgroup('refresh');
			$('.post a.view_comments').button().button('refresh');
			$('a.more_profile_posts').button().button('refresh');
			$('a.more_profile_posts').click(function(e) {
				$(e.target).parent().remove();
				loadMoreProfilePosts(id);
			});
			profileViews++;
			$.mobile.changePage('#profile');
			$.mobile.loading('hide');
		});
		$.mobile.loading('hide');
	});
}

// load more profile posts
function loadMoreProfilePosts(id) {
	profileOffset += postsPerPage;
	$.mobile.loading('show');
	// get profile posts
	$.post(url + 'get_profile_posts.php', {id:id,offset:profileOffset,session_id:(sessionId ? sessionId : false)}, function(d) {
		if (d == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			return;
		}
		if (d == 'private') {
			$('div#profile_main').append('<p>This user is private. Become their fan or VIP to view their posts.</p>')
			return;
		}
		$.post(url + 'get_posts_by_id.php', {post_ids:d,session_id:(sessionId ? sessionId : false)}, function(d2) {
			console.log(d2);
			profilePosts = JSON.parse(d2);
			for (var i = 0; i < profilePosts.length; i++) {
				var post = individualPost(profilePosts[i], false);
				$('div#profile_main').append(post);
			}
			$('div#profile_main').append('<a data-role="button" data-icon="plus" class="more_profile_posts">More Posts</a>');
			$('.post_metrics').controlgroup().controlgroup('refresh');
			// only refresh buttons for newly added posts in order to prevent original
			// buttons from becoming double for whatever reason
			for (var i = 0; i < profilePosts.length; i++) {
				$('#view_comments' + profilePosts[i].id).button().button('refresh');
			}
			$('a.more_profile_posts').button().button('refresh').click(function(e) {
				$(e.target).parent().remove();
				loadMoreProfilePosts(id);
			});
			$.mobile.loading('hide');
		});
	});
}

// submit a new post
function newPost(form) {
	$.mobile.loading('show');
	$('#session_id').val(sessionId);
	var options = {
		url: url + form.attr("action"),
		success: function(d) {
			console.log(d);
			if (d == 'error') {
				// not logged in
				$.mobile.loading('hide');
				alert('Please log in to add a post.');
				loggedIn = false;
				sessionId = false;
				showLogIn();
				return;
			} else if (d == 'no data') {
				// no post data
				$.mobile.loading('hide');
				alert('Sorry, something went wrong. Please try again.');
				return;
			} else {
				// successfully added post
				var newPostId = d;
				$('#post_img').val('');
				$('#post_text').val('');
				$('#post_submit').val('Share');
				currentIndividualPost = newPostId;
				$.mobile.loading('hide');
				$.mobile.changePage('#individual_post');
			}
		}
	};
	$.mobile.loading('show');
	form.ajaxSubmit(options);
	return false;
}

// build list page
function buildListPage(type) {
	$.mobile.loading('show');
	$('#' + type + '_content ul').empty();
	$.post(url + 'get_list.php', {type:type,session_id:sessionId}, function(data) {
		console.log(data);
		if (data == 'error') {
			// not logged in
			alert('Please log in to view fans and VIPs.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		} else if (data == 'no data') {
			// no post data
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		} else if (data == 'no users') {
			$('#' + type + '_content ul').append('<p>No users to show yet.</p>');
			$.mobile.loading('hide');
			return;
		}
		var list = JSON.parse(data);
		for (var i = 0; i < list.length; i++) {
			var liHtml = userListItem(list[i]);
			$('#' + type + '_content ul').append(liHtml);
		}
		$('#' + type + '_content ul').listview().listview('refresh');
		$.mobile.loading('hide');
	});
}

// build profile list page
function buildProfileListPage(type) {
	$.mobile.loading('show');
	$('#profile_' + type + '_content ul').empty();
	$.post(url + 'get_profile_list.php', {type:type,id:currentProfile,session_id:sessionId}, function(data) {
		console.log(data);
		if (data == 'no data') {
			// no post data
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		} else if (data == 'private') {
			// profile is private and user can't see it
			$('#profile_' + type + '_content ul').append("This user's profile is private");
			$.mobile.loading('hide');
			return;
		} else if (data == 'no users') {
			$('#profile_' + type + '_content ul').append('No users to show yet.');
			$.mobile.loading('hide');
			return;
		} else if (data == 'not a vip') {
			$('#profile_' + type + '_content ul').append('Only VIPs can see this list.');
			$.mobile.loading('hide');
			return;
		}
		var list = JSON.parse(data);
		for (var i = 0; i < list.length; i++) {
			var liHtml = userListItem(list[i]);
			$('#profile_' + type + '_content ul').append(liHtml);
		}
		$('#profile_' + type + '_content ul').listview().listview('refresh');
		$.mobile.loading('hide');
	});
}

// search for a set type and query
function search(type, query) {
	$.mobile.loading('show');
	$('#search_results').empty();
	searchOffset = 0;
	console.log('searching ' + query + ' of type ' + type);
	$.post(url + 'search.php', {type:type,query:query,offset:searchOffset,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'no results') {
			$.mobile.loading('hide');
			return;
		}
		if (type == 'hashtag') {
			// build list of posts
			var searchPosts = JSON.parse(data);
			console.log(searchPosts);
			for (var i = 0; i < searchPosts.length; i++) {
				var post = individualPost(searchPosts[i]);
				$('#search_results').append(post);
			}
			$('.post_metrics').controlgroup().controlgroup('refresh');
			$('.view_comments').button().button('refresh');
		}
		if (type == 'username' || type == 'realname') {
			// build list of users
			var users = JSON.parse(data);
			$('#search_results').append('<ul data-role="listview"></ul>');
			for (var i = 0; i < users.length; i++) {
				var liHtml = userListItem(users[i])
				$('#search_results ul').append(liHtml);
			}
			$('#search_results ul').listview().listview('refresh');
		}
		$('#search_results').append('<a data-role="button" id="more_search_results">More Search Results</a>');
		$('#more_search_results').button().button('refresh').click(function(e) {
			$(e.target).parent().remove();
			loadMoreSearchResults(type, query);
		});
		$.mobile.loading('hide');
	});
}

// load more search results
function loadMoreSearchResults(type, query) {
	$.mobile.loading('show');
	searchOffset += postsPerPage;
	$.post(url + 'search.php', {type:type,query:query,offset:searchOffset,session_id:(sessionId ? sessionId : false)}, function(data) {
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'no results') {
			$.mobile.loading('hide');
			return;
		}
		if (type == 'hashtag') {
			// build list of posts
			var searchPosts = JSON.parse(data);
			console.log(searchPosts);
			for (var i = 0; i < searchPosts.length; i++) {
				var post = individualPost(searchPosts[i]);
				$('#search_results').append(post);
			}
			$('.post_metrics').controlgroup().controlgroup('refresh');
			$('.view_comments').button().button('refresh');
		}
		if (type == 'username' || type == 'realname') {
			// build list of users
			var users = JSON.parse(data);
			for (var i = 0; i < users.length; i++) {
				var liHtml = userListItem(users[i])
				$('#search_results ul').append(liHtml);
			}
			$('#search_results ul').listview().listview('refresh');
		}
		$('#search_results').append('<a data-role="button" id="more_search_results">More Search Results</a>');
		$('#more_search_results').button().button('refresh').click(function(e) {
			$(e.target).parent().remove();
			loadMoreSearchResults(type, query);
		});
		$.mobile.loading('hide');
	});
}

// send fan request
function requestFan(id) {
	$.mobile.loading('show');
	$.post(url + 'request_fan.php', {id:id,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to become a fan.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		}
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'already a fan') {
			alert("You're already a fan!");
			$.mobile.loading('hide');
			return;
		}
		if (data == 'own') {
			alert("You can't become your own fan!");
			$.mobile.loading('hide');
			return;
		}
		if (data == 'already pending') {
			alert('You already have a pending fan request.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'request submitted') {
			alert('Your fan request has been submitted.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'success') {
			alert("You are now a fan! You'll see this user's posts on your home page.");
			$.mobile.loading('hide');
			return;
		}
	});
}

// send vip request
function requestVip(id) {
	$.mobile.loading('show');
	$.post(url + 'request_vip.php', {id:id,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to send a VIP request.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		}
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'already a vip') {
			alert("You're already a VIP!");
			$.mobile.loading('hide');
			return;
		}
		if (data == 'own') {
			alert("You can't become your own VIP!");
			$.mobile.loading('hide');
			return;
		}
		if (data == 'already pending') {
			alert('You already have a pending VIP request.');
			$.mobile.loading('hide');
			return;
		}
		if (data == 'request submitted') {
			alert('Your VIP request has been submitted.');
			$.mobile.loading('hide');
			return;
		}
	});
}

// build account page
function buildAccountPage() {
	$.mobile.loading('show');
	$.post(url + 'get_user_data.php', {require_log_in:true,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to make changes to your account.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		}
		if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.');
			$.mobile.loading('hide');
			return;
		}
		var userData = JSON.parse(data);
		$('#account_current_img').html('<img src="' + profileImageUrl + userData.image + '">');
		$('#account_bio').text(userData.bio);
		if (userData['private'] == 1) {
			$('#account_private').attr('checked', 'checked').checkboxradio().checkboxradio('refresh');
		}
		$.mobile.loading('hide');
	});
}

// submit changes to account
function editAccount(form) {
	$.mobile.loading('show');
	$('#account_session_id').val(sessionId);
	var options = {
		url: url + form.attr("action"),
		success: function(d) {
			console.log(d);
			if (d == 'error') {
				// not logged in
				alert('Please log in to make changes to your account.');
				loggedIn = false;
				sessionId = false;
				showLogIn();
				return;
			} else if (d == 'no data') {
				// no post data
				alert('Sorry, something went wrong. Please try again.');
				return;
			} else {
				var userData = JSON.parse(d);
				$('#account_current_img').html('<img src="' + profileImageUrl + userData.image + '">');
				$('#account_bio').text(userData.bio);
				if (userData['private'] == 1) {
					$('#account_private').attr('checked', 'checked').checkboxradio().checkboxradio('refresh');
				}
				$.mobile.loading('hide');
			}
		}
	};
	form.ajaxSubmit(options);
	return false;
}

// build notifications page
function buildNotificationsPage() {
	$.mobile.loading('show');
	notificationsCount = false;
	$('#notifications_content').empty();
	$.post(url + 'get_notifications.php', {session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to view your notifications.');
			loggedIn = false;
			sessionId = false;
			$.mobile.loading('hide');
			showLogIn();
			return;
		}
		if (data == 'no notifications') {
			$('#notifications_content').append('<p>No notifications.</p>');
			$.mobile.loading('hide');
			return;
		}
		notifications = JSON.parse(data);
		var ulHtml = '';
		for (var i = 0; i < notifications.length; i++) {
			ulHtml += notificationsListItem(notifications[i]);
		}
		$('#notifications_content').append(ulHtml).listview().listview('refresh');
		$('.notification_button').button().button('refresh');
		$.mobile.loading('hide');
	});
}

// delete a notification
function deleteNotification(id) {
	$.mobile.loading('show');
	$.post(url + 'delete_notification.php', {id:id,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to delete notifications.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		} else if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.')
			return;
		} else if (data == 'success') {
			$.mobile.loading('hide');
			notificationsCount = false;
			buildNotificationsPage();		
			return;
		}
	});
}

// vip response
function vipResponse(type, id) {
	$.mobile.loading('show');
	$.post(url + 'vip_response.php', {id:id,type:type,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to respond to VIP requests.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		} else if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.')
			return;
		} else if (data == 'success') {
			$.mobile.loading('show');
			buildNotificationsPage();		
			return;
		}
	});
}

// fan response
function fanResponse(type, id) {
	$.mobile.loading('show');
	$.post(url + 'fan_response.php', {id:id,type:type,session_id:(sessionId ? sessionId : null)}, function(data) {
		if (data == 'error') {
			// not logged in
			alert('Please log in to respond to fan requests.');
			loggedIn = false;
			sessionId = false;
			showLogIn();
			return;
		} else if (data == 'no data') {
			alert('Sorry, something went wrong. Please try again.')
			return;
		} else if (data == 'success') {
			$.mobile.loading('show');
			buildNotificationsPage();		
			return;
		}
	});
}

// populate notifications count
function populateNotificationsCount() {
	if (!notificationsCount) {
		$.post(url + 'get_notifications_count.php', {session_id:(sessionId ? sessionId : null)}, function(data) {
			if (data == 'error') {
				// not logged in
				alert('Please log in.');
				loggedIn = false;
				sessionId = false;
				showLogIn();
				return;
			} else if (data == 1) {
				notificationsCount = data;
				$('#notifications_count').text(notificationsCount + ' Notification');
			} else {
				notificationsCount = data;
				$('#notifications_count').text(notificationsCount + ' Notifications');
			}
		});
	} else {
		(notificationsCount == 1 ? $('#notifications_count').text(notificationsCount + ' Notification') : $('#notifications_count').text(notificationsCount + ' Notifications'));
	}
}

// build top page
function buildTopPage() {
	$.mobile.loading('show');
	$('#top_content ul').empty();
	$('#top_content div').empty();
	$.post(url + 'get_top_hashtags.php', function(data) {
		var hashtags = JSON.parse(data);
		for (var i = 0; i < hashtags.length; i++) {
			$('#top_content ul').append('<li><a class="hashtag_link">' + hashtags[i] + '</a></li>');
		}
		$('#top_content ul').listview().listview('refresh');
	});
	$.post(url + 'get_top_posts.php', function(data) {
		var posts = JSON.parse(data);
		var postsHtml = '';
		for (var i = 0; i < posts.length; i++) {
			postsHtml += individualPost(posts[i]);
		}
		$('#top_content div').append(postsHtml);
		$('.post_metrics').controlgroup().controlgroup('refresh');
		$('.post a.view_comments').button().button('refresh');
		$('a.more_profile_posts').button().button('refresh');
		$.mobile.loading('hide');
	});
}