function requestFriend(friend_id, stream) {
	if (typeof(stream) == 'undefined') { stream = false; }

	$.ajax({
		type: "POST",
		url: '/friends/request.json',
		data: { 
			friend_id: friend_id
		},
		beforeSend: function(){
			if ($('#friend_' + friend_id)) {
				$('#friend_' + friend_id).find('.cell-content-actions').html('<div class="loading"><img src="/images/icon_loading_white.gif"/></div>');
			}
		},
		success: function(data){
			if ($('#friend_' + friend_id)) {
				$('#friend_' + friend_id).slideUp();
			}
			if ($('a#request-friend')) {
				$('a#request-friend').hide();
			}
			if ($('a#remove-friend')) {
				$('a#remove-friend').show();
			}

			// Tracking
			if (stream) {
				if (stream == 'Profile' || stream == 'Facebook Find' || stream == 'Twitter Find') {
					_gaq.push(['_trackEvent', 'Count', 'Friend Requests', stream]);
				}
			}
		}
	});
}

function removeFriend(friend_id, stream) {
	if (typeof(stream) == 'undefined') { stream = false; }

	confirmed = confirm('Are you sure you want to remove this friend?');
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/friends/remove.json',
			data: { 
				friend_id: friend_id
			},
			beforeSend: function(){
			},
			success: function(data){
				if ($('#num_friends').length && $('.cell-collection').length) {
					f_count = parseInt($('#num_friends').html());
					f_count--;
					$('#num_friends').html(f_count);
					$('#friend_' + friend_id).slideUp(400, function() {
						$('.cell-item:visible:first', '.cell-collection').addClass('first');
					});
				} else {
					if ($('a#remove-friend')) {
						$('a#remove-friend').hide();
					}
					if ($('a#request-friend')) {
						$('a#request-friend').show();
					}
				}

				// Tracking
				if (stream) {
					if (stream == 'Profile' || stream == 'List') {
						_gaq.push(['_trackEvent', 'Count', 'Friends Deleted', stream]);
					}
				}
			}
		});
	}
}

function acceptFriend(friend_id) {
	$.ajax({
		type: "POST",
		url: '/friends/accept.json',
		data: { 
			friend_id: friend_id
		},
		beforeSend: function(){
		},
		success: function(data){
			num_requests = $('#num_requests').html();
			num_requests--;
			$('#num_requests').html(num_requests);
			$('#request_' + friend_id).slideUp(400, function() {
				$('.cell-item:visible:first', '.cell-collection').addClass('first');
				if (num_requests <= 0) {
					$('#no-requests').show();
				}
			});

			// Tracking
			_gaq.push(['_trackEvent', 'Count', 'Friends Confirmed']);
		}
	});
}

function declineFriend(friend_id) {
	$.ajax({
		type: "POST",
		url: '/friends/decline.json',
		data: { 
			friend_id: friend_id
		},
		beforeSend: function(){
		},
		success: function(data){
			num_requests = $('#num_requests').html();
			num_requests--;
			$('#num_requests').html(num_requests);
			$('#request_' + friend_id).slideUp(400, function() {
				$('.cell-item:visible:first', '.cell-collection').addClass('first');
				if (num_requests <= 0) {
					$('#no-requests').show();
				}
			});

			// Tracking
			_gaq.push(['_trackEvent', 'Count', 'Friends Declined']);
		}
	});
}

var total_votes = 0;
var up_votes = 0;
var neutral_votes = 0;
var can_vote = true;
var has_data = true;
var no_questions = false;
var color_placeholder = '#999',
    color_default = '#555';

function vote(value, is_friend_stream, is_direct) {
	if (typeof(is_friend_stream) == 'undefined') { is_friend_stream = false; }
	if (typeof(is_direct) == 'undefined') { is_direct = false; }
	if (can_vote != false) {
		var tracking = []; // Tracking
		can_vote = false;
		comment = '';
		total_votes++;
		if (value == 0) {
			$('#vote-choice').html('Thumbs Down');
			// Tracking
			if (is_friend_stream) {
				if (is_direct) {
					tracking.push(['_trackEvent', 'Votes', 'Thumbs Down - DQ']);
				} else {
					tracking.push(['_trackEvent', 'Votes', 'Thumbs Down - FQ']);
				}
			} else {
				tracking.push(['_trackEvent', 'Votes', 'Thumbs Down']);
			}
		}
		if (value == 1) {
			up_votes++;
			$('#vote-choice').html('Thumbs Up');
			// Tracking
			if (is_friend_stream) {
				if (is_direct) {
					tracking.push(['_trackEvent', 'Votes', 'Thumbs Up - DQ']);
				} else {
					tracking.push(['_trackEvent', 'Votes', 'Thumbs Up - FQ']);
				}
			} else {
				tracking.push(['_trackEvent', 'Votes', 'Thumbs Up']);
			}
		}
		if (value == 2) {
			neutral_votes++;
			$('#vote-choice').html('Neutral');
			// Tracking
			if (is_friend_stream) {
				if (is_direct) {
					tracking.push(['_trackEvent', 'Votes', 'Neutral - DQ']);
				} else {
					tracking.push(['_trackEvent', 'Votes', 'Neutral - FQ']);
				}
			} else {
				tracking.push(['_trackEvent', 'Votes', 'Neutral']);
			}
		}

		total_votes_for_calc = (total_votes - neutral_votes);
		up_percentage = Math.round(up_votes / total_votes_for_calc * 100);
		down_votes = total_votes_for_calc - up_votes;
		down_percentage = Math.round(down_votes / total_votes_for_calc * 100);

		$('#percentages span.up-percentage').html(up_percentage + '%');
		$('#percentages span.down-percentage').html(down_percentage + '%');
		$('#total-votes').html(total_votes);

		if (neutral_votes != total_votes) {
			$('#percentages').show();
			$('#neutral').hide();
		} else {
			$('#percentages').hide();
			$('#neutral').show();
		}

		if ($('#comment').val() != '' && $('#comment').val() != 'Please leave a comment') {
			comment = $('#comment').val();
			// Tracking
			if (is_friend_stream) {
				if (is_direct) {
					tracking.push(['_trackEvent', 'Count', 'Comments', 'Direct']);
				} else { 
					tracking.push(['_trackEvent', 'Count', 'Comments', 'Friend']);
				}
			} else {
				tracking.push(['_trackEvent', 'Count', 'Comments', 'Public']);
			}
		}
		question_id = $('.question-vote').attr('id').split('_');
		question_id = question_id[1];
		$.ajax({
			type: "POST",
			url: '/vote/add.json',
			timeout: 10000,
			data: {
				question_id: question_id,
				value: value,
				comment: comment
			},
			beforeSend: function(){
				has_data = false;
				showSummary();
			},
			error: function(jqXHR, textStatus, errorThrown) {
				if (textStatus == 'timeout') {
					handleVoteTimeout();
				}
			},
			success: function(data){
				result = jQuery.parseJSON(data);
				if (result.meta.code == 200) {
					// Tracking 
					if (is_friend_stream) {
						if (is_direct) {
							tracking.push(['_trackEvent', 'Count', 'Votes', 'Direct']);
						} else {
							tracking.push(['_trackEvent', 'Count', 'Votes', 'Friend']);
						}
					} else {
						tracking.push(['_trackEvent', 'Count', 'Votes', 'Public']);
					}

					// Add pageview 
					tracking.push(['_trackPageview', '/vote']);

					// Tracking (Send)
					$.each(tracking, function(index, event) {
						_gaq.push(event);
					});
					
					if (!is_friend_stream) {
						getNextQuestion();
					} else {
						getNextFriendQuestion();
					}
					var timeout = setTimeout(function(){
						count = parseInt($('#rail-profile-vote-count').html());
						count++;
						$('#rail-profile-vote-count').html(count);
						$('#comment').val('Please leave a comment');
						$('#comment').val($('#comment').attr('title')).css('color', color_placeholder);
						$('#question_' + question_id).remove();
						waitForData(is_friend_stream);
					}, 2000);
				} else if (result.meta.code == 403) {
					if (!is_friend_stream) {
						getNextQuestion();
					} else {
						getNextFriendQuestion();
					}
					var timeout = setTimeout(function(){
						$('#comment').val('Please leave a comment');
						$('#comment').val($('#comment').attr('title')).css('color', color_placeholder);
						$('#question_' + question_id).remove();
						waitForData(is_friend_stream);
					}, 2000);
				}
			}
		});	
	}
}

function showSummary() {
	$('#overlay-vote-summary').show();
	var timeout = setTimeout(function(){
		$('#overlay-vote-summary').hide();
		if (!has_data) {
			$('#overlay-loader').show();
			$('#overlay-loader .text').html('Loading...');
		}
	}, 2000);
}

function handleVoteTimeout() {
	can_vote = true;
	$('#overlay-loader').hide();
	alert('There was a problem sending your vote. Please try again.');
}

function waitForData(is_friend_stream) {
	if (has_data) {
		clearTimeout(loading_timeout);
		can_vote = true;
		$('#overlay-loader').hide();
		if (!no_questions) {
			setVoteImageOrientation();
			$('span#category-name').html($('div#question-inject div.question-vote span.question-category-name').html());
		} else {
			$('div#bummer').show();
			$('div#question-container').hide();
			if (!is_friend_stream) {
				$('div.category-title').hide();
			} else {
				$('div.filter-vote-stream-button').hide();
			}
		}
		return;
	} else {
		var loading_timeout = setTimeout('waitForData(' + is_friend_stream + ')', 100);
	}
}

function getNextQuestion() {
	$.ajax({
		type: "POST",
		url: '/questions/publicstream.fragment',
		data: {
		},
		success: function(data){
			data = jQuery.trim(data);

			// Check for any alerts/commands that need to be displayed
			checkActions(['confirm_dob']);

			if (data != '') {
				$('#question-inject').append(data);
			} else {
				no_questions = true;
			}
			has_data = true;
		}
	});
}

