def post(self):
		currentTrip = userprefs.get_users_current_trip()
		if self.request.get('is_delete') == 'True':
			try:
				currentTrip.delete_transaction(int(self.request.get('transaction_id')))
			except:
				logging.warning("Error: Exception occurred and transaction was not deleted.")
		elif self.request.get('is_add_on') == 'True':
			try:
				email_address = self.request.get('email_address')
				currentTrip.create_add_on(email_address = self.request.get('email_address'),
					challenge_type = int(self.request.get('challenge_type')),
					used_add_on=True)
			except:
				logging.warning("Error: Exception occurred and add on was not added.")
		else:
			try:
				gamePlayed = self.request.get('game_played_select')
				if not gamePlayed or len(gamePlayed) == 0 or gamePlayed == "Other":
					gamePlayed = self.request.get('game_played_text')
				if len(gamePlayed) == 0:
					gamePlayed = 'No game listed'
			 	casino = self.request.get('casino_select')
				if not casino or len(casino) == 0 or casino == "Other":
					casino = self.request.get('casino_text')
				if len(casino) == 0:
					casino = 'No casino'
				amount = self.request.get('amount')
				if len(amount) == 0:
					amount = 0
				# logging.info(self.request.get('email_address'))	
				# logging.info(str(int(self.request.get('challenge_type'))))
				# logging.info(self.request.get('amount'))	
				# logging.info(self.request.get('casino'))
				# logging.info(gamePlayed)
				# logging.info(self.request.get('notes'))
				editingTransactionId = self.request.get('transaction_id')
				if editingTransactionId and int(editingTransactionId) != 0: # Shouldn't ever send 0, but just in case my other code glitches :)
					currentTrip.update_transaction(transaction_id = int(editingTransactionId),
						email_address = self.request.get('email_address'),
						challenge_type = int(self.request.get('challenge_type')),
						amount = float(amount),
						casino = casino,
						game_played = gamePlayed,
						notes = self.request.get('notes'))				
				else: 
					currentTrip.create_transaction(email_address = self.request.get('email_address'),
						challenge_type = int(self.request.get('challenge_type')),
						amount = float(amount),
						casino = casino,
						game_played = gamePlayed,
						notes = self.request.get('notes'))
			except:
				logging.warning("Error: Exception occurred and transaction was not added.")
		
		if int(self.request.get('challenge_type')) == transaction.CHALLENGE_TYPE_INDIVIDUAL_ONLY:
			self.redirect('/individual')
		else:
			self.redirect('/leaderboard')
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		user = users.get_current_user()
		currentTrip = userprefs.get_users_current_trip()
		allMyTrips = member.get_all_trips_for_email(user.email())
		tripFields = []
		for trip in allMyTrips:
			if trip.key().id() == currentTrip.key().id():
				continue # Don't add the current trip to this list
			tripField = {'tripName': trip.trip_name, 'tripKeyId': trip.key().id()}
			tripFields.append(tripField)
		values = {'tripFields': tripFields, 'currentTripName': currentTrip.trip_name, 'currentTripKeyId': currentTrip.key().id()}
		self.response.out.write(template.render('templates/options.html', values))
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		if self.request.get('flush'):
			logging.info("Flushing the entire memcache")
			memcache.flush_all()
		# Determine if a user is logged in or not and render appropriate page.
		user = users.get_current_user()
		if not user:
			values = {'login_link': users.create_login_url(self.request.path)}
			self.response.out.write(template.render('templates/home_not_logged_in.html', values))
		else:
			currentTrip = userprefs.get_users_current_trip()
			values = {'logout_link': users.create_logout_url(self.request.path),
								'name': user.nickname(),
								'current_trip_name': currentTrip.trip_name} # I believe this trigger automatic dereferencing of the Reference key
			self.response.out.write(template.render('templates/home_logged_in.html', values))	
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		playerResults = {}
		currentTrip = userprefs.get_users_current_trip()
		allTransactions = currentTrip.get_all_transactions()
		for aTransaction in allTransactions:
			if aTransaction.challenge_type == transaction.CHALLENGE_TYPE_INDIVIDUAL_ONLY:
				continue # Skip individual only for this page.
			# Building up a dictionary of playerResults using the email and challenge type as the key in a dictionary
			key = aTransaction.email_address + str(aTransaction.challenge_type)
			if not key in playerResults:
				# This is a new entry in the playerResult dictionary fill in from scratch
				playerResult = {}
				playerResult['total'] = 150
				thisMember = member.get_member_for_trip(currentTrip.key(), aTransaction.email_address);
				playerResult['name'] = thisMember.display_name
				playerResult['email'] = thisMember.email_address
				playerResult['challengeType'] = aTransaction.challenge_type
				playerResult['gamblingEvents'] = []
			else:
				playerResult = playerResults[key]
			
			# Each playerResult has a list of gamblingEvents, add this transaction to the gamblingEvents list
			gamblingEvent = {}
			gamblingEvent['amount'] = aTransaction.amount
			if (aTransaction.amount < 0):
				amountStr = "-$%0.2f" % + abs(aTransaction.amount)
			else:
				amountStr = "+$%0.2f" % aTransaction.amount
			gamblingEvent['amountStr'] = amountStr.replace('.00', '')  # Remove trailing zeros if integer
			gamblingEvent['casino'] = aTransaction.casino
			gamblingEvent['gamePlayed'] = aTransaction.game_played
			gamblingEvent['notes'] = aTransaction.notes
			gamblingEvent['id'] = aTransaction.key().id()
			playerResult['gamblingEvents'].append(gamblingEvent)
			
			playerResult['total'] = playerResult['total'] + aTransaction.amount
			
			playerResults[key] = playerResult
		
		# Okay at this point all of the transactions have been organized into the playerResults dictionary the structure is like this
		# {'[email protected]':
		#    {'total': 165.5,
		#     'name': 'Dave',
		#     'challengeType': 1,
		#     'gamblingEvents': [{'amount': 10.0, 'casino': 'Luxor', 'gamePlayed': 'Blackjack',     'notes': 'blah blah', 'id': 432},
		#                        {'amount':  5.5, 'casino': 'MGM',   'gamePlayed': "Texas Hold'em", 'notes': 'blah blah', 'id': 511}, ... ]},
		#   ... }
		
		# TODO: Change the total and add the usedAddOn boolean
		
		allAddOns = currentTrip.get_all_addons()
		for anAddOn in allAddOns:
			if anAddOn.used_add_on:
				standardized_email_address = member.standardize_email_address(anAddOn.email_address)
				# Find the player key for this Add on
				playerKeyForAddOn = standardized_email_address + str(anAddOn.challenge_type)
				if playerKeyForAddOn in playerResults:
					playerResults[playerKeyForAddOn]['usedAddOn'] = True;
					playerResults[playerKeyForAddOn]['total'] = playerResults[playerKeyForAddOn]['total'] + 50
				
		
		# Next we need to lookup and add the Add-Ons
		#   Change the total and add a field to the dictionary
		# {'[email protected]':
		#    {'total': 215.5,
		#     'name': 'Dave',
		#     'challengeType': 1,
		#     'usedAddOn': True,
		#     'gamblingEvents': [{'amount': 10.0, 'casino': 'Luxor', 'gamePlayed': 'Blackjack',     'notes': 'blah blah', 'id': 432},
		#                        {'amount':  5.5, 'casino': 'MGM',   'gamePlayed': "Texas Hold'em", 'notes': 'blah blah', 'id': 511}, ... ]},
		#   ... }
		
		# Order the keys by their total and create the necessary strings for the renderer
		allKeys = playerResults.keys()
		# sort the keys using the total
		sortedKeys = sorted(allKeys, key=lambda resultKey: -playerResults[resultKey]['total'])
		displayResults = []
		for aKey in sortedKeys:
			displayResult = {}
			if playerResults[aKey]['total'] > 300:
				playerResults[aKey]['total'] = 300
			if playerResults[aKey]['total'] < 0:
				playerResults[aKey]['total'] = 0
			displayResult['challengeId'] = playerResults[aKey]['email'] + '_type_' + str(playerResults[aKey]['challengeType'])
			# Prepare the text that will be displayed at the top level
			challengeText = ''
			if playerResults[aKey]['challengeType'] == transaction.CHALLENGE_TYPE_300_DOLLAR_CHALLENGE:
				challengeText = '$300 Challenge'
			elif playerResults[aKey]['challengeType'] == transaction.CHALLENGE_TYPE_SECOND_CHANCE:
				challengeText = '2nd Chance'
			addOnText = ''
			if 'usedAddOn' in playerResults[aKey] and playerResults[aKey]['usedAddOn']:
				addOnText = '*'
			displayResult['name'] = playerResults[aKey]['name'] + addOnText
			displayResult['challengeType'] = challengeText
			displayResult['total'] = playerResults[aKey]['total']
			totalStr = "$%0.2f" % playerResults[aKey]['total']
			displayResult['totalStr'] = totalStr.replace('.00', '')  # Remove trailing zeros if integer
			displayResult['gamblingEvents'] = playerResults[aKey]['gamblingEvents']
			displayResults.append(displayResult)

		values = {'displayResults': displayResults}
		self.response.out.write(template.render('templates/leaderboard.html', values))
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		playerResults = {}
		currentTrip = userprefs.get_users_current_trip()
		allTransactions = currentTrip.get_all_transactions()
		for aTransaction in allTransactions:
			# Building up a dictionary of playerResults using the email as the key in a dictionary
			key = aTransaction.email_address
			if not key in playerResults:
				# This is a new entry in the playerResult dictionary fill in from scratch
				playerResult = {}
				playerResult['total'] = 0
				thisMember = member.get_member_for_trip(currentTrip.key(), aTransaction.email_address);
				playerResult['name'] = thisMember.display_name
				playerResult['email'] = thisMember.email_address
				playerResult['gamblingEvents'] = []
			else:
				playerResult = playerResults[key]

			# Add this transaction to the gamblingEvents
			gamblingEvent = {}
			gamblingEvent['challengeType'] = ''
			if aTransaction.challenge_type == transaction.CHALLENGE_TYPE_300_DOLLAR_CHALLENGE:
				gamblingEvent['challengeType'] = '$300 Challenge'
			elif aTransaction.challenge_type == transaction.CHALLENGE_TYPE_SECOND_CHANCE:
				gamblingEvent['challengeType'] = '2nd Chance'
			elif aTransaction.challenge_type == transaction.CHALLENGE_TYPE_INDIVIDUAL_ONLY:
				gamblingEvent['challengeType'] = 'Individual only'
			
			if (aTransaction.amount < 0):
				amountStr = "-$%0.2f" % + abs(aTransaction.amount)
			else:
				amountStr = "+$%0.2f" % aTransaction.amount
			gamblingEvent['amountStr'] = amountStr.replace('.00', '')  # Remove trailing zeros if integer	
			gamblingEvent['amount'] = aTransaction.amount
			gamblingEvent['casino'] = aTransaction.casino
			gamblingEvent['gamePlayed'] = aTransaction.game_played
			gamblingEvent['notes'] = aTransaction.notes
			gamblingEvent['id'] = aTransaction.key().id()
			
			playerResult['gamblingEvents'].append(gamblingEvent)
			playerResult['total'] = playerResult['total'] + aTransaction.amount
			playerResults[key] = playerResult
		
		# Okay at this point all of the transactions have been organized into the playerResults dictionary the structure is like this
		# {'*****@*****.**':
		#    {'total': 15.5,
		#     'name': 'Dave',
		#     'gamblingEvents': [{'id': 1, 'amount': 10.0, 'casino': 'Luxor', 'gamePlayed': 'Blackjack',     'notes': 'blah blah', 'id': 432},
		#                        {'id': 3, 'amount':  5.5, 'casino': 'MGM',   'gamePlayed': "Texas Hold'em", 'notes': 'blah blah', 'id': 511}, ... ]},
		#   ... }		
		
		# Order the keys by amount and create the necessary strings
		allKeys = playerResults.keys()
		sortedKeys = sorted(allKeys, key=lambda resultKey: -playerResults[resultKey]['total'])
		displayResults = []
		for aKey in sortedKeys:
			displayResult = {}
			displayResult['name'] = playerResults[aKey]['name']
			displayResult['id'] = playerResults[aKey]['email']
			displayResult['total'] = playerResults[aKey]['total']
			if (playerResults[aKey]['total'] < 0):
				totalStr = "-$%0.2f" % + abs(playerResults[aKey]['total'])
			else:
				totalStr = "+$%0.2f" % playerResults[aKey]['total']
			displayResult['totalStr'] = totalStr.replace('.00', '')  # Remove trailing zeros if integer
			displayResult['gamblingEvents'] = playerResults[aKey]['gamblingEvents']
			displayResults.append(displayResult)

		values = {'displayResults': displayResults}
		self.response.out.write(template.render('templates/individual.html', values))
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		currentTrip = userprefs.get_users_current_trip()
		user = users.get_current_user()
		currentMember = member.get_member_for_trip(currentTrip.key(), user.email())
		select_email = member.standardize_email_address(user.email())
		amountValue = ''
		select_challenge_type = 0
		selectCasino = ''
		selectGamePlayed = ''
		transaction_id = 0
		
		# Hardcode some games to practice with the JS
		# These are used by Django
		gamePlayedOptions = ['Blackjack', "Hold'em (no limit)", "Hold'em (limit)","Hold'em (tournament)",
			'Roulette', 'Craps', 'Slots', 'Pai gow poker']
		
		# Hardcode add ons used to practice with the JS
		# These are passed into the JavaScript
		# addOn1 = {'email_address': '*****@*****.**', 'challenge_type': '0'}
		# addOn2 = {'email_address': '*****@*****.**', 'challenge_type': '1'}
		
		addOnsUsed = []
		allAddOns = currentTrip.get_all_addons()
		for anAddOn in allAddOns:
			if anAddOn.used_add_on:
				standardized_email_address = member.standardize_email_address(anAddOn.email_address)
				# Find the player key for this Add on
				addOnsUsed.append({'email_address': standardized_email_address, 'challenge_type': str(anAddOn.challenge_type)})
		
		editingTransactionId = self.request.get('id')
		if editingTransactionId and int(editingTransactionId) != 0: # Shouldn't ever send 0, but just in case my other code glitches :)
			# Get the transaction with this id
			transaction_id = int(editingTransactionId)
			editingTransaction = transaction.get_trip_transaction(currentTrip.key(), transaction_id)
			notes = editingTransaction.notes
			select_email = editingTransaction.email_address
			amountValue = str(editingTransaction.amount)
			select_challenge_type = editingTransaction.challenge_type
			selectCasino = editingTransaction.casino
			selectGamePlayed = editingTransaction.game_played
		else:
			time = datetime.datetime.now()
			now = datetime.datetime.now()
			now += datetime.timedelta(0, 0, 0, 0, 0, -7);  # TODO: Handle daylight savings time issue (-8 standard)
			# for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
			#     print attr, ':', getattr(now, attr)
			# format = "%a %b %d %Y at %H:%M"
			format = "%a"
			dayString = now.strftime(format)
			# notes = 'Created by ' + currentMember.display_name + ' on ' + dateString
			dateString = str(now.month) + "/" + str(now.day) + "/" + str(now.year)
			if now.hour == 0:
				hourStr = '12'
				amPm = 'am'
			elif now.hour < 12:
				hourStr = str(now.hour)
				amPm = 'am'
			elif now.hour == 12:
				hourStr = str(now.hour)
				amPm = 'pm'
			else:
				hourStr = str(now.hour - 12)
				amPm = 'pm'
			timeString =  "%s:%02d %s" % (hourStr, now.minute, amPm)
			notes = 'Created by ' + currentMember.display_name + ' on ' + dayString + ' ' + dateString + ' at ' + timeString
			# DateTime docs at http://docs.python.org/library/datetime.html
		
		
		values = {'transaction_id': transaction_id,
				  'trip_member_options': currentTrip.get_all_members(),
				  'select_email': select_email,
				  'challenge_type_options': transaction.CHALLENGE_TYPES,
				  'select_challenge_type': select_challenge_type,
				  'amount_value': amountValue,
				  'select_casino': selectCasino,
				  'game_played_options': gamePlayedOptions,
				  'all_games': gamePlayedOptions,
				  'select_game_played': selectGamePlayed,
				  'notes': notes,
				  'add_ons_used': addOnsUsed}
		self.response.out.write(template.render('templates/transaction.html', values))