ajax_loader_small = '<img src="'+TEMPLATE_VIEW_PATH+'images/ajax_loader_orange.gif">';

function logout() {
	var onlogout = function() {
		$.cookies.set("userPerms", null);
		location.href = '.';
	};
	if (window.FacebookProxy) {
		FacebookProxy.logout(onlogout);
	} else {
		FB.logout(onlogout);
	}
	return false;
}

var APP_IDS = {
	rmn: 1,
	theconstellations: 2,
	guetta: 3,
	getmarried: 4,
	kaptur: 5,
	weddings: 6,
	gayweddings: 7,
	kapturcards: 8
};

var APP_ID = APP_IDS[KEYWORD];

var memoryCreationWizard = {
	selected_friends: {},
	friends_to_remove: {},
	total_friends: 0,
	selected_photos: {},
	new_selected_photos: {},
	remove_selected_photos: {},
	new_photos: 0,
	total_photos: 0,
	user: null,
	bulk_saved_friends: {},
	loaded_friends: {},
	loaded_photos: {},
	saved_attendees: {},
	stream_photos: [],
	stream_photo_tags: {},
	tagged_photos: {},
	tagged_photo_tags: {},
	tagged_photo_albums: [],
	albums_loading: 0,
	loaded_albums: {},
	selected_albums: {},
	minimized_attendees: 12,
	open_album: null,
	location: {},

	adjustPointTime: function (utc_time) {
		var segmentData = {
			start: Math.floor(this.start_time.getTime() / 1000),
			startYear: this.start_year,
			startMonth: this.start_month,
			startDay: this.start_day,
			startHour: this.start_hour,
			startMintue: this.start_minute,
			end: Math.floor(this.end_time.getTime() / 1000),
			endYear: this.end_year,
			endMonth: this.end_month,
			endDay: this.end_day,
			endHour: this.end_hour,
			endMintue: this.end_minute,
			tzoffset: this.timezone_offset
		};

		if ((utc_time < segmentData.start) || (utc_time > segmentData.end)) {
			// adjust time to original time but on current segment date
			var utc_normal = parseInt(new Date(segmentData.startMonth+'/'+segmentData.startDay+'/'+segmentData.startYear+' '+getFormattedTime(getAdjustedTime(utc_time*1000,segmentData.tzoffset), 1)+offsetToGMTStr(segmentData.tzoffset)).getTime()/1000, 10);

			// wrap excess time till it fits into segment range
			var segment_length = segmentData.end - segmentData.start;
			if (utc_normal > segmentData.end) {
				var excess_time = utc_normal - segmentData.end;
				var time_overlap = excess_time % segment_length;
				utc_normal = parseInt(segmentData.start, 10) + time_overlap;
			} else if (utc_normal < segmentData.start) {
				var excess_time = segmentData.start - utc_normal;
				var time_overlap = excess_time % segment_length;
				utc_normal = parseInt(segmentData.end) - time_overlap;
			}
			return utc_normal;
		} else {
			return utc_time;
		}
	},

	loadUser: function (callback) {
		var user_fql = 'SELECT first_name, last_name, uid FROM user WHERE uid = {0}';
		if (loggedInUser) {
			queryFacebook(user_fql, [loggedInUser], (function (callback) {
				return function (user_data) {
					var user = null;
					if (user_data.length > 0) {
						user = {};
						user.first_name = user_data[0].first_name;
						user.last_name = user_data[0].last_name;
						user.thumbnail = 'http://graph.facebook.com/' + user_data[0].uid + '/picture';
						memoryCreationWizard.user = user;
					}
					if ((typeof callback) == "function") {
						callback(user);
					}
				}
			})(callback));
		} else if (FB) {
			FB.getLoginStatus(function (fb_response) {
				var session = getFacebookSession();
				if (session) {
					loggedInUser = getFacebookUserId(session);
					$("#createMemoryFriendsContentWrapperWrapper, #selectPhotosWrapper").removeClass("hidden");
					$("#createMemoryFriendsLogin, .skip_this_step, #createMemoryPhotosLogin").addClass("hidden");
					if (memoryCreationWizard.weddingPromo) {
						$('#createMemoryWeddingPromoHint1').css("display", "none");
						$('#createMemoryWeddingPromoHint2').css("display", "block");
					}
					memoryCreationWizard.loadUser(callback);
					loadRmnUserInfo();
				} else {
					if (memoryCreationWizard.weddingPromo && rmnAppId != '10' && location.href.indexOf('p=create_weddingpromo') == -1) {
						$('#createMemoryWeddingPromoHint1').css("display", "block");
						$('#createMemoryWeddingPromoHint2').css("display", "none");
					}
					if ((typeof callback) == "function") {
						callback();
					}
				}
			});
		} else {
			if ((typeof callback) == "function") {
				callback();
			}
		}
		
		memoryCreationWizard.displayTip(0);
	},
	
	
	
	displayAlbums: function (albums, album_div, user, fbid) {
		var friend_album_div = $("#" + album_div), i = 0, friend_album_html = "", checked, selected, album_id;
		var friend_album_div_html = friend_album_div.html();
		var friend_content_exists = friend_album_div_html.indexOf('friend_photos_loader') == -1;
		if (albums && (albums.length > 0)) {
			$("#createMemoryAllPhotosFriendsAlbumsWrapperChooseText").css("display", "none");
			var wedding_cover = document.getElementById('memoryEditWrapper') && (user == 'cover');
			for (i = 0; i < albums.length; i++) {
				if (memoryCreationWizard.selected_albums[albums[i].id]) {
					checked = 'checked="checked"';selected = '_selected';
				} else {
					checked = '';selected = '';
				}
				
				album_id = 'album' + albums[i].id;
				if (user == 'suggested') album_id += 'suggested';
				else if (user == 'cover') album_id += 'cover';
				
				if (!document.getElementById(album_id)) {
					var skip = 0;
					if (albums[i].id.indexOf('stream_photos') != -1 && $('#createMemoryAllPhotosSuggestedAlbums div.album_wrapper[id^="albumstream_photos"]').length) skip = 1;
					if (!skip) {
						if (!wedding_cover) {
							friend_album_html += '<div id="'+album_id+'" class="album_wrapper" ' +
								'onmouseover="memoryCreationWizard.showAlbumControls(this, event)" ' +
								'onmouseout="memoryCreationWizard.hideAlbumControls(this, event)" ' +
								'onclick="memoryCreationWizard.friendPhotosLoad(this, \'' +
								albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
								(user ? ', \''+user+'\'' : '') + ')"><div class="album_wrapper_inner"><img class="photo_thumb'+selected+'" src="' +
								albums[i].cover + '"/><div class="createMemoryViewAlbumOverlay"><img src="'+
								TEMPLATE_VIEW_PATH+'images/create_memory_wizard/magnifyer.png"/>View Album</div>';
							if (albums[i].id.indexOf('tagged_photos') == -1 && albums[i].id.indexOf('stream_photos') == -1)
								friend_album_html += '<div class="createMemorySelectAlbumOverlay" onclick="memoryCreationWizard.friendPhotosSelectToggle(this.nextSibling, \'' +
									albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
									(user ? ', \''+user+'\'' : ',null') + ',event);">Select Album</div>' +
									'<input type="checkbox" class="createMemoryViewAlbumCheckbox" ' +
									'onclick="memoryCreationWizard.friendPhotosSelectToggle(this, \'' +
									albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
									(user ? ', \''+user+'\'' : ',null') + ',event);" '+checked+'/>';
							friend_album_html += '</div><div class="album_title">' + albums[i].name + '</div></div>';
						} else {
							friend_album_html += '<div id="'+album_id+'" class="album_wrapper" ' +
								'onclick="memoryCreationWizard.friendPhotosLoad(this, \'' +
								albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
								(user ? ', \''+user+'\'' : '') + ')"><div class="album_wrapper_inner"><img class="photo_thumb'+selected+'" src="' + albums[i].cover + '"/></div><div class="album_title">' + albums[i].name + '</div></div>';
						}
					}
				}
			}
		} else {
			if (!friend_content_exists) {
				$("#createMemoryAllPhotosFriendsAlbumsWrapperChooseText").css("display", "none");
				friend_album_html = '<div id="createMemoryAllPhotosFriendsAlbumsEmpty">'+(user?'You don\'t':'Your friend doesn\'t')+' have any Facebook photos, or they are unavailable due to privacy settings.'+(!user?'<br><br>Click <a href="#" style="color:#f09" onclick="memoryCreationWizard.inviteFriend(\''+fbid+'\'); return false">here</a> to invite them to use Kaptur!':'')+'</div>';//f96
			}
		}
		
		if (user == 'suggested' && friend_content_exists)
			friend_album_html = friend_album_div_html+friend_album_html;
		friend_album_div.html(friend_album_html);
		
		// recheck album checkboxes that have been checked
		for (var i in memoryCreationWizard.selected_albums) {
			if (typeof i != 'function') {
				var album_id = 'album'+i;
				if (user == 'suggested') album_id += 'suggested';
				$('#'+album_id+' .createMemoryViewAlbumCheckbox').attr('checked', 'checked');
			}
		}
	},
	
	
	loadVideos: function() {
		if (!this.videos_loaded) {
			if (loggedInUser) {
				this.videos_loaded = 1;
				var getVideosFQL = {
					fql: 'SELECT vid, owner, title, description, embed_html, thumbnail_link, src, created_time FROM video WHERE owner="{0}" OR vid IN (SELECT vid FROM video_tag WHERE subject="{0}") ORDER BY created_time DESC',
					args: [loggedInUser]
				};
				var getVideoTagsFQL = {//, updated_time, created_time
					fql: 'SELECT vid, subject FROM video_tag WHERE vid IN (SELECT vid FROM {0})',
					args: [getVideosFQL]
				};
				var getVideoTagsUsersFQL = {
					fql: 'SELECT uid, name FROM user WHERE uid IN (SELECT subject FROM {0})',
					args: [getVideoTagsFQL]
				};
				multipleQueryFacebook([getVideosFQL, getVideoTagsFQL, getVideoTagsUsersFQL], function() {
					var videos = getVideosFQL.value;
					var video_tags = getVideoTagsFQL.value;
					var video_tag_users = getVideoTagsUsersFQL.value;
					var createMemoryAllVideosUserVideos = document.getElementById('createMemoryAllVideosUserVideos');
					if (videos && videos.length) {
						var videos_html = '';
						for (var i=0; i<videos.length; i++) {
							var video = videos[i];
							var video_id = video['vid'];
							var video_title = escapeQuotes(video['title']);
							var video_thumb = video['thumbnail_link'];
							var video_uploaded = video['created_time'];
							var video_src = video['src'];
							var video_size = extractFbVideoSize(video['embed_html']);
							var video_width = '', video_height = '';
							if (video_size) {
								video_width = video_size[0];
								video_height = video_size[1];
								video['width'] = video_width;
								video['height'] = video_height;
							}fbVideos[video_id] = video; // store video data in memory
							var checked = fbVideoPointIds[video_id]?' checked':'';
							videos_html += '<div class="photo_wrapper" onmouseout="memoryCreationWizard.hidePhotoControls(this, event)" onmouseover="memoryCreationWizard.showPhotoControls(this, event)" onclick="addToCanvas(\''+video_id+'\', {\'video\':\'fb\'})"><img id="m'+video_id+'thumb" src="'+video_thumb+'" class="photo_thumb'+(checked?'_selected':'')+'"  alt="'+video_title+'" title="'+video_title+'"><div class="createMemorySelectPhotoOverlay" style="display:none">Select Video</div><input type="checkbox" class="createMemoryViewAlbumCheckbox"'+checked+'></div>';
						}createMemoryAllVideosUserVideos.innerHTML = videos_html;
					} else createMemoryAllVideosUserVideos.innerHTML = 'No videos retrieved.';
					
					//updateCustomScrollbar('fbVideoContents');
					storeMediaTags(video_tags, video_tag_users);
				});
			}
		}
	},
	
	displayTip: function (step_number) {
		var delay = 1500, //1.5 seconds
			url_params = getUrlParams(),
			tip;
		if (((step_number != 0) || ((url_params['aff'] !=  "weddingpromo") && (url_params['p'] != 'create_weddingpromo'))) &&
				((step_number != 3) || ((url_params['aff'] ==  "weddingpromo") || (url_params['p'] == 'create_weddingpromo')))) {
			setTimeout (function () {
				tip = $("#createMemoryStep" + (step_number+1) + "Tip");
				tip.fadeIn("slow");
				/*
				for (i = 0;i < 3;i++) {
					tip = $("#createMemoryStep" + (i+1) + "Tip");
					if (i == step_number && !((step_number == 0) && (getUrlParams()['aff'] ==  "weddingpromo"))) {
						tip.fadeIn();
					} else {
						//tip.hide();
					}
				}*/
			}, delay);
		}
	},

	displayUser: function (user) {
		if (user) {
			$("#createMemorySignedIn").css("display", "block");
			$("#createMemorySignedOut").css("display", "none");
			$("#createMemorySignInPicture").html('<img src="'+user.thumbnail + '"/>');
			$("#createMemorySignInName").html(user.first_name + ' ' + user.last_name);
			$("#createMemorySignOutLink").html('Not ' + user.first_name + '?');
		} else {
			$("#createMemorySignedIn").css("display", "none");
			$("#createMemorySignedOut").css("display", "block");
		}
	},

	displayStep: (function () {
		var step_name_array = ["createMemoryStepOne","createMemoryStepTwo","createMemoryStepThree","createMemoryComplete"];
		return function (step_number) {
			this.updateHints(step_number);
			var step_div, step_nav_div, i;
			step_number = step_number - 1;
			for(i = 0; i < step_name_array.length; i++) {
				step_div = $("#" + step_name_array[i]);
				step_nav_div = $("#" + step_name_array[i] + "Nav");
				if (i == step_number) {
					step_div.removeClass('hidden');
					step_nav_div.removeClass().addClass('create_memory_step_nav_selected');
				} else {
					step_div.addClass('hidden');
					if (i < step_number) {
						step_nav_div.removeClass().addClass('create_memory_step_nav_complete');
					} else {
						step_nav_div.removeClass().addClass('create_memory_step_nav');
					}
				}
			}
			
			// proceed to step 2 on any progress
			if (!loggedInUser) dataFlags.proceedStep2 = step_number+1;

			memoryCreationWizard.displayTip(step_number);
		};
	})(),

	setStartTime: function () {
		var start_time = new Date(),
			hour_offset = Math.floor(this.timezone_offset),
			minute_offset = Math.floor((parseFloat(this.timezone_offset) - hour_offset) * 60),
			start_hour = parseInt(this.start_hour, 10),
			start_minute = parseInt(this.start_minute, 10) - minute_offset;
		if ((this.start_am_pm == "pm") && (start_hour != 12)) start_hour += 12;
		else if ((this.start_am_pm == "am") && (start_hour == 12)) start_hour = 0;
		
		start_hour = start_hour - hour_offset;
		start_time.setUTCFullYear(this.start_year, this.start_month - 1, this.start_day);
		start_time.setUTCHours(start_hour, start_minute, 0, 0);

		this.start_time = start_time;
	},

	setEndTime: function () {
		var end_time = new Date(),
			hour_offset = parseInt(this.timezone_offset),
			minute_offset = Math.floor((parseFloat(this.timezone_offset) - hour_offset) * 60),
			end_hour = parseInt(this.end_hour, 10),
			end_minute = parseInt(this.end_minute, 10) - minute_offset;
		if ((this.end_am_pm == "pm") && (end_hour != 12)) end_hour += 12;
		else if ((this.end_am_pm == "am") && (end_hour == 12)) end_hour = 0;

		end_hour = end_hour - hour_offset;
		end_time.setUTCFullYear(this.end_year, this.end_month - 1, this.end_day);
		if (this.start_month == this.end_month && this.start_day == this.end_day && this.start_year == this.end_year) {
			end_hour = 23 - hour_offset;end_minute = 59 - minute_offset;
		}
		
		end_time.setUTCHours(end_hour, end_minute, 0, 0);

		this.end_time = end_time;
	},

	setDefaultTime: function () {
		var now = new Date();

		//set start time (default is today at midnight)
		$("#createMemoryStartTimeInput .create_memory_year").val(now.getFullYear());
		$("#createMemoryStartTimeInput .create_memory_month").val(now.getMonth() + 1);
		$("#createMemoryStartTimeInput .create_memory_day").val(now.getDate());
		$("#createMemoryStartTimeInput .create_memory_hour").val(12);
		$("#createMemoryStartTimeInput .create_memory_minute").val("00");
	},

	validateMemoryDescription: function () {
		
		var error_msg = '';
		if (this.start_month=="m" && this.start_day=="d" && this.start_year=="yyyy"){
			if (dataFlags.lastBasicDateEdit == "first"){
				error_msg = ' '; // hacky!  this is deliberately blank! want validator to display a blank message the first time
				dataFlags.lastBasicDateEdit = 1;
			} else {
				error_msg = 'Please enter a date!';
			}
		} else if (!this.start_month || isNaN(this.start_month) || this.start_month < 1 || this.start_month > 12) {
			error_msg = 'Please enter 1 to 12 for the month.';
		} else if (!this.start_day || isNaN(this.start_day) || this.start_day < 1 || this.start_day > 31) {
			error_msg = 'Please enter 1 to 31 for the day.';
		} else if (!this.start_year || isNaN(this.start_year) || this.start_year.toString().length != 4 || (this.start_year < 1)) {
			error_msg = 'Please enter a valid year.';
			if (this.start_year.toString().length != 4) error_msg = 'Please enter a four-digit year!';
		} else if (!this.start_hour || isNaN(this.start_hour) || (this.start_hour < 1 || this.start_hour > 12)) {
			error_msg = 'Please enter 1 to 12 for the hour.';
		} else if (this.start_minute == null || isNaN(this.start_minute) || this.start_minute < 0 || this.start_minute > 59) {
			error_msg = 'Please enter 0 to 59 for minutes.';
		} else if (this.start_time == "Invalid Date") {
			error_msg = 'Please enter a valid start date.';
		} else if (!this.end_month || isNaN(this.end_month) || (this.end_month < 1 || this.end_month > 12)) {
			error_msg = 'Please enter 1 to 12 for the month.';
		} else if (!this.end_day || isNaN(this.end_day) || (this.end_day < 1 || this.end_day > 31)) {
			error_msg = 'Please enter 1 to 31 for the day.';
		} else if (!this.end_year || isNaN(this.end_year) || this.end_year.toString().length != 4) {
			error_msg = 'Please enter a valid year.';
			if (this.end_year.toString().length != 4) error_msg = 'Please enter a four-digit year!';
		} else if (!this.end_hour || isNaN(this.end_hour) || (this.end_hour < 1 || this.end_hour > 12)) {
			error_msg = 'Please enter 1 to 12 for the hour.';
		} else if (this.end_minute == null || isNaN(this.end_minute) || (this.end_minute < 0 || this.end_minute > 59)) {
			error_msg = 'Please enter 0 to 59 for minutes.';
		} else if (this.end_time == "Invalid Date") {
			error_msg = 'Please enter a valid date!';
		} else if (this.start_time >= this.end_time) {
			error_msg = 'The start date must come before the end date!';
		}

		return error_msg;
	},

	processMemoryDescription: function () {
		var error_msg = '', default_end_time_info;
		
		var memory_title = $("#createMemoryTitleInput").attr('value');
		if (memory_title.match(/\s*e\.g\. Chris and Jenny's Wedding in San Diego!\s*$/)) memory_title = '';
		this.title = memory_title;
		this.location = $("#createMemoryLocationInput").attr('value');
		this.description = $("#createMemoryDescriptionInput").attr('value');

		// get start time
		this.start_year = $("#createMemoryStartTimeInput .create_memory_year").attr('value');
		this.start_month = $("#createMemoryStartTimeInput .create_memory_month").attr('value');
		this.start_day = $("#createMemoryStartTimeInput .create_memory_day").attr('value');
		this.start_hour = $("#createMemoryStartTimeInput .create_memory_hour").attr('value');
		this.start_minute = $("#createMemoryStartTimeInput .create_memory_minute").attr('value');
		if (this.start_minute < 10) {
			this.start_minute = '0' + parseInt(this.start_minute);
		}
		this.start_am_pm = $("#createMemoryStartTimeInput .create_memory_am_pm").attr('value');;
		this.timezone_offset = new Date(Date.parse(this.start_month+'/'+this.start_day+'/'+this.start_year+' '+this.start_hour+':'+this.start_minute+' '+this.start_am_pm)).getTimezoneOffset()/-60;
		//$("#createMemoryTimezoneDropDown").attr('value');
		this.setStartTime();

		// get end time
		this.end_year = $("#createMemoryEndTimeInput .create_memory_year").attr('value');
		this.end_month = $("#createMemoryEndTimeInput .create_memory_month").attr('value');
		this.end_day = $("#createMemoryEndTimeInput .create_memory_day").attr('value');
		this.end_hour = $("#createMemoryEndTimeInput .create_memory_hour").attr('value');
		this.end_minute = $("#createMemoryEndTimeInput .create_memory_minute").attr('value');
		this.end_am_pm = $("#createMemoryEndTimeInput .create_memory_am_pm").attr('value');

		if (this.end_year || this.end_month || this.end_day) {
			this.setEndTime();
		} else {
			this.end_time = new Date(this.start_time.getTime() + (36*60*60*1000)); //start time plus 36 hours (36*3600000)
			default_end_time_info = (new Date(this.end_time.getTime() + (this.timezone_offset * 36*60*60*1000))); // 3600000
			this.end_year = default_end_time_info.getUTCFullYear();
			this.end_month = default_end_time_info.getUTCMonth() + 1;
			this.end_day = default_end_time_info.getUTCDate();
			this.end_hour = default_end_time_info.getUTCHours();
			this.end_minute = default_end_time_info.getUTCMinutes();
			if (this.end_minute < 10) {
				this.end_minute = '0' + this.end_minute;
			}
			if (this.end_hour >= 12) {
				if (this.end_hour != 12) this.end_hour = this.end_hour - 12;
				this.end_am_pm = "pm";
			} else {
				if (this.end_hour == 0) {
					this.end_hour = 12;
				}
				this.end_am_pm = "am";
			}
		}
		
		// double-check that title isn't blank or 'test'
		if (!memory_title) {
			if (!dataFlags.allowNoTitle) {
				this.showCustomAlert('noTitle');
				return false;
			}
		} else if (memory_title.match(/^\s*test.*/i)) {
			if (!dataFlags.allowTestTitle) {
				this.showCustomAlert('testTitle');
				return false;
			}
		}
		
		var wedding_start = parseInt(this.start_time.getTime()/1000, 10);
		var current_time = parseInt(new Date().getTime()/1000, 10);
		var future_date = wedding_start > current_time;
		/*if (memoryCreationWizard.weddingPromo) {
			if (!memoryCreationWizard.storedWeddingEmail && location.href.indexOf('storedEmail=1') == -1) { // loggedInUser && 
				// for weddings outside of 2011
				if (wedding_start < parseInt(Date.parse('Jan 1, 2011')/1000, 10) || wedding_start > parseInt(Date.parse('Dec 31, 2011')/1000,10)) {
					this.showCustomAlert('weddingDate');
					return false;
				}// don't store future wedding emails
				else if (future_date) {
					this.showCustomAlert('futureWedding');
					return false;
				}
			}
		}*/
		
		// for future events
		var createMemoryFriendsLabel = document.getElementById('createMemoryFriendsLabel');
		var createMemoryFriendsLabelBlack = document.getElementById('createMemoryFriendsLabelBlack');
		var createMemoryFriendsLabelTab = document.getElementById('createMemoryStepTwoNav');
		var futureSuggestionsHint = document.getElementById('future'+(memoryCreationWizard.weddingPromo?'Wedding':'Memory')+'SuggestionsHint');
		var createMemoryAllPhotosSuggestedContents = document.getElementById('createMemoryAllPhotosSuggestedContents');
		if (future_date) {
			// back up app-specific tense text
			if (!memoryCreationWizard.backupSelectFriendsLabel)
				memoryCreationWizard.backupSelectFriendsLabel = '2. Who attended?'
				//memoryCreationWizard.backupSelectFriendsLabel = createMemoryFriendsLabelBlack.innerHTML;
			var future_event_friends_label = '2. Who will attend?';
			createMemoryFriendsLabel.innerHTML = future_event_friends_label;
			createMemoryFriendsLabelBlack.innerHTML = future_event_friends_label;
			createMemoryFriendsLabelTab.innerHTML = future_event_friends_label;
			// toggle future suggestions hint
			futureSuggestionsHint.style.display = 'block';
			createMemoryAllPhotosSuggestedContents.style.display = 'none';
		} else {
			if (memoryCreationWizard.backupSelectFriendsLabel) {
				createMemoryFriendsLabel.innerHTML = memoryCreationWizard.backupSelectFriendsLabel;
				createMemoryFriendsLabelBlack.innerHTML = memoryCreationWizard.backupSelectFriendsLabel;
				createMemoryFriendsLabelTab.innerHTML = memoryCreationWizard.backupSelectFriendsLabel;
			} // toggle future suggestions hint
			futureSuggestionsHint.style.display = '';
			createMemoryAllPhotosSuggestedContents.style.display = '';
		}memoryCreationWizard.futureMemory = future_date;
		
		error_msg = this.validateMemoryDescription();
		//$("#createMemoryStepOne .create_memory_error").html(error_msg);
		if (error_msg) {
			//alert(error_msg);
			var title = 'Invalid input';
			if (!loggedInUser) title = 'Please connect to Facebook';
			this.showAlert(title, error_msg);
			return false;
		}
		
		return true;
	},
	
	weddingEmailStored: function() {
		this.showCustomAlert('futureWeddingMsg', 1);
		this.storedWeddingEmail = 1;
		this.completedStep(1);
	},

	buildDateString: function (year, month, day, hour, minute, am_pm) {
		return month + '/' + day + '/' + year + '&emsp;' + hour + ':' + minute + am_pm;
	},
	
	displayMemoryDescription: function () {
		if (!this.title) this.title = '';
		if (!this.location) this.location = '';
		if (!this.description) this.description = '';
		$("#createMemoryTitleValue").text(this.title);
		$("#createMemoryLocation").text(this.location);
		$("#createMemoryDescription").text(this.description);

		/*$("#createMemoryStartTime").html(this.buildDateString(this.start_year,
			this.start_month, this.start_day, this.start_hour, this.start_minute,
			this.start_am_pm));
		
		if (this.end_year) {
			$("#createMemoryEndTime").html(this.buildDateString(this.end_year,
				this.end_month, this.end_day, this.end_hour, this.end_minute,
				this.end_am_pm));
		}*/
		var start_date = formatDateStr(this.start_time);
		var end_date = this.end_time.getTime() - this.start_time.getTime() > 36*60*60*1000?formatDateStr(this.end_time):'';
		var date_str = start_date + ((end_date && start_date!=end_date)?' to '+end_date:'');
		$("#createMemoryStartTime").html(date_str);
	},

	processAttendees: function () {
		return true;
	},
	
	loaded_friend_lists: {},
	loadFriendsFromList: function (flid, callback) {
		var friends_fql = 'SELECT uid FROM friendlist_member WHERE flid={0}';
		if (memoryCreationWizard.loaded_friend_lists[flid]) {
			safeCall(callback, [memoryCreationWizard.loaded_friend_lists[flid]]);
		} else {
			queryFacebook(friends_fql, [flid], function (callback, flid) {
				return function (friends) {
					memoryCreationWizard.loaded_friend_lists[flid] = friends;

					safeCall(callback, [friends]);
				}
			}(callback, flid))
		}
	},

	loadFriends: function (callback) {
		var friends_fql = 'SELECT first_name, last_name, name, uid, pic_square, sex, locale FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY last_name ASC';//uid="{0}" OR 
		if (this.friends_loaded) {
			return;
		} else {
			this.friends_loaded = true;
		}
		queryFacebook(friends_fql, [loggedInUser], function (data) {
			var i = 0,
				friend_array = [],
				friend = {};
			for (i in data) {
				friend = {};
				friend.name = data[i].name;
				friend.first_name = data[i].first_name;
				friend.last_name = data[i].last_name;
				friend.gender = data[i].sex;
				friend.locale = data[i].locale;
				friend.thumbnail = data[i].pic_square;//'http://graph.facebook.com/' + data[i].uid + '/picture';
				friend.facebook_id = data[i].uid;

				friend_array[i] = friend;
				memoryCreationWizard.loaded_friends[friend.facebook_id] = friend;
			}

			//memoryCreationWizard.displayFriends(friend_array);
			if (!$.browser.msie) {
				friend_array = friend_array.sort(function (a,b) {
					if (a.last_name < b.last_name) return -1;
					else if (a.last_name > b.last_name) return 1;
					else if (a.first_name < b.first_name) return -1; //last names are known to be equal
					else if (a.first_name > b.first_name) return 1;
					else return 0;
				});
			}
			
			memoryCreationWizard.renderFriendNav(friend_array);
			
			safeCall(callback, []);
		});
	},

	addFriend: function (facebook_id) {
		var friend_data = this.loaded_friends[facebook_id];
		var kaptur_id = friend_data.kaptur_id;
		this.total_friends++;
		this.selected_friends[facebook_id] = true;
		if (kaptur_id && this.friends_to_remove[kaptur_id]) {
			delete this.friends_to_remove[kaptur_id];
		}
		safeCall(toggleFriendSelected, [facebook_id, 0, friend_data.first_name, friend_data.last_name]);
	},

	removeFriend: function (facebook_id) {
		var friend_data = this.loaded_friends[facebook_id];
		if (!friend_data) friend_data = {};
		//var kaptur_id = friend_data.kaptur_id;
		if (this.selected_friends[facebook_id]) {
			//if (kaptur_id) { }
			this.total_friends--;
			delete this.selected_friends[facebook_id];
		}
		safeCall(toggleFriendSelected, [facebook_id, 1, friend_data.first_name, friend_data.last_name]);
	},

	toggleFriendSelected: function (friend_div, facebook_id, event) {
		var target;
		event = getEvent(event);
		target = getEventTarget(event) || friend_div;
		
		if (this.selected_friends[facebook_id]) {
			this.removeFriend(facebook_id);
			$(friend_div).removeClass('friend_wrapper_selected').addClass('friend_wrapper');
			if (target.nodeName.toLowerCase() != 'input')
				$("input", friend_div).attr('checked', false);
			else preventBubbling(event);
		} else {
			this.addFriend(facebook_id);
			$(friend_div).removeClass('friend_wrapper').addClass('friend_wrapper_selected');
			if (target.nodeName.toLowerCase() != 'input') {
				$("input", friend_div).attr('checked', true);
			} else {
				preventBubbling(event);
			}
		}
	},

	clearFriendFilter: function () {
		var friendsSearchInput = document.getElementById('createMemoryFriendsSearchInput');
		friendsSearchInput.value = '';
		memoryCreationWizard.updateShownFriends();
		friendsSearchInput.focus();
		friendsSearchInput.blur();
		document.getElementById('createMemoryFriendFilterClear').style.display = 'none';
	},

	updateShownFriends: function () {
		var friends_wrapper = document.getElementById('createMemoryFriendsContent'),
			friend_links = friends_wrapper.getElementsByTagName('a'),
			friendFilter, friendFilterClear, i, friend_link;
		if (friend_links && friend_links.length) {
			friendFilter = document.getElementById('createMemoryFriendsSearchInput').value.replace(/\s/g, '').toLowerCase();
			friendFilterClear = document.getElementById('createMemoryFriendFilterClear');
			if (!friendFilter) {
				friendFilterClear.style.display = 'none';
			} else {
				friendFilterClear.style.display = 'inline-block';
			}

			for (i = 0; i < friend_links.length; i++) {
				friend_link = friend_links[i];
				if (!friendFilter) {
					friend_link.style.display = '';
				} else {
					try {
						/*var friend_node = friend_link.firstChild.firstChild.nextSibling;
						var friend_name = friend_node.textContent;
						if (!friend_name) friend_name = friend_node.innerText;*/
						var friend_name = $(friend_link).find('.friend_wrapper_name').html()
						friend_name = friend_name.replace(/\s/g, '').toLowerCase();
						if (friend_name.indexOf(friendFilter) == -1) friend_link.style.display = 'none';
						else friend_link.style.display = '';
					} catch(err) {}
				}
			}
		}
	},
	
	renderFriendNavFriendAndNavHTML: function (friend, current_letter) {
		var first_name = friend['first_name'],
			middle_name = friend['middle_name'],
			last_name = friend['last_name'],
			birthday = friend['birthday_date'],
			navHtml = '',
			friendsHtml = '',
			uid, profile_thumb, new_letter, friend_selected, onclick_handler;

		if (!first_name) first_name = '';
		if (!last_name) {
			if (middle_name) {
				last_name = middle_name;
			} else {
				last_name = first_name;
				first_name = '';
			}
		}

		uid = friend.facebook_id;
		profile_thumb = friend.thumbnail;
		//if (uid && (first_name || last_name || profile_thumb) && (!segmentData || (!segmentData.fbOwner && uid != loggedInUser) || (segmentData.fbOwner && segmentData.fbOwner != uid))) {
		if (uid && (first_name || last_name || profile_thumb) && ((!memoryCreationWizard.fb_owner && uid != loggedInUser) || (memoryCreationWizard.fb_owner && memoryCreationWizard.fb_owner != uid))) {
			new_letter = ((last_name) ? (last_name.charAt(0).toUpperCase()) : '');

			if (current_letter != new_letter && new_letter.match(/[A-Z]/) && (!current_letter || current_letter < new_letter)) {
				// append nav link
				current_letter = new_letter;
				navHtml += '<div><a href="#' + new_letter + '" onclick="memoryCreationWizard.clearFriendFilter()">' + new_letter + '</a></div>';

				// append anchor mark
				//friendsHtml += '<div class="float_left"><a name="'+new_letter+'"></a></div>';
				friendsHtml += '<a name="' + new_letter + '" class="float_left"></a>';
			}

			// create and extract link element using a div wrapper (ensures proper onclick hanlder for html caching)
			friend_selected = this.selected_friends[uid];
			onclick_handler = "memoryCreationWizard.toggleFriendSelected(this, '" + uid  + "',event)";
			first_name = (first_name ? (first_name + ' ') : '')
			friendsHtml += '<a href="#" onclick="return false;"><div onclick="'+onclick_handler +'" id="f'+uid+'" class="friend_wrapper'+(friend_selected ? '_selected' : '')+'">'+'<div class="friend_wrapper_thumb">'+'<img src="' + profile_thumb + '" class="profile_pic" title="' + first_name + last_name + '"/></div>'+'<div class="friend_wrapper_name">'+(first_name ? first_name + ' ': '' )+last_name+'</div></div></a>';//<div class="friend_wrapper_checkbox"><input type="checkbox" /><label>select friend</label></div>
			memoryCreationWizard.uniqueid++;
			if (friend_selected && !this.bulk_saved_friends[uid]) {
				safeCall(toggleFriendSelected, [uid, '', '', '', 1]);
			}
		}
		
		return {friends: friendsHtml, nav: navHtml, current_letter:current_letter};
	},
	
	renderFriendNavChunked: function (friends, current_letter, start, size, fbFriendsNav, fbFriends) {
		var last_item_index = ((start + size) < friends.length) ? start + size : friends.length,
			navHTML = '', friendsHTML = '', i, html, friend;
		for (i = start; i < last_item_index; i++) {
			friend = friends[i];
			html = memoryCreationWizard.renderFriendNavFriendAndNavHTML(friend, current_letter);
			current_letter = html.current_letter;
			navHTML += html.nav;
			friendsHTML += html.friends;
		}
		
		if (navHTML) {
			$(navHTML).appendTo(fbFriendsNav);
		}
		$(friendsHTML).appendTo(fbFriends);
		
		if (last_item_index < friends.length) {
			setTimeout((function (friends, current_letter, start, size, fbFriendsNav, fbFriends) {
				return function () {
					memoryCreationWizard.renderFriendNavChunked(friends, current_letter, start, size, fbFriendsNav, fbFriends);
				};
			})(friends, current_letter, start+size, size, fbFriendsNav, fbFriends), 100);
		}
	},

	renderFriendNav: function (friends) {
		var fbFriends = $('#createMemoryFriendsContent'),
			fbFriendsNav = $('#createMemoryFriendsNavigation'),
			//fbFriendsFilterWrapper = document.getElementById('friendFilterWrapper'),
			current_letter = '';

		fbFriends.empty();
		if (friends && (friends.length > 0)) {
			document.getElementById('createMemoryFriendsSearch').style.display = 'block';
			memoryCreationWizard.renderFriendNavChunked(friends, current_letter, 0, 200, fbFriendsNav, fbFriends);
		} else {
			fbFriends.html('<div id="fbFriendStatus">No friends retrieved</div>');
			// hide the filter
			//fbFriendsFilterWrapper.style.display = '';
		} //updateCustomScrollbar('fbFriendContents');
	},
	
	displayFriends: function (friends_info) {
		var friends_html = '', i = 0;
		this.friends_info = friends_info;
		if (this.friends_loaded) return;
		if (friends_info) {
			if (friends_info.length > 0) {
				for (i in friends_info) {
					if (friends_info[i].name && friends_info[i].thumbnail) {
						friends_html += '<div class="facebook_friend" onclick="memoryCreationWizard.toggleFriendSelected(this, \'' + friends_info[i].facebook_id + '\',event)"><img width="50" height="50" src="' + friends_info[i].thumbnail + '"/>' +
											'<div class="facebook_friend_name">' +
												friends_info[i].name +
											'</div>' +
										'</div>';
					}
				}
			} else {
				friends_html = "no friends";
			}
		} else {
			friends_html = '<div style="text-align:center;padding-top:20px"><div style="padding-bottom:8px;font-size:14px">Loading friends</div>' + ajax_loader + '</div>';
		}

		$("#createMemoryFriendsContent").html(friends_html);
	},

	expandAttendees: function () {
		$('#createMemoryAttendeeList, .create_memory_expand_attendees_button').toggleClass('expanded');
	},

	displayAttendees: function () {
		var i = 0,
			num_attendees = 0,
			attendees_html = '',
			attendee;

		for (i in this.selected_friends) {
			num_attendees++;
			attendee = this.loaded_friends[i];
			attendees_html += '<div class="create_memory_attendee"><div class="float_left"><img class="create_memory_attendee_thumb" src="' +
				attendee.thumbnail + '" title="' + attendee.name + '" alt="' + attendee.name + '"/></div><div class="create_memory_attendee_name">'+attendee.name+'</div></div>';
		}

		$("#createMemoryAttendeeList.expanded").removeClass('expanded');
		
		if (num_attendees > this.minimized_attendees) {
			$(".create_memory_expand_attendees_button").css("display", "block");
		} else {
			$(".create_memory_expand_attendees_button").css("display", "none");
		}

		$("#createMemoryAttendeeList").html(attendees_html);
	},
	
	loadStreamAlbums: function(friend_ids) {
		if (loggedInUser) {
			if (!friend_ids) {dataFlags.suggestionsLoaded = '';memoryCreationWizard.stream_photos = [];tagged_photo_albums = [];
				$("#createMemoryAllPhotosFriendsAlbumsWrapperChooseText").css("display", "none");}
			if (!memoryCreationWizard.futureMemory) {
				var stream_fql = 'SELECT attachment FROM stream WHERE source_id '+(friend_ids?'IN ('+friend_ids+')':'= "{0}"')+' AND created_time >= "{1}" AND created_time < "{2}" ORDER BY created_time DESC', // created_time, post_id, actor_id, target_id, message, tagged_ids
					start_time = parseInt(memoryCreationWizard.start_time.getTime()/1000, 10),
					end_time = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);
				queryFacebook(stream_fql, [start_time, end_time], function(data) {
						var albums, album_ids = [], album_pids = [], album_ids_hash = {}, album_pids_hash = new Object(), has_suggested_album = false;
						var stream_album_cover = '';
						if (!data) {
							//handle error
							return;
						}
						
						for (var i=0; i<data.length; i++) {
							var stream_item = data[i], media;
							var item_attachment = stream_item['attachment'];
							if (item_attachment) media = item_attachment['media'];
							if (media && media.length) {
								for (var j=0; j<media.length; j++) {
									var media_type = media[j]['type'];
									if (media_type == "photo") {
										var photo = media[j]['photo'];
										var album_id = photo['aid'];
										var media_id = photo['pid'];
										var media_title = media[j]['alt'];
										var media_src = media[j]['src'];
										var media_href = media[j]['href'];
										//album_id, media_id, media_title, media_src, media_href;
										
										// compile stream photo ids array
										if (!album_pids_hash[media_id.toString()]) {
											album_pids.push(media_id);
											album_pids_hash[media_id.toString()] = 1;
										}
										
										// compile stream photo albums list
										if (!album_ids_hash[album_id.toString()]) {
											if (album_id == memoryCreationWizard.suggested_album_id) {
												has_suggested_album = true;
											}
											album_ids.push(album_id);
											album_ids_hash[album_id.toString()] = 1;
										}
										
										// update stream album cover
										if (!stream_album_cover) {
											stream_album_cover = media_src;
										}
									}
								}
							}
						}
						
						var albums = [];
						if (album_pids && album_pids.length) {
							// insert stream photos album
							memoryCreationWizard.stream_photos = memoryCreationWizard.stream_photos.concat(album_pids);
							albums.push({'id':'stream_photos'+loggedInUser, 'name':'Wall Photos', 'cover':stream_album_cover});
						}if (!friend_ids) {
							$('#createMemoryAllPhotosSuggestedAlbumsHint').css('display', '');
							$('#createMemoryAllPhotosSuggestedAlbumsTitle').css('display', '');
						}
						
						//forces the suggested of an album
						if (memoryCreationWizard.suggested_album_id && !has_suggested_album) {
							album_ids.push(memoryCreationWizard.suggested_album_id);
						}
						
						// query for photo albums
						var album_covers_fql = 'SELECT aid, name, cover_pid FROM album WHERE aid IN ("'+album_ids.join('","')+'") ORDER BY created DESC';
						queryFacebook(album_covers_fql, [], function(data) {
							if (data && data.length) {
								var album_covers = [];
								for (var i=0; i<data.length; i++) {
									var album_cover = data[i];
									var album_id = album_cover['aid'];
									var album_name = album_cover['name'];
									var cover_id = album_cover['cover_pid'];
									album_ids_hash[album_id.toString()] = {'id':album_id, 'name':album_name};
									albums.push(album_id);
									album_covers.push(cover_id);
								}
								
								var album_cover_photo_fql = 'SELECT aid, src FROM photo WHERE pid IN ("'+album_covers.join('","')+'")';
								queryFacebook(album_cover_photo_fql, [], function(data) {
									if (data && data.length) {
										for (var i=0; i<data.length; i++) {
											var album_cover = data[i];
											var album_id = album_cover['aid'];
											var cover_img = album_cover['src'];
											album_ids_hash[album_id.toString()]['cover'] = cover_img;
										}
									}
									
									// construct album array for display
									for (var i=0; i<albums.length; i++) {
										var album_id = albums[i];
										if (typeof album_id == 'string') albums[i] = album_ids_hash[album_id.toString()];
									}
									memoryCreationWizard.displayAlbums(albums, 'createMemoryAllPhotosSuggestedAlbums', 'suggested');
									memoryCreationWizard.flagStreamSuggestions(friend_ids);
								});
							} else {
								// default to your photos tab and display no suggestions found text
								if ($('#createMemoryAllPhotosSuggestedAlbums').html().indexOf('friend_photos_loader') != -1 && !dataFlags.suggestionsLoading) {
									if (document.getElementById('createMemoryAddSuggestedPhotosTab').className == 'create_memory_tab_selected') memoryCreationWizard.selectTab(document.getElementById('createMemoryAddYourPhotosTab'), 'createMemoryAllPhotosFacebookContentWrapper');
									$('#createMemoryAllPhotosSuggestedAlbums').html('<div id="createMemoryAllPhotosNoSuggestedAlbumsHint">Kaptur will make suggestions as to what might be part of this memory. If nothing appears in this section please click on "Your Photos" or "Friends\' Photos" to manually add photos.</div>');
									//$('#createMemoryAllPhotosSuggestedPhotos').html('');
									$('#createMemoryAllPhotosSuggestedAlbumsHint').css('display', 'none');
									$('#createMemoryAllPhotosSuggestedAlbumsTitle').css('display', 'none');
								}
								memoryCreationWizard.flagStreamSuggestions(friend_ids);
							}
							
							
						});
					});
			}
		}
	},
	
	flagStreamSuggestions: function(friend_ids) {
		if (friend_ids) dataFlags.friendStreamSuggestions = 1;
		else dataFlags.userStreamSuggestions = 1;
		memoryCreationWizard.checkNoSuggestions();
	},
	
	loadAlbums: function (facebook_id, callback) {
		var albums = {//, owner, modified, description, location, link, size, visible
			fql: 'SELECT aid, cover_pid, created, name FROM album WHERE owner="{0}" ORDER BY modified DESC',
			args: [facebook_id.toString()]
		},
		album_covers = {
			fql: 'SELECT src FROM photo WHERE pid IN (SELECT cover_pid FROM {0})',
			args: [albums]
		},
		tagged_photos = {
			fql: 'SELECT pid, aid, src, src_big, created, owner, images, src_big_width, src_big_height, src_small, link, caption, modified FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject="{0}") AND owner != "{0}" ORDER BY created DESC',
			args: [facebook_id.toString()]
		}/*,
		tagged_photos_tags = {
			fql: 'SELECT pid, subject, text FROM photo_tag WHERE pid IN (SELECT pid FROM {0})',
			args: [tagged_photos]
		}*/;
		//, tagged_photos_tags
		multipleQueryFacebook([albums, album_covers, tagged_photos], (function (that, facebook_id, callback, albums_proxy, album_covers_proxy, tagged_photos_proxy) {//, tagged_photos_tags_proxy
			return function (data) {
				var proxydata = [albums_proxy.value, album_covers_proxy.value, tagged_photos_proxy.value]//, tagged_photos_tags_proxy.value
				if (!data) data = proxydata;
				var albums = data[0],
					num_albums = arrayLength(albums),
					covers = data[1] || [],
					tagged_photos = data[2] || [],
					album, album_cover,
					albums_with_covers = [],
					i = 0;

					if (tagged_photos && tagged_photos.length > 0) {
						album = {
							id: 'tagged_photos' + facebook_id,
							tagged_photos: true,
							name: 'Tagged Photos',
							cover: tagged_photos[0].src
						}

						that.tagged_photos[facebook_id] = tagged_photos;
						that.tagged_photo_tags[facebook_id] = data[3];

						albums_with_covers.push(album);
					}
					
					covers.reverse(); // reverse covers array to prepare for pop
					for (i = 0; i <  num_albums; i++) {
						album = albums[i];
						album_cover = album.cover_pid!=0?covers.pop():'';
						album_cover = album_cover?album_cover.src:TEMPLATE_VIEW_PATH+'images/placeholders/night_thumb.png';
						album = {
							id: album.aid,
							name: album.name,
							cover: album_cover
						};
						memoryCreationWizard.loaded_albums[album.id] = album;
						albums_with_covers.push(album);
					}
					
					if ((typeof callback) == "function") {
						callback(albums_with_covers);
					}
			}
		})(this, facebook_id, callback, albums, album_covers, tagged_photos));//, tagged_photos_tags
	},
	
	displayMemoryComplete: function () {
		memoryCreationWizard.aviaryPhotos = new Object();
		memoryCreationWizard.aviaryHashes = new Object();
		memoryCreationWizard.aviary_photos = 0;
		if (memoryCreationWizard.total_photos) {
			// load memory thumbnail selection panel
			var selected_photos_html = '', first_media_id;
			for (var i in memoryCreationWizard.selected_photos) {
				var photo_data = memoryCreationWizard.loaded_photos[i];
				if (!first_media_id) first_media_id = i;
				selected_photos_html += '<div id="m'+i+'" class="create_memory_photo"><img src="'+photo_data['thumbnail']+'" onclick="memoryCreationWizard.updateMemoryThumb(\''+i+'\')"></div>';
			}document.getElementById('createMemoryPhotos').innerHTML = selected_photos_html;
			memoryCreationWizard.updateMemoryThumb(first_media_id);
		} else {
			document.getElementById('createMemoryCompleteHeader').style.textAlign = 'center';
			document.getElementById('createMemoryCompleteHeaderThumb').style.display = 'none';
			document.getElementById('createMemoryCompleteEditWrapper').style.display = 'none';
			document.getElementById('allowPostToFacebookWrapper').style.display = 'none';
			document.getElementById('createMemoryCompleteText').style.cssFloat = 'none';
			document.getElementById('createMemoryCompleteText').style.styleFloat = 'none';
			document.getElementById('createMemoryCompleteText').style.marginTop = '-15px';
		}
		
		var num_attendees = 0;
		for (var i in memoryCreationWizard.selected_friends) num_attendees++;
		if (num_attendees) document.getElementById('allowPostToFriendsWrapper').style.display = 'block';
		
		// update friend post title
		if (memoryCreationWizard.title) memoryCreationWizard.notifyFriendsTitle = ucfirst(memoryCreationWizard.title)+': '+formatDateStr(memoryCreationWizard.start_time)+' Captured';
		
		$('#createMemoryCompleteWrapper').removeClass('hidden');
		$('#createMemorySaving').addClass('hidden');
		memoryCreationWizard.updateHints('complete');
		if (memoryCreationWizard.total_photos && memoryCreationWizard.updateProgressInterval) {clearInterval(memoryCreationWizard.updateProgressInterval);memoryCreationWizard.updateProgressInterval = null;}
	},
	
	updateSavingProgress: function() {
		var current = this.totalProgress;
		var total = (1 + 1 + 4/7 + 4/70 + 3/35 + 1/7)*this.total_photos; // 35 35 20 2 3 5 (%)
		$('#savingProgress').progressBar(Math.min(Math.ceil((current/total)*100), 100));
	},
	
	processPhotos: function () {
		if (memoryCreationWizard.albums_loading) {
			setTimeout("memoryCreationWizard.processPhotos()", 200);
			return true;
		}
		// set progress bar update timer
		if (memoryCreationWizard.total_photos) {
			memoryCreationWizard.totalProgress = 0;
			//this.updateProgressInterval = setInterval('memoryCreationWizard.updateSavingProgress()', 2000);
		}
		
		var callback = (function (that) {
			return function () {
				// update progress bar
				//if (this.total_photos) $('#savingProgress').progressBar(5);
				that.totalProgress += Math.ceil((3/35)*that.total_photos);
				
				that.saveAttendeesToDatabase(function () {
					that.savePhotosToDatabase(that.displayMemoryComplete);
				});
			};
		})(memoryCreationWizard);
		
		/*if (userProfileObj.id) {
			readFromDB('getSegment', [*segment_id*], function(data){
				data = JSON.parse(data);
				if (data && data['status'] == "ok") {
					var segment_data = data['result'];
					if (segment_data && segment_data['user_id'] == userProfileObj.id) {
						memoryCreationWizard.segment_id = segment_id;
						writeToDB('editSegment', [{'title':d_escape(memoryCreationWizard.title), 'utcStartSec':parseInt(memoryCreationWizard.start_time.getTime()/1000, 10), 'utcEndSec':parseInt(memoryCreationWizard.end_time.getTime()/1000, 10)}, segment_id], callback);
					} else memoryCreationWizard.createSegment(callback);
				} else memoryCreationWizard.createSegment(callback);
			});
		} else this.createSegment(callback);*/
		// don't create a new segment if a valid segment id has already been specified
		if (memoryCreationWizard.segment_id) {
			writeToDB('editSegment', [{
					'title':d_escape(memoryCreationWizard.title),
					'utcStartSec':parseInt(memoryCreationWizard.start_time.getTime()/1000, 10),
					'utcEndSec':parseInt(memoryCreationWizard.end_time.getTime()/1000, 10)},
					memoryCreationWizard.segment_id],
					callback);
		} else {
			memoryCreationWizard.createSegment(callback);
		}
		
		// update progress bar -- deprecated after implementing server hand-off saving method
		if (0&&memoryCreationWizard.total_photos) {
			memoryCreationWizard.totalProgress += Math.ceil((4/70)*memoryCreationWizard.total_photos);
		} else {//$('#savingProgress').progressBar(2);
			//document.getElementById('savingLoading').style.display = 'block';
			//document.getElementById('savingProgress').style.display = 'none';
		}
		
		return true;
	},
	
	updateMemoryThumb: function(photo_id) {
		if (photo_id && photo_id != this.prevSelectedThumb) {
			$('#m'+this.prevSelectedThumb).removeClass('create_memory_photo_selected');
			$('#m'+photo_id).addClass('create_memory_photo_selected');
			this.prevSelectedThumb = photo_id;
			var photo_data = this.loaded_photos[photo_id];
			// swap in aviary src
			var aviary_fb_photo = this.aviaryHashes[photo_id];
			if (aviary_fb_photo) photo_data = {'aviary_src':aviary_fb_photo['url']};
			var aviary_photo = photo_data['aviary_src'] && photo_id != photo_data['id'];
			var createMemoryThumb = document.getElementById('createMemoryThumb');
			createMemoryThumb.src = '';
			createMemoryThumb.src = aviary_photo?photo_data['aviary_src']:photo_data['thumbnail'];
			var createMemoryAviaryCanvas = document.getElementById('createMemoryAviaryCanvas');
			createMemoryAviaryCanvas.src = aviary_photo?photo_data['aviary_src']:photo_data['source'];
			createMemoryAviaryCanvas.setAttribute('point_id', photo_data['point_id']);
			createMemoryAviaryCanvas.setAttribute('media_pid', aviary_photo?photo_id:photo_data['id']);
			// refresh img element for aviary
			var createMemoryAviaryCanvasClone = createMemoryAviaryCanvas.cloneNode(true);
			var createMemoryAviaryCanvasWrapper = createMemoryAviaryCanvas.parentNode;
			createMemoryAviaryCanvasWrapper.removeChild(createMemoryAviaryCanvas);
			createMemoryAviaryCanvasWrapper.appendChild(createMemoryAviaryCanvasClone);
			//kapturDb.setMemoryThumb(aviary_photo?photo_data['aviary_media_id']:photo_data['media_id']);
		}
	},

	addPhotoToSelectAll: function(div, photo_id) {
		
		if (div && div.length) {
			div.attr("id", "selectAll" + photo_id);
			div.append('<div class="delete_btn"></div>');
			div.find('.delete_btn')[0].onclick = div[0].onclick;
			div[0].onclick = null;
			div.find('.createMemoryViewAlbumCheckbox, .createMemorySelectPhotoOverlay').remove();
			div.mouseout(function () {
				$(this).find('.delete_btn').hide();
			});
			div.mouseover(function () {
				$(this).find('.delete_btn').show();
			});
			$('#allSelectedPhotos').prepend(div);
			if (!this.remove_selected_photos[photo_id]) {
				memoryCreationWizard.new_photos++;
				memoryCreationWizard.new_selected_photos[photo_id] = true;
			} else {
				delete this.remove_selected_photos[photo_id];
			}
		}
	},
	
	photoInAlbum: function (photo_id, album_id) {
		var i, user_id;
		if (memoryCreationWizard.loaded_albums[album_id] &&
			memoryCreationWizard.loaded_albums[album_id].photos) {
			for (i = 0; i < memoryCreationWizard.loaded_albums[album_id].photos.length; i++) {
				if (memoryCreationWizard.loaded_albums[album_id].photos[i].id == photo_id) {
					return true;
				}
			}
		} else if ((album_id.substr(0, 13) == 'stream_photos') && memoryCreationWizard.stream_photos) {
			for (i = 0; i < memoryCreationWizard.stream_photos.length; i++) {
				if (memoryCreationWizard.stream_photos[i] == photo_id) {
					return true;
				}
			}
		} else if ((album_id.substr(0, 13) == 'tagged_photos') && memoryCreationWizard.tagged_photos) {
			user_id = album_id.split('tagged_photos')[1];
			for (i = 0; i < memoryCreationWizard.tagged_photos[user_id].length; i++) {
				if (memoryCreationWizard.tagged_photos[user_id][i].pid == photo_id) {
					return true;
				}
			}
		}
		
		return false;
	},

	togglePhotoSelected: function (photo_div, photo_id, tagged) {
		// keep track of added tagged albums for suggestions
		if (tagged) memoryCreationWizard.tagged_photo_albums.push(photo_id);
		var photo_checkbox = $('#photos'+photo_id+' .createMemoryViewAlbumCheckbox'),
			suggested_photo_div = $("#photos" + photo_id + "suggested"),
			suggested_checkbox = $("#photos" + photo_id + "suggested .createMemoryViewAlbumCheckbox"),
			album_checkbox, album_id;
		if (this.selected_photos[photo_id]) {
			// check to make sure user is owner before removing
			var point_id = fbPhotoPointIds[photo_id];
			if (memoryCreationWizard.sid && (rmnPoints[point_id] && userProfileObj.id != rmnPoints[point_id]['user_id'])) {
				if (!dataFlags.processingAddAll) {
					alert('You can only remove what you have added.');
					if (!photo_checkbox.attr('checked')) {
						photo_checkbox.attr('checked', true);
						suggested_checkbox.attr('checked', true);
						suggested_photo_div.addClass('create_memory_photo_selected');
					}
				}
			} else {
				if (this.new_selected_photos[photo_id]) {
					this.new_photos--;
					delete this.new_selected_photos[photo_id];
				}this.remove_selected_photos[photo_id] = 1;
				this.total_photos--;
				delete this.selected_photos[photo_id];
				$('.create_memory_photo[id="photos'+photo_id+'"]').removeClass('create_memory_photo_selected');
				$('#photos' + photo_id + "suggested").removeClass('create_memory_photo_selected');
				$('#photos' + photo_id + "suggested .createMemoryViewAlbumCheckbox").attr('checked', false);
				//$('#photos' + photo_id).removeClass('create_memory_photo_selected');
				$('#selectAll' + photo_id).remove();
				if (photo_checkbox.attr('checked')) {
					photo_checkbox.attr('checked', false);
					suggested_checkbox.attr('checked', false);
					suggested_photo_div.removeClass('create_memory_photo_selected');
				}
				
				for (album_id in memoryCreationWizard.selected_albums) {
					if (memoryCreationWizard.photoInAlbum(photo_id, album_id)) {
						album_checkbox = $("#album" + album_id).find(".createMemoryViewAlbumCheckbox");
						$("#album" + album_id + 'suggested').find(".createMemoryViewAlbumCheckbox").attr('checked', false);
						if (album_checkbox.attr('checked')) {
							album_checkbox.attr('checked', false);
							delete memoryCreationWizard.selected_albums[album_id];
						}
					}
				}
			}
		} else {
			memoryCreationWizard.total_photos++;
			memoryCreationWizard.selected_photos[photo_id] = true;
			//$(photo_div).addClass('create_memory_photo_selected');
			$('.create_memory_photo[id="photos'+photo_id+'"]').addClass('create_memory_photo_selected');
			
			//new photos are added here
			memoryCreationWizard.addPhotoToSelectAll($(photo_div).clone().attr('id', 'selectAll' + photo_id), photo_id);
			if (!photo_checkbox.attr('checked')) {
				photo_checkbox.attr('checked', 'checked');
				suggested_checkbox.attr('checked', 'checked');
				suggested_photo_div.addClass('create_memory_photo_selected');
			}
		}

		if (this.total_photos > 0) {
			$("#allSelectedPhotosText").html('Remove a photo from your album by mousing over it and clicking the "X"');
		} else {
			$("#allSelectedPhotosText").html('As you add photos, you will see them here.');
		}
	},

	displayUserAlbums: function (albums) {
		memoryCreationWizard.displayAlbums(albums, 'createMemoryAllPhotosUserAlbums', 1);
	},

	displayUserCoverAlbums: function (albums) {
		memoryCreationWizard.displayAlbums(albums, 'createMemoryAllPhotosUserCoverAlbums', 'cover');
	},

	displaySelectPhotos: function (photos) {
		var select_photos_div = $('#createMemoryAllPhotosUserPhotos'),
			select_photos_html = '',
			i = 0;

		if (photos.length > 0) {
			select_photos_html += '<div class="add_all_button">+ add all photos</div><div class="clear"></div>';
		}
		
		for (i = 0; i < photos.length; i++) {
			select_photos_html += '<div class="create_memory_photo" onclick="memoryCreationWizard.togglePhotoSelected(this, \'' +
				photos[i].id + '\')" id="photos'+photos[i].id+'"><img src="' +
				photos[i].thumbnail + '"/></div>';
		}

		select_photos_html += '<div class="clear"></div>';

		select_photos_div.html(select_photos_html);
	},
	
	processAlbumPhotos : function (data) {//, fb_photo_tags_proxy.value
		var proxy_data = window.fb_photos_proxy ? [fb_photos_proxy.value] : [],
			album_id;
			
		if (!data) data = proxy_data;
		var tags = data[1];
		data = data[0];
		album_id = data && data[0] && data[0]['aid'];
		var photos = [],
			photo,
			i = 0;
		if (data && (data.length > 0)) {
			for (i = 0; i < data.length; i++) {
				photo = {
					aid: data[i].aid,
					page_url: data[i].link,
					source: data[i].src_big,
					thumbnail: data[i].src,
					width: data[i].src_big_width,
					height: data[i].src_big_height,
					id: data[i].pid,
					description: data[i].caption,
					utc_time_second: data[i].created,
					owner_facebook_id: data[i].owner,
					timezone_offset: memoryCreationWizard.timezone_offset,
					contributor_kaptur_id: userProfileObj.id
				}; // store high-res url
				try {var high_res_url = data[i]['images'][0]['source'];
					if (photo['src_big'] != high_res_url) photo['src_high_res'] = high_res_url;
				} catch (err) {}
				photos.push(photo);
				memoryCreationWizard.loaded_photos[photo.id] = photo;
			}
			storeMediaTags(tags);
		}

		if (memoryCreationWizard.loaded_albums[album_id]) {
			memoryCreationWizard.loaded_albums[album_id].photos = photos;
		}
	},

	loadAlbumPhotos: function (album_id, callback, suggested, select) {
		var fb_photos = {fql: 'SELECT pid, aid, src, src_big, created, owner, images, src_big_width, src_big_height, src_small, link, caption, modified FROM photo WHERE '+(album_id.indexOf('stream_photos') != -1?'pid IN ("'+this.stream_photos.join('","')+'")':'aid = "{0}"')+(suggested?' AND created >= '+parseInt(memoryCreationWizard.start_time.getTime()/1000, 10):'')+' ORDER BY created DESC', args: [album_id]},
			/*fb_photo_tags = {fql: 'SELECT pid, subject, text FROM photo_tag WHERE pid IN (SELECT pid FROM {0})',
				args: [fb_photos]},*/
			processPhotos;
		
		var tagged_photos = album_id.indexOf('tagged_photos') != -1;
		if (memoryCreationWizard.loaded_albums[album_id] && memoryCreationWizard.loaded_albums[album_id].photos) {
			if ((typeof callback) == "function") {
				callback(memoryCreationWizard.loaded_albums[album_id].photos, select, tagged_photos);
			}
		} else {//fb_photo_tags_proxy, 
			processPhotos = (function (callback, fb_photos_proxy, album_id, select) {
				return function (data) {//, fb_photo_tags_proxy.value
					var proxy_data = [fb_photos_proxy.value];
					if (!data) data = proxy_data;
					var tags = data[1];
					data = data[0];
					var photos = [],
						photo,
						i = 0;
					if (data && (data.length > 0)) {
						for (i = 0; i < data.length; i++) {
							photo = {
								aid: data[i].aid,
								page_url: data[i].link,
								source: data[i].src_big,
								thumbnail: data[i].src,
								width: data[i].src_big_width,
								height: data[i].src_big_height,
								id: data[i].pid,
								description: data[i].caption,
								utc_time_second: data[i].created,
								owner_facebook_id: data[i].owner,
								timezone_offset: memoryCreationWizard.timezone_offset,
								contributor_kaptur_id: userProfileObj.id
							}; // store high-res url
							try {var high_res_url = data[i]['images'][0]['source'];
								if (photo['src_big'] != high_res_url) photo['src_high_res'] = high_res_url;
								photo['width'] = data[i]['images'][0]['width'];
								photo['height'] = data[i]['images'][0]['height'];
							} catch (err) {}
							photos.push(photo);
							memoryCreationWizard.loaded_photos[photo.id] = photo;
						}
						storeMediaTags(tags);
					}
					
					if (memoryCreationWizard.loaded_albums[album_id])
						memoryCreationWizard.loaded_albums[album_id].photos = photos;
					
					memoryCreationWizard.albums_loading--;

					if ((typeof callback) == "function")
						callback(photos, select, tagged_photos);
				};
			})(callback, fb_photos, album_id, select);//fb_photo_tags, 

			memoryCreationWizard.albums_loading++;
			if (album_id.indexOf('tagged_photos') != -1) {
				var fbid = album_id.split('tagged_photos')[1];
				processPhotos([this.tagged_photos[fbid], this.tagged_photo_tags[fbid]]);
			} else multipleQueryFacebook([fb_photos], processPhotos);//, fb_photo_tags
		}
	},

	displayPhotos: function (photos, photos_div, select, tagged_photos) {
		var friend_photos_div = $("#" + photos_div),
			friend_photos_html = "", friend_photo_html = "",
			suggested = '', photo_class, checked, i = 0;
		
		if (photos_div == 'createMemoryAllPhotosSuggestedPhotos') suggested = 'suggested';
		if (photos.length > 0) {
			var wedding_cover = document.getElementById('memoryEditWrapper') && photos_div.indexOf('Cover') != -1;
			for (i = 0; i < photos.length; i++) {
				photo_class = 'create_memory_photo';
				checked = '';
				
				var non_cover_selected = (!wedding_cover) && (select == 'all' || (select != 'none' && memoryCreationWizard.selected_photos[photos[i].id]));
				var cover_selected = wedding_cover && memoryCreationWizard.weddingCover == photos[i].id;
				//alert(non_cover_selected+' '+cover_selected)
				if (non_cover_selected || cover_selected) {
					photo_class += ' create_memory_photo_selected';
					checked = ' checked="checked"';
				}
				
				if (!wedding_cover) {
					friend_photo_html = '<div class="'+ photo_class +
						'" onclick="memoryCreationWizard.togglePhotoSelected(this, \'' +
						photos[i].id + '\''+(tagged_photos?', 1':'')+')" id="photos'+photos[i].id+suggested+'" '+
						'onmouseover="memoryCreationWizard.showPhotoControls(this, event)" '+
						'onmouseout="memoryCreationWizard.hidePhotoControls(this, event)"'+
						'><img src="' + photos[i].thumbnail + '"/>'+
						'<div class="createMemorySelectPhotoOverlay">Select Photo</div>'+
						'<input type="checkbox" class="createMemoryViewAlbumCheckbox" '+checked+'/></div>';
				} else {
					friend_photo_html = '<div class="'+ photo_class +
						'" onclick="setWeddingCover(\'' +
						photos[i].id + '\''+(tagged_photos?', 1':'')+')" id="photos'+photos[i].id+suggested+'" '+
						'><img src="' + photos[i].thumbnail + '"/></div>';
				}
				
				friend_photos_html += friend_photo_html;
				if (select == 'all') {
					if (!memoryCreationWizard.selected_photos[photos[i].id]) {
						memoryCreationWizard.total_photos++;
						memoryCreationWizard.selected_photos[photos[i].id] = true;
						memoryCreationWizard.addPhotoToSelectAll($(friend_photo_html.replace('id="photos', 'id="selectAll')), photos[i].id);
						$("#photos" + photos[i].id + "suggested .createMemoryViewAlbumCheckbox").attr("checked", "checked");
						$("#photos" + photos[i].id + "suggested").addClass("create_memory_photo_selected");
					}
				} else if ((select == 'none') && memoryCreationWizard.selected_photos[photos[i].id]) {
					memoryCreationWizard.togglePhotoSelected(null, photos[i].id);
				}
			}
		} else {
			friend_photos_html = "No photos";
		}
		
		if (!select) {
			friend_photos_div.css("display","block");
		} else if (memoryCreationWizard.open_album == null) {
			friend_photos_div.css("display","none");
		}

		friend_photos_div.html(friend_photos_html);
	},

	displayFriendPhotos: function (photos, select, tagged_photos) {
		memoryCreationWizard.displayPhotos(photos, 'createMemoryAllPhotosFriendsPhotos', select, tagged_photos);
		var display_style = !tagged_photos?'block':'none';
		if (!select) {
			$('#createMemoryAllPhotosFriendPhotosSelectAll').css('display', display_style);
			$('#createMemoryAllPhotosFriendPhotosDeselectAll').css('display', display_style);
		}
	},

	displayUserPhotos: function (photos, select, tagged_photos, cover) {
		var cover_id = cover?'Cover':'';
		memoryCreationWizard.displayPhotos(photos, 'createMemoryAllPhotosUser'+cover_id+'Photos', select, tagged_photos);
		if (!document.getElementById('memoryEditWrapper') || !cover) {
			var display_style = !tagged_photos?'block':'none';
			$('#createMemoryAllPhotosUserPhotos'+cover_id+'SelectAll').css('display',display_style);
			$('#createMemoryAllPhotosUserPhotos'+cover_id+'DeselectAll').css('display',display_style);
		}
	},
	
	displaySuggestedPhotos: function (photos, select) {
		memoryCreationWizard.displayPhotos(photos, 'createMemoryAllPhotosSuggestedPhotos', select);
		document.getElementById('createMemoryAllPhotosSuggestedPhotosSelectAll').style.display = 'block';
		document.getElementById('createMemoryAllPhotosSuggestedPhotosDeselectAll').style.display = 'block';
	},
	
	
	friendPhotosSelectToggle: function (checkbox_element, album_id, album_name, user, event) {
		var target,parent;
		event = getEvent(event);
		target = getEventTarget(event);
		parent = getParentElement(checkbox_element);
		preventBubbling(event);
		if (checkbox_element != target) checkbox_element.checked = !checkbox_element.checked;
		$("#album" + album_id + ' .createMemoryViewAlbumCheckbox').attr('checked', checkbox_element.checked);
		$("#album" + album_id + 'suggested .createMemoryViewAlbumCheckbox').attr('checked', checkbox_element.checked);
		if (checkbox_element.checked) {
			$('.photo_thumb', parent).removeClass('photo_thumb').addClass('photo_thumb_selected');
			memoryCreationWizard.friendPhotosLoad(checkbox_element, album_id, album_name, user, 'all');
		} else {
			$('.photo_thumb_selected', parent).removeClass('photo_thumb_selected').addClass('photo_thumb');
			memoryCreationWizard.friendPhotosLoad(checkbox_element, album_id, album_name, user, 'none');
		}
	},
	
	friendPhotosLoad: function (calling_div, album_id, album_name, user, select) {
		var section = '';
		if (!select) location.href = '#';
		if (!select) this.open_album = album_id;
		//$(".photo_thumb_selected", calling_div.parentNode).removeClass("photo_thumb_selected");
		//$(".photo_thumb", calling_div).addClass("photo_thumb_selected");
		if (select == 'all') {
			if (!memoryCreationWizard.selected_albums[album_id])
				memoryCreationWizard.selected_albums[album_id] = true;
		} else if (select == 'none')
			delete memoryCreationWizard.selected_albums[album_id];
		if (user) {
			if (user == 'suggested') {
				$('#createMemoryAllPhotosSuggestedPhotos').html('<div class="friend_photos_loader">' + ajax_loader_small + '</div>');
				$('#createMemoryAllPhotosSuggestedAlbumTitle').html(album_name);
				var callback = function(photos_param, select_param) {dataFlags.processingAddAll = 1;memoryCreationWizard.displaySuggestedPhotos(photos_param, select_param);delete dataFlags.processingAddAll;}
				memoryCreationWizard.loadAlbumPhotos(album_id, callback, 1, select);
				section = 'Suggested';
			} else {
				var display_photos_function = memoryCreationWizard.displayUserPhotos;
				section = 'User';
				if (user == 'cover') {
					section += 'Cover';
					display_photos_function = function(data) {memoryCreationWizard.displayUserPhotos(data, '', '', 1);};
				}
				
				$('#createMemoryAllPhotos'+section+'Photos').html('<div class="friend_photos_loader">' + ajax_loader_small + '</div>');
				$('#createMemoryAllPhotos'+section+'AlbumTitle').html(album_name);
				var callback = function(photos_param, select_param, tagged_photos_param, cover_param) {dataFlags.processingAddAll = 1;display_photos_function(photos_param, select_param, tagged_photos_param, cover_param);delete dataFlags.processingAddAll;}
				memoryCreationWizard.loadAlbumPhotos(album_id, callback, false, select);
			}
		} else {
			if (!select) {
				$('#createMemoryAllPhotosFriendsPhotos').html('<div class="friend_photos_loader">' + ajax_loader_small + '</div>');
			}
			$('#createMemoryAllPhotosFriendAlbumTitle').html(album_name);
			
			var callback = function(photos_param, select_param, tagged_photos_param) {dataFlags.processingAddAll = 1;memoryCreationWizard.displayFriendPhotos(photos_param, select_param, tagged_photos_param);delete dataFlags.processingAddAll;}
			memoryCreationWizard.loadAlbumPhotos(album_id, callback, false, select);
			section = 'Friends';
		}
		if (!select) {
			document.getElementById('createMemoryAllPhotos'+section+'AlbumsWrapper').style.display = 'none';
			document.getElementById('createMemoryAllPhotos'+section+'PhotosWrapper').style.display = 'block';
		}
	},
	
	showAlbumSelector: function(section) {
		this.open_album = null;
		document.getElementById('createMemoryAllPhotos'+section+'AlbumsWrapper').style.display = 'block';
		document.getElementById('createMemoryAllPhotos'+section+'PhotosWrapper').style.display = 'none';
		if (section == "Friends") document.getElementById('createMemoryAllPhotosFriendsPhotos').innerHTML='';
		$('#createMemoryAllPhotosSuggestedAlbumsHint').css('display', 'none');
	},
	
	showPhotoControls: function (div, event) {
		$(".createMemorySelectPhotoOverlay", div).show();
	},
	
	hidePhotoControls: function (div, event) {
		$(".createMemorySelectPhotoOverlay", div).hide();
	},
	
	showAlbumControls: function (div, event) {
		$(".createMemoryViewAlbumOverlay, .createMemorySelectAlbumOverlay", div).show();
	},
	
	hideAlbumControls: function (div, event) {
		$(".createMemoryViewAlbumOverlay, .createMemorySelectAlbumOverlay", div).hide();
	},
	
	displayAlbums: function (albums, album_div, user, fbid) {
		var friend_album_div = $("#" + album_div), i = 0, friend_album_html = "", checked, selected, album_id;
		var friend_album_div_html = friend_album_div.html();
		var friend_content_exists = friend_album_div_html.indexOf('friend_photos_loader') == -1;
		if (albums && (albums.length > 0)) {
			$("#createMemoryAllPhotosFriendsAlbumsWrapperChooseText").css("display", "none");
			var wedding_cover = document.getElementById('memoryEditWrapper') && (user == 'cover');
			for (i = 0; i < albums.length; i++) {
				if (memoryCreationWizard.selected_albums[albums[i].id]) {
					checked = 'checked="checked"';selected = '_selected';
				} else {
					checked = '';selected = '';
				}
				
				album_id = 'album' + albums[i].id;
				if (user == 'suggested') album_id += 'suggested';
				else if (user == 'cover') album_id += 'cover';
				
				if (!document.getElementById(album_id)) {
					var skip = 0;
					if (albums[i].id.indexOf('stream_photos') != -1 && $('#createMemoryAllPhotosSuggestedAlbums div.album_wrapper[id^="albumstream_photos"]').length) skip = 1;
					if (!skip) {
						if (!wedding_cover) {
							friend_album_html += '<div id="'+album_id+'" class="album_wrapper" ' +
								'onmouseover="memoryCreationWizard.showAlbumControls(this, event)" ' +
								'onmouseout="memoryCreationWizard.hideAlbumControls(this, event)" ' +
								'onclick="memoryCreationWizard.friendPhotosLoad(this, \'' +
								albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
								(user ? ', \''+user+'\'' : '') + ')"><div class="album_wrapper_inner"><img class="photo_thumb'+selected+'" src="' +
								albums[i].cover + '"/><div class="createMemoryViewAlbumOverlay"><img src="'+
								TEMPLATE_VIEW_PATH+'images/create_memory_wizard/magnifyer.png"/>View Album</div>';
							if (albums[i].id.indexOf('tagged_photos') == -1 && albums[i].id.indexOf('stream_photos') == -1)
								friend_album_html += '<div class="createMemorySelectAlbumOverlay" onclick="memoryCreationWizard.friendPhotosSelectToggle(this.nextSibling, \'' +
									albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
									(user ? ', \''+user+'\'' : ',null') + ',event);">Select Album</div>' +
									'<input type="checkbox" class="createMemoryViewAlbumCheckbox" ' +
									'onclick="memoryCreationWizard.friendPhotosSelectToggle(this, \'' +
									albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
									(user ? ', \''+user+'\'' : ',null') + ',event);" '+checked+'/>';
							friend_album_html += '</div><div class="album_title">' + albums[i].name + '</div></div>';
						} else {
							friend_album_html += '<div id="'+album_id+'" class="album_wrapper" ' +
								'onclick="memoryCreationWizard.friendPhotosLoad(this, \'' +
								albums[i].id + '\', \'' + escapeQuotes(albums[i].name) + '\'' +
								(user ? ', \''+user+'\'' : '') + ')"><div class="album_wrapper_inner"><img class="photo_thumb'+selected+'" src="' + albums[i].cover + '"/></div><div class="album_title">' + albums[i].name + '</div></div>';
						}
					}
				}
			}
		} else {
			if (!friend_content_exists) {
				$("#createMemoryAllPhotosFriendsAlbumsWrapperChooseText").css("display", "none");
				friend_album_html = '<div id="createMemoryAllPhotosFriendsAlbumsEmpty">'+(user?'You don\'t':'Your friend doesn\'t')+' have any Facebook photos, or they are unavailable due to privacy settings.'+(!user?'<br><br>Click <a href="#" style="color:#f09" onclick="memoryCreationWizard.inviteFriend(\''+fbid+'\'); return false">here</a> to invite them to use Kaptur!':'')+'</div>';//f96
			}
		}
		
		if (user == 'suggested' && friend_content_exists)
			friend_album_html = friend_album_div_html+friend_album_html;
		friend_album_div.html(friend_album_html);
		
		// recheck album checkboxes that have been checked
		for (var i in memoryCreationWizard.selected_albums) {
			if (typeof i != 'function') {
				var album_id = 'album'+i;
				if (user == 'suggested') album_id += 'suggested';
				$('#'+album_id+' .createMemoryViewAlbumCheckbox').attr('checked', 'checked');
			}
		}
	},
	
	inviteFriend: function(uid) {
		var post_msg = memoryCreationWizard.title;
		var post_thumb = DOMAIN_URL+TEMPLATE_VIEW_PATH+"images/fb_thumb.jpg";
		var night_owner = userProfileObj.first_name;
		var post_title = night_owner?night_owner+" invited you to check out "+(post_msg?post_msg+' on ':'')+"Kaptur!":'';
		var post_desc = memoryCreationWizard.shareDesc;//notifyFriendsDesc
		//if (!post_desc) post_desc = 'I\'m capturing my memory on Kaptur right now. I\'d like to invite you to join so we can create shared memories using all of our friends\' photos.';
		/*try {
			var segment_thumb = rmnPoints[memoryCreationWizard.cover_point_id]['media_thumb'];
			if (segment_thumb) post_thumb = encodeURIComponent(AJAX_WRAPPER_PATH+'?q='+encodeURIComponent(segment_thumb)+'&redirect=1'); // see show_link_share() and getShortenerUrl()
		} catch(err) {}*/
		var action_link_text = "Kaptur";
		var night_url = DOMAIN_URL+'?ref=fb_invite';
		night_url = 'http://apps.facebook.com/kapturit/';
		var ui_args = { // show fb prompt
			method: 'stream.publish',
			message: post_msg,
			attachment: {
				name: post_title,
				caption: location.host,
				description: post_desc,
				href: night_url,
				media: [{type:"image", src:post_thumb, href:night_url}]
			}, target_id: uid,
			action_links: [{text:action_link_text, href:night_url}]
		};
		
		FB.ui(ui_args);
	},

	displayFriendAlbums: function (albums, fbid) {
		memoryCreationWizard.displayAlbums(albums, "createMemoryAllPhotosFriendsAlbums", "", fbid);
	},

	friendAlbumLoad: function (friend_div, facebook_id) {
		friend_div = $(friend_div);
		$('.friend_list_thumbnail_selected').removeClass('friend_list_thumbnail_selected');
		friend_div.addClass('friend_list_thumbnail_selected');
		location.href = "#";
		$("#createMemoryAllPhotosFriendsAlbums").html('<div class="friend_photos_loader">' + ajax_loader_small + '</div>');
		memoryCreationWizard.loadAlbums(facebook_id, function (albums) {
			memoryCreationWizard.displayFriendAlbums(albums, facebook_id);
			$("#createMemoryAllPhotosFriendsPhotos").html('');
		});
	},
	
	displayAddFriendsPhotos: function () {
		var friends_list = $("#createMemoryAllPhotosFriendsList"),
			friend_list_html = "", friend, i = 0;
	
		for (i in this.selected_friends) {
			friend = this.loaded_friends[i];
			friend_list_html += '<div class="friend_wrapper" onclick="memoryCreationWizard.unhideFriendAlbum(this, \'' +
				friend.facebook_id + '\')"><div class="friend_wrapper_thumb">' +
				'<img src="' + friend.thumbnail + '" class="profile_pic" title="'+
				friend.name +'"></div><div class="friend_wrapper_name">' + friend.name + '</div></div>';
		}
	
		if (!friend_list_html) friend_list_html = "None";
		friends_list.html(friend_list_html);
	},
	
	unhideFriendAlbum: function (that, id) {
		$('#createMemoryAllPhotosFriendsListWrapper').css('display','none');
		$('#createMemoryAllPhotosFriendsAlbumsWrapper').css('display', 'inline-block');
		//$('#createMemoryAllPhotosFriendsPhotosWrapper').css('display', 'inline-block');
		this.friendAlbumLoad(that, id);
	},
	
	hideFriendAlbums: function () {
		$('#createMemoryAllPhotosFriendsListWrapper').css('display','block');
		$('#createMemoryAllPhotosFriendsAlbumsWrapper').css('display', 'none');
		$('#createMemoryAllPhotosFriendsPhotosWrapper').css('display', 'none');
		$('#createMemoryAllPhotosFriendsPhotos').html('');
	},
	
	displaySaving: function () {
		$("#createMemorySaving").removeClass('hidden');
		$("#createMemoryCompleteWrapper").addClass('hidden');
	},

	processStep: function (num) {
		var valid = true;
		switch (num) {
			case 1:
				valid = this.processMemoryDescription();
				this.displayMemoryDescription();
				this.displayFriends();
				this.loadFriendLists(this.displayFriendLists);
				this.loadFriends(this.displayFriends);
				
				// query existing segments
				if (memoryCreationWizard.sid && userProfileObj.id && !memoryCreationWizard.segment_id) {
					var segment_id = memoryCreationWizard.sid;
					readFromDB('getSegment', [segment_id], function(data){
						data = JSON.parse(data);
						if (data && data['status'] == "ok") {
							var segment_data = data['result'];
							if (segment_data && segment_data['user_id'] == userProfileObj.id)
								memoryCreationWizard.segment_id = segment_id;
							else memoryCreationWizard.queryExistingSegments();
						} else memoryCreationWizard.queryExistingSegments();
					});
				} else memoryCreationWizard.queryExistingSegments();
				
				break;
			case 2:
				valid = this.processAttendees();
				this.displayAttendees();
				//this.selectTab(document.getElementById('createMemoryAddSuggestedPhotosTab'), 'createMemoryAllPhotosSuggestedContentWrapper'); //suggested tab
				this.selectTab(document.getElementById('createMemoryAddYourPhotosTab'), 'createMemoryAllPhotosFacebookContentWrapper'); //user photos tab
				$('#createMemoryAllPhotosSuggestedAlbums').html('<div class="friend_photos_loader">' + ajax_loader_small + '</div>');
				$('#createMemoryAllPhotosUserAlbums').html('<div class="friend_photos_loader">' + ajax_loader_small + '</div>');
				$('#createMemoryAllPhotosSuggestedPhotos').html('<div id="createMemorySuggestedPhotosLoadingHint">Kaptur will make suggestions as to what might be part of this memory. If nothing appears in this section please click on "Your Photos" or "Your Friends\' Photos" to manually add photos.</div>');
				$('#createMemoryAllPhotosUserPhotos').html('');
				this.loadStreamAlbums();
				this.loadAlbums(loggedInUser, this.displayUserAlbums);
				this.displayAddFriendsPhotos();
				break;
			case 3:
				if (loggedInUser) {
					this.displaySaving();
					valid = this.processPhotos();
				} else {
					var title = 'Please connect to Facebook';
					var error_msg = 'Please click on the Sign in with Facebook button to continue!';
					this.showAlert(title, error_msg);
					valid = false;
				}
				break;
		}
		
		return valid;
	},
	
	updateHints: function(step) {
		if (memoryCreationWizard.weddingPromo) {
			var step4_hint_id = 'createMemoryWeddingPromoHint4';
			if (memoryCreationWizard.futureMemory) step4_hint_id += 'Future';
			if (step == 1) {
				document.getElementById('headerBar').style.backgroundImage = 'url("'+TEMPLATE_VIEW_PATH+'images/create_memory_wizard/wedding_promo_logo.png")';
				document.getElementById('headerBarLeft').style.backgroundImage = 'none';
				document.getElementById('createMemoryHeader').style.display = 'none';
				document.getElementById('weddingPromoTagLine').style.display = 'block';
				
				if (!loggedInUser && rmnAppId != '10') document.getElementById('createMemoryWeddingPromoHint1').style.display = '';
				else document.getElementById('createMemoryWeddingPromoHint2').style.display = '';
				document.getElementById(step4_hint_id).style.display = '';
			}if (step == 2) {
				document.getElementById('headerBar').style.backgroundImage = 'none';
				document.getElementById('headerBarLeft').style.backgroundImage = 'url("'+TEMPLATE_VIEW_PATH+'images/create_memory_wizard/wedding_promo_logo_small.png")';
				document.getElementById('createMemoryHeader').style.display = 'block';
				document.getElementById('weddingPromoTagLine').style.display = 'none';
				
				document.getElementById('createMemoryWeddingPromoHint1').style.display = 'none';
				document.getElementById('createMemoryWeddingPromoHint2').style.display = 'none';
				document.getElementById('createMemoryWeddingPromoHint3').style.display = '';
				document.getElementById(step4_hint_id).style.display = 'block';
				document.getElementById('createMemoryWeddingPromoHint5').style.display = '';
			} else if (step == 3) {
				document.getElementById('headerBar').style.backgroundImage = 'none';
				document.getElementById('headerBarLeft').style.backgroundImage = 'url("'+TEMPLATE_VIEW_PATH+'images/create_memory_wizard/wedding_promo_logo_small.png")';
				document.getElementById('createMemoryHeader').style.display = 'block';
				document.getElementById('weddingPromoTagLine').style.display = 'none';
				
				document.getElementById(step4_hint_id).style.display = '';
				document.getElementById('createMemoryWeddingPromoHint1').style.display = 'none';
				document.getElementById('createMemoryWeddingPromoHint2').style.display = 'none';
				document.getElementById('createMemoryWeddingPromoHint3').style.display = '';
				document.getElementById('createMemoryWeddingPromoHint5').style.display = 'block';
				document.getElementById('createMemoryWeddingPromoHint6').style.display = '';
				document.getElementById('createMemoryWeddingPromoHint7').style.display = '';
			} else if (step == 4) {
				document.getElementById('createMemoryWeddingPromoHint5').style.display = '';
			} else if (step == 'complete') {
				var num_photos = 0, num_attendees = 0;
				for (var i in this.selected_photos) num_photos++;
				for (var i in this.selected_friends) num_attendees++;
				if (num_photos) {
					document.getElementById('createMemoryWeddingPromoHint6').style.display = 'block';
					document.getElementById('createMemoryWeddingPromoHint7').style.display = 'block';
				}
			} else if (step == 'showMemory') {
				document.getElementById('createMemoryWeddingPromoHint6').style.display = '';
				document.getElementById('createMemoryWeddingPromoHint7').style.display = '';
				document.getElementById('createMemoryWeddingPromoHint8').style.display = '';
				document.getElementById('createMemoryWeddingPromoHint9').style.display = '';
			}
		}
	},
	
	completedStep: function (num, next_num) {
		// ask for base permissions for vacation promo users
		if (loggedInUser && num == 2 && !userProfileObj.perms['user_photos']) {
			FB.login(function(response) {
				var session = getFacebookSession();
				if (session) {
					getFacebookPermissions(function (perms) {
						if (perms) {
							for (var i in perms) {
								userProfileObj.perms[i] = 1;
							}
							if (userProfileObj.perms['user_photos']) {
								memoryCreationWizard.completedStep(num, next_num);
								$.cookies.set("userPerms", null);
							}
						}
					});
				}
			}, {scope:'email, friends_photos, user_photos, friends_videos, user_videos, friends_relationships, friends_relationship_details, read_stream'});//user_photo_video_tags, friends_photo_video_tags, 
			return;//user_relationships, user_relationship_details, 
		}
		
		if (this.processStep(num)) {
			if (!next_num) {
				next_num = num+1;
			} else if (next_num && next_num != num+1) {
				this.processStep(num+1, next_num);
			}
			this.displayStep(next_num);
			window.frames['ga_iframe'].location = create_page_url+'&step='+next_num+'&fid='+loggedInUser+'&p=v';
		}
		location.href = "#";
	},

	selectTab: function (tab, content_id) {
		var tab_name = '', section = '', section_id = 'selectPhotosWrapper', tab_section_id = 'createMemoryAddPhotosTabs';
		switch (content_id) {
			case "createMemoryAllPhotosFacebookContentWrapper":
				memoryCreationWizard.showAlbumSelector('User');
				tab_name = 'user_tab';
				break;
			case "createMemoryAllPhotosSuggestedContentWrapper":
				memoryCreationWizard.showAlbumSelector('Suggested');
				tab_name = 'suggested_tab';
				break;
			case "createMemoryAllPhotosFriendsContentWrapper":
				memoryCreationWizard.showAlbumSelector('Friends');
				tab_name = 'friends_tab';
				memoryCreationWizard.hideFriendAlbums();
				break;
			case "createMemoryAllVideosUserVideosWrapper":
				tab_name = 'user_videos';
				section = 'videos';
				break;
			case "createMemoryAllVideosYouTubeVideosWrapper":
				tab_name = 'yt_videos';
				section = 'videos';
				break;
		}if (section == 'videos') {
			tab_section_id = 'createMemoryAddVideosTabs';
			section_id = 'selectVideosWrapper';
		}
		
		$('#'+section_id+' .create_memory_tabbed_content_selected', tab.parentNode.parentNode.parentNode).removeClass('create_memory_tabbed_content_selected').addClass('create_memory_tabbed_content');
		$('#' + content_id).removeClass('create_memory_tabbed_content').addClass('create_memory_tabbed_content_selected');
		$('#'+tab_section_id+' .create_memory_tab_selected', tab.parentNode.parentNode).removeClass('create_memory_tab_selected').addClass('create_memory_tab');
		$(tab).removeClass('create_memory_tab').addClass('create_memory_tab_selected');
		trackClick(tab_name, loggedInUser); // track in analytics
		
		// load extended suggestions
		if (tab.id == 'createMemoryAddSuggestedPhotosTab') memoryCreationWizard.loadExtendedSuggestions();
		else if (tab.id == 'createMemoryAddUploadPhotosTab') retrieveUploadedMedia();
	},
	
	loadExtendedSuggestions: function() {
		if (loggedInUser) {
			if (!dataFlags.suggestionsLoaded) {
				var friend_ids = '', friend_id_chunks = [], j = 0;
				for (var i in memoryCreationWizard.selected_friends) {
					friend_ids += (friend_ids?',':'')+'"'+i+'"';
					if (++j > 9) { // load in chunks of 10
						friend_id_chunks.push(friend_ids);
						friend_ids = '';
						j = 0;
					}
				}
				if (friend_ids) friend_id_chunks.push(friend_ids);
				if (friend_ids) memoryCreationWizard.loadStreamAlbums(friend_ids);
				else {
					dataFlags.friendStreamSuggestions = 1;
					memoryCreationWizard.checkNoSuggestions();
				}
				memoryCreationWizard.queryAlbumSuggestions(friend_id_chunks);
				dataFlags.suggestionsLoaded = 1;
			}
			var tagged_album_ids = memoryCreationWizard.tagged_photo_albums;
			if (tagged_album_ids.length) {
				var query_tagged_albums = [], tagged_album_thumbs = {};
				for (var i=0; i<tagged_album_ids.length; i++) {
					var photo_id = tagged_album_ids[i];
					var tagged_photo = memoryCreationWizard.loaded_photos[photo_id];
					if (tagged_photo) {
						var album_id = tagged_photo['aid'];
						if (!document.getElementById('album'+album_id+'suggested')) {
							query_tagged_albums.push(album_id);
							tagged_album_thumbs[album_id] = tagged_photo['thumbnail'];
						}
					}
				}
				
				var user_fql = 'SELECT aid, name FROM album WHERE aid IN ("'+query_tagged_albums.join('","')+'")';
				queryFacebook(user_fql, [], function (data) {
					if (data && data.length) {
						var albums = [];
						for (var i=0; i<data.length; i++) {
							var tagged_photo_album = data[i];
							var tagged_photo_aid = tagged_photo_album['aid'];
							var tagged_photo_album_name = tagged_photo_album['name'];
							var tagged_photo_thumb = tagged_album_thumbs[tagged_photo_aid];
							if (!tagged_photo_thumb) tagged_photo_thumb = TEMPLATE_VIEW_PATH+'images/placeholders/night_thumb.png';
							albums.push({id:tagged_photo_aid, name:tagged_photo_album_name, cover:tagged_photo_thumb});
						}memoryCreationWizard.displayAlbums(albums, 'createMemoryAllPhotosSuggestedAlbums', 'suggested');
						memoryCreationWizard.clearSuggestedHints();
					}
				});memoryCreationWizard.tagged_photo_albums = [];
			}
		}
	},
	
	queryAlbumSuggestions: function(friend_id_chunks) {
		dataFlags.suggestionsLoading = 1;
		var suggestedAlbumsLoading = document.getElementById('createMemoryAllPhotosSuggestedAlbumsLoading');
		if ($('#createMemoryAllPhotosSuggestedAlbums').html().indexOf('friend_photos_loader') == -1)
			suggestedAlbumsLoading.style.display = 'block';
		if (friend_id_chunks && !friend_id_chunks.length) friend_id_chunks = null;
		var start_time = parseInt(memoryCreationWizard.start_time.getTime()/1000, 10);
		var end_time = Math.min(parseInt(new Date().getTime()/1000, 10),
			parseInt(memoryCreationWizard.end_time.getTime()/1000, 10)+(20*24*60*60));
		var albums = {
			fql: 'SELECT aid, cover_pid, created, name FROM album WHERE owner'+(friend_id_chunks?' IN ('+friend_id_chunks[0]+')':'="{0}"')+' AND created >= {1} AND created <= {2} ORDER BY modified DESC',
			args: [loggedInUser, start_time, end_time]
		}, album_covers = {
			fql: 'SELECT src FROM photo WHERE pid IN (SELECT cover_pid FROM {0})',
			args: [albums]
		};
		multipleQueryFacebook([albums, album_covers], function () {
			albums = albums.value, album_covers = album_covers.value;
			if (albums && albums.length) {
				var albums_with_covers = [];
				album_covers.reverse(); // reverse covers array to prepare for pop
				for (var i = 0; i <  albums.length; i++) {
					var album = albums[i];
					var album_cover = album.cover_pid!=0?album_covers.pop():'';
					album_cover = album_cover?album_cover.src:TEMPLATE_VIEW_PATH+'images/placeholders/night_thumb.png';
					album = {
						id: album.aid,
						name: album.name,
						cover: album_cover
					};
					memoryCreationWizard.loaded_albums[album.id] = album;
					albums_with_covers.push(album);
				}
				memoryCreationWizard.displayAlbums(albums_with_covers, 'createMemoryAllPhotosSuggestedAlbums', 'suggested');
				memoryCreationWizard.clearSuggestedHints();
			} // call recursively until all chunks are loaded
			if (friend_id_chunks) {
				if (friend_id_chunks.length > 1) memoryCreationWizard.queryAlbumSuggestions(friend_id_chunks.slice(1));
				else memoryCreationWizard.queryAlbumSuggestions();
			} else {
				suggestedAlbumsLoading.style.display = '';
				delete dataFlags.suggestionsLoading;
				dataFlags.loadedAlbumSuggestions = 1;
				memoryCreationWizard.checkNoSuggestions();
			}
		});
	},
	
	checkNoSuggestions: function() {
		// load user fb photos instead if there are no suggestions
		if (!dataFlags.noSuggestionsProceed) {
			if (dataFlags.loadedAlbumSuggestions && dataFlags.userStreamSuggestions && dataFlags.friendStreamSuggestions) {
				if (!$('#createMemoryAllPhotosSuggestedAlbums').html() && $('#createMemoryAddSuggestedPhotosTab').hasClass('create_memory_tab_selected')) {
					$('#createMemoryAddYourPhotosTab').click();
					dataFlags.noSuggestionsProceed = 1;
				}
			}
		}
	},
	
	clearSuggestedHints: function() {
		$('#createMemoryAllPhotosSuggestedAlbumsHint').css('display', '');
		$('#createMemoryAllPhotosSuggestedAlbumsTitle').css('display', '');
		var noSuggestedHint = document.getElementById('createMemoryAllPhotosNoSuggestedAlbumsHint');
		if (noSuggestedHint) noSuggestedHint.parentNode.removeChild(noSuggestedHint);
	},

	loadFlickrPhotoset: function (photoset_id, page) {
		var photos_per_page = 12,
			flickr_photos_div = $("#createMemoryAllPhotosFlickrPhotos");
		
		page = page||1;
		flickr_photos_div.html("<span>Loading...<span> " + ajax_loader);

		//deselect the previously selected photoset and select this one
		$("#createMemoryAllPhotosFlickrAlbums .photo_thumb_selected").removeClass("photo_thumb_selected").addClass("photo_thumb");
		$("#flickralbum" + photoset_id).find("img").removeClass("photo_thumb").addClass("photo_thumb_selected");

		flickrDataManager.getPhotosFromPhotosetPage(photoset_id, page, photos_per_page, function(photos, page_info) {
			if (photos) {
				var flickr_photos_div = $("#createMemoryAllPhotosFlickrPhotos");
				flickr_photos_div.html('');

				var next_page_click = "";
				if (page_info.page < page_info.total_pages) {
					next_page_click = "memoryCreationWizard.loadFlickrPhotoset('"+photoset_id+"','"+(page_info.page+1)+"')";
				}
				var next_page_html = ' <span onclick="'+next_page_click+'">next</span> ';

				var previous_page_click = "";
				if (page_info.page > 1) {
					previous_page_click = "memoryCreationWizard.loadFlickrPhotoset('"+photoset_id+"','"+(page_info.page-1)+"')";
				}
				var previous_page_html = ' <span onclick="'+previous_page_click+'">previous</span> ';
				var first_page_html = ' <span onclick="memoryCreationWizard.loadFlickrPhotoset(\''+photoset_id+'\',\''+(1)+'\')">first</span> ';;
				var last_page_html = ' <span onclick="memoryCreationWizard.loadFlickrPhotoset(\''+photoset_id+'\',\''+(page_info.total_pages)+'\')">last</span> ';

				var flickr_navigation_html = "";
				if (page_info.total_pages > 1) {
						flickr_navigation_html = '( ' + first_page_html + previous_page_html + next_page_html + last_page_html + ' )';
				}

				var flickr_page_info_html = '<div style="clear:both;"><span>viewing photos '+page_info.first_photo+' to '+page_info.last_photo+'</span> on <span>page '+page_info.page+' of '+page_info.total_pages+'</span><span id="flickrPhotoNavigation">'+flickr_navigation_html+'</span></div>'

				for (var i = 0; i < photos.length; i++) {
					var new_photo_html = memoryCreationWizard.createPhotoDisplay(photos[i]);
					if (new_photo_html) {
						flickr_page_info_html += new_photo_html;
					}

					photos[i].utc_time_second = photos[i].created_time;
					photos[i].partnerId_id = PARTNER_TYPES.flickr_photo;
					photos[i].service = SERVICE_TYPES.flickr;
					photos[i].contributor_kaptur_id = userProfileObj.id;

					memoryCreationWizard.loaded_photos[photos[i].id + 'flickr'] = photos[i];
				}
				flickr_photos_div.html(flickr_page_info_html);
			}
		});
	},
	
	createAlbumDisplay: function(photoset_data) {
		var photoset_title = photoset_data.title._content || "Untitled",
			photoset_id = photoset_data.id,
			photoset_primary_url = photoset_data.primary_url,
			album_image_html = '<img src="'+photoset_primary_url+'" class="photo_thumb" />',
			album_display_html = '<div class="album_wrapper" id="flickralbum' +
				photoset_id + '" onclick="memoryCreationWizard.loadFlickrPhotoset(\'' +
				photoset_id + '\');">' + album_image_html + '<div class="album_title">' +
				photoset_title + "</div></div>";

		return album_display_html;
	},

	createAllPhotoDisplay: function(user_id) {
		var album_image_html = '<img src="'+TEMPLATE_VIEW_PATH+'images/placeholders/night_thumb.png" class="photo_thumb_selected" />',
			album_display_html = '<div class="album_wrapper" id="flickrallphotos'+user_id+'" onclick="memoryCreationWizard.loadAllFlickrPhotos(\''+user_id+'\', 1);">'+album_image_html+'<div class="album_title">All Photos</div></div>';

		return album_display_html;
	},

	createPhotoDisplay: function(photo_data) {
		//var photo_url = photo_data.url;
		var photo_thumb_url = photo_data.thumb_url,
			photo_id = photo_data.id,
			photo_display_html = "",
			photo_json = JSON.stringify(photo_data),
			photo_clicked = "memoryCreationWizard.togglePhotoSelected(this, '" + photo_data.id + "flickr')",
			photo_class = "create_memory_photo";

		if (memoryCreationWizard.selected_photos[photo_id + 'flickr']) {
			photo_class += ' create_memory_photo_selected';
		}

		if (photo_thumb_url) {
			photo_display_html = '<div class="' + photo_class + '" onclick="' + photo_clicked + '"><img id="m' +
				photo_id + 'flickrthumb" src="' + photo_thumb_url +
				'"/></div>';
		}

		return photo_display_html;
	},

	loadAllFlickrPhotos: function (user_id, page) {
		var per_page = 12;
		var flickr_photos_div = $("#createMemoryAllPhotosFlickrPhotos");
		var all_photos_album_div = document.getElementById('flickrallphotos' + user_id); //jquery will fail on many user_ids
		flickr_photos_div.html("<span>Loading...<span> " + ajax_loader);

		//deselect the previously selected photoset and select this one
		$("#createMemoryAllPhotosFlickrAlbums .photo_thumb_selected").removeClass("photo_thumb_selected").addClass("photo_thumb");

		if (all_photos_album_div) {
			$(all_photos_album_div).find("img").removeClass("photo_thumb").addClass("photo_thumb_selected");
		}

		flickrDataManager.getPhotosFromUserByPage(user_id, page, per_page, function(response) {
			var flickr_photos_div = $("#createMemoryAllPhotosFlickrPhotos"),
				photos,
				page_info,
				error_message = '';

			if (response && (response.error.status = "ok")) {
				photos = response.photos;
				page_info = response.page_info;

				flickr_photos_div.html("");
				var flickr_page_info_html = "";

				if (page_info.total_photos > 0) {
					var next_page_click = "";
					var next_page_html = "";
					var last_page_html = "";
					if (page_info.page < page_info.total_pages) {
						next_page_click = "memoryCreationWizard.loadAllFlickrPhotos('"+user_id+"','"+(page_info.page+1)+"')";
						next_page_html = ' <span onclick="'+next_page_click+'">next</span> ';
						last_page_html = ' <span onclick="memoryCreationWizard.loadAllFlickrPhotos(\''+user_id+'\',\''+(page_info.total_pages)+'\')">last</span> ';
					}

					var previous_page_click = "";
					var previous_page_html = "";
					var first_page_html = "";
					if (page_info.page > 1) {
						previous_page_click = "memoryCreationWizard.loadAllFlickrPhotos('"+user_id+"','"+(page_info.page-1)+"')";
						previous_page_html = ' <span onclick="'+previous_page_click+'">previous</span> ';
						first_page_html = ' <span onclick="memoryCreationWizard.loadAllFlickrPhotos(\''+user_id+'\',\''+(1)+'\')">first</span> ';
					}

					var flickr_navigation_html = "";

					if (page_info.total_pages > 1) {
						flickr_navigation_html = '( ' + first_page_html + previous_page_html + next_page_html + last_page_html + ' )';
					}

					flickr_page_info_html = '<div style="clear:both;"><span>viewing photos '+page_info.first_photo+' to '+page_info.last_photo+'</span> on <span>page '+page_info.page+' of '+page_info.total_pages+'</span><span id="flickrPhotoNavigation">'+flickr_navigation_html+'</span></div>'
				} else {
					flickr_page_info_html = '<div style="clear:both;">No photos available</div>'
				}

				for (var i = 0; i < photos.length; i++) {
					var new_photo_html = memoryCreationWizard.createPhotoDisplay(photos[i]);
					if (new_photo_html) {
						flickr_page_info_html += new_photo_html;
					}

					photos[i].utc_time_second = photos[i].created_time;
					photos[i].partnerId_id = PARTNER_TYPES.flickr_photo;
					photos[i].service = SERVICE_TYPES.flickr;
					photos[i].contributor_kaptur_id = userProfileObj.id;

					memoryCreationWizard.loaded_photos[photos[i].id + 'flickr'] = photos[i];
				}
				flickr_photos_div.html(flickr_page_info_html);
			} else {
				error_message = "An error occurred making this request";
				if (response && response.error.message) {
					error_message = response.error.message;
				}

				flickr_photos_div.html('<div>'+error_message+'<div>');
			}
		});
	},

	handleFlickrIdSubmit: function () {
		var user_name = $("#createMemoryAllPhotosGetFlickrIdInput").val();

		flickrDataManager.getUserId(user_name, function(response) {
			var flickr_error_div = $("#createMemoryAllPhotosFlickrError"),
				user_id,
				display_all_html = '',
				display_albums_html = '';
			if(response && (response.error.status == "ok")) {
				user_id = response.user_id;
				flickr_error_div.html('');
				flickrDataManager.getPhotosets(user_id, function(photosets) {
					var flickr_albums_div = $("#createMemoryAllPhotosFlickrAlbums");
					display_all_html = memoryCreationWizard.createAllPhotoDisplay(user_id);
					display_albums_html = display_all_html
					//flickr_albums_div.innerHTML = display_all_html;
					if (photosets.length > 0) {
						for (var i = 0; i < photosets.length; i++) {
							var new_album_html = memoryCreationWizard.createAlbumDisplay(photosets[i]);
							display_albums_html += new_album_html; // flickr_albums_div.innerHTML
						}
					}

					flickr_albums_div.html(display_albums_html);
				});
				memoryCreationWizard.loadAllFlickrPhotos(user_id, 1); //by default display the All Photos photoset
			} else {
				var error_message = "";
				if (response) {
					error_message = response.error.message;
				} else {
					error_message = "Sorry, it looks like the flickr servers are not responding";
				}

				flickr_error_div.html(error_message);
			}
		});
	},

	editMemoryDescription: function () {
		this.displayStep(1);
	},

	editAttendees: function () {
		this.displayStep(2);
	},

	setCover: function (cover_id, callback) {
		var save_segment_params = {
			media_id: cover_id
		}

		kapturDb.saveSegment(this.segment_id, save_segment_params, callback);
	},
	
	addAviaryPhoto: function (args) {
		var fb_photo_id = args['fb_photo_id'];
		var aviary_hash = args['aviary_hash'];
		var aviary_url = args['aviary_url'];
		
		// swap in fb photo id reference if modifying an already modified fb photo
		var existing_hashes = memoryCreationWizard.aviaryHashes[fb_photo_id];
		if (existing_hashes) fb_photo_id = existing_hashes['pid'];
		
		// insert new aviary photo and set it as the memory thumb
		var aviary_thumb = document.createElement('div');
		aviary_thumb.id = 'm'+aviary_hash;
		aviary_thumb.className = 'create_memory_photo';
		aviary_thumb.innerHTML = '<img src="'+aviary_url+'" onclick="memoryCreationWizard.updateMemoryThumb(\''+aviary_hash+'\')">';
		document.getElementById('createMemoryPhotos').appendChild(aviary_thumb);
		if (!memoryCreationWizard.aviaryPhotos[fb_photo_id]) memoryCreationWizard.aviaryPhotos[fb_photo_id] = [];
		memoryCreationWizard.aviaryPhotos[fb_photo_id].push({'hash':aviary_hash, 'url':aviary_url});//'pid':fb_photo_id, 
		memoryCreationWizard.aviaryHashes[aviary_hash] = {'pid':fb_photo_id, 'url':aviary_url};
		//memoryCreationWizard.loaded_photos[aviary_hash] = {'source':aviary_url, 'thumbnail':aviary_url, 'id':aviary_hash};
		memoryCreationWizard.updateMemoryThumb(aviary_hash);
		aviaryeditor_close();
		memoryCreationWizard.aviary_photos++;
	},
	
	savePhoto: function (photo, callback, args) {
		this.points_created = 0, this.photos_created = 0;
		var aviary_hash;if (args) {
			aviary_hash = args['aviary_hash'];
			var aviary_url = args['aviary_url'];
			photo['aviary_src'] = aviary_url;
			photo['aviary_hash'] = aviary_hash;
		}photo.utc_time_second = getUniqueTime(this.adjustPointTime(photo.utc_time_second));
		kapturDb.createPhotoPoint(photo, (function (that, photo, callback) {
			return function (point_id) {
				// update progress bar
				that.points_created++;
				that.totalProgress++;
				//if (that.points_created % Math.ceil(that.total_photos/35) == 0)
					//$('#savingProgress').progressBar(35*(that.points_created/that.total_photos)+10);
				
				// pair users and point
				kapturDb.pairUsersAndPoint(point_id);
				
				// create media
				kapturDb.createPhotoMedia(photo, (function (that, photo, point_id, callback) {
					return function (media_id) {
						// update progress bar
						that.photos_created++;
						that.totalProgress++;
						//if (that.photos_created % Math.ceil(that.total_photos/35) == 0)
							//$('#savingProgress').progressBar(35*(that.photos_created/that.total_photos)+45);
						
						/* -- handled by setMemoryThumb --
						if (that.cover_id == null) {
							that.setCover(media_id);
						}*/
						kapturDb.pairMediaAndPoint(media_id, point_id, function () {
							if (aviary_hash) {
								photo.aviary_media_id = media_id;
								photo.aviary_point_id = point_id;
							} else {
								photo.media_id = media_id;
								photo.point_id = point_id;
							}
							
							// insert new aviary photo and set it as the memory thumb
							if (aviary_hash) {
								var aviary_thumb = document.createElement('div');
								aviary_thumb.id = 'm'+aviary_hash;
								aviary_thumb.className = 'create_memory_photo';
								aviary_thumb.innerHTML = '<img src="'+aviary_url+'" onclick="memoryCreationWizard.updateMemoryThumb(\''+aviary_hash+'\')">';
								document.getElementById('createMemoryPhotos').appendChild(aviary_thumb);
								
								memoryCreationWizard.loaded_photos[aviary_hash] = photo;//selected_photos
								memoryCreationWizard.updateMemoryThumb(aviary_hash);
								aviaryeditor_close();
							}
							
							if ((typeof callback) == "function") {
								callback(photo);
							}
						});
						
						var fb_photo = fbPhotos[photo.id];
						if (fb_photo) {
							var media_tags = fb_photo['tags'];
							for (var i in media_tags) if (i) kapturDb.createMediaUserTag(media_id, {'uid':i});
						}
					};
				})(that, photo, point_id, callback));
			};
		})(this, photo, callback));
	},

	savePhotosToDatabase: function (callback) {
		if (typeof callback == "function") callback(this.selected_photos);
		/*var i, saved_photos = 0;
		if (this.total_photos > 0) {
			readFromDB('getUniqueKapturIds', [this.total_photos*2, 'bulkIdsForAggregateCreatePointAndMedia|'+new Date().getTime()+'|'+this.segment_id], function(response) {
				response = JSON.parse(response);
				if (response['status'] == "ok") {
					var kptr_ids = response['result'];
					// generate data arrays
					var photo_ids = [], photo_times = [], friend_kptr_ids = [], photo_count = 0;
					for (var j in memoryCreationWizard.selected_photos) {
						var photo_time = memoryCreationWizard.loaded_photos[j]['utc_time_second'];
						memoryCreationWizard.loaded_photos[j]['point_id'] = kptr_ids[2*photo_count];
						memoryCreationWizard.loaded_photos[j]['media_id'] = kptr_ids[(2*photo_count)+1];
						photo_times.push(getUniqueTime(memoryCreationWizard.adjustPointTime(photo_time)));
						photo_ids.push(j); photo_count++;
					} for (var j in memoryCreationWizard.saved_attendees) { friend_kptr_ids.push(j); }
					// relay curl to create points
					var cookies_str = encodeURIComponent(encodeURIComponent(JSON.stringify(parseCookies())));
					readFromDB('addDataInBulkFromWizard', [{"kptr_ids":kptr_ids,"pids":photo_ids,"friend_ids":friend_kptr_ids,"utctimes":photo_times, 'user_id':userProfileObj.id, 'app_id':rmnAppId, 'tzoffset':-new Date().getTimezoneOffset()/60, 'segment_id':memoryCreationWizard.segment_id, 'cookies':cookies_str}]);//relayCurl ,{"domain":DOMAIN_URL.replace(/^http:\/\//, '').replace(/\/$/, ''),"page":"wizard_add"}
					callback();
				}
			});
			
			/*for (i in this.selected_photos) {
				this.loaded_photos[i].timezone_offset = this.timezone_offset;
				this.savePhoto(this.loaded_photos[i], (function (that) {
					return function (photo) {
						saved_photos++;
						if (saved_photos == that.total_photos) {
							if (typeof callback == "function") {
								callback(that.selected_photos);
							}
						};
						
						// update progress bar
						that.totalProgress += 4/7;
						//if (saved_photos % Math.ceil(that.total_photos/20) == 0)
							//$('#savingProgress').progressBar(20*(saved_photos/that.total_photos)+80);
					}
				})(this));
			}/
		} else {
			if (typeof callback == "function") {
				callback(this.selected_photos);
			}
		}*/
	},

	saveAttendeesToDatabase: function (callback) {
		var i = 0, saved_attendees = 0;
		if (this.total_friends > 0) {
			for (i in this.selected_friends) {
				//kapturDb.addFacebookUserToSegment(this.loaded_friends[i], this.segment_id, (function (that, friend, callback) {
					//return function () {
						var friend = this.loaded_friends[i];
						saved_attendees++;
						this.saved_attendees[friend.kaptur_id] = friend;
						if (saved_attendees == memoryCreationWizard.total_friends) {
							if (typeof callback == "function") {
								callback();
							}
						} // update progress bar
						//$('#savingProgress').progressBar(5*(saved_attendees/that.total_friends)+5);
						this.totalProgress += (1/7)*(this.total_photos/this.total_friends);
					//};
				//})(this, this.loaded_friends[i], callback));
			}
		} else {
			if (typeof callback == "function") {
				callback();
			}
		}
	},

	saveLocation: function () {
		var save_location_params = {
			user_id: userProfileObj.id,
			name: d_escape(this.location) || ''
		};

		kapturDb.saveLocation(this.location_id, save_location_params);
	},

	saveSegment: function () {
		var create_segment_params = {
			user_id: userProfileObj.id,
			utcStartSec: (this.start_time / 1000),
			utcEndSec: (this.end_time / 1000),
			timezoneOffset: this.timezone_offset,
			location_id: this.location_id
		};

		if (this.title) create_segment_params.title = d_escape(this.title);
		if (this.description) create_segment_params.description = d_escape(this.description);

		kapturDb.saveSegment(this.segment_id, create_segment_params);
	},

	createSegment: function (callback) {
		var create_location_params = {
			user_id: userProfileObj.id,
			name: d_escape(this.location) || ''
		};

		if (!userProfileObj.id) {
			alert('Facebook is not responding, please refresh the page');
			return;
		}

		kapturDb.createLocation(create_location_params, (function (that, callback) {
			return function (location_id) {
				var create_segment_params = {
					user_id: userProfileObj.id,
					utcStartSec: (that.start_time / 1000),
					utcEndSec: (that.end_time / 1000),
					timezoneOffset: that.timezone_offset,
					location_id: location_id,
					privacy_ids: 'vli,cfr'//,nai
				};
				
				// set wedding promo app id
				//if (memoryCreationWizard.weddingPromo) {
					create_segment_params['app_id'] = rmnAppId;//10;
				//}
				
				if (that.title) {
					create_segment_params.title = d_escape(that.title);
				}

				if (that.description) {
					create_segment_params.description = d_escape(that.description);
				}

				that.location_id = location_id;

				kapturDb.createSegment(create_segment_params, function (sid) {
					that.segment_id = sid;
					if ((typeof callback) == 'function') {
						callback();
					}
					// custom segment tagging
					if (memoryCreationWizard.weddingPromo) {
						writeToDB('createTag', [{'objectType':'segment', 'objectIdValue':sid, 'name':'wedding'}]);
					}
				});
			};
		})(this, callback));
	},

	createMemoryJson: function () {
		var json = '', segment_json = '', media_json = '',
			segment_title = $("#createMemoryTitleInput").val(),
			segment_description = $("#createMemoryDescriptionInput").val(),
			segment_start_second = Math.floor((this.start_time.getTime() / 1000)),
			segment_end_second = Math.floor((this.end_time.getTime() / 1000)),
			segment_timezone_offset = this.timezone_offset,
			segment_fbuser_id = loggedInUser,
			segment_rmn_owner_id = userProfileObj.id,
			num_content_objects = 0,
			media_type, media_src, media_alt_src, media_thumb, media_description,
			media_height, media_width, media_time, photo_id, rmn_media_id, media_point_id,
			media_owner_id, media_point_partner_id, media_point_partner_id_value,
			media_timezone_offset, i, photo;

		media_type = 'photo';
		media_owner_id = userProfileObj.id;
		
		//create json for photos
		if (this.total_photos > 0) {
			for (i in this.selected_photos) {
				photo = this.loaded_photos[i];
				media_src = encodeURI(photo.source);
				media_alt_src = encodeURI(photo.src_high_res);
				media_thumb = encodeURI(photo.thumbnail);
				media_description = escape(photo.description);
				media_height = photo.height;
				media_width = photo.width;
				photo_id = photo.id;
				rmn_media_id = photo.media_id;
				media_point_id = photo.point_id;
				media_point_partner_id_value = photo.owner_facebook_id || photo.ownername;
				media_point_partner_id = photo.uploaded?'16':'4';
				media_timezone_offset = photo.timezone_offset;
				media_time = photo.utc_time_second;//this.adjustPointTime()
				
				media_json = '{"type":"'+media_type+'","metadata":{"url":"'+ media_src +'",'+
					'"alt_src":"'+media_alt_src+'","src":"'+media_src+'","thumb":"'+media_thumb+'",'+
					'"caption":"'+media_description+'","height":"'+media_height+'",'+
					'"width":"'+media_width+'","utcTimeSec":"'+media_time+'",'+
					'"photoid":"'+photo_id+'","rmnMediaId":"'+rmn_media_id+'",'+
					'"rmnMediaDesc":"","rmnMediaTitle":"'+media_description+'",'+
					'"rmnPointId":"'+media_point_id+'","rmnPointDesc":"'+media_description+'",'+
					'"rmnOwnerId":"'+media_owner_id+'","rmnPointPartnerIdId":"'+media_point_partner_id+'",'+
					'"rmnPointPartnerIdValue":"'+media_point_partner_id_value+'","timezoneOffset":"'+media_timezone_offset+'",'+
					'"rmnPointUtcTimeSec":"'+media_time+'"}}';
				
				// add aviary content to post data
				var aviary_photos = this.aviaryPhotos[photo_id];
				if (aviary_photos) {
					for (var j=0; j<aviary_photos.length; j++) {
						var aviary_photo_hash = aviary_photos[j]['hash'];
						var aviary_photo_url = aviary_photos[j]['url'];
						media_src = encodeURI(aviary_photo_url);
						media_thumb = encodeURI(aviary_photo_url);
						media_alt_src = '';
						photo_id = aviary_photo_hash;
						media_point_partner_id = 17;
						media_point_id = photo.aviary_point_ids.shift();
						rmn_media_id = photo.aviary_media_ids.shift();
						this.aviaryHashes[aviary_photo_hash]['point_id'] = media_point_id;
						this.aviaryHashes[aviary_photo_hash]['media_id'] = rmn_media_id;
						
						media_json += ',{"type":"'+media_type+'","metadata":{"url":"'+ media_src +'",'+
							'"alt_src":"'+media_alt_src+'","src":"'+media_src+'","thumb":"'+media_thumb+'",'+
							'"caption":"'+media_description+'","height":"'+media_height+'",'+
							'"width":"'+media_width+'","utcTimeSec":"'+media_time+'",'+
							'"photoid":"'+photo_id+'","rmnMediaId":"'+rmn_media_id+'",'+
							'"rmnMediaDesc":"","rmnMediaTitle":"'+media_description+'",'+
							'"rmnPointId":"'+media_point_id+'","rmnPointDesc":"'+media_description+'",'+
							'"rmnOwnerId":"'+media_owner_id+'","rmnPointPartnerIdId":"'+media_point_partner_id+'",'+
							'"rmnPointPartnerIdValue":"'+media_point_partner_id_value+'","timezoneOffset":"'+media_timezone_offset+'",'+
							'"rmnPointUtcTimeSec":"'+media_time+'"}}';
					}
				}
				
				json += ',' + media_json;
				num_content_objects++;
			}
		}

		//create segment json
		segment_json = '{"type":"segment","metadata":{'+
			'"title":"'+segment_title+'","description":"'+segment_description+'",'+
			'"utcStartSec":"'+segment_start_second+'","utcEndSec":"'+segment_end_second+'",'+
			'"timezoneOffset":"'+segment_timezone_offset+'","fbUserId":"'+segment_fbuser_id+'",'+
			'"rmnOwnerId":"'+segment_rmn_owner_id+'","numContentObjects":'+num_content_objects+'}}';

		json = '[' + segment_json + json + ']';
		return json;
	},

	/**
	 * Redirects the user to the memory page
	 */
	goToMemory: function (wedding_create_segment_url) {
		var hiddenMemoryForm = $('#hiddenMemoryPostForm'),
			memoryJson = $('#memoryJson', hiddenMemoryForm);

		memoryJson.val(memoryCreationWizard.createMemoryJson());
		
		// propagate thumbnail data
		var cover_data;
		var media_pid = document.getElementById('createMemoryAviaryCanvas').getAttribute('media_pid');
		// swap in proper data for aviary photos
		var aviary_photo = memoryCreationWizard.aviaryHashes[media_pid];
		if (aviary_photo) cover_data = aviary_photo;
		else cover_data = memoryCreationWizard.loaded_photos[media_pid];
		var cover_media_id = cover_data?cover_data.media_id:'';
		var cover_thumb = document.getElementById('createMemoryThumb').src;
		var cover_src = document.getElementById('createMemoryAviaryCanvas').src;
		$('#memoryThumbnail').val(JSON.stringify([cover_media_id, cover_thumb, cover_src]));
		
		if (location.href.indexOf('viewMode=canvas') != -1) {
			//top.location.href = 'http://' + location.host + wedding_create_segment_url;
			hiddenMemoryForm.attr('action', 'http://' + location.host + wedding_create_segment_url);
			hiddenMemoryForm.attr('target', '_top');
		} else {
			//location.href = wedding_create_segment_url;
			hiddenMemoryForm.attr('action', wedding_create_segment_url);
		}
		
		// update privacy for featured segments
		if (document.getElementById('allowFeatureMemory').checked) writeToDB('editSegment', [{privacy_ids: 'vft,cfr'/*,nai*/}, memoryCreationWizard.segment_id], function() {document.getElementById('hiddenMemoryPostForm').submit()});
		else hiddenMemoryForm.submit();
	},
	
	/**
	 * Displays the memory
	 */
	showMemory: function () {
		if (((document.getElementById('allowPostToFacebook').checked && document.getElementById('createMemoryThumb').src) || document.getElementById('allowPostAlbumToWall').checked) && !userProfileObj.perms['publish_stream']) {
			FB.login(function(response) {
				var session = getFacebookSession();
				if (session) {
					userProfileObj.perms['publish_stream'] = 1;
					$.cookies.set("userPerms", null);
					memoryCreationWizard.showMemory();
				}
			}, {scope:'publish_stream'});
			return;
		}
		
		this.updateHints('showMemory');
		document.getElementById('createMemoryCompleteLoading').style.display = 'block';
		document.getElementById('createMemoryCompleteLoadingBg').style.display = 'block';
		readFromDB('getUniqueKapturIds', [2*(this.total_photos+this.aviary_photos), 'bulkIdsForAggregateCreatePointAndMedia|'+new Date().getTime()+'|'+this.segment_id], function(response) { // (this.total_photos+elem_count(this.aviaryPhotos))*2
			response = JSON.parse(response);
			if (response['status'] == "ok") {
				var kptr_ids = response['result'];
				
				// generate data arrays
				var photo_ids = [], photo_times = [], friend_fbids = [], upload_photos = [], photo_count = 0, aviary_count = 0;
				for (var j in memoryCreationWizard.selected_friends) friend_fbids.push(j);
				for (var j in memoryCreationWizard.selected_photos) {
					var upload_photo = 0;
					memoryCreationWizard.loaded_photos[j]['utc_time_second'] = getUniqueTime(memoryCreationWizard.adjustPointTime(memoryCreationWizard.loaded_photos[j]['utc_time_second']));
					var photo_time = memoryCreationWizard.loaded_photos[j]['utc_time_second'];
					memoryCreationWizard.loaded_photos[j]['point_id'] = kptr_ids[2*photo_count];
					memoryCreationWizard.loaded_photos[j]['media_id'] = kptr_ids[(2*photo_count)+1];
					// set aside data for uploaded photos
					if (memoryCreationWizard.loaded_photos[j]['uploaded']) {
						upload_photos.push(memoryCreationWizard.loaded_photos[j]);
						upload_photo = 1;
					}
					
					// set point id for aviary photos for POST data
					var aviary_photos = memoryCreationWizard.aviaryPhotos[j];
					if (aviary_photos) {
						for (var k in aviary_photos) {
							var kptr_id_index = 2*(memoryCreationWizard.total_photos+aviary_count);
							if (!memoryCreationWizard.loaded_photos[j]['aviary_point_ids']) memoryCreationWizard.loaded_photos[j]['aviary_point_ids'] = [];
							if (!memoryCreationWizard.loaded_photos[j]['aviary_media_ids']) memoryCreationWizard.loaded_photos[j]['aviary_media_ids'] = [];
							memoryCreationWizard.loaded_photos[j]['aviary_point_ids'].push(kptr_ids[kptr_id_index]);
							memoryCreationWizard.loaded_photos[j]['aviary_media_ids'].push(kptr_ids[kptr_id_index+1]);
							aviary_count++;
						}
					}
					
					photo_times.push(memoryCreationWizard.adjustPointTime(photo_time));
					if (!upload_photo) photo_ids.push(j);
					photo_count++;
				} // relay curl to create points
				var cookies_str = d_escape(JSON.stringify(parseCookies()));
				var aviary_photos = d_escape(JSON.stringify(memoryCreationWizard.aviaryPhotos));//addDataInBulkFromWizard
				var upload_photos = d_escape(JSON.stringify(upload_photos));
				//writeToDB('relayCurl', [{"kptr_ids":kptr_ids,"pids":photo_ids,"friend_ids":friend_fbids,"utctimes":photo_times, 'user_id':userProfileObj.id, 'app_id':rmnAppId, 'tzoffset':-new Date().getTimezoneOffset()/60, 'segment_id':memoryCreationWizard.segment_id, 'cookies':cookies_str, 'memory_thumb':memoryCreationWizard.prevSelectedThumb, 'aviary_photos':aviary_photos},{"domain":DOMAIN_URL.replace(/^http:\/\//, '').replace(/\/$/, ''),"page":"wizard_add"}]);//readFromDB
				
				/*if (location.href.indexOf('useWrite=')!=-1) writeToDB('addDataInBulkFromWizard', [{"kptr_ids":kptr_ids,"pids":photo_ids,"friend_ids":friend_fbids,"utctimes":photo_times, 'user_id':userProfileObj.id, 'app_id':rmnAppId, 'tzoffset':-new Date().getTimezoneOffset()/60, 'segment_id':memoryCreationWizard.segment_id, 'cookies':cookies_str, 'memory_thumb':memoryCreationWizard.prevSelectedThumb, 'aviary_photos':aviary_photos}]);
				else *//*writeToDB('addDataInBulkFromWizard', [{"kptr_ids":kptr_ids,"pids":photo_ids,"friend_ids":friend_fbids,"utctimes":photo_times, 'user_id':userProfileObj.id, 'app_id':rmnAppId, 'tzoffset':-new Date().getTimezoneOffset()/60, 'segment_id':memoryCreationWizard.segment_id, 'cookies':cookies_str, 'memory_thumb':memoryCreationWizard.prevSelectedThumb, 'aviary_photos':aviary_photos}], function () {*/
				
				// push off saving till the next page
				$('#memoryBulkSave').val(JSON.stringify([{"kptr_ids":kptr_ids,"pids":photo_ids,"friend_ids":friend_fbids,"utctimes":photo_times, 'user_id':userProfileObj.id, 'app_id':rmnAppId, 'tzoffset':-new Date().getTimezoneOffset()/60, 'segment_id':memoryCreationWizard.segment_id, 'cookies':cookies_str, 'memory_thumb':memoryCreationWizard.prevSelectedThumb, 'aviary_photos':aviary_photos, 'upload_photos':upload_photos}]));
				//,{"domain":DOMAIN_URL.replace(/^http:\/\//, '').replace(/\/$/, ''),"page":"wizard_add"}
				
				// generate friend json array
				var memoryFriendData = [];//[[loggedInUser, userProfileObj.first_name, userProfileObj.last_name]];
				for (var j in memoryCreationWizard.selected_friends) {
					var loaded_friend = memoryCreationWizard.loaded_friends[j];
					memoryFriendData.push([j, escape(loaded_friend['first_name']), escape(loaded_friend['last_name'])]);
				}
				$('#memoryFriendData').val(JSON.stringify(memoryFriendData));
				
				// update segment and fb share
				//kapturDb.updateSegment(memoryCreationWizard.segment_id, function () {
					var url_params = getUrlParams();
					if (url_params['aff'] == 'weddingpromo') delete url_params['aff'];
					delete url_params['p'];
					delete url_params['viewMode'];
					delete url_params['sid'];
					var segment_url = '?p=n&sid=' + memoryCreationWizard.segment_id + url_params;
					var wedding_create_segment_url = segment_url+((memoryCreationWizard.weddingPromo)?'&aff=wedding_create':'')+'&viewMedia=1';
					var title = memoryCreationWizard.title, date_str = '';
					if (title) {
						var start_date = formatDateStr(memoryCreationWizard.start_time, 'slashed');
						var end_date = formatDateStr(memoryCreationWizard.end_time, 'slashed');
						date_str = ' ('+start_date+(start_date!=end_date?' - '+end_date:'')+')';
					}
					var createMemoryAviaryCanvas = document.getElementById('createMemoryAviaryCanvas');
					var img_caption = title+date_str;//+"\nView full memory at ";
					var caption_url = DOMAIN_URL+segment_url+"&ref=fb_thumb";
					var img_src = createMemoryAviaryCanvas.src;
					postToFacebook(createMemoryAviaryCanvas.getAttribute('media_pid'), img_src, function() {
						var args, feed_post_url, timeout = 10000; //10 seconds
						if (document.getElementById('allowPostAlbumToWall').checked) {
							// facebook share
							args = {'title':title, 'url':segment_url+'&ref=facebook', 'src':img_src, 'token':FB.getSession()['access_token'], 'sid':memoryCreationWizard.segment_id, 'photo_count':memoryCreationWizard.total_photos+memoryCreationWizard.aviary_photos};
							feed_post_url = DOMAIN_URL+'?p=facebook_feed&args='+encodeURIComponent(JSON.stringify(args));
							setTimeout(function () {memoryCreationWizard.goToMemory(wedding_create_segment_url);}, timeout);
							jx.load(feed_post_url, function(data) {
								memoryCreationWizard.goToMemory(wedding_create_segment_url);
								clearTimeout(timeout);
							}, '', 'POST');
						} else memoryCreationWizard.goToMemory(wedding_create_segment_url);
					}, img_caption, caption_url);
				//});
				//}, 1);
			}
		});
	},
	
	showAlert: function(title, msg) {
		var display_style = (title||msg)? 'block':'';
		document.getElementById('customAlertOverlay').style.display = display_style;
		document.getElementById('customAlert').style.display = display_style;
		document.getElementById('customAlertTitle').innerHTML = title?title:'';
		document.getElementById('customAlertText').innerHTML = msg?msg:'';
	},
	
	showCustomAlert: function(alert_id, hide) {
		var display_style = !hide? 'block':'';
		document.getElementById('customAlertOverlay').style.display = display_style;
		document.getElementById(alert_id+'Alert').style.display = display_style;
	},
	
	showWhyFBAlert: function() {
		this.showAlert('Why Facebook?', 'Kaptur has chosen Facebook as our login partner to make it easy for you to add friends and photos seamlessly. By connecting with Facebook, you bring the power of Kaptur into your social graph.');
	},
	
	showWhyFeatureAlert: function() {
		this.showAlert('Feature my album!', 'By marking this checkbox, you give Kaptur permission to use your album for promotional purposes. For example, your album might be featured on our blog, on Twitter, or on Facebook.');
	},
	
	showAppRequestDialog: function() { // limit 255
		var memory_title = memoryCreationWizard.title;
		FB.ui({method: 'apprequests', message: 'I\'m capturing '+(memory_title?'"'+limitLen(memory_title, 117)+'" ':'my memory')+' on Kaptur right now. I\'d like to invite you to join so we can create shared memories using all of our friends\' photos.'});//userProfileObj.first_name
		trackClick('invite_dialogue', loggedInUser); // track in analytics
	},
	
	selectAlbum: function(deselect, opt) {
		var checkbox = $("#album" + memoryCreationWizard.open_album + (opt==2?'suggested':'') + " .createMemoryViewAlbumCheckbox"), i;
		if (checkbox.attr("checked") == (!!deselect)) {
			checkbox.click();
			checkbox.filter(':gt(0)').each(function() {
				$(this).attr('checked', !deselect);
			});
		} else if (deselect) {
			dataFlags.processingAddAll = 1;
			$('#createMemoryAllPhotos'+(opt?(opt==2?'Suggested':'Friends'):'User')+'Photos').children('.create_memory_photo_selected').each(function() {
				try {
					this.onclick();
					this.checked = false;
				} catch(err) {}
			});delete dataFlags.processingAddAll;
		}
	},
	
	showNotifyFriends: function() {
		var notify_friends = document.getElementById('allowPostToFriends').checked;
		if (notify_friends) {
			var notifyFriendsSelector = document.getElementById('notifyFriendsSelector');
			if (!notifyFriendsSelector.innerHTML) {
				var attendees_html = '<div class="create_memory_header">Notify Friends</div><div class="clear" style="padding-bottom:15px"></div>';
				attendees_html += '<div id="notifyFriendsPreviewWrapper"><div>Preview of Wall Post</div><div id="notifyFriendsPreview"><div id="notifyPreviewThumbWrapper"><img id="notifyPreviewThumb" /></div><div id="notifyPreviewText"><div id="notifyPreviewTitle">'+memoryCreationWizard.notifyFriendsTitle+'</div><div id="notifyPreviewLink">'+DOMAIN_URL.replace(/^http:\/\//, '').replace(/\/$/, '')+'</div><div id="notifyPreviewDesc">'+memoryCreationWizard.notifyFriendsDesc+'</div></div><div class="clear"></div><div id="notifyPreviewEditBtn"><div class="notify_preview_btn" onclick="memoryCreationWizard.editNotifyFriends()">edit</div></div><div id="notifyPreviewSaveBtns" class="hidden"><div class="notify_preview_btn" onclick="memoryCreationWizard.editNotifyFriends(1)">done</div><div id="notifyFriendsCancelLink" onclick="memoryCreationWizard.editNotifyFriends(2)">cancel</div></div><div class="clear"></div></div></div>';
				for (i in this.selected_friends) {
					var attendee = this.loaded_friends[i];
					attendees_html += '<div id="f'+i+'invite_wrapper" class="friend_post_wrapper" style="cursor:pointer" onclick="memoryCreationWizard.notifyFriend(\''+i+'\')"><div class="friend_wrapper_thumb"><img src="'+attendee.thumbnail+'" class="profile_pic" title="'+attendee.name+'"></div><div class="friend_wrapper_name"><div class="friend_wrapper_name_text">'+attendee.name+'</div><div id="f'+i+'invite_btn" class="friend_post_btn"></div></div></div>';
				}notifyFriendsSelector.innerHTML = attendees_html+'<div class="clear"></div>';
			}initColorbox('', 'notifyFriendsSelector', function () {
				if (!dataFlags.shownHint9 && memoryCreationWizard.weddingPromo) {
					document.getElementById('createMemoryWeddingPromoHint7').style.display = '';
					document.getElementById('createMemoryWeddingPromoHint8').style.display = '';
					if (memoryCreationWizard.total_photos) document.getElementById('createMemoryWeddingPromoHint9').style.display = 'block';
					dataFlags.shownHint9 = 1;
				}});
		}document.getElementById('notifyPreviewThumb').src = document.getElementById('createMemoryAviaryCanvas').src?document.getElementById('createMemoryAviaryCanvas').src:TEMPLATE_VIEW_PATH+'images/fb_thumb.jpg';
	},
	
	notifyFriend: function(fid) {
		if (!userProfileObj.perms.publish_stream) {
			FB.login(function(response) {
				var session = getFacebookSession();
				if (session) {
					getFacebookPermissions(function (perms) {
						if (perms['publish_stream']) {
							userProfileObj.perms.publish_stream = 1;
							$.cookies.set("userPerms", null);
							memoryCreationWizard.notifyFriend(fid);
						}
					});
				}
			}, {scope:'publish_stream'});
		} else {
			var notify_friend_wrapper = document.getElementById('f'+fid+'invite_wrapper');
			notify_friend_wrapper.onclick = '';
			notify_friend_wrapper.style.cursor = 'auto';
			document.getElementById('f'+fid+'invite_btn').className = 'friend_posted_btn';
			var img_src, createMemoryAviaryCanvas = document.getElementById('createMemoryAviaryCanvas');
			if (createMemoryAviaryCanvas) img_src = createMemoryAviaryCanvas.src;
			if (!img_src) img_src = DOMAIN_URL+TEMPLATE_VIEW_PATH+'images/fb_thumb.png';
			var args = {'title':memoryCreationWizard.notifyFriendsTitle, 'desc':memoryCreationWizard.notifyFriendsDesc, 'url':'?p=n&sid='+memoryCreationWizard.segment_id+'&ref=friend_post', 'src':img_src, 'token':FB.getSession()['access_token'], 'sid':memoryCreationWizard.segment_id, 'target':fid, 'owner_name':userProfileObj.first_name, 'photo_count':memoryCreationWizard.total_photos+memoryCreationWizard.aviary_photos};
			var feed_post_url = DOMAIN_URL+'?p=facebook_feed&args='+encodeURIComponent(JSON.stringify(args));
			jx.load(feed_post_url, '', '', 'POST');
		}
	},
	
	queryExistingSegments: function() {
		readFromDB('getSegments', [userProfileObj.id, parseInt(memoryCreationWizard.start_time.getTime()/1000, 10),
		  parseInt(memoryCreationWizard.end_time.getTime()/1000, 10)], function(response) {
			response = JSON.parse(response);
			if (response['status'] == "ok") {
				var rmn_segments = response['result'];
				if (rmn_segments != '') {
					showSegmentsHTML(rmn_segments, 'choose_segment');
				}
			}
		});
	},
	
	storeFutureWeddingEmail: function() {
		var err_msg = '';
		var futureWeddingEmail = document.getElementById('futureWeddingEmail').value;
		if (!futureWeddingEmail) err_msg = 'Please enter your email address!';
		else if (!futureWeddingEmail.match(new RegExp('^(?:[A-Z0-9._%+-]|\')+@[A-Z0-9.-]+\\.[A-Z]{2,4}$', 'i')))
			err_msg = 'Please enter a valid email address!';
		document.getElementById('futureWeddingEmailError').innerHTML = err_msg;
		if (!err_msg) {
			var start_utc = memoryCreationWizard.start_time.getTime();
			var start_utc_offset = new Date(start_utc).getTimezoneOffset()/-60;
			start_utc = parseInt(start_utc/1000, 10);
			// store email address and alert date
			writeToDB('addUserEmailAddress', [{'user_id':userProfileObj.id, 'app_id':rmnAppId, 'emailAddress':d_escape(futureWeddingEmail), 'alertUtcSec':start_utc, 'timezoneOffset':start_utc_offset}]); // 10
			
			// send confirmation email
			var body_content = 'Name: '+encodeURIComponent(userProfileObj.first_name+' '+userProfileObj.last_name)+'\nContact Email: '+encodeURIComponent(futureWeddingEmail)+'\nFB Email: '+encodeURIComponent(userProfileObj.email)+'\nWedding Date: '+encodeURIComponent(memoryCreationWizard.start_time)+(memoryCreationWizard.title?'\nAlbum Title: '+encodeURIComponent(memoryCreationWizard.title):'')+'\n\nFBID: '+loggedInUser+'\nKPTRID: '+userProfileObj.id;
			
			// user alternate body message for email logins
			var emailLoginData = $.cookies.get("emailLoginId");
			if (!loggedInUser && emailLoginData) {
				var loginEmail = emailLoginData[0];
				var emailLoginId = emailLoginData[1];
				body_content = 'Contact Email: '+encodeURIComponent(futureWeddingEmail)+'\nLogin Email: '+encodeURIComponent(loginEmail)+'\nWedding Date: '+encodeURIComponent(memoryCreationWizard.start_time)+(memoryCreationWizard.title?'\nAlbum Title: '+encodeURIComponent(memoryCreationWizard.title):'')+'\n\nKPTRID: '+emailLoginId;
			}
			
			// construct email post url
			var post_url = DOMAIN_URL+'?p=s&share=email&type=proxy&subject=Kaptur Weddings&body='+body_content+'&sender='+encodeURIComponent('Tej <tej@kaptur.com>')+'&recipient='+encodeURIComponent('Tej <tej@kaptur.com>');
			jx.load(post_url, '', '', 'POST');
			
			memoryCreationWizard.showCustomAlert('futureWedding', 1);
			memoryCreationWizard.showCustomAlert('futureWeddingMsg');
		}
	},
	
	allowCurrentTitle: function(alertId, skip) {
		this.showCustomAlert(alertId, 1);
		if (skip) {
			if (alertId == 'noTitle') dataFlags.allowNoTitle = 1;
			else if (alertId == 'testTitle') dataFlags.allowTestTitle = 1;
			this.completedStep(1);
		} else {
			var createMemoryTitleInput = document.getElementById('createMemoryTitleInput');
			createMemoryTitleInput.focus();createMemoryTitleInput.select();
		}
	},

	toggleSeeAllPhotos: function(e) {
		var target;
		e = getEvent(e);
		target = $(getEventTarget(e));

		$("#createMemoryAddPhotosWrapper, #createMemorySelectedPhotosWrapper").toggleClass('hidden');

		if (target.text() == 'See Added Photos') {
			target.html('Add More Photos');
			trackClick('added_photos_toggle', loggedInUser);
		} else {
			target.html('See Added Photos');
		}
	},
	
	editNotifyFriends: function(action) {
		var notifyPreviewTitle = document.getElementById('notifyPreviewTitle');
		var notifyPreviewDesc = document.getElementById('notifyPreviewDesc');
		var notifyPreviewTitleEdit = document.getElementById('notifyPreviewTitleEdit');
		var notifyPreviewDescEdit = document.getElementById('notifyPreviewDescEdit');
		var notifyPreviewEditBtn = document.getElementById('notifyPreviewEditBtn');
		var notifyPreviewSaveBtns = document.getElementById('notifyPreviewSaveBtns');
		if (action == 1) {
			var notifyPreviewTitleVal = notifyPreviewTitleEdit.value;
			notifyPreviewTitle.innerHTML = notifyPreviewTitleVal;
			var notifyPreviewDescVal = notifyPreviewDescEdit.value;
			notifyPreviewDesc.innerHTML = notifyPreviewDescVal;
			this.notifyFriendsTitle = notifyPreviewTitleVal;
			this.notifyFriendsDesc = notifyPreviewDescVal;
			notifyPreviewEditBtn.className = '';
			notifyPreviewSaveBtns.className = 'hidden';
		} else if (action == 2) {
			notifyPreviewTitle.innerHTML = this.notifyFriendsTitle?this.notifyFriendsTitle:'';
			notifyPreviewDesc.innerHTML = this.notifyFriendsDesc?this.notifyFriendsDesc:'';
			notifyPreviewEditBtn.className = '';
			notifyPreviewSaveBtns.className = 'hidden';
		} else {
			var notifyPreviewTitleVal = notifyPreviewTitle.innerHTML;
			notifyPreviewTitle.innerHTML = '<input id="notifyPreviewTitleEdit" />';
			var notifyPreviewDescVal = notifyPreviewDesc.innerHTML;
			notifyPreviewDesc.innerHTML = '<textarea id="notifyPreviewDescEdit" />';
			notifyPreviewTitleEdit = document.getElementById('notifyPreviewTitleEdit');
			notifyPreviewDescEdit = document.getElementById('notifyPreviewDescEdit');
			notifyPreviewTitleEdit.value = notifyPreviewTitleVal;
			notifyPreviewDescEdit.value = notifyPreviewDescVal;
			this.notifyFriendsTitle = notifyPreviewTitleVal;
			this.notifyFriendsDesc = notifyPreviewDescVal;
			notifyPreviewEditBtn.className = 'hidden';
			notifyPreviewSaveBtns.className = '';
		}
	},
	
	displayFriendLists: function (friend_lists) {
		var friend_list_html = '<option value="">Add a list of friends</option>',
			friend_list_select = $('#createMemoryFriendListSelector'), i;
		
		if (friend_lists && (friend_lists.length > 0)) {
			for (i = 0; i < friend_lists.length; i++) {
				friend_list_html += '<option value="' + friend_lists[i].flid + '">' + 
					friend_lists[i].name + '</option>';
			}
			friend_list_select.html(friend_list_html).css("display", "block");
		} else {
			var friend_list_grant_permissions = $('#createMemoryFriendListGrantPermission');
			if (userProfileObj.perms['read_friendlists']) friend_list_grant_permissions.html('No friend lists');
			friend_list_grant_permissions.css("display", "block");
		}
	},
	
	getFriendListPermission: function() {
		if (!userProfileObj.perms['read_friendlists']) {
			FB.login(function(response) {
				var session = getFacebookSession();
				if (session) {
					getFacebookPermission(function (perms) {
						if (perms['read_friendlists']) {
							$('#createMemoryFriendListGrantPermission').css("display", "");
							memoryCreationWizard.loadFriendLists(memoryCreationWizard.displayFriendLists);
							userProfileObj.perms['read_friendlists'] = 1;
							$.cookies.set("userPerms", null);
						}
					});
				}
			}, {scope:'read_friendlists'});
		}
	},
	
	loadFriendLists: function (callback) {
		queryFacebook('SELECT flid, name FROM friendlist WHERE owner={0}',
			[loggedInUser],
			function (callback) {
				return function (fb_response) {
					var i;
					if (fb_response) {
						for (i = 0; i < fb_response.length; i++) {
							memoryCreationWizard.loadFriendsFromList(fb_response.uid);
						}
					}
					safeCall(callback, [fb_response]);
				};
			}(callback)
		);
	},
	
	selected_lists: {},
	friendListSelected: function (option, event) {
		event = getEvent(event);
		if (option.selectedIndex) {
			if (memoryCreationWizard.selected_lists[option.value]) {
				memoryCreationWizard.selected_lists[option.value] = false;
				option.childNodes[option.selectedIndex].innerHTML = option.childNodes[option.selectedIndex].innerHTML.replace('✓ ', '');
				option.childNodes[option.selectedIndex].className = '';
				memoryCreationWizard.loadFriendsFromList(option.value, function (friends) {
					var i,e;
					for (i = 0; i < friends.length; i++) {
						e = jQuery.Event('click');
						e.target = $("#f" + friends[i].uid);
						if (e.target.hasClass('friend_wrapper_selected')) {
							e.target.trigger(e);
						}
					}
				});
			} else {
				memoryCreationWizard.selected_lists[option.value] = true;
				option.childNodes[option.selectedIndex].innerHTML = '✓ ' + option.childNodes[option.selectedIndex].innerHTML;
				option.childNodes[option.selectedIndex].className = 'highlighted_option';
				memoryCreationWizard.loadFriendsFromList(option.value, function (friends) {
					var i,e;
					for (i = 0; i < friends.length; i++) {
						e = jQuery.Event('click');
						e.target = $("#f" + friends[i].uid);
						if (e.target.hasClass('friend_wrapper')) {
							e.target.trigger(e);
						}
					}
				});
			}
		}
		option.selectedIndex = 0;
	}
}

var kapturDb = {
	dup: 0,
	
	models : {
		segment_point_tables : {},
		getSegmentPointTable : function (segment_id) {
			var segment_point_table = kapturDb.models.segment_point_tables[segment_id];
			
			if (!segment_point_table) {
				kapturDb.models.segment_point_tables[segment_id] = [];
				segment_point_table = kapturDb.models.segment_point_tables[segment_id];
			}
			
			return segment_point_table;
		},
		
		clearSegmentPointTable : function (segment_id) {
			kapturDb.models.segment_point_tables[segment_id] = [];
		},
		
		setSegmentPointTable : function (segment_id, new_table) {
			kapturDb.models.segment_point_tables[segment_id] = new_table;
		}
	},
	
	/**
	 * Gets the result out of the json returned by kaptur functions
	 */
	extractJsonResult : function (response) {
		if (response) {
			response = JSON.parse(response);
			if (response && (response['status'] == 'ok') && (response['result'] != null)) {
				response = response.result;
			} else {
				response = null;
			}
		} else {
			response = null;
		}
		
		return response;
	},
	
	/**
	 * Many functions return a JSON encoded object with just an id in it as the
	 * result.  This funcition grabs that id from the result if it is there otherwise
	 * it returns null
	 */
	extractJsonEncodedId : function (response) {
		response = kapturDb.extractJsonResult(response);
		if (response) {
			response = JSON.parse(response);
			if (response && response.id) {
				response = response.id;
			} else {
				response = null;
			}
		} else {
			response = null;
		}
		
		return response;
	},
	
	/**
	 * Most functions return a json response that is an object with fields for
	 * status and result.  This function wraps a given callback so that it can
	 * recieve that result directly rather than need to do the parsing itself.
	 */
	passJsonResponseToCallback : function (callback) {
		return function (response) {
			response = kapturDb.extractJsonResult(response);
			safeCall(callback, [response]);
		}
	},
	
	/**
	 * Many functions return a result that is json encoded object with only an
	 * id field.  This function wraps the given callback so that it will be passed
	 * the id rather than need to do a bunch of parsing itself.
	 */
	passJsonEncodedIdToCallback : function (callback) {
		return function (response) {
			response = kapturDb.extractJsonEncodedId(response);
			
			safeCall(callback, [response]);
		}
	},

	updateSegment: function (segment_id, callback) {
		writeToDB('editSegment', [{'utcLastModifiedSec':1,'dup':new Date().getTime()}, segment_id], callback);
	},
	
	touchSegment : function (segment_id) {
		kapturDb.saveSegment(segment_id, {'utcLastModifiedSec':'1'});
	},

	saveSegment: function (segment_id, save_segment_params, callback) {
		writeToDB('editSegment', [save_segment_params, segment_id], callback);
	},

	saveLocation: function (location_id, save_location_params, callback) {
		writeToDB('editLocation', [save_location_params, location_id], callback);
	},

	addKapturUserToSegment: function (user, segment_id, callback) {
		writeToDB('addConfirmedUserToSegmentIfUserAbsent', [user.kaptur_id, segment_id], (function (callback){
			return function (data) {
				safeCall(callback);
			};
		})(callback));
	},

	addFacebookUserToSegment: function (user, segment_id, callback) {
		if (user.kaptur_id) {
			//if they already have a kaptur id loaded we can add them more directly
			kapturDb.addKapturUserToSegment(user, callback);
		} else {
			//get the kaptur id then add them
			readFromDB('getRmnUserIdByFacebookId', [user.facebook_id], (function (user, segment_id) {return function (data) {
				data = JSON.parse(data);
				data = data.result;

				if (data) {
					user.kaptur_id = data;
					kapturDb.addKapturUserToSegment(user, segment_id, callback)
				} else {
					writeToDB('addRmnUserByFacebookId', [user.facebook_id], (function (user, segment_id, callback) {
						return function (data) {
							data = JSON.parse(data);
							data = JSON.parse(data.result).id; // , app_id: rmnAppId
							writeToDB('setRmnUserInfo', [{firstName: user.first_name, lastName: user.last_name}, data]); // APP_ID
							user.kaptur_id = data;
							kapturDb.addKapturUserToSegment(user, segment_id, callback);
							// set friend relationship status (put inside a try catch block so there is not a dependency on control.js)
							try {
								setRelationshipStatus(user.facebook_id, user.kaptur_id);
							} catch (err) {
								//do nothing
							}
						};
					})(user, segment_id, callback));
				}
			};})(user, segment_id));
		}
	},
	
	getFacebookUser: function (facebook_id, callback) {
		readFromDB('getRmnUserIdByFacebookId', [facebook_id], kapturDb.passJsonResponseToCallback(callback));
	},
	
	getFacebookUserInfo : function (facebook_id, callback) {
		kapturDb.getFacebookUser(facebook_id, function (kaptur_id) {
			kapturDb.getKapturUserInfo(kaptur_id, callback);
		});
		//readFromDB('getRmnUserInfoByFacebookId', [facebook_id], kapturDb.passJsonResponseToCallback(callback));
	},
	
	getKapturUserInfo : function (kaptur_id, callback) {
		var columns = [
			"firstName",
			"lastName",
			"gender",
			"emailAddress",
			"mobileNumber",
			"app_id",
			"thumb",
			"relationshipStatus",
			"user_idSignificantOther",
			"locale"
		];
		readFromDB('getRmnUserInfo', [columns,kaptur_id], kapturDb.passJsonResponseToCallback(function (user_info) {
			if (user_info) {
				user_info['emailAddress'] = decodeURIComponent(user_info['emailAddress']);
				user_info['thumb'] = decodeURIComponent(user_info['thumb']);
				user_info['user_id'] = kaptur_id;
			}
			safeCall(callback, [user_info]);
		}));
	},
	
	editUserApp : function (user_id, app_id, callback) {
		writeToDB('setRmnUserInfo', [{app_id:app_id},user_id], function (response) {
			safeCall(callback, [response]);
		});
	},
	
	editUser : function (user_id, user_info, callback) {
		for (var i in user_info) { // ensure proper encoding
			if (in_array(i, ['firstName', 'lastName', 'emailAddress', 'thumb'])) user_info[i] = d_escape(user_info[i]);
		}
		writeToDB('setRmnUserInfo', [user_info,user_id], function (response) {
			safeCall(callback, [response]);
		});
	},
	
	addFacebookUser: function (facebook_id, callback) {
		writeToDB('addRmnUserByFacebookId', [facebook_id], function (response) {
			var user_id = kapturDb.extractJsonEncodedId(response);
			
			safeCall(callback, [user_id]);
		});
	},

	createLocation: function (create_location_params, callback) {
		writeToDB('createLocation', [create_location_params], function (data) {
			var lid = null;
			if (data) {
				data = JSON.parse(data);
				if (data.status == 'ok') {
					lid = JSON.parse(data.result).id;
				}
			}

			if ((typeof callback) == "function") {
				callback(lid);
			}
		});
	},

	createSegment: function (create_segment_params, callback) {
		writeToDB('createSegment', [create_segment_params], kapturDb.passJsonEncodedIdToCallback(callback));
	},

	createPhotoPoint: function (photo, callback) {
		var point_args = {
			user_id: photo.user_id || userProfileObj.id,
			utcTimeSec: photo.utc_time_second,
			description: d_escape(photo.description) || '',
			partnerId_id: photo.partnerId_id || (photo.aviary_src?PARTNER_TYPES.aviary_photo:PARTNER_TYPES.facebook_photo),
			partnerIdValue: photo.owner_facebook_id || photo.ownername,
			timezone_offset: photo.timezone_offset,
			privacy: 'public',
			dup: kapturDb.dup++
		};
		
		if (window.rmnAppId) {
			point_args['app_id'] = rmnAppId;
		}
		
		writeToDB('createPoint', [point_args, loggedInUser], (function () {
			return kapturDb.passJsonEncodedIdToCallback(callback);
		})(callback));
	},

	createPhotoMedia: function (photo, callback) {
		var media_args = {
			'mediaType_id': MEDIA_TYPES.photo,
			'title': d_escape(photo.description),
			'description': '',
			'url': d_escape(photo.page_url),
			'src': d_escape(photo.aviary_src || photo.source || photo.url),
			'thumb': d_escape(photo.aviary_src || photo.thumbnail || photo.thumb_url),
			'height': photo.height,
			'width': photo.width,
			'service': photo.service || (photo.aviary_src ? SERVICE_TYPES.aviary : SERVICE_TYPES.facebook),
			'utcTimeSec': photo.utc_time_second,
			'user_id': photo.contributor_kaptur_id,
			'partnerId_id': photo.partnerId_id || (photo.aviary_src ? PARTNER_TYPES.aviary_photo : PARTNER_TYPES.facebook_photo),
			'partnerIdValue': photo.aviary_hash || photo.id
		},
		point_owner = loggedInUser;
		
		if (photo.src_high_res) {
			media_args['alt_src'] = !photo.aviary_src ? d_escape(photo.src_high_res) : '';
		}
		
		writeToDB('createMedia', [media_args, point_owner], (function (callback) {
			return kapturDb.passJsonEncodedIdToCallback(callback);
		})(callback));
	},

	pairMediaAndPoint: function (media_id, point_id, callback) {
		writeToDB('pairMediaAndPoint', [[media_id], point_id], (function (media_id, point_id, callback) {
			return function (data) {
				safeCall(callback, [media_id, point_id]);
			};
		})(media_id, point_id, callback));
	},
	
	createPairedPhotoPointAndMedia : function (callback) {
		(function () {
			var ids = {}
			kapturDb.createPhotoPoint(photo, function (point_id) {
				ids['point_id'] = point_id;
				kapturDb.createPhotoMedia(photo, function (media_id) {
					ids['media_id'] = media_id;
					kapturDb.pairMediaAndPoint(media_id, point_id, function () {
						safeCall(callback, [ids]);
					});
				});
			});
		});
	},
	
	pairUsersAndPoint: function(point_id) {
		if (!memoryCreationWizard.saved_attendees_array) {
			memoryCreationWizard.saved_attendees_array = [];
			for (var i in memoryCreationWizard.saved_attendees) {
				memoryCreationWizard.saved_attendees_array.push(i);
			}
		}if (memoryCreationWizard.saved_attendees_array.length)
			writeToDB('pairUsersAndPoint', [memoryCreationWizard.saved_attendees_array, point_id, "suggested"]);
	},
	
	createMediaUserTag: function(media_id, tag_data) {
		writeToDB('createTag', [{
			'objectType':'media',
			'objectIdValue':media_id,
			'name':tag_data['uid'],
			'partnerId_id':'15',
			'partnerIdValue':d_escape(JSON.stringify(tag_data))}]);
	},
	
	setMemoryThumb: function(media_id) {
		if (memoryCreationWizard.segment_id){
			writeToDB('editSegment', [{'media_id':media_id, 'dup':kapturDb.dup++}, memoryCreationWizard.segment_id]);
		}
	},
	
	getSegments : function (user_id, app_id, callback) {
		(function (user_id, app_id) {
			readFromDB('getSegments', [user_id], function (response) {
				var results = null,
					filtered_results;
				results = kapturDb.extractJsonResult(response);
				
				if (results && app_id) {
					//filter by the app_id if it is specified
					filtered_results = [];
					forEach(results, function (i, result) {
						if (result['app_id'] == app_id) {
							filtered_results.push(result);
						}
					});
					
					results = filtered_results;
				}
				
				safeCall(callback, [results]);
			});
		})(user_id, app_id);
	},
	
	getUniqueKapturIds : function (number, purpose, callback) {
		(function (number, purpose, callback) {
			readFromDB('getUniqueKapturIds', [number, purpose], kapturDb.passJsonResponseToCallback(callback));
		})(number, purpose, callback);
	},
	
	addDataInBulk : function (args, callback) {
		writeToDB("addDataInBulkFromWizard", [args], callback, 1);
		kapturDb.touchSegment(args['segment_id']);
	},
	
	addUsersInBulk : function (segment_id, user_id, friend_fbids, cookies_str, callback) {
		var memoryBulkSave = {
			"kptr_ids": [],
			"pids": [],
			"utctimes": [],
			"friend_ids":friend_fbids,
			'user_id': user_id,
			//'app_id': null,
			'tzoffset':-((new Date()).getTimezoneOffset()/60),
			'segment_id':segment_id,
			'cookies':cookies_str,
			'memory_thumb': '',
			'aviary_photos': '',
			'upload_photos': ''
		}

		kapturDb.addDataInBulk(memoryBulkSave, callback);		
	},
	
	/**
	 * gets the media info for the passed in array of media_ids
	 */
	getMedia : function (media_ids, callback) {
		readFromDB('getMedia', [media_ids], kapturDb.passJsonResponseToCallback(callback));
	},
	
	/**
	 * if position is null or invalid, point will be added onto the end of the segment
	 * otherwise point will be inserted at position and points after will be shifted up
	 * 
	 * passes an id to the callback that tells you nothing about the success of the
	 * function.  Use an appropriate read function if you need to verify the write.
	 */
	addPointToSegment : function (segment_id, point_id, position, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id),
			args = {
			"sid" : segment_id,
			"pid" : point_id
		}

		position = parseInt(position, 10) || null;

		if (position != null) {
			args['pos'] = position;
			addItemToArray(segment_point_table, point_id, position - 1);
		} else {
			segment_point_table.push(point_id);
		}

		writeToDB("addPointToSegment", [args], kapturDb.passJsonEncodedIdToCallback(callback));
	},

	/**
	 * if position is null or invalid, points will be added onto the end of the segment
	 * otherwise points will be inserted at position and points after will be shifted up
	 * 
	 * passes an id to the callback that tells you nothing about the success of the
	 * function.  Use an appropriate read function if you need to verify the write.
	 */
	addPointsToSegment : function (segment_id, point_ids, position, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id),
			args = {
			"sid" : segment_id,
			"pids" : point_ids
		}

		position = parseInt(position, 10) || null;

		if (position != null) {
			args['pos'] = position;
			addItemsToArray(segment_point_table, point_ids, position - 1);
		} else {
			addItemsToArray(segment_point_table, point_ids, segment_point_table.length);
		}

		if (position != null) {
			args['pos'] = position;
		}

		writeToDB("addPointsToSegment", [args], kapturDb.passJsonResponseToCallback(callback));
	},

	/** 
	 * deletes the entry linking segment_id and point_id in the 
	 * segment points table. updates the positions of the remaining points
	 * associated with that seg
	 * 
	 */
	removePointFromSegment : function (segment_id, point_id, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id);
		
		removeItemFromArray(segment_point_table, point_id);
		
		writeToDB("removePointFromSegment", [segment_id, point_id], kapturDb.passJsonEncodedIdToCallback(callback));
	},

	/**
	 * removes all points from the segmentPoints table for segment segment_id
	 */
	removeAllPointsFromSegment : function (segment_id, callback){
		kapturDb.models.clearSegmentPointTable(segment_id);
		
		writeToDB("removeAllPointsFromSegment", [segment_id], kapturDb.passJsonEncodedIdToCallback(callback));
	},

	/* first delete the points from the segmentPoints table
	 * where segment_id is $segId and $pointIdArray is a 1D array of 
	 * points to remove
	 *
	 * returns true on success, null on failure
	 */
	removePointsFromSegment : function (segment_id, point_id_array, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id),
			num_points = arrayLength(point_id_array),
			point_id, i;
		for (i = 0; i < num_points; i++) {
			point_id = point_id_array[i];
			removeItemFromArray(segment_point_table, point_id);
		}
		
		writeToDB("removePointsFromSegment", [segment_id, point_id_array], kapturDb.passJsonEncodedIdToCallback(callback));
	},

	/** 
	 * updates the position of point_id to new_position, and updates positions of 
	 * of points which are affected by the move
	 * positions start from 1, not 0
	 */
	changePointPositionInSegment : function (segment_id, point_id, new_position, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id),
			old_position = segment_point_table.indexOf(point_id);
		
		if (old_position != -1) {
			old_position = old_position + 1;
			if (old_position == new_position) {
				return;
			} else if (old_position < new_position) {
				new_position = new_position - 1;
			}
		}
		
		removeItemFromArray(segment_point_table, point_id);
		addItemToArray(segment_point_table, point_id, new_position - 1);
		
		writeToDB("changePointPositionInSegment", [segment_id, point_id, new_position], kapturDb.passJsonEncodedIdToCallback(callback));
	},

	/** 
	 * reorders points associated with segment given new point positions
	 * positions start at 1, not 0
	 * ex, want to reorder a seg with five photos
	 * new_point_positions should be [1,5,2,3,4] to move the 5th photo to the 2nd slot
	 * returns true on success, null on failure
	 */
	changePointPositionsInSegment : function (segment_id, new_point_positions, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id),
			new_segment_point_table = [],
			num_new_point_positions = arrayLength(new_point_positions),
			i, new_point_position, point_id;
		
		for (i = 0; i < num_new_point_positions; i++) {
			new_point_position = new_point_positions[i];
			point_id = segment_point_table[new_point_position - 1];
			new_segment_point_table.push(point_id);
		}
		
		kapturDb.models.setSegmentPointTable(segment_id, new_segment_point_table);
		
		writeToDB("changePointPositionsInSegment", [segment_id, new_point_positions], kapturDb.passJsonEncodedIdToCallback(callback));
	},
	
	movePointInSegmentBefore : function (segment_id, target_point, destination_point, callback) {
		var segment_point_table = kapturDb.models.getSegmentPointTable(segment_id),
			destination_position;
		
		if (destination_point) {
			destination_position = segment_point_table.indexOf(destination_point);
		} else {
			destination_position = arrayLength(segment_point_table);
		}
		
		//positions start at 1
		destination_position = destination_position + 1;
		
		kapturDb.changePointPositionInSegment(segment_id, target_point, destination_position, callback)
	},

	/** appends all points from src seg onto end of target seg
	 * and deletes src seg from segmentPoints table
	 * if a point in src already exists in target, it is ignored
	 * 
	 * true on success, null on failure
	 */
	mergeSegments : function (source_segment_id, target_segment_id, callback){
		var source_segment_point_table = kapturDb.models.getSegmentPointTable(source_segment_id),
			source_segment_point_table_length = arrayLength(source_segment_point_table),
			target_segment_point_table = kapturDb.models.getSegmentPointTable(target_segment_id),
			i, item;
		
		for (i = 0; i < source_segment_point_table_length; i++) {
			item = source_segment_point_table[i];
			if (!in_array(target_segment_point_table)) {
				target_segment_point_table.push(item);
			}
		}
		
		kapturDb.models.clearSegmentPointTable(source_segment_id);
		
		writeToDB("getMediaInSegmentByFilter", [source_segment_id, target_segment_id], kapturDb.passJsonEncodedIdToCallback(callback));
	},
	
	/** 
	 * returns a multidimensional array of points associated with seg $segId
	 * where filter is an optional 2D array of the form {"<filterOnColumnName>":"<is_value>"}
	 * with one or more column name / value pairs, and where columns
	 * is an optional 1D array that lists the columns of point data you wish returned
	 *
	 * valid column names are 
	 *                point_id
	 *                user_id
	 *                utcCreatedSec
	 *                utcLastModifiedSec
	 *                utcTimeSec
	 *                timezoneOffset
	 *                description
	 *                partnerId_id
	 *                partnerIdValue
	 *                location_id
	 *                app_id
	 *                position
	 *
	 * returns a multidimensional array of matches
	 */
	getPointsInSegmentByFilter : function (segment_id, filters, columns, callback) {
		readFromDB("getPointsInSegmentByFilter", [segment_id, filters, columns], kapturDb.passJsonResponseToCallback(callback));
	},

	/**
	 * returns a multidimensional array of media associated with seg $segId
	 * where filter is an optional 2D array of the form {"<filterOnColumnName>":"<is_value>"}
	 * with one or more column name / value pairs, and where columns
	 * is an optional 1D array that lists the columns of point data you wish returned
	 *
	 * valid column names are
	 *                position
	 *                media_id
	 *                point_id
	 *                mediaType_id
	 *                utcCreatedSec
	 *                utcLastModifiedSec
	 *                title
	 *                description
	 *                url
	 *                src
	 *                alt_src
	 *                thumb
	 *                duration
	 *                height
	 *                width
	 *                utcTimeSec
	 *                user_id
	 *                partnerId_id
	 *                partnerIdValue
	 *                location_id
	 *                
	 * returns a multidimensional array of matches
	 */
	getMediaInSegmentByFilter : function (segment_id, filters, columns, callback){
		readFromDB("getMediaInSegmentByFilter", [segment_id, filters, columns], kapturDb.passJsonResponseToCallback(callback));
	},

	/**
	 * returns a 1D array of pointIds associated with seg $segId
	 * ordered by position (ascending)
	 */
	getPointsInSegment : function (segment_id, callback){
		readFromDB("getPointsInSegment", [segment_id], function (response) {
			response = kapturDb.extractJsonResult(response);
			
			if (response) {
				kapturDb.models.setSegmentPointTable(segment_id, response);
			}
			
			safeCall(callback, [response]);
		});
	},
	
	/**
	 * returns a 1d array of objects containing point data
	 */
	getPointsInSegmentWithInfo : function (segment_id, callback) {
		var columns = [
			"point_id",
			"user_id",
			"utcCreatedSec",
			"utcLastModifiedSec",
			"utcTimeSec",
			"timezoneOffset",
			"description",
			"partnerId_id",
			"partnerIdValue",
			"location_id",
			"privacy",
			"app_id",
			"position"
		];
		
		kapturDb.getPointsInSegmentByFilter(segment_id, null, columns, function (response) {
			var point_ids = [],
				num_points, i, point_id, point;
			if (response) {
				num_points = arrayLength(response);
				for (i = 0; i < num_points; i++) {
					point = response[i];
					point_id = point['point_id'];
					point_ids.push(point_id);
					point['id'] = point_id;
				}
			}
			
			kapturDb.models.setSegmentPointTable(segment_id, point_ids);
			
			safeCall(callback, [response]);
		});
	},

	/**
	 * returns a count of the the point associated with segment segment_id
	 */
	getSegmentPointsCount : function (segment_id, callback) {
		readFromDB("getSegmentPointsCount", [segment_id], kapturDb.passJsonResponseToCallback(callback));
	},
	
	/**
	 * Creates a point and corresponding media for a photo then the photo in the
	 * position specified.  If no position is specified the current default for
	 * adding a point to the segment is used (see documentation for addPoinToSegment
	 * for more info).
	 * 
	 * This function takes a callback which will be passed an object containing
	 * fields for the point_id and media_id with those values if they are set.
	 * If either fails to be created the corresponding value will be undefined
	 * or null.
	 */
	createPhotoPointAndMediaForSegment : function (segment_id, photo, position, callback) {
		kapturDb.createPairedPhotoPointAndMedia(photo, function (ids) {
			var point_id = ids['point_id'],
				media_id = ids['media_id'];
			
			position = position || null;
			
			if (point_id && media_id) {
				kapturDb.addPointToSegment(segment_id, point_id, position, function () {
					safeCall(callback, [ids]);
				});
			} else {
				safeCall(callback, [ids]);
			}
		});
	}
}

$(document).ready(function () {
	if (window.memoryCreationWizard && memoryCreationWizard.setDefaultTime) {
		memoryCreationWizard.setDefaultTime();
	}
});