function getNextFriendQuestion() {
	$.ajax({
		type: "POST",
		url: '/questions/friendstream.fragment',
		data: {
		},
		success: function(data){
			data = jQuery.trim(data);
			if (data != '') {
				$('#question-inject').append(data);
			} else {
				no_questions = true;
			}
			has_data = true;
		}
	});
}

function filterStream() {
	ages = new Array();
	$("#age-filters input:checked").each(function(){
		ages.push($(this).val());
	});
	ages = ages.join(',');

	categories = new Array();
	$("#category-filters input:checked").each(function(){
		categories.push($(this).val());
	});
	categories = categories.join(',');

	$.ajax({
		type: "POST",
		url: '/vote/filter.json',
		data: {
			ages: ages,
			categories: categories
		},
		success: function(data){
			window.location.reload();
		}
	});
}

function checkQuestion() {
	if ($('#question').val() == 'Ask your question here') {
		$('#question').val('');
	}
}

function loginFacebook(access_token) {
	$.ajax({
		type: "POST",
		url: '/users/loginfacebook.json',
		data: {
			access_token: access_token
		},
		beforeSend: function(){
			$('#overlay-loader').show();
			$('#overlay-loader .text').html('Logging in...');
		},
		success: function(data){
			result = jQuery.parseJSON(data);
			if (result.redirect != '') {
				window.location = result.redirect;
			} else {
				window.location.reload();
			}
		}
	});
}

function socialConnect(method, token, callback) {
	if (typeof(callback) == 'undefined') { callback = false; }

	$.ajax({
		type: "POST",
		url: '/users/connect.json',
		data: {
			method: method,
			token: token
		},
		beforeSend: function(){
			$('#overlay-loader').show();
			$('#overlay-loader .text').html('Connecting...');
		},
		success: function(data){
			// Tracking
			// Note: Twitter does not use this function. See twitter.js
			// authorizeTwitter for tracking
			_gaq.push(['_trackEvent', 'User', 'Link', method.ucfirst()]);

			result = jQuery.parseJSON(data);
			$('#overlay-loader').hide();
			if ($('a#connect-facebook')) {
				$('a#connect-facebook').hide();
				$('a#disconnect-facebook').show();
			}
			if (result.result) {
				if (callback) {
					callback(method);
				}
			} else {
			}
		}
	});
}

function socialDisconnect(method) {
	$.ajax({
		type: "POST",
		url: '/users/disconnect.json',
		data: {
			method: method
		},
		beforeSend: function(){
			$('#overlay-loader').show();
			$('#overlay-loader .text').html('Unlinking...');
		},
		success: function(data){
			// Tracking
			_gaq.push(['_trackEvent', 'User', 'Unlink', method.ucfirst()]);

			result = jQuery.parseJSON(data);
			$('#overlay-loader').hide();
			if (method == 'facebook') {
				$('a#connect-facebook').show();
				$('a#disconnect-facebook').hide();
			}
			if (method == 'twitter') {
				oa.twitter_connected = false;
				$('a#connect-twitter').show();
				$('a#disconnect-twitter').hide();
			}
		}
	});
}

var shareQuestionVote = function (method, fb_uid, email) {
	question_id = $('.question-vote').attr('id').split('_');
	question_id = question_id[1];

	$.ajax({
		type: "POST",
		url: '/questions/share.json',
		data: {
			method: method,
			question_id: question_id,
			fb_uid: fb_uid,
			email: email
		},
		beforeSend: function(){
			$('#overlay-loader').show();
			$('#overlay-loader .text').html('Sharing...');
		},
		success: function(data){
			result = jQuery.parseJSON(data);
			if (!result.result) {
				$('#overlay-loader').hide();
				$('#refer-overlay span.warning').show();
			} else {
				$('#refer-overlay').hide();
				$('#refer-overlay span.warning').hide();
				$('#refer-email').val('');
				$('#overlay-loader #loading-image').hide();
				$('#overlay-loader .text').html('Shared.');
				$('#overlay-loader #ok-button').show();

				// Tracking
				_gaq.push(['_trackEvent', 'Sharing', 'Vote', method.ucfirst()]);
			}
		}
	});
}

var shareQuestionResults = function (method) {
	question_id = $('.question-results').attr('id').split('_');
	question_id = question_id[1];
	
	$.ajax({
		type: "POST",
		url: '/questions/shareresults.json',
		data: {
			method: method,
			question_id: question_id
		},
		beforeSend: function(){
			$('#overlay-loader').show();
		},
		success: function(data){
			result = jQuery.parseJSON(data);
			$('#overlay-loader #loading-image').hide();
			$('#overlay-loader .text').html('Shared.');
			$('#overlay-loader #ok-button').show();

			// Tracking
			_gaq.push(['_trackEvent', 'Sharing', 'Results', method.ucfirst()]);
		}
	});
}

function inviteFriendsFacebook(fb_uid) {
	if (typeof(fb_uid) == 'undefined') { fb_uid = ''; }

	$.ajax({
		type: "POST",
		url: '/friends/invite.json',
		data: {
			method: 'facebook',
			fb_uid: fb_uid
		},
		beforeSend: function(){
			if (fb_uid != '' && $('#friend_' + fb_uid)) {
				$('#friend_' + fb_uid).find('.cell-content-actions').html('<div class="loading"><img src="/images/icon_loading_white.gif"/></div>');
			} else {
				$('#overlay-loader').show();
			}
		},
		success: function(data){
			obj = jQuery.parseJSON(data);
			if (obj.result == true) {
				if (fb_uid != '' && $('#friend_' + fb_uid)) {
					$('#friend_' + fb_uid).find('.cell-content-actions').html('<span class="sent">Sent!</span>');

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Invites', 'Facebook Find']);
				} else {
					$('#overlay-loader #loading-image').hide();
					$('#overlay-loader .text').html('Posted.');
					$('#overlay-loader #ok-button').show();
					
					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Invites', 'Post to Facebook']);
				}
			} else {
				if ($('#overlay-loader')) {
					$('#overlay-loader #loading-image').hide();
					$('#overlay-loader .text').html('Posted.');
					$('#overlay-loader #ok-button').show();

					// Note: invitations are limited so only track event if
					// return is successful
				}
			}
		}
	});
}

function inviteFriendsTwitter(twitter_uid) {
	if (typeof(twitter_uid) == 'undefined') { twitter_uid = ''; }

	$.ajax({
		type: "POST",
		url: '/friends/invite.json',
		data: {
			method: 'twitter',
			twitter_uid: twitter_uid
		},
		beforeSend: function(){
			if (twitter_uid != '' && $('#friend_' + twitter_uid)) {
				$('#friend_' + twitter_uid).find('.cell-content-actions').html('<div class="loading"><img src="/images/icon_loading_white.gif"/></div>');
			} else {
				$('#overlay-loader').show();
				$('#overlay-loader .text').html('Tweeting...');
			}
		},
		success: function(data){
			obj = jQuery.parseJSON(data);
			if (obj.result == true) {
				if (twitter_uid != '' && $('#friend_' + twitter_uid)) {
					$('#friend_' + twitter_uid).find('.cell-content-actions').html('<span class="sent">Sent!</span>');

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Invites', 'Twitter Find']);
				} else {
					$('#overlay-loader #loading-image').hide();
					$('#overlay-loader .text').html('Tweeted.');
					$('#overlay-loader #ok-button').show();

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Invites', 'Post to Twitter']);
				}
			} else {
				if ($('#overlay-loader')) {
					$('#overlay-loader #loading-image').hide();
					$('#overlay-loader .text').html('Tweeted.');
					$('#overlay-loader #ok-button').show();

					// Note: invitations are limited so only track event if
					// return is successful
				}
			}
		}
	});
}

function inviteFriendsEmail() {
	var email_pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	var emails = new Array();
	$('#invite-box input.text').each(function() {
		email = $(this).val();
		if (email_pattern.test(email)) {
			emails.push(email);
		}
	});
	if (emails.length > 0) {
		var tracking = emails;

		emails = emails.join(',');

		$.ajax({
			type: "POST",
			url: '/friends/invite.json',
			data: {
				method: 'email',
				email: emails
			},
			beforeSend: function(){
				$('#overlay-loader .text').html('Sending...');
				$('#overlay-loader').show();
			},
			success: function(data){
				obj = jQuery.parseJSON(data);
				$('#overlay-loader #loading-image').hide();
				$('#overlay-loader .text').html('Sent.');
				$('#overlay-loader #ok-button').show();

				// Tracking (Send)
				$.each(tracking, function(index, email) {
					_gaq.push(['_trackEvent', 'Count', 'Invites', 'Email']);
				});
			}
		});
	} else { 
		alert('Please enter some valid e-mail addresses.');
	}
}

var findFriends = function (method) {
	window.location = '/friends/find?method=' + method;
}

function askCheckTwitter() {
	if (!oa.twitter_connected) {
		$('input#share_twitter').attr('checked', false);
	} else {
		$('input#share_twitter').attr('checked', true);
	}
}

function loadRegions() {
	country = $('select#country :selected').attr('id');

	if (country) {
		$.ajax({
			type: "POST",
			url: '/locations/regions.json',
			data: {
				country: country
			},
			beforeSend: function(){
				$('#overlay-loader').show();
				$('#overlay-loader .text').html('Loading...');
			},
			success: function(data){
				var regions = jQuery.parseJSON(data);
				$('select#region').html('');
				$('select#region').append('<option value="">--- SELECT ---</option>');
				$(regions.region).each(function() { 
					option = $('<option value="' + this.id + '">' + this.name + '</option>');				
					$('select#region').append(option);
				});
				$('select#region').attr('disabled', false);
				$('#overlay-loader').hide();
			}
		});
	} else {
		$('select#region').html('');
		$('select#region').append('<option value="">--- SELECT ---</option>');
	}	
}

function setHelpful(answer_id, stream) {
	if (typeof(stream) == 'undefined') { stream = false; }
	
	$.ajax({
		type: "POST",
		url: '/answers/sethelpful.json',
		data: {
			answer_id: answer_id
		},
		beforeSend: function(){
		},
		success: function(data){
			$('a#star_' + answer_id).addClass('active');
			$('a#star_' + answer_id).click(function() { return false; });
			
			// Tracking
			if (stream) {
				if (stream == 'Conversation' || stream == 'Details') {
					_gaq.push(['_trackEvent', 'Count', 'Helpful', stream]);
				}
			}
		}
	});
}

var friends_loaded = false;
var flash_upload = true;
var default_visible = true; 
function selectFriends() {
	if (!$('#question-picture').is(':visible')) { flash_upload = false; }
	if (flash_upload) {
		if ($('#question-picture').find('#question-placeholder-default-container').is(':visible')) {
			$('#question-picture').find('#question-placeholder-default-container').hide();
		}
		if ($('#question-picture').find('#question-placeholder-change-container').is(':visible')) {
			$('#question-picture').find('#question-placeholder-change-container').hide();
			default_visible = false;
		}
	}

	$('#overlay').show();
	if (!friends_loaded) {
		$.ajax({
			type: "POST",
			url: '/ask/friends.fragment',
			beforeSend: function(){
				$('#overlay-loader').show();
				$('#overlay-loader p.text').html('Loading...');
			},
			success: function(data){
				friends_loaded = true;
				$('#overlay-loader').hide();
				$('#friends-inject').html(data);
			}
		});
	}
}

function selectFriendsDone() {
	count = $('.ask-friends-cells input:checked').size();
	if (flash_upload) {
		if (default_visible) {
			$('#question-picture').find('#question-placeholder-default-container').show();
		} else {
			$('#question-picture').find('#question-placeholder-change-container').show();
		}
	}
	$('#overlay').hide();
	$('#selected-friend-count').html(count);
	$('#selected-friend-count-input').val(count);
}

function closeQuestion(question_id) {
	confirmed = confirm('Are you sure you want to delete this question?');
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/questions/close.json',
			data: {
				question_id: question_id
			},
			beforeSend: function(){
			},
			success: function(data){
				$('#question_' + question_id).slideUp(400, function() {
					$('div:visible:first', '.cell-collection').addClass('first');
					if ($('div:visible', '.cell-collection').length == 0) {
						$('div.no-content').show();
					}
				});
				offset--;

				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Deleted Questions', 'Asked']);
			}
		});
	}
}

function closeAnswer(answer_id) {
	confirmed = confirm('Are you sure you want to delete this question?');
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/answers/close.json',
			data: {
				answer_id: answer_id
			},
			beforeSend: function(){
			},
			success: function(data){
				$('#answer_' + answer_id).slideUp(400, function() {
					$('div:visible:first', '.cell-collection').addClass('first');
					if ($('div:visible', '.cell-collection').length == 0) {
						$('div.no-content').show();
					}
				});
				offset--;

				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Deleted Questions', 'Helped']);
			}
		});
	}
}

function closeConversation(answer_id, stream) {
	if (typeof(stream) == 'undefined') { stream = false; }
	confirmed = confirm('Are you sure you want to permanently end this conversation?');
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/answers/blockreplies.json',
			data: {
				answer_id: answer_id
			},
			beforeSend: function(){
			},
			success: function(data){
				// Tracking
				if (stream) {
					if (stream == 'Asked' || stream == 'Helped') {
						_gaq.push(['_trackEvent', 'Count', 'Closed Conversations', stream]);
					}
				}

				window.location.reload();
			}
		});
	}
}

function closeFriendQuestion(question_id) {
	confirmed = confirm('Are you sure you want to delete this question?');
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/questions/skip.json',
			data: {
				question_id: question_id
			},
			beforeSend: function(){
			},
			success: function(data){
				q_count = parseInt($('#friend-question-count').html());
				q_count--;
				$('#friend-question-count').html(q_count);
				//$('#question_' + question_id).slideUp();
				$('#question_' + question_id).slideUp(400, function() {
					$('.cell-item:visible:first', '.cell-collection').addClass('first');
				});
				offset--;

				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Deleted Friend Questions']);
			}
		});
	}
}

function notifyAndroid() {
	email = $('#android-email').val();
	$.ajax({
		type: "POST",
		url: '/users/notifyandroid.json',
		data: {
			email: email
		},
		beforeSend: function(){
		},
		success: function(data){
			var result = jQuery.parseJSON(data);
			if (!result.result) {
				$('#android-warning').show();
			} else {
				$('#android-warning').hide();

				if ($('#android-form-container').length) {
					// splash
					$('#android-form-container').hide();
				} else {
					$('#android-signup-box').hide();
				}
				if ($('#android-form-thanks').length) {
					// splash
					$('#android-form-thanks').show();
				} else {
					$('#android-thanks').show();
				}

				if ($('#android-bot').length) {
					$('#android-bot').addClass('speak');
				}
				if ($('div.droid-bot').length) {
					$('div.droid-bot').addClass('speak');
				}

				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Android Notification Signups']);
			}
		}
	});
}

function maybeFlagQuestion(is_friend_stream) {
	if (typeof(is_friend_stream) == 'undefined') { is_friend_stream = false; }

	question_id = $('.question-vote').attr('id').split('_'),
	question_id = question_id[1],
	flag_id = $('#flag-question-category').val(),
	message = "Thank you for helping keep Thumb clean. We take our community seriously and want to ensure that everyone has a great experience. We ask that you take it seriously as well. Are you sure you want to flag this question?",
	$flag_warning = $('#flag-question-category-error');

	if (!flag_id || flag_id === '') {
		$flag_warning.show();
		return false;
	}
	$flag_warning.hide();

	confirmed = confirm(message);
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/questions/flag.json',
			data: {
				question_id: question_id,
				flag_id: flag_id
			},
			beforeSend: function(){
				has_data = false;
			},
			success: function(data){
				if (!is_friend_stream) {
					getNextQuestion();

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Flagged Questions', 'Public']);
				} else {
					getNextFriendQuestion();

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Flagged Questions', 'Friend']);
				}

				$('#question_' + question_id).remove();
				hideFlagQuestion();
				waitForData(is_friend_stream);
			}
		});

		delete confirmed; // reset confirm dialog
	} else {
		delete confirmed; // reset confirm dialog
	}
}

function maybeSuggestCategory(is_friend_stream) {
	if (typeof(is_friend_stream) == 'undefined') { is_friend_stream = false; }

	question_id = $('.question-vote').attr('id').split('_'),
	question_id = question_id[1],
	category_id = $('#suggest-category-category').val(),
	message = "Thank you for helping keep Thumb clean. Keeping questions properly categorized helps people get better opinions and advice. Please make sure you've selected a relevant category. Are you sure you want to suggest a new category for this question?";
	$category_warning = $('#suggest-category-error');
	
	if (!category_id || category_id === '') {
		$category_warning.show();
		return false;
	}
	$category_warning.hide();

	confirmed = confirm(message);
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/questions/suggestcategory.json',
			data: {
				question_id: question_id,
				category_id: category_id
			},
			beforeSend: function(){
				has_data = false;
			},
			success: function(data){
				if (!is_friend_stream) {
					getNextQuestion();

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Question Category Suggestions', 'Public']);
				} else {
					getNextFriendQuestion();

					// Tracking
					_gaq.push(['_trackEvent', 'Count', 'Question Category Suggestions', 'Friend']);
				}

				$('#question_' + question_id).remove();
				hideFlagQuestion();
				waitForData(is_friend_stream);
			}
		});

		delete confirmed; // reset confirm dialog
	} else {
		delete confirmed; // reset confirm dialog
	}
}

function maybeFlagComment(user_id, comment) {
	message = "Thank you for helping keep Thumb clean. We take our community seriously and want to ensure that everyone has a great experience. We ask that you take it seriously as well. Are you sure you want to flag this comment?",
	flag_id = 8;	

	confirmed = confirm(message);
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/users/flag.json',
			data: {
				user_id: user_id,
				flag_id: flag_id,
				comment: comment
			},
			beforeSend: function(){
			},
			success: function(data){
				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Flagged Comments']);
			}
		});

		delete confirmed; // reset confirm dialog
	} else {
		delete confirmed; // reset confirm dialog
	}
}

function maybeFlagUser() {
	user_id = $('#flag-user-id').val(),
	comment = $('#flag-user-comment').val(),
	flag_id = 9,
	message = "Thank you for helping keep Thumb clean. We take our community seriously and want to ensure that everyone has a great experience. We ask that you take it seriously as well. Are you sure you want to flag this user?",
	$flag_warning = $('#flag-user-error');

	comment = jQuery.trim(comment);

	if (!comment || comment === '') {
		$flag_warning.show();
		return false;
	}
	$flag_warning.hide();

	confirmed = confirm(message);
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/users/flag.json',
			data: {
				user_id: user_id,
				flag_id: flag_id,
				comment: comment
			},
			beforeSend: function(){
			},
			success: function(data){
				hideFlagUser();

				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Flagged Profiles']);
			}
		});

		delete confirmed; // reset confirm dialog
	} else {
		delete confirmed; // reset confirm dialog
	}
}

function maybeBlockUser(user_id) {
	message = "Are you sure you want to permanently block this person?";

	confirmed = confirm(message);
	if (confirmed) {
		$.ajax({
			type: "POST",
			url: '/users/block.json',
			data: {
				user_id: user_id
			},
			beforeSend: function(){
			},
			success: function(data){
				$('#user-flag-controls').hide();
				$('#user-blocked').show();

				// Tracking
				_gaq.push(['_trackEvent', 'Count', 'Profile Blocks']);
			}
		});

		delete confirmed; // reset confirm dialog
	} else {
		delete confirmed; // reset confirm dialog
	}
}

/* ***************************************************************************
 *
 * ALERT / COMMAND / ERROR (ACE) POP-UPS AND CACHING CONTROL
 *
 * *************************************************************************** */

// ACE: (error) user_underage 
// Note: User is redirected out of site when this is activated.
function forceUnderagePopup() {
	$('#error-user-underage').modal({ show: true, keyboard: false, backdrop: 'static' });

	// Tracking
	_gaq.push(['_trackEvent', 'Count', 'Underage Redirects']);

	$('#error-user-underage-redirect').bind('click', function(e) {
		e.preventDefault();
		window.location = 'http://thumb.it/underage';
	});
}

// ACE: (error) invalid_dob 
// Note: See updateNoDOB() helper function. Error is not saved in cache and should
// appear every time a user tries to ask a question and does not have a valid birthdate.
function forceNoDOBPopup() {
	$('#error-no-dob').modal({ keyboard: false, backdrop: 'static', show: true });
}

// ACE: (error) invalid_email 
// Note: See updateInvalidEmail() helper function. Error is not saved in cache and should
// appear every time a user tries to ask a question and does not have a valid email.
function forceInvalidEmailPopup() {
	$('#error-invalid-email').modal({ keyboard: false, backdrop: 'static', show: true });
}

function updateInvalidEmail() {
	var email = $('#email').val();
	if ( email === "Email" ) { email = '' }

	$.ajax({
		type: "POST",
		url: '/profile/updateemail.json',
		data: {
			email: email
		},
		beforeSend: function(){
		},
		success: function(data){
			var result = jQuery.parseJSON(data);
			if (!result.result) {
				$('#error-invalid-email-form-error').find('li').text(result.error).end().show();
			} else {
				// Tracking

				// Submit form once the user enters a valid email
				$('#question-form').submit();
			}
		}
	});
}

function updateNoDOB() {
	var month = $('#dob_month').val(),
		day = $('#dob_day').val(),
		year = $('#dob_year').val();

	$.ajax({
		type: "POST",
		url: '/profile/updatebirthdate.json',
		data: {
			dob_month: month,
			dob_day: day,
			dob_year: year
		},
		beforeSend: function(){
		},
		success: function(data){
			var result = jQuery.parseJSON(data);
			if (!result.result) {
				$('#error-no-dob-form-error').find('li').text(result.error).end().show();
			} else {
				// Tracking

				// Submit form once the user enters a valid birthdate
				$('#question-form').submit();
			}
		}
	});
}

function confirmDOB(id) {
	var month = $('#dob_month').val(),
		day = $('#dob_day').val(),
		year = $('#dob_year').val();

	$.ajax({
		type: "POST",
		url: '/profile/confirmbirthdate.json',
		data: {
			dob_month: month,
			dob_day: day,
			dob_year: year
		},
		beforeSend: function(){
		},
		success: function(data){
			var result = jQuery.parseJSON(data);
			if (!result.result) {
				$('#command-confirm-dob-form-error').find('li').text(result.error).end().show();
			} else {
				// Hide alert
				$('#command-confirm-dob').modal({ hide: true });
				
				// Dismiss
				//dismissCommand(id);	

				// Tracking
			}
		}
	});
}

function dismissCommand(id) {
	// Dismiss command (user has responded successfully)
	/*var commands_viewed = false;
	if ($.cookie('commands_viewed')) {
		commands_viewed = JSON.parse($.cookie('commands_viewed'));
	}
	if (commands_viewed) {
		commands_viewed.push(id);
		commands_viewed = JSON.stringify(commands_viewed);
	} else {
		commands_viewed = [id];
		commands_viewed = JSON.stringify(commands_viewed);
	}
	$.cookie('commands_viewed', commands_viewed, { path: '/' });*/

	var has_commands = false;

	if ($.cookie('commands')) {
		var commands = jQuery.parseJSON($.cookie('commands'));
		has_commands = true;
	}

	if (has_commands) {
		// Remove command based on index
		commands.splice(id, 1);	

		if (commands.length === 0) {
			// Delete commands cookie
			$.cookie('commands', null, { path: '/' });
		} else {
			// Update commands cookie
			$.cookie('commands', commands, { path: '/' });
		}
	}
}

function checkActions(type) {
	if (typeof type === 'undefined') { var type = false; }

	var has_alerts = false,
		has_commands = false,
		commands_viewed = false,
		alerts_viewed = false,
		skip_alerts = false;

	// If there is no 'type', there is no need to check for commands
	if (type) {
		// Get dismissed commands
		/*if ($.cookie('commands_viewed')) {
			commands_viewed = JSON.parse($.cookie('commands_viewed'));
		}*/

		// Check if commands cookie exists and if there are any relevant commands
		if ($.cookie('commands')) {
			var commands = jQuery.parseJSON($.cookie('commands'));
			has_commands = true;
		}

		if (has_commands) {
			var show_command_index = false;

			$.each(commands, function(index, command) {
				// Does the type match?
				if ($.inArray(command.type, type) > -1) {
					show_command_index = index;
					return false; // breaks loop

					// Make sure it has not already been viewed
					/*if (commands_viewed) {
						if ($.inArray(command.id, commands_viewed) == -1) {
							show_command_index = index;
							return false; // breaks loop
						}
					} else {
						show_command_index = index;
						return false; // breaks loop
					}*/
				}
			});

			// Render a command (if needed)
			if (show_command_index !== false) {
				skip_alerts = true;
				renderCommand(type, JSON.stringify(commands[show_command_index]));  				

				// Dismiss
				dismissCommand(show_command_index);
			}
		}
	}

	// Check for alerts
	if (!skip_alerts) {
		// Get dismissed alerts
		if ($.cookie('alerts_viewed')) {
			alerts_viewed = JSON.parse($.cookie('alerts_viewed'));
		}

		// Check if alerts cookie exists and if there are any relevant alerts
		if ($.cookie('alerts')) {
			var alerts = jQuery.parseJSON($.cookie('alerts'));
			has_alerts = true;
		}

		if (has_alerts) {
			var show_alert_index = false;
			
			$.each(alerts, function(index, item) {
				if (alerts_viewed) {
					// Make sure it has not already been viewed
					if (typeof item.id !== "undefined") {
						var id = item.id.toString();
						if ($.inArray(id, alerts_viewed) == -1) {
							show_alert_index = index;
							return false; // breaks loop
						}
					}
					if (typeof item.nonce !== "undefined") {
						var nonce = item.nonce.toString();
						if ($.inArray(nonce, alerts_viewed) == -1) {
							show_alert_index = index;
							return false; // breaks loop
						}
					}

					// For potential unidentified alerts? 
					//show_alert_index = index;
					//return false; // breaks loop
				} else {
					show_alert_index = index;
					return false; // breaks loop
				}
			});

			if (show_alert_index !== false) {
				renderAlert(JSON.stringify(alerts[show_alert_index]));
				
				// Dismiss 
				if (typeof alerts[show_alert_index].id !== "undefined") { var dismiss_id = alerts[show_alert_index].id.toString(); }
				if (typeof alerts[show_alert_index].nonce !== "undefined") { var dismiss_id = alerts[show_command_index].nonce.toString(); }
				if (alerts_viewed) {
					alerts_viewed.push(dismiss_id);
				} else {
					alerts_viewed = [dismiss_id];
				}
				alerts_viewed = JSON.stringify(alerts_viewed);
				$.cookie('alerts_viewed', alerts_viewed, { path: '/' });
			}
		}
	}
}

function renderCommand(type, data) {
	// 'confirm_dob'
	if (typeof type !== "undefined" && type == 'confirm_dob') {
		data = JSON.parse(data);
		$('#confirm_dob_template').tmpl(data, {
			id: function() {
				return data.id; 
			},
			dob_month: function() {
				if (typeof data.info !== "undefined") {
					if (typeof data.info.dob !== "undefined" ) {
						var dob = data.info.dob.split('-');
						return (dob[1] != '00') ? dob[1] : 'MM';
					}
					return 'MM';
				} else {
					return 'MM';
				}
			},
			dob_day: function() {
				if (typeof data.info !== "undefined") {
					if (typeof data.info.dob !== "undefined" ) {
						var dob = data.info.dob.split('-');
						return (dob[2] != '00') ? dob[2] : 'DD';
					}
					return 'DD';
				} else {
					return 'DD';
				}
			},
			dob_year: function() {
				if (typeof data.info !== "undefined") {
					if (typeof data.info.dob !== "undefined" ) {
						var dob = data.info.dob.split('-');
						return (dob[0] != '0000') ? dob[0] : 'YYYY';
					}
					return 'YYYY';
				} else {
					return 'YYYY';
				}
			}
		}).appendTo('body');
	
		// Respect newlines! 
		replaceNewLines();

		// Setup date picker widget on inserted form
		$('#dob_widget').dobWidget();

		// Launch alert
		$('#command-confirm-dob').modal({ keyboard: false, backdrop: 'static', show: true });
	} /* end: confirm_dob */

	// Other types of commands ... 
}

function renderAlert(data) {
	data = JSON.parse(data);
	$('#generic_alert_template').tmpl(data, {
		title: function() {
			return data.title.replace(/\+/g, " ");
		},
		message: function() {
			return data.message.replace(/\+/g, " ");
		},
		id: function() {
			return data.id; 
		}
	}).appendTo('body');

	// Respect newlines! 
	replaceNewLines();

	// Launch alert
	$('#alert-generic-' + data.id).modal({ keyboard: true, backdrop: true, show: true });
}

function replaceNewLines() {
	var $popups = $('div[id^="alert-generic-"]');
	if ($popups.length > 0) {
		$.each($popups, function(index, item) {
			var msg = $(item).find('.modal-body p:first').html().replace(/(\r\n|\n|\r)/gm, "<br/><br/>");
			$(item).find('.modal-body p:first').html(msg);
		});
	}
}

function alertButtonPress() {
	$('div[id^="alert-generic-"]').modal({hide: true});
}

