function toggleExpand(div, expand) {
	if (memoryCreationWizard.lastDropdown && memoryCreationWizard.lastDropdown != div) toggleExpand(memoryCreationWizard.lastDropdown, 0);
	memoryCreationWizard.lastDropdown = div;
	var c = $("#topCalloutsWrapper");
	if (c.length && (c.css("top")!="0px")) animateMemoryHeaderCallout("up");
	
	if (in_array(div, ['share', 'add', 'finish'])) {
		var memoryShare, memoryShareList, memoryShareListEnd;
		if (div == 'share') memoryShare = document.getElementById('memoryShare');
		else if (div == 'add') {
			if (!expand && !dataFlags.edit_mode) {
				redirectToEditMode(true);
				return;
			}
		} memoryShareList = document.getElementById('memory'+ucfirst(div)+'List');
		memoryShareListEnd = document.getElementById('memory'+ucfirst(div)+'ListEnd');
		if (expand == null) expand = !memoryShareList.style.display;
		if (expand) {
			//memoryShare.style.backgroundImage = 'none';
			memoryShareList.style.display = 'block';
			memoryShareListEnd.style.display = 'block';
			if (div == 'finish' || div == 'share') gaIframe(div);
		} else {
			//memoryShare.style.backgroundImage = '';
			memoryShareList.style.display = '';
			memoryShareListEnd.style.display = '';
		}
	} else if (div == 'profile' && !loggedInUser && expand !== 0) {
		var profile_callback = function() {loginAndSave('profile_dropdown');toggleMemoryFooterTabWrapper();};
		if (location.href.indexOf('p=f&') != -1) profile_callback = function() {location.href=location.href+'&loggedIn=1'};
		loginToFacebook(profile_callback);
	} else {
		var dropdown = document.getElementById(div+'Dropdown');
		if (expand == null) expand = !dropdown.style.display;
		if (expand) dropdown.style.display = 'block';
		else dropdown.style.display = '';
		if (div == 'tools') memoryCreationWizard.toolsActive = 1;
	}
	
	var btn_id = '#topNav'+ucfirst(div)+'Btn';
	if (expand) $(btn_id).addClass('selected');
	else $(btn_id).removeClass('selected');
}

function getEditPhotosButton() {
	var button = document.getElementById('topNavEditModeBtn'),
		button_html;
	
	if (editNight && !button && checkPermsForContribute()) {
		button_html = '<div id="topNavEditModeBtn" class="top_nav_btn" onclick="toggleEditPhotos()">Edit</div>';
		$("#topNavAddBtn").after(button_html);
		button = $("#topNavEditModeBtn")[0];
	}
	
	return button? button : null;
}

function toggleTab(div, expand) {
	toggleExpand('share', 0);
	if (memoryCreationWizard.lastTab && memoryCreationWizard.lastTab != div)
		toggleTab(memoryCreationWizard.lastTab, 0);
	
	memoryCreationWizard.lastTab = div;
	var memorySummaryWrapper = document.getElementById('memorySummaryWrapper');
	var tab_bg = document.getElementById('pageTabBg');
	var editModeButton = getEditPhotosButton();
	var tab_wrapper = document.getElementById('pageTabWrapper');
	var tab = document.getElementById(div+'Tab');
	var tab_btn = $('#'+div+'TabBtn');
	var min_toggle = document.getElementById('topNavToggleMin');
	if (expand == null) expand = !tab.style.display;
	if (expand) {		
		if (editModeButton) {
			if (div == 'photos') {
				editModeButton.style.display = 'block';
			} else {
				editModeButton.style.display = '';
			}
		}
		memorySummaryWrapper.style.height = '0';
		memorySummaryWrapper.style.overflow = 'hidden';
		tab_bg.style.display = 'block';
		tab_wrapper.style.display = 'block';
		tab.style.display = 'block';
		min_toggle.className = 'reset';
		tab_btn.addClass('selected');
		if (div == 'photos') {
			//$(window).trigger('updatecanvas');
			$(window).trigger('scroll');
			checkTriggerPaginate();
			
			// update menu bar
			showNavBar('media');
			
			// pause slideshow if it's playing
			weddingCoverSlideshow.pause();
		}
		
		if (in_array(div, ['photos', 'statuses'])) {
			// trigger client load only on click
			if (clientLoadDelayed) {
				clientLoadDelayed();
				clientLoadDelayed = null;
			}
		}
		if (in_array(div, ['photos', 'statuses', 'friends'])) {
			memoryCreationWizard[div+'Active'] = 1;
			// hide the share callout if its visible
			if ($("#memoryFooterTab").css("display")=="block" || $("#memoryFooterTabTall").css("display")=="block"){
				$("#memoryFooterTabWrapper").css("display","none");
			}
		}
	} else {
		if (editModeButton) {
			editModeButton.style.display = '';
		}
		memorySummaryWrapper.style.height = '';
		memorySummaryWrapper.style.overflow = '';
		tab_bg.style.display = '';
		tab_wrapper.style.display = '';
		tab.style.display = '';
		min_toggle.className = '';
		tab_btn.removeClass('selected');

		// show the share callout if it should be visible
		if ($("#memoryFooterTab").css("display")=="block" || $("#memoryFooterTabTall").css("display")=="block"){
			$("#memoryFooterTabWrapper").css("display","block");
		}
		
		// hide open callouts (ie. timeline callout)
		showCallout();
		
		// return to main menu if all tabs are closed
		setTimeout("if (!$('#topNavMedia #topNavCenter .top_nav_btn.selected').length) showNavBar('media', 1, 1);", 0);
	}
}

function toggleBuyTab(div, hide, no_toggle) {
	if (!hide && div == 'photobook') {
		if (!dataFlags.edit_mode) {
			redirectToEditMode(true, true);
			return;
		}
	}
	
	var buyTabBg = document.getElementById(div+'TabBg');
	var buyTabWrapper = document.getElementById(div+'TabWrapper');
	var buyTab = document.getElementById(div+'Tab');
	if (!hide) {
		//if (div != 'photobook') {
		buyTabBg.style.display = 'block';
		buyTabWrapper.style.display = 'block';
		buyTab.style.display = 'block';
		if (div == 'buy') {
			// close memory edit lightbox if it's open
			if (document.getElementById('memoryEditWrapper').style.display == 'block') showMemoryEdit('info', 1);
			
			// close share callout if it's open
			if ($("#topCalloutsWrapper").length && ($("#topCalloutsWrapper").css("top")!="0px"))
				animateMemoryHeaderCallout("up");
			
			weddingCoverSlideshow.pause(); // pause slideshow if it's playing
			gaIframe('finish'); // track click in ga
			//$.scrollTo({top: '0px', left: '0px'}, 0);
			$('.top_nav_btn.selected').click();
		} else if (div == 'photobook') {
			setLayoutStyles();
			loadPhotobook();
			//toggleBuyTab('buy', 1, 1);
			gaIframe('photobook'); // track click in ga
		} showNavBar(div);
		/*} else {
			// temporary dev handling
			if (DOMAIN_URL.indexOf('aws-dev') != -1) {
				// copy start
				buyTabBg.style.display = 'block';
				buyTabWrapper.style.display = 'block';
				buyTab.style.display = 'block';
				if (div == 'buy') {
					showMemoryEdit('info', 1);
				} else if (div == 'photobook') {
					setLayoutStyles();
					autoFlowLayouts();
					toggleBuyTab('buy', 1, 1);
				}
				showNavBar(div);
				// copy end
			} else window.open('https://docs.google.com/spreadsheet/viewform?formkey=dFdIb3Y1UnRiOFdHUDM0NUZCejdqT1E6MQ','photobooks_survey');
		}*/
	} else {
		buyTabBg.style.display = '';
		buyTabWrapper.style.display = '';
		buyTab.style.display = '';
		showNavBar(div, 1, no_toggle);
		//if (div == 'photobook') toggleBuyTab('buy');
	}
}

function togglePhotobookCheckout(type) {
	var photobookPageEditWrapper = document.getElementById('photobookPageEditWrapper');
	var photobookCheckoutWrapper = document.getElementById('photobookCheckoutWrapper');
	var topNavPhotobook = document.getElementById('topNavPhotobook');
	var topNavPhotobookCheckout = document.getElementById('topNavPhotobookCheckout');
	if (type == 'checkout') {
		if (loggedInUser) {
			savePhotobook();
			photobookPageEditWrapper.style.display = 'none';
			photobookCheckoutWrapper.style.display = 'block';
			topNavPhotobook.style.display = 'none';
			topNavPhotobookCheckout.style.display = 'block';
			highlightSelectedPage();
			memoryCreationWizard.photobookCheckout = 1;
		} else loginToFacebook(function() { loginAndSave('checkout'); });
	} else if (type == 'photobook') {
		photobookPageEditWrapper.style.display = 'block';
		photobookCheckoutWrapper.style.display = 'none';
		topNavPhotobook.style.display = 'block';
		topNavPhotobookCheckout.style.display = 'none';
		highlightSelectedPage(memoryCreationWizard.photobook_page);
		delete memoryCreationWizard.photobookCheckout;
	}
}

function showNextTab() {
	var next_tab = $('.memory_edit_tab_selected').next(':first');
	var next_tab_id = next_tab.attr('id');
	if (next_tab_id && !(editNight && next_tab_id == 'memoryEditBgTab')) next_tab.click();
	else showMemoryEdit(null, 1);
}

function checkSetPerms(perms, set) {
	for (var i in perms) {
		var perm = perms[i];
		if (typeof perm == 'string') {
			if (set) {
				userProfileObj.perms[perm] = 1;
				if (perm == 'user_photos') delete memoryCreationWizard.userAlbumsLoaded;
				else if (perm == 'user_videos') delete dataFlags.videosLoaded;
			} else if (!userProfileObj.perms[perm]) return false;
		}
	}return true;
}

function checkStandardPerms(callback, ignore_perms) {
	// check permissions
	var permCheck, checkPerms = perms = ['email', 'friends_photos', 'user_photos', 'friends_videos', 'user_videos', 'friends_relationships', 'friends_relationship_details', 'read_stream'];//'user_photo_video_tags', 'friends_photo_video_tags', 
	if (ignore_perms) {
		checkPerms = [];
		for (var i=0; i<perms.length; i++) {
			var perm = perms[i];
			if (!ignore_perms[perm]) checkPerms.push(perm);
		}
	}
	var requestPerms = checkPerms?checkPerms:perms;
	if (loggedInUser && !checkSetPerms(requestPerms)) {
		getFacebookExtendedPermissions(requestPerms.join(','), function(response) {
			var session = getFacebookSession(),
				perm_array = [];
			if (session) {
				getFacebookPermissions(function (fb_perms) {
					if (fb_perms) {
						forEach(fb_perms, function (key, val) {
							perm_array.push(key);
						});
						checkSetPerms(perm_array, 1);
						if (checkSetPerms(perms)) {
							$.cookies.set("userPerms", null);
							callback();
						}
					}
				});
			}
		});
		
		/*FB.login(function(response) {
			var session = getFacebookSession(),
				perm_array = [];
			if (session) {
				getFacebookPermissions(function (fb_perms) {
					if (fb_perms) {
						forEach(fb_perms, function (key, val) {
							perm_array.push(key);
						});
						checkSetPerms(perm_array, 1);
						if (checkSetPerms(perms)) {
							$.cookies.set("userPerms", null);
							callback();
						}
					}
				});
			}
		}, {scope:perms.join(',')});*/
		permCheck = 1;
	} else callback();
}

function showTab(tab, verified) {
	if (in_array(tab, ['addPhotos', 'addVideos']) && !verified) {
		var ignore_perms = (tab == 'addPhotos')?{'user_videos':1,'friends_videos':1}:null;
		checkStandardPerms(function() {showTab(tab, 1)}, ignore_perms);
	} else {
		var memoryEditBgTab = document.getElementById('memoryEditBgTab');
		var memoryEditInfoTab = document.getElementById('memoryEditInfoTab');
		var memoryEditGuestsTab = document.getElementById('memoryEditGuestsTab');
		var memoryEditAddPhotosTab = document.getElementById('memoryEditAddPhotosTab');
		var memoryEditAddVideosTab = document.getElementById('memoryEditAddVideosTab');
		//var memoryEditShareTab = document.getElementById('memoryEditShareTab');
		var bgTab = document.getElementById('bgTab');
		var infoTab = document.getElementById('infoTab');
		var guestsTab = document.getElementById('guestsTab');
		var photosTab = document.getElementById('addPhotosTab');
		var videosTab = document.getElementById('addVideosTab');
		//var shareTab = document.getElementById('shareTab');
		if (memoryEditInfoTab.className == 'memory_edit_tab_selected') {
			var valid_date = updateMemoryInfo();
			if (!valid_date) return;
			$("#memoryEditClose").css("display","block");
		} else if (memoryEditAddPhotosTab.className == 'memory_edit_tab_selected') callBulkSave();
		memoryEditBgTab.className = 'memory_edit_tab';
		memoryEditInfoTab.className = 'memory_edit_tab';
		memoryEditGuestsTab.className = 'memory_edit_tab';
		memoryEditAddPhotosTab.className = 'memory_edit_tab';
		memoryEditAddVideosTab.className = 'memory_edit_tab';
		//memoryEditShareTab.className = 'memory_edit_tab';
		bgTab.style.display = 'none';
		infoTab.style.display = 'none';
		guestsTab.style.display = 'none';
		photosTab.style.display = 'none';
		videosTab.style.display = 'none';
		//shareTab.style.display = 'none';
		document.getElementById('memoryEdit'+ucfirst(tab)+'Tab').className = 'memory_edit_tab_selected';
		document.getElementById(tab+'Tab').style.display = '';
		memoryCreationWizard.activeTab = tab+'Tab';
		
		if (tab == 'bg') {loadLayoutSelector();showPhotos('FacebookCover', 1);showPhotos('Upload', 1);showPhotos('Kaptur');}
		else if (tab == 'guests') {
			if (!memoryCreationWizard.friends_loaded && loggedInUser) memoryCreationWizard.loadFriends();
		} else if (tab == 'addPhotos') {
			//$('#nightCanvasRow td').length
			if (dataFlags.noSuggestionsProceed) $('#createMemoryAddYourPhotosTab').click();
			else $('#createMemoryAddSuggestedPhotosTab').click();
			//memoryCreationWizard.loadExtendedSuggestions();
		} else if (tab == 'addVideos') {
			$('#createMemoryAddYourVideosTab').click();
			memoryCreationWizard.loadVideos();
		}
		
		// manage bg tab color (for beyonce)
		document.getElementById('memoryTabsWrapper').style.backgroundColor = (tab == 'info'?'':'white');
		
		// update finish button
		//var btn_img = (tab == (editNight?'addVideos':'share'))? 'url("'+TEMPLATE_VIEW_PATH+'images/future_wedding/btn/finish.png")' : '';
		var btn_img = (tab == (editNight?'addVideos':'bg'))? 'url("'+TEMPLATE_VIEW_PATH+'images/future_wedding/btn/finish.png")' : '';
		document.getElementById('memoryEditDescNext').style.backgroundImage = btn_img;
		
		// hide any existing callouts
		showCallout();
		
		// show first callouts for first time users
		showFirstCallout();
	}
}

function authAction(action) {
	var callback, loginCallback, activeFlag;
	if (!action) action = 'photos';
	if (action == 'slideshow') {
		callback = function() {showSegment(memoryCreationWizard.sid)};
		loginCallback = function() {loginAndSave('view_slideshow')};
		toggleExpand('share', 0);
	} else if (action == 'tools') {
		callback = function() {toggleExpand(action)};
		loginCallback = function() {loginAndSave(action+'_dropdown')};
	} else if (action == 'quickstart') {
		callback = function() {
			initializeQuickstart();
			toggleTab(action)
		};
		loginCallback = function() {loginAndSave(action+'_tab')};
	} else if (action == 'profile') {
		callback = loginCallback = function() {location.href = '?p=f';};
	} else if (action == 'slideshow_prev') {
		callback = function() {weddingCoverSlideshow.previous()};
		loginCallback = function() {loginAndSave(action)};
	} else if (action == 'slideshow_play') {
		callback = function() {weddingCoverSlideshow.play()};
		loginCallback = function() {loginAndSave(action)};
	} else if (action == 'slideshow_next') {
		callback = function() {weddingCoverSlideshow.next()};
		loginCallback = function() {loginAndSave(action)};
	} else if (action == 'buy') {
		callback = function() {toggleExpand('finish')};//toggleBuyTab('buy')
		loginCallback = function() {loginAndSave(action)};
	} else {
		callback = function() {toggleTab(action)};
		loginCallback = function() {loginAndSave(action+'_tab')};
	}
	
	activeFlag = memoryCreationWizard[action+'Active'];
	
	// check for permissions or execute
	if (!activeFlag) {
		var callbackWrapper = function() {
			//document.getElementById('exportShareLinks').style.display = 'block';
			//memoryCreationWizard.exportActive = 1;
			callback();
		};
		checkPermsForView(callbackWrapper, loginCallback);
	} else callback();
}

function checkPermsForContribute () {
	var contribute_permissions = memoryCreationWizard.privacy.contribute,
		permitted = (loggedInUser == segmentData.fbOwner);
	
	switch (contribute_permissions) {
		case 'cli' :
			permitted = permitted || !!loggedInUser;
			break;
			
		case 'cfr' :
			permitted = permitted || !!segmentFlags.viewerIsFriend;
			break;
	}
	
	return permitted;
}

function checkPermsForView(callback, loginCallback) {
	if (loggedInUser != memoryCreationWizard.fb_owner) {
		var memory_privacy_ids = parsePrivacyIds(memoryCreationWizard.privacy_ids);
		var memory_view_privacy = memory_privacy_ids['view'];
		var memory_contribute_privacy = memory_privacy_ids['contribute'];
		var memory_auto_import_privacy = memory_privacy_ids['autoimport'];
		if (memory_view_privacy == 'vpr') {
			if (loggedInUser) showEditError(1);
			else loginToFacebook(loginCallback);
		} else if (memory_view_privacy == 'vli') {
			if (!loggedInUser) loginToFacebook(loginCallback);
			else callback();
		} else if (memory_view_privacy == 'vfr') {
			if (loggedInUser) checkFbFriendsForViewNew(callback);
			else loginToFacebook(loginCallback);
		} else callback();
	} else callback();
}

function checkViewForExport() {
	var exportShareLinks = document.getElementById('exportShareLinks'), show_export, export_checked;
	if (!memoryCreationWizard.exportActive) {
		if (loggedInUser != memoryCreationWizard.fb_owner) {
			var memory_privacy_ids = parsePrivacyIds(memoryCreationWizard.privacy_ids);
			var memory_view_privacy = memory_privacy_ids['view'];
			var memory_contribute_privacy = memory_privacy_ids['contribute'];
			var memory_auto_import_privacy = memory_privacy_ids['autoimport'];
			if (memory_view_privacy == 'vpr') {
				if (loggedInUser) export_checked = 1;
			} else if (memory_view_privacy == 'vli') {
				if (loggedInUser) show_export = 1;
			} else if (memory_view_privacy == 'vfr') {
				if (loggedInUser) {
					if (memoryCreationWizard.viewerIsFriend !== undefined) {
						if (memoryCreationWizard.viewerIsFriend) show_export = 1;
						else export_checked = 1;
					} else checkFbFriendsForViewNew(checkViewForExport);
				}
			} else show_export = 1;
		} else show_export = 1;
		if (show_export || export_checked) memoryCreationWizard.exportActive = 1;
		if (show_export) exportShareLinks.style.display = 'block';
	}
}

function checkFbFriendsForViewNew(callback) {
	if (memoryCreationWizard.viewerIsFriend == null) {
		var isFriendsFQL = buildIsFriendFQL(memoryCreationWizard.fb_owner);
		queryFacebook(isFriendsFQL.fql, isFriendsFQL.args, function(data) {
			if (data && data.length) {
				memoryCreationWizard.viewerIsFriend = 1;
				callback();
			} else {
				memoryCreationWizard.viewerIsFriend = 0;
				showEditError(2);
			}
		});
	} else if (memoryCreationWizard.viewerIsFriend) callback();
	else showEditError(2);
}

function showMemoryEdit(tab, closed) {
	var memoryEditWrapper = document.getElementById('memoryEditWrapper');
	var memoryBgEdit = document.getElementById('memoryBgEdit');
	var memorySlideshowControls = document.getElementById('memorySlideshowControls');
	var musicPlayerWrapper = document.getElementById('musicPlayerWrapper');
	
	var c = $("#topCalloutsWrapper");
	if (c.length && (c.css("top")!="0px")) animateMemoryHeaderCallout("up");
	
	// change nothing! memory has an invalid date
	if (closed && $("#memoryEditClose").css("display")=="none") return;
	if (closed) {
		memoryBgEdit.style.height = '';
		memoryBgEdit.style.overflow = '';
		memoryEditWrapper.style.display = '';
		memorySlideshowControls.style.height = '';
		memorySlideshowControls.style.overflow = '';
		musicPlayerWrapper.style.height = '';
		musicPlayerWrapper.style.overflow = '';
		//$('#topNavAddBtn').removeClass('selected');
		if (!editNight) {
			updateMemoryInfo();
		}
		callBulkSave();
		checkShowBookmarkPrompt();
		// hide any existing callouts
		showCallout();
		//lint the page so that the opengraph data is updated
		lintPage($(document.getElementsByTagName('fb:like')).attr('href'));
	} else {
		memoryBgEdit.style.height = '0';
		memoryBgEdit.style.overflow = 'hidden';
		memoryEditWrapper.style.display = 'block';
		memorySlideshowControls.style.height = '0';
		memorySlideshowControls.style.overflow = 'hidden';
		musicPlayerWrapper.style.height = '0';
		musicPlayerWrapper.style.overflow = 'hidden';
		//$('#topNavAddBtn').addClass('selected');
		$.scrollTo({top: '0px', left: '0px'}, 0);
		if (tab) showTab(tab);
	}
	
	//document.getElementById('topNavAddBtn').onclick = function() {showMemoryEdit('info', !closed)};
	toggleExpand('share', 0);
	//$.colorbox({inline:true, href:'#memoryEditWrapper', innerWidth: 685, innerHeight: 634, onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){updateMemoryInfo();checkShowBookmarkPrompt();hideEmbed(1)}, open:true});
}

function loginAndSave(type) {
	var callback, view_action = !in_array(type, ['edit_bg', 'edit_info', 'edit_menu']);
	if (in_array(type, ['guests', 'notify_guests'])) callback = function() {memoryCreationWizard.loadFriends();if (type=='notify_guests') show_notify_share();};
	else if (type == 'fb_cover_photos') callback = function() {showPhotos('FacebookCover', 0, 1)};
	else if (type == 'fb_videos') callback = function() {delete dataFlags.videosLoaded;loadUserVideos();toggleSection('fbVideos')};
	else if (type == 'upload_photos') callback = function() {showPhotos('Upload')};
	else if (type == 'edit_bg') callback = function() {checkPermissions(function() {showMemoryEdit('bg')}, 0, 1)};
	else if (type == 'edit_info') callback = function() {checkPermissions(function() {showMemoryEdit('info')}, 0, 1)};
	else if (type == 'edit_menu') callback = function() {checkPermissions(function() {toggleExpand('add')}, 0, 1)};
	else if (type == 'edit_hash') callback = function() {checkVanityUrl()};
	else if (type == 'view_slideshow') callback = function() {checkPermissions(function() {authAction('slideshow')}, 1)};
	else if (type == 'profile_dropdown') callback = function() {checkPermissions(function() {toggleExpand('profile')}, 1)};
	else if (type == 'tools_dropdown') callback = function() {checkPermissions(function() {authAction('tools')}, 1)};
	else if (type == 'photos_tab') callback = function() {checkPermissions(function() {authAction('photos')}, 1)};
	else if (type == 'statuses_tab') callback = function() {checkPermissions(function() {authAction('statuses')}, 1)};
	else if (type == 'friends_tab') callback = function() {checkPermissions(function() {authAction('friends')}, 1)};
	else if (type == 'checkout') callback = function() {checkPermissions(function() { togglePhotobookCheckout('checkout'); }, 1)};
	else if (type == 'increment_vote') callback = incrementVoteCount;
	else if (type == 'add_photos') callback = function() {$('#createMemoryAddSuggestedPhotosTab').click();};
	else if (in_array(type, ['slideshow_prev', 'slideshow_play', 'slideshow_next', 'buy'])) callback = function() {checkPermissions(function() {authAction(type)}, 1)};
	/*var unflagLoaded = function() {
		delete memoryCreationWizard.userAlbumsLoaded;
		delete memoryCreationWizard.friends_loaded;
		delete dataFlags.albumsLoaded;
		delete dataFlags.suggestionsLoaded;
		delete dataFlags.suggestionsLoading;
		delete dataFlags.loadedAlbumSuggestions;
		delete dataFlags.noSuggestionsProceed;
	}; if (dataFlags.segmentCreateCalled) dataFlags.initCallback = function() { unflagLoaded(); createFutureSegment(callback); };
	else dataFlags.initCallback = function() {unflagLoaded();callback()};*/
	dataFlags.initCallback = function(delay) {
		if (!delay) {
			createFutureSegment();
			setTimeout('dataFlags.initCallback(1)', 1000);
		} else {
			var msg = 'Oops, Facebook is not responding.<br>Click <a href="#" onclick="location.href = location.href.replace(/#/g, \'\')" style="color:#f09">here</a> to try again.';
			var msg_div = '<div style="width:350px"><div id="memoryEditClose"><a onclick="$.colorbox.close(); return false" href="#" style="text-decoration:none">x</a></div><div class="clear"></div><div style="padding:3px 0 9px 0">'+msg+'</div></div>';showError(msg_div, function() {location.href = location.href.replace(/#/g, '');});
		}
	};
	var callbackWrapper = function() {
		loadRmnSegment();
		var profile_pic = getPartnerLink(loggedInUser, 'profile_pic');
		document.getElementById('notifyPreviewProfilePic').src = profile_pic;
		//document.getElementById('topNavProfilePic').src = profile_pic;
		//var notifyShareLink = document.getElementById('notifyShareLink');
		if (dataFlags.segmentCreateCalled) {
			createFutureSegment(callback);
		} else {
			checkFbFriendsForEdit(callback, null, null, view_action);//dataFlags.initCallback();
		}
	};
	$('div[id="whyFBWrapper"]').css('display', '');
	$('.logged_in_wrapper').css('display', '');
	$('div[id="memoryEditBgNext"]').removeClass('hidden');
	$('div[id="memoryEditDescNext"]').removeClass('hidden');
	$('#createMemoryPhotosLogin').addClass('hidden');
	$('#selectPhotosWrapper').removeClass('hidden');
	$('#memoryFooterCallout').css('display', 'none');
	delete dataFlags.offlineView;
	welcomeFBUser(callbackWrapper);
	var memorySaveLink = document.getElementById('memorySaveLink');
	var memoryEditClose = document.getElementById('memoryEditClose');
	memorySaveLink.innerHTML = 'Edit';
	memorySaveLink.onclick = function() {showMemoryEdit('info');return false;};
	memoryEditClose.innerHTML = memoryEditClose.innerHTML.replace('Close &amp; Preview', 'Save &amp; Close');
}

function checkFbFriendsForEdit(callback, checked_is_friend, enable_contribute, view_action) {
	var notifyShareLink = document.getElementById('notifyShareLink');
	if (memoryCreationWizard.privacy.contribute != 'cfr' || (memoryCreationWizard.privacy.contribute == 'cfr' && checked_is_friend != null)) {
		var topNavAddBtn = document.getElementById('topNavAddBtn'), topNavAddBtnClick, enable_contribute;
		if (memoryCreationWizard.fb_owner && loggedInUser != memoryCreationWizard.fb_owner) {
			memoryCreationWizard.friendShareParam = '&friend=1';
			notifyShareLink.style.display = '';
			if (memoryCreationWizard.privacy.contribute == 'cfr') {
				if (segmentFlags.viewerIsFriend) {
					enable_contribute = 1;
				} else {
					topNavAddBtnClick = function() {
						showEditError(3);
					};
				}
			} else if (memoryCreationWizard.privacy.contribute == 'cli') {
				enable_contribute = 1;
			} else {
				topNavAddBtnClick = function() {
					showEditError();
				};
			}
			
			if (topNavAddBtnClick && !view_action) {
				topNavAddBtnClick();
			}
			$('#memoryEditInfoTab, #memoryEditBgTab, #memoryEditShareTab, #memoryAddMusicBtn, #memoryAddBgBtn, #memoryAddInfoBtn').css('display', 'none');
			$('#memoryEditGuestsTab').css('margin-left', 0);
			editNight = 1;
		} else {
			enable_contribute = 1;
		}
		
		if (enable_contribute) {
			memoryCreationWizard.friendShareParam = '';
			if (loggedInUser == memoryCreationWizard.fb_owner) {
				notifyShareLink.style.display = 'block';
			}
			var memorySummaryText = document.getElementById('memorySummaryText');
			memorySummaryText.style.cursor = 'pointer';
			memorySummaryText.onclick = function() {showMemoryEdit('info');};
			if (!memoryCreationWizard.title) document.getElementById('memorySummaryTitle').innerHTML = '[Title]';
			if (!memoryCreationWizard.location.name) document.getElementById('memorySummaryLocation').innerHTML = '[Location]';
			if (!memoryCreationWizard.description) document.getElementById('memorySummaryDesc').innerHTML = '[Description goes here]';
			//topNavAddBtnClick = function() {showMemoryEdit('info');return false;};
			topNavAddBtnClick = function() {toggleExpand('add');return false;};
			callback();
		} else {
			if (view_action) {
				callback();
			}
		}
		topNavAddBtn.onclick = topNavAddBtnClick;
		addToAttendList(editNight?loggedInUser:memoryCreationWizard.fb_owner, 1); // remove logged in user from the picture
	} else {
		var isFriendsFQL = buildIsFriendFQL(memoryCreationWizard.fb_owner);
		queryFacebook(isFriendsFQL.fql, isFriendsFQL.args, function(data) {
			if (data && data.length) {
				segmentFlags.viewerIsFriend = 1;
			} else {
				segmentFlags.viewerIsFriend = 0;
			}
			checkFbFriendsForEdit(callback, 1, segmentFlags.viewerIsFriend, view_action);
		});
	}
}

function checkPermissions(callback, custom_error, contribute) {
	var kc_url_params = '?';
	var photosTimelineWrapper = document.getElementById('photosTimelineWrapper');
	var photosTabContents = document.getElementById('photosTabContents');
	var kapturcardsAdLink = document.getElementById('kapturcardsAdLink');
	var kapturcardsBuyLink = document.getElementById('kapturcardsBuyLink');
	var kapturcardsBuyPicLink = document.getElementById('kapturcardsBuyPicLink');
	var memory_owner = !memoryCreationWizard.owner_id || userProfileObj.id == memoryCreationWizard.owner_id;
	if (memory_owner || (contribute && in_array(memoryCreationWizard.privacy.contribute, ['cfr', 'cli']))) {
		if (memory_owner) {
			photosTimelineWrapper.style.display = '';
			photosTabContents.style.paddingRight = '';
		}
		kc_url_params += 'p=choose&sid='+memoryCreationWizard.sid+'&';
		$('#photosTab table').css('width', '100%');
		
		setTimeout(function () {
			$('#photosTab table').css('width', '');
		}, 0);
		
		callback();
	} else {
		var memorySummaryText = document.getElementById('memorySummaryText');
		memorySummaryText.style.cursor = 'auto';
		memorySummaryText.onclick = '';
		document.getElementById('memorySaveLinkWrapper').style.display = 'none';
		photosTimelineWrapper.style.display = 'none';
		photosTabContents.style.paddingRight = 0;
		if (!custom_error) {
			showEditError();
		} else {
			callback();
		}
	}
	kc_url_params += 'aff=finish';
	var kc_link = 'http://'+KC_CONTEXT+'kapturcards.com/'+kc_url_params;//+'&aff=fb25'
	kapturcardsAdLink.href = kc_link;
	kapturcardsBuyLink.href = kc_link;
	kapturcardsBuyPicLink.href = kc_link;
}

function showEditError(code) {
	var msg = '';
	if (!code) msg = 'Only the memory creator can edit this page.';
	else if (code == 1) msg = 'This is a private memory.';
	else if (code == 2) msg = 'Only friends can view this memory.';
	else if (code == 3) msg = 'Only friends can contribute to this memory.';
	var msg_div = '<div style="width:350px"><div id="memoryEditClose"><a onclick="$.colorbox.close(); return false" href="#" style="text-decoration:none">x</a></div><div class="clear"></div><div style="padding:3px 0 9px 0">'+msg+'</div></div>';
	showError(msg_div);
}

function insertNotifyFriendWrapper(args, remove) {
	var notifyFriendsSelector = document.getElementById('notifyFriendsSelector');
	var fid = args['fid'];var div_id = 'f'+fid+'invite_wrapper';
	if (!remove) {
		var name = args['name'];
		var thumb = args['thumb'];
		var invite_friend_wrapper = document.createElement('div');
		//invite_friend_wrapper.innerHTML = '<div id="'+div_id+'" class="friend_post_wrapper" onclick="notifyFriend(\''+fid+'\')" style="cursor:pointer"><div class="friend_wrapper_thumb"><img title="'+name+'" class="profile_pic" src="'+thumb+'"></div><div class="friend_wrapper_name"><div class="friend_wrapper_name_text">'+name+'</div><div class="friend_post_btn" id="f'+fid+'invite_btn"></div></div></div>';
		invite_friend_wrapper.innerHTML = '<div id="'+div_id+'" class="friend_post_wrapper"><div class="friend_wrapper_thumb"><img title="'+name+'" class="profile_pic" src="'+thumb+'"></div><div class="friend_wrapper_name"><div class="friend_wrapper_name_text">'+name+'</div></div><div class="friend_post_remove"><a href="#" onclick="this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)" style="text-decoration:none">x</a></div></div>';
		invite_friend_wrapper = invite_friend_wrapper.childNodes[0];
		notifyFriendsSelector.insertBefore(invite_friend_wrapper, document.getElementById('inviteWrappersEnd'));
	} else {
		var invite_friend_wrapper = document.getElementById(div_id);
		if (invite_friend_wrapper) notifyFriendsSelector.removeChild(invite_friend_wrapper);
	}if ($('#cboxContent #notifyFriendsSelector').length && !memoryCreationWizard.resize_timeout) {
		setTimeout("$.colorbox.resize()", 100);
		//memoryCreationWizard.resize_timeout = setTimeout("$.colorbox.resize(); $.colorbox.resize(); memoryCreationWizard.resize_timeout = null", 100);
	}var notify_loader = document.getElementById('notifyFriendsPreviewLoading');
	if (notify_loader) notify_loader.parentNode.removeChild(notify_loader);
}

function toggleFriendSelected(fbid, remove, firstName, lastName, load_only) {
	var friend_list = document.getElementById('guestsTabFriendList');
	var friend_div_id = 'f'+fbid+'list';
	if (!remove) {
		var friend_data = memoryCreationWizard.loaded_friends[fbid];
		var friend_name = friend_data.name;
		var friend_pic = friend_data.thumbnail;
		var friend_gender = friend_data.gender;
		var friend_locale = friend_data.locale;
		var friend_div = document.createElement('div');
		friend_div.id = friend_div_id;
		friend_div.className = 'create_memory_attendee';
		friend_div.innerHTML = '<div class="float_left"><img alt="'+friend_name+'" title="'+friend_name+'" src="'+friend_pic+'" class="create_memory_attendee_thumb"></div><div class="create_memory_attendee_name">'+friend_name+'</div>';
		friend_list.appendChild(friend_div);
	} else {
		var friend_div = document.getElementById(friend_div_id);
		if (friend_div) friend_div.parentNode.removeChild(friend_div);
	}
	
	insertNotifyFriendWrapper({'fid':fbid, 'name':friend_name, 'thumb':friend_pic}, remove);
	
	if (!load_only) {
		addFbUserToNight(fbid, remove, firstName, lastName, friend_gender, friend_locale);
	}
}

function showPhotos(type, goBack, verified) {
	if (type == 'FacebookCover' && !goBack && !verified) checkStandardPerms(function() {showPhotos(type, goBack, 1)});
	else {
		var memoryEditBgSelect = document.getElementById('memoryEditBgSelect');
		var photos_wrapper = document.getElementById('createMemoryAllPhotos'+type+'ContentWrapper');
		if (!goBack) {
			if (memoryCreationWizard.prevAlbumWrapper) showPhotos(memoryCreationWizard.prevAlbumWrapper, 1);
			//memoryEditBgSelect.style.display = 'none';
			photos_wrapper.style.display = 'block';
			if (type == 'Upload') retrieveUploadedMedia();
			else if (type == 'FacebookCover') {
				if (!dataFlags.albumsLoaded && loggedInUser) {
					memoryCreationWizard.loadAlbums(loggedInUser, memoryCreationWizard.displayUserCoverAlbums);
					//setTimeout('memoryCreationWizard.loadAlbums(loggedInUser, memoryCreationWizard.displayUserCoverAlbums);',5000);
					dataFlags.albumsLoaded = 1;
				}
			} else if (type == 'Kaptur') updateFromKapturPhotos();
			memoryCreationWizard.prevAlbumWrapper = type;
			document.getElementById('layoutOptions').style.display = '';
		} else {
			//memoryEditBgSelect.style.display = '';
			photos_wrapper.style.display = '';
			delete memoryCreationWizard.prevAlbumWrapper;
			if (type == 'FacebookCover') memoryCreationWizard.showAlbumSelector('UserCover');
		}
	}
}

function setWeddingCover(photo_id, flickr, kaptur_id) {
	if (photo_id || kaptur_id) {
		var memory_cover = memoryCreationWizard.loaded_photos[photo_id];
		if (flickr) { // alias media values for flickr
			memory_cover = flickrDataManager.getPhotoById(photo_id);
			memory_cover.source = memory_cover.url;
		} else if (kaptur_id) {
			memory_cover = rmnPoints[kaptur_id];
			if (memory_cover.media_src) memory_cover.source = memory_cover.media_src;
			if (memory_cover.media_type_id) photo_id = memory_cover.media_type_id;
			memoryCreationWizard.cover_point_id = kaptur_id;
		}memory_cover = memory_cover['src_high_res']? memory_cover['src_high_res'] : memory_cover['source'];
		var prev_photo_thumb = document.getElementById('photos'+memoryCreationWizard.weddingCover);
		var prev_kaptur_photo_thumb = document.getElementById('kapturPhotos'+memoryCreationWizard.weddingCover);
		var photo_thumb = document.getElementById('photos'+photo_id);
		var kaptur_photo_thumb = document.getElementById('kapturPhotos'+photo_id);
		if (prev_photo_thumb) $(prev_photo_thumb).removeClass('create_memory_photo_selected');
		if (prev_kaptur_photo_thumb) $(prev_kaptur_photo_thumb).removeClass('create_memory_photo_selected');
		$(photo_thumb).addClass('create_memory_photo_selected');
		$(kaptur_photo_thumb).addClass('create_memory_photo_selected');
		//delete memoryCreationWizard.selected_photos[memoryCreationWizard.weddingCover];
		memoryCreationWizard.weddingCover = photo_id;
		//memoryCreationWizard.selected_photos[photo_id] = true;
		var memory_cover_img = new Image();
		memory_cover_img.onload = function() {
			if (memoryCreationWizard.weddingCover == photo_id) {
				var memorySummaryWrapper = $('#memorySummaryWrapper');
				var memoryCoverWrapper = $('#memoryCoverWrapper');
				document.getElementById('memoryBgEdit').style.display = 'none';
				memoryCoverWrapper.css('display', 'block');
				var img_width = memory_cover_img.width;
				var img_height = memory_cover_img.height;
				var prev_skin = memorySummaryWrapper.hasClass('light')? 'light':'dark', new_skin;
				if (img_height > img_width) new_skin = 'light';
				else new_skin = 'dark';
				if (new_skin != prev_skin) {
					memorySummaryWrapper.addClass(new_skin);
					memorySummaryWrapper.removeClass(prev_skin);
					memoryCoverWrapper.addClass(new_skin);
					memoryCoverWrapper.removeClass(prev_skin);
					/*var memoryCommentsWrapper = document.getElementById('memoryCommentsWrapper');
					memoryCommentsWrapper.innerHTML = '<fb:comments href="'+memoryCreationWizard.memory_url+'" num_posts="4" width="380"'+(new_skin=='dark'?' colorscheme="dark"':'')+'></fb:comments>';
					loadFBML(memoryCommentsWrapper);*/
					loadLayoutSelector(1);
				} //document.title = img_width+' '+img_height;
				updateBgImage(memory_cover, new_skin, img_width, img_height, photo_id);
			}
		};
		memory_cover_img.src = memory_cover;
		createFutureSegment(function() {updateSegmentCover(flickr, kaptur_id)});
		//document.getElementById('layoutOptions').style.display = 'block';
		//if (memoryCreationWizard.prevAlbumWrapper) showPhotos(memoryCreationWizard.prevAlbumWrapper, 1);
	} else {
		if (memoryCreationWizard.weddingCover) {
			var prev_photo_thumb = document.getElementById('photos'+memoryCreationWizard.weddingCover);
			var prev_kaptur_photo_thumb = document.getElementById('kapturPhotos'+memoryCreationWizard.weddingCover);
			if (prev_photo_thumb) $(prev_photo_thumb).removeClass('create_memory_photo_selected');
			if (prev_kaptur_photo_thumb) $(prev_kaptur_photo_thumb).removeClass('create_memory_photo_selected');
			//delete memoryCreationWizard.selected_photos[memoryCreationWizard.weddingCover];
		}delete memoryCreationWizard.weddingCover;
		
		var memorySummaryWrapper = $('#memorySummaryWrapper');
		var memoryCoverWrapper = $('#memoryCoverWrapper');
		document.getElementById('memoryBgEdit').style.display = '';
		memoryCoverWrapper.css('display', '');
		var prev_skin = memorySummaryWrapper.hasClass('light')? 'light':'dark', new_skin = 'light';
		if (new_skin != prev_skin) {
			memorySummaryWrapper.addClass(new_skin);
			memorySummaryWrapper.removeClass(prev_skin);
			memoryCoverWrapper.addClass(new_skin);
			memoryCoverWrapper.removeClass(prev_skin);
			loadLayoutSelector(1);
		}updateBgImage('', new_skin);
		//createFutureSegment(updateSegmentCover);
		//document.getElementById('layoutOptions').style.display = '';
		//if (memoryCreationWizard.prevAlbumWrapper) showPhotos(memoryCreationWizard.prevAlbumWrapper, 1);
	}
	
	// flag slideshow reload
	weddingCoverSlideshow.flagReload();
}

function updateBgImage(img_src, mode, img_width, img_height, partner_id) {
	var memoryCover = document.getElementById('memoryCover');
	var memoryCoverPageWrapper = document.getElementById('memoryCoverPageWrapper');
	var notifyPreviewThumb = document.getElementById('notifyPreviewThumb');
	//var backstretch = document.getElementById('backstretch');
	//if (backstretch) document.body.removeChild(backstretch);
	if (mode == 'dark') {
		memoryCover.style.display = 'none';
		memoryCover.src = '';
		//document.body.style.background = 'black';
		memoryCoverPageWrapper.style.width = 'auto';
		var opts = {'bannerHeight':42};
		if (memoryCreationWizard.layout > 2) {
			opts['overlayWidth'] = 400;
			opts['bgOffsetLeft'] = memoryCreationWizard.layout%2?0:opts['overlayWidth'];
		} else opts['centeredY'] = false;
		//$.backstretch(img_src, opts);
	} else {
		memoryCover.style.display = '';
		//document.body.style.background = 'url("'+TEMPLATE_VIEW_PATH+'images/future_wedding/shadow_gradient.png") center repeat-y #fffff6';
		memoryCoverPageWrapper.style.width = '';
		/*memoryCover.onload = function() {setTimeout('resizePortraitBg()',100);document.getElementById('memoryCover').onload='';};
		memoryCover.src = img_src;setTimeout('resizePortraitBg()',100);
		$(window).resize(resizePortraitBg);*/
	}if (notifyPreviewThumb) notifyPreviewThumb.src = img_src;
	$('.layout_option img').attr('src', img_src).removeClass('hidden');
	memoryCreationWizard.thumb = img_src;
	//updates the fb info for the like/share/etc
	$('meta[property="og:image"]').attr('content', img_src);
	dataFlags.needsLinting = 1;
	
	// update slideshow cover img
	if (!weddingCoverSlideshow.slideshowPlayed) {//SlideShow.autoscroll_playing
		memoryCreationWizard.img_width = img_width;
		memoryCreationWizard.img_height = img_height;
		memoryCreationWizard.thumb_partner_id = partner_id;
		var memory_cover = [{'type':'photo', 'metadata':{
			'src':memoryCreationWizard.thumb,
			'alt_src':memoryCreationWizard.thumb_big?memoryCreationWizard.thumb_big:'',
			'width':img_width,
			'height':img_height,
			'photoid':partner_id
		}}];
		$("."+SlideShow.slideshow_display_class+":first").remove();
		weddingCoverSlideshow.load(null, memory_cover);
	}
}

function lintPage(url, callback) {
	var location = window.location,
		dataFlags = window.dataFlags,
		page_to_lint = url,
		linter_url = getPageBaseUrl() + TEMPLATE_VIEW_PATH + 'facebook_linter.php?url=' + encodeURIComponent(page_to_lint);
	
	if (!url || !dataFlags.needsLinting) {
		dataFlags.needsLinting = 0;
		safeCall(callback, []);
	}

	jx.load(linter_url, callback);
}

function resizePortraitBg() {
	//var memoryCover = $('#memoryCover').css('min-height', window_height);
	var window_height = (("onorientationchange" in window) ? $(document) : $(window)).height();
	if ($('#memoryCover').width() < 600) {
		$('#memoryCover').css('width', '600px');
		$('#memoryCover').css('height', 'auto');
	} else if ($('#memoryCover').height() < window_height) {
		$('#memoryCover').css('width', 'auto');
		$('#memoryCover').css('height', '100%');
	}
}

function updateMemoryInfo() {
	var err_msg = '';var memoryInfoError = document.getElementById('memoryInfoError');
	var memoryDescError = document.getElementById('memoryDescError');
	var memoryTitle = document.getElementById('memoryTitle');
	var topNavTitle = document.getElementById('topNavTitle');
	var memoryLocation = document.getElementById('memoryLocation');
	var memoryDesc = document.getElementById('memoryDesc');
	var memory_title = removeHtmlTags(memoryTitle.value);
	var memory_location = removeHtmlTags(memoryLocation.value);
	var memory_desc = removeHtmlTags(memoryDesc.value);
	memoryTitle.value = memory_title;
	//topNavTitle.innerHTML = memory_title;
	$('.top_nav_title').html(memory_title);
	$('#topNav .top_nav_title').html('<div onclick="showMemoryEdit(\'info\')" style="cursor:pointer">'+memory_title+'</div>');
	memoryLocation.value = memory_location;
	memoryDesc.value = memory_desc;
	
	// check desc length
	if (memory_desc.length > 280) {
		memoryDescError.innerHTML = 'Please enter a shorter description!';
		memoryInfoError.innerHTML = '';
		return false;
	} else {
		memoryDescError.innerHTML = '';
	}
	
	document.getElementById('memorySummaryTitle').innerHTML = memory_title?memory_title:'[Title]';
	document.getElementById('memorySummaryLocation').innerHTML = memory_location?memory_location:'[Location]';
	document.getElementById('memorySummaryDesc').innerHTML = memory_desc?memory_desc:'[Description goes here]';
	
	// check date
	var old_start_time = memoryCreationWizard.start_time.getTime();
	var old_end_time = memoryCreationWizard.end_time.getTime();
	updateStartEndDates();
	//reload the stream if the date has changed
	if (window.segmentData && (memoryCreationWizard.start_time.getTime() != old_start_time) || (memoryCreationWizard.end_time.getTime() != old_end_time)) {
		segmentData.start = memoryCreationWizard.start_time.getTime() / 1000;
		segmentData.end = memoryCreationWizard.end_time.getTime() /1000;
		reloadFacebookStream();
	}
	
	memoryCreationWizard.title = memory_title;
	memoryCreationWizard.description = memory_desc;
	memoryCreationWizard.location.name = memory_location;
	err_msg = memoryCreationWizard.validateMemoryDescription();
	if (dataFlags.lastBasicDateEdit) {
		memoryInfoError.innerHTML = '';
		memoryDescError.innerHTML = err_msg;
	} else {
		memoryInfoError.innerHTML = err_msg;
		memoryDescError.innerHTML = '';
	}if (!err_msg) {
		// update privacy settings
		memoryCreationWizard.privacy.view = document.getElementById('nightSummaryViewPrivacy').value;
		memoryCreationWizard.privacy.contribute = document.getElementById('nightSummaryContributePrivacy').value;
		memoryCreationWizard.privacy.autoimport = document.getElementById('nightSummaryAutoImportPrivacy').checked;
		
		if (document.getElementById('setVanityKeywordBtn').className == 'enabled') {
			// create shortened url
			var vanityKeyword = document.getElementById('vanityKeyword');
			var vanityUrlStatus = document.getElementById('vanityUrlStatus');
			if (vanityUrlStatus.className == 'available') {
				var vanityKeywordText = vanityKeyword.value.toLowerCase();
				if (vanityKeywordText != memoryCreationWizard.hash) {
					/*if (vanityKeywordText) {
						// if segment is associated with an existing hash, clear it first
						//if (memoryCreationWizard.hash) writeToDB('editSegment', [{'hash':'null'}, memoryCreationWizard.sid], function() {shortenUrl(vanityKeywordText)}); //else 
						shortenUrl(vanityKeywordText);
					} else {
						memoryCreationWizard.hash = '';
						memoryCreationWizard.hash_updated = 1;
						createFutureSegment();
					}*/ //shortenUrl(vanityKeywordText, vanityKeywordText?'':'{"status":"cleared"}');
					if (!vanityKeywordText) shortenUrl('', '{"status":"cleared"}');
				} else {
					createFutureSegment();
				}
			} else {
				vanityKeyword.value = memoryCreationWizard.hash;
				updateVanityUrlStatus();
			
				// create / update segment
				createFutureSegment();
			}
		} else {
			createFutureSegment();
		}
		/*if (memoryCreationWizard.VanityUrlCheckTimeout) {
			clearTimeout(memoryCreationWizard.VanityUrlCheckTimeout);
			memoryCreationWizard.VanityUrlCheckTimeout = null;
		}*/
	} else return false;
	
	// date and desc are valid
	updateDisplayedDate();
	return true;
}

function updateStartEndDates(setDefaultEndTime) {
	var start_month = document.getElementById('memoryStartMonth').value;
	var start_day = document.getElementById('memoryStartDay').value;
	var start_year = document.getElementById('memoryStartYear').value;
	var start_hour = document.getElementById('memoryStartHour').value;
	var start_minute = document.getElementById('memoryStartMinute').value;
	var start_am_pm = document.getElementById('memoryStartAMPM').value.toLowerCase();
	var memory_tzoffset = document.getElementById('nightSummaryTZ').value;
	var memoryEndMonth = document.getElementById('memoryEndMonth');
	var memoryEndDay = document.getElementById('memoryEndDay');
	var memoryEndYear = document.getElementById('memoryEndYear');
	var memoryEndHour = document.getElementById('memoryEndHour');
	var memoryEndMinute = document.getElementById('memoryEndMinute');
	var memoryEndAMPM = document.getElementById('memoryEndAMPM');
	var end_month = memoryEndMonth.value;
	var end_day = memoryEndDay.value;
	var end_year = memoryEndYear.value;
	var end_hour = memoryEndHour.value;
	var end_minute = memoryEndMinute.value;
	var end_am_pm = memoryEndAMPM.value.toLowerCase();
	
	memoryCreationWizard.timezone_offset = memory_tzoffset;
	memoryCreationWizard.start_year = start_year;
	memoryCreationWizard.start_month = start_month;
	memoryCreationWizard.start_day = start_day;
	memoryCreationWizard.start_hour = start_hour; //12
	memoryCreationWizard.start_minute = start_minute;//0
	memoryCreationWizard.start_am_pm = start_am_pm;//'am'
	memoryCreationWizard.setStartTime();
	if (!setDefaultEndTime) {
		memoryCreationWizard.end_year = end_year;
		memoryCreationWizard.end_month = end_month;
		memoryCreationWizard.end_day = end_day;
		memoryCreationWizard.end_hour = end_hour;//11
		memoryCreationWizard.end_minute = end_minute;//59
		memoryCreationWizard.end_am_pm = end_am_pm;//'pm'
		memoryCreationWizard.setEndTime();
	} else {
		memoryCreationWizard.end_time = new Date(memoryCreationWizard.start_time.getTime() + (36*60*60*1000)); //start time + 36 hrs
		default_end_time_info = memoryCreationWizard.end_time; // 3600000
		var adjusted_end_date = getAdjustedTimeWrap(default_end_time_info);
		memoryCreationWizard.end_year = adjusted_end_date.getUTCFullYear();
		memoryCreationWizard.end_month = adjusted_end_date.getUTCMonth() + 1;
		memoryCreationWizard.end_day = adjusted_end_date.getUTCDate();
		memoryCreationWizard.end_hour = adjusted_end_date.getHours();
		memoryCreationWizard.end_minute = adjusted_end_date.getMinutes();
		if (memoryCreationWizard.end_minute < 10)
			memoryCreationWizard.end_minute = '0' + memoryCreationWizard.end_minute;
		if (memoryCreationWizard.end_hour >= 12) {
			if (memoryCreationWizard.end_hour != 12) memoryCreationWizard.end_hour = memoryCreationWizard.end_hour - 12;
			memoryCreationWizard.end_am_pm = "pm";
		} else {
			if (memoryCreationWizard.end_hour == 0) memoryCreationWizard.end_hour = 12;
			memoryCreationWizard.end_am_pm = "am";
		}
		
		// update fields
		if (!memoryCreationWizard.validateMemoryDescription()) {
			memoryEndMonth.value = memoryCreationWizard.end_month;
			memoryEndDay.value = memoryCreationWizard.end_day;
			memoryEndYear.value = memoryCreationWizard.end_year;
			memoryEndHour.value = memoryCreationWizard.end_hour;
			memoryEndMinute.value = memoryCreationWizard.end_minute;
			memoryEndAMPM.value = memoryCreationWizard.end_am_pm.toUpperCase();
		}
	}
}

function updateDisplayedDate() {
	var start_month = document.getElementById('memoryStartMonth').value;
	var start_day = document.getElementById('memoryStartDay').value;
	var start_year = document.getElementById('memoryStartYear').value;
	var end_month = document.getElementById('memoryEndMonth').value;
	var end_day = document.getElementById('memoryEndDay').value;
	var end_year = document.getElementById('memoryEndYear').value;
	var start_date = full_months[start_month-1]+' '+start_day+', '+start_year;
	var end_date = full_months[end_month-1]+' '+end_day+', '+end_year;
	var start_time = memoryCreationWizard.start_time.getTime();
	var end_time = memoryCreationWizard.end_time.getTime();
	var memory_length = end_time - start_time;
	if (memory_length > 24*60*60*1000 && memory_length > 36*60*60*1000) start_date += ' - ' + end_date;
	document.getElementById('memorySummaryDate').innerHTML = (start_month&&start_day&&start_year)?start_date:'[Date]';
	
	// show / hide future tooltip
	var memorySummaryTooltip = document.getElementById('memorySummaryTooltip');
	if (memorySummaryTooltip) {
		var tooltip_display = '';
		if (start_time < new Date().getTime()) tooltip_display = 'none';
		memorySummaryTooltip.style.display = tooltip_display;
	}togglePhotosTimeline(1); // update timeline
}

function createFutureSegment(callback) {
	if (!dataFlags.segmentCreated) {
		//if (!memoryCreationWizard.segmentCreateQueue) {
			//memoryCreationWizard.segmentCreateQueue = [];
			if (loggedInUser) {
				writeToDB('createLocation', [{'user_id':userProfileObj.id, 'name':d_escape(memoryCreationWizard.title), 'description':d_escape(memoryCreationWizard.location.name)}], function(data) {
					var location_id = extractJSONid(data);
					memoryCreationWizard.location.id = location_id;
					var start_time = parseInt(memoryCreationWizard.start_time.getTime()/1000, 10);
					var end_time = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);
					//var privacy_ids = $('#nightSummaryViewPrivacy').val()+','+$('#nightSummaryContributePrivacy').val()+(!document.getElementById('nightSummaryAutoImportPrivacy').checked?',nai':''); //'vli,cfr';
					var privacy_ids = memoryCreationWizard.privacy.view+','+memoryCreationWizard.privacy.contribute+(!memoryCreationWizard.privacy.autoimport?',nai':'');
					var segment_params = {'id':memoryCreationWizard.sid, 'user_id':userProfileObj.id, 'utcStartSec':start_time, 'utcEndSec':end_time, 'title':d_escape(memoryCreationWizard.title), 'description':d_escape(memoryCreationWizard.description), 'location_id':location_id, 'timezoneOffset':memoryCreationWizard.timezone_offset, 'privacy':'public', 'privacy_ids':privacy_ids, 'app_id':memoryCreationWizard.app_id};
					if (memoryCreationWizard.hash_updated) {
						segment_params['hash'] = memoryCreationWizard.hash?memoryCreationWizard.hash:'null';
						delete memoryCreationWizard.hash_updated;
					}if (memoryCreationWizard.layout) segment_params['layout'] = memoryCreationWizard.layout;
					writeToDB('createSegment', [segment_params], function (data) {
						var queued_call;if (callback) callback();
						//while (queued_call = memoryCreationWizard.segmentCreateQueue.pop()) queued_call();
						//memoryCreationWizard.segmentCreateQueue = null;
						if (memoryCreationWizard.app_id=="20"){
							// tag beyonce memory as wedding
							tagKapturAsWedding(memoryCreationWizard.sid);
						}
						dataFlags.segmentCreated = 1;
						dataFlags.promptBookmark = 1;
						checkShowBookmarkPrompt();
					});
				});
			} else dataFlags.segmentCreateCalled = 1;
		//} else if (callback) memoryCreationWizard.segmentCreateQueue.push(callback);
	} else if (callback) {
		safeCall(callback, []);
	} else {
		var start_time = parseInt(memoryCreationWizard.start_time.getTime()/1000, 10);
		var end_time = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);
		var privacy_ids = memoryCreationWizard.privacy.view+','+memoryCreationWizard.privacy.contribute+(!memoryCreationWizard.privacy.autoimport?',nai':'');
		var segment_params = {'utcStartSec':start_time, 'utcEndSec':end_time, 'title':d_escape(memoryCreationWizard.title), 'description':d_escape(memoryCreationWizard.description), 'layout':memoryCreationWizard.layout, 'timezoneOffset':memoryCreationWizard.timezone_offset, 'privacy':'public', 'privacy_ids':privacy_ids};
		if (memoryCreationWizard.hash_updated) {
			segment_params['hash'] = memoryCreationWizard.hash?memoryCreationWizard.hash:'null';
			delete memoryCreationWizard.hash_updated;
		}
		writeToDB('editSegment', [segment_params, memoryCreationWizard.sid]);
		writeToDB('editLocation', [{'name':d_escape(memoryCreationWizard.title), 'description':d_escape(memoryCreationWizard.location.name)}, memoryCreationWizard.location.id]);
	}
}

function checkShowBookmarkPrompt() {
	// repurposed this function for retreival of stream items
	if (dataFlags.promptBookmark && document.getElementById('memoryEditWrapper').style.display != 'block') {
		segmentData.start = parseInt(memoryCreationWizard.start_time.getTime()/1000, 10);
		segmentData.end = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);
		loadRmnPointsFromDB(userProfileObj.id, segmentData.start, segmentData.end);
		if (!segmentData.privacy) segmentData.privacy = {}
		//segmentData.privacy.autoimport = 1;
		reloadFacebookStream();
		delete dataFlags.promptBookmark;
		if (typeof showFbLikeComment == 'function') showFbLikeComment();
		
		// start music player
		startMusic();
	} /* deprecated
	if (dataFlags.promptBookmark && document.getElementById('memoryEditWrapper').style.display != 'block') {
		$.colorbox({inline:true, href:'#memoryBookmarkWrapper', onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){hideEmbed(1)}, open:true});//innerWidth:430, innerHeight:350, 
		delete dataFlags.promptBookmark;
	}*/
}

function updateSegmentCover(flickr, kaptur_id) {
	//if (memoryCreationWizard.cover_point_id) writeToDB('deletePoint', [memoryCreationWizard.cover_point_id]);
	var photo_data = memoryCreationWizard.loaded_photos[memoryCreationWizard.weddingCover];
	if (flickr) { // alias media values for flickr and from kaptur
		photo_data = flickrDataManager.getPhotoById(memoryCreationWizard.weddingCover);
		photo_data.utc_time_second = photo_data.created_time;
		photo_data.description = photo_data.title;
		photo_data.source = photo_data.url;
		photo_data.thumbnail = photo_data.thumb_url;
	} else if (kaptur_id) {
		photo_data = rmnPoints[kaptur_id];
		if (photo_data.utcTimeSec) photo_data.utc_time_second = photo_data.utcTimeSec;
		if (photo_data.media_src) photo_data.source = photo_data.media_src;
		if (photo_data.media_thumb) photo_data.thumbnail = photo_data.media_thumb;
	}
	
	if (kaptur_id) {
		var media_id = photo_data.media_id;
		writeToDB('editSegment', [{'media_id':media_id}, memoryCreationWizard.sid]);
	} else {
		var point_time = getUniqueTime(memoryCreationWizard.adjustPointTime(photo_data.utc_time_second));
		var partner_type = photo_data.uploaded?PARTNER_TYPES.kaptur_photo:PARTNER_TYPES.facebook_photo;
		var partner_val = photo_data.uploaded?memoryCreationWizard.weddingCover:photo_data.owner_facebook_id;
		var point_args = {
			'utcTimeSec':point_time,
			'description':d_escape(photo_data.description),
			'partnerId_id':partner_type,
			'partnerIdValue':partner_val,
			'user_id':userProfileObj.id,
			'timezoneOffset':memoryCreationWizard.timezone_offset,
			'privacy':'public',
			'app_id':memoryCreationWizard.app_id};
		
		var media_args = {
			'mediaType_id':MEDIA_TYPES.photo,
			'title':d_escape(photo_data.description),
			'url':d_escape(photo_data.page_url),
			'src':d_escape(photo_data.source),
			'alt_src':d_escape(photo_data.src_high_res),
			'thumb':d_escape(photo_data.thumbnail),
			'height':photo_data.height,
			'width':photo_data.width,
			'utcTimeSec':point_time,
			'user_id':userProfileObj.id,
			'partnerId_id':partner_type,
			'partnerIdValue':memoryCreationWizard.weddingCover};
		
		writeToDB('createPoint', [point_args, null], function(data) {
			memoryCreationWizard.cover_point_id = extractJSONid(data);
			writeToDB('createMedia', [media_args, null], function(data) {
				var media_id = extractJSONid(data);
				writeToDB('pairMediaAndPoint', [[media_id], memoryCreationWizard.cover_point_id]);
				writeToDB('editSegment', [{'media_id':media_id}, memoryCreationWizard.sid]);
				addPointToSegmentPointTable(memoryCreationWizard.sid, memoryCreationWizard.cover_point_id, point_time);
			});
		});
	}
	refreshSegmentThumb(photo_data.source, photo_data.thumbnail);
}

function loadMemoryEditFields() {
	var memory_desc = memoryCreationWizard.description;
	var memory_title = memoryCreationWizard.title?memoryCreationWizard.title:'';
	document.getElementById('memoryTitle').value = memory_title;
	//document.getElementById('topNavTitle').value = memory_title;
	//$('.top_nav_title').html(memory_title);
	document.getElementById('memoryLocation').value = memoryCreationWizard.location.name?memoryCreationWizard.location.name:'';
	document.getElementById('memoryDesc').value = memory_desc?memory_desc:'';updateDescCount();
	document.getElementById('vanityKeyword').value = memoryCreationWizard.hash?memoryCreationWizard.hash:'';
}

function updateDescCount() {
	var memory_desc_count = 280 - document.getElementById('memoryDesc').value.length;
	var memoryDescCount = document.getElementById('memoryDescCount');
	memoryDescCount.innerHTML = memory_desc_count+' remaining';
	if (memory_desc_count < 0) memoryDescCount.style.color = 'red';
	else memoryDescCount.style.color = '';
}

function loadFBSession(callback) {
	var sessionUser = getFacebookSession();
	if (sessionUser) {
		welcomeFBUser();
		loggedInUser = sessionUser.uid;
		// load rmn id
		readFromDB('getRmnUserInfoByFacebookId', [loggedInUser.toString()], function(data) {
			var result = JSON.parse(data);
			result = result['result'];
			if (result && result['user_id']) {
				if (!userProfileObj.id) userProfileObj.id = result['user_id'];
			}if (callback) callback();
		});
	}
}

function show_email_share() {
	var memoryEmailShare = document.getElementById('memoryEmailShare');
	if (memoryCreationWizard.friendShareParam) memoryEmailShare.src = memoryEmailShare.src + memoryCreationWizard.friendShareParam;
	else memoryEmailShare.src = memoryEmailShare.src.replace(memoryCreationWizard.friendShareParam, '');
	memoryEmailShare.src = replaceUrlParam('custom', memoryCreationWizard.hash?memoryCreationWizard.hash:'', memoryEmailShare.src);
	$.colorbox({inline:true, href:'#memoryEmailShareWrapper', innerWidth:430, innerHeight:350, onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){hideEmbed(1)}, open:true});
}

function show_link_share() {
	if (!memoryCreationWizard.hash) {
		if (!memoryCreationWizard.short_url) {
			try{$.colorbox({inline:true,onOpen:function(){toggleExpand('share', 0)}});} catch(err) {}
			var url = location.href.split('#')[0]+'&ref=link';
			url = url.replace(/&edit_mode=1/g, '');
			var kptrit_url = getShortenerUrl('&action=shorturl&url='+encodeURIComponent(url));
			memoryCreationWizard.shorten_url_timeout = setTimeout("show_link_share_lightbox();delete memoryCreationWizard.shorten_url_timeout;", 4000);
			jx.load(kptrit_url, function(response) {
				response = JSON.parse(response);
				if (response.statusCode == '200') {
					url = response.shorturl;
					memoryCreationWizard.short_url = response.shorturl;
				}document.getElementById('share_link').value = url;
				if (memoryCreationWizard.shorten_url_timeout) {
					clearTimeout(memoryCreationWizard.shorten_url_timeout);
					delete memoryCreationWizard.shorten_url_timeout;
					show_link_share_lightbox();
				}
			});
		} else {
			document.getElementById('share_link').value = memoryCreationWizard.short_url;
			show_link_share_lightbox();
		}
	} else show_link_share_lightbox();
}

function show_notify_share() {
	if (loggedInUser) {
		if (!memoryCreationWizard.friends_loaded) memoryCreationWizard.loadFriends();
		$.colorbox({inline:true, href:'#notifyFriendsSelector', onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){hideEmbed(1)}, open:true});
	} else $.colorbox({inline:true, href:'#notifyFriendsSelector .hidden #whyFBWrapper', onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){hideEmbed(1)}, open:true});
}

function show_link_share_lightbox() {
	$.colorbox({inline:true, href:'#memoryLinkWrapper', onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){hideEmbed(1)}, open:true});
}

function updateVanityUrlStatus(classStr, msg) {
	if (!classStr) classStr = '';
	if (!msg) msg = '';
	var vanityUrlStatus = document.getElementById('vanityUrlStatus');
	vanityUrlStatus.className = classStr;
	vanityUrlStatus.innerHTML = msg;
	
	// update set keyword button
	var setVanityKeywordBtn = document.getElementById('setVanityKeywordBtn');
	if (classStr == 'available') setVanityKeywordBtn.className = 'enabled';
	else setVanityKeywordBtn.className = '';
}

function sanitize_context(context) {
	if (context.indexOf('aws-dev.') != -1) context = 'aws-dev.';
	else if (context.indexOf('stg.') != -1) context = 'stg.';
	else context = 'www.';
	return context;
}

function getShortenerUrl(action) {
	var context = sanitize_context(CONTEXT);
	var kptrit_url = 'http://'+CONTEXT+'kptr.it/yourls-api.php?signature=ed5c2b6dcb&format=json'+action;
	kptrit_url = '?p=proxy&u='+encodeURIComponent(kptrit_url);
	return kptrit_url;
}

function shortenUrl(hash, response) {
	if (!response) {
		var setVanityKeywordBtn = document.getElementById('setVanityKeywordBtn');
		if (setVanityKeywordBtn.className == 'enabled') {
			setVanityKeywordBtn.className = '';
			if (!hash) hash = document.getElementById('vanityKeyword').value.toLowerCase();
			var page_url = encodeURIComponent(DOMAIN_URL+'?p=nw&sid='+memoryCreationWizard.sid+'&ref=custom');
			var kptrit_url = getShortenerUrl('&action=shorturl&url='+page_url+(hash?'&keyword='+hash:''));
			jx.load(kptrit_url, function(response) {shortenUrl(hash, response)});
		}
	} else {response = JSON.parse(response);
		if (response.status == "fail" && response.code == "error:keyword")
			updateVanityUrlStatus('unavailable', 'Sorry, this address is already taken. Please choose another one.');
		else {
			updateVanityUrlStatus();
			memoryCreationWizard.hash = hash;
			memoryCreationWizard.hash_updated = 1;
			createFutureSegment();
			var vanityUrlDisplay = document.getElementById('vanityUrlDisplay');
			var share_link = document.getElementById('share_link');
			if (hash) {
				var custom_url = (CONTEXT!='www.'?CONTEXT:'')+'kptr.it/'+hash;//'http://'+
				vanityUrlDisplay.innerHTML = '<div class="memory_edit_field_item"><input class="memory_edit_desc_field" value="'+custom_url+'" onclick="this.select()"></div>';// readonly
				share_link.value = custom_url;
			} else {
				vanityUrlDisplay.innerHTML = '';
				share_link.value = location.href.split('#')[0]+'&ref=link';
			}
		}
	}
}

function checkVanityUrl(response) {
	var classStr = 'unavailable';
	if (!response) {
		if (loggedInUser) {
			var vanity_keyword = document.getElementById('vanityKeyword').value.toLowerCase();
			//if (!vanity_keyword) msg = 'Please enter a keyword for your url.'; else 
			if (vanity_keyword) {
				if (vanity_keyword != memoryCreationWizard.hash) {
					if (!vanity_keyword.match(/^[a-z0-9-_]+$/))
						msg = 'Your address can only consist of letters and numbers.';
					
					// passes format check
					if (!msg) {
						if (vanity_keyword != memoryCreationWizard.hash) {
							updateVanityUrlStatus();
							var kptrit_url = getShortenerUrl('&action=url-stats&shorturl='+vanity_keyword);
							jx.load(kptrit_url, checkVanityUrl);
						}
					} else {updateVanityUrlStatus(classStr, msg);}
				} else updateVanityUrlStatus();
			} else if (vanity_keyword != memoryCreationWizard.hash) {
				classStr = 'available';
				msg = 'Your address will be cleared.';
				updateVanityUrlStatus(classStr, msg);
			}
		} else {
			msg = 'Please <a href="#" onclick="loginToFacebook(function() {loginAndSave(\'edit_hash\')})">sign in</a> to set an address for your page.';
			updateVanityUrlStatus(classStr, msg);
		}
	} else {
		var msg = 'Sorry, this address is already taken. Please choose another one.';
		response = JSON.parse(response);
		if (response.statusCode == '404') {
			classStr = 'available';
			msg = 'This address is available. Click "Set as URL" to save.';
		}updateVanityUrlStatus(classStr, msg);
	}
}

function checkVanityUrlLink() {
	var vanityKeyword = document.getElementById('vanityKeyword').value.toLowerCase();;
	if (!vanityKeyword) updateVanityUrlStatus('unavailable', 'Please enter a keyword for your address.');
	else if (vanityKeyword == memoryCreationWizard.hash) updateVanityUrlStatus('unavailable', 'This is the keyword for your current address.');
	else checkVanityUrl();
}

function callVanityUrlCheck() {
	if (memoryCreationWizard.VanityUrlCheckTimeout) {
		clearTimeout(memoryCreationWizard.VanityUrlCheckTimeout);
		delete memoryCreationWizard.VanityUrlCheckTimeout;
	}memoryCreationWizard.VanityUrlCheckTimeout = setTimeout("delete memoryCreationWizard.VanityUrlCheckTimeout; checkVanityUrl()", 500);
}

function loadLayoutSelector(layoutChanged) {return;
	var layoutOptions = $('#layoutOptions');
	var portrait_layout = $('#memorySummaryWrapper').hasClass('light');
	if (!layoutOptions.html()) {
		var layoutOptionsHTML = '';
		var layout_hide = portrait_layout? ' style="display:none"' : '';
		var layout_class = portrait_layout? ' portrait' : '';
		var order_array = [3,4,1,2];
		for (var index in order_array) {
			var i = order_array[index];
			if (parseInt(i)) {
				var current_layout = memoryCreationWizard.layout;
				if (portrait_layout && current_layout < 3) current_layout = parseInt(current_layout, 10) + 2;
				layoutOptionsHTML += '<div id="layout'+i+'" class="layout_option'+layout_class+(i==current_layout? ' selected':'')+'"'+(i<3?layout_hide:'')+' onclick="setLayout('+i+')"><table cellspacing="0" cellpadding="0" width="100%" height="100%"><tr><td valign="middle"><img '+(memoryCreationWizard.thumb?'src="'+memoryCreationWizard.thumb+'"':'class="hidden"')+'></td></tr></table><div></div></div>';
			}
		}layoutOptions.html(layoutOptionsHTML);
	} else if (layoutChanged) {
		for (var i=1; i<5; i++) {
			var layout_option = $('#layout'+i);
			if (portrait_layout) layout_option.addClass('portrait');
			else layout_option.removeClass('portrait');
			if (i < 3) layout_option.css('display', portrait_layout?'none':'');
		}if (portrait_layout && memoryCreationWizard.layout < 3) setLayout(parseInt(memoryCreationWizard.layout, 10) + 2);
	}if (memoryCreationWizard.weddingCover) layoutOptions.css('display', 'block');
}

function setLayout(layout) {
	if (layout != memoryCreationWizard.layout) {
		if (parseInt(layout, 10) % 2 == 0) {
			$('#memoryCoverWrapper').addClass('swap');
			$('#memorySummaryWrapper').addClass('swap');
			$('#memoryBgEdit').addClass('swap');
			$('#memoryFooterTab').addClass('swap');
			$('#memoryFooterTabTall').addClass('swap');
		} else {
			$('#memoryCoverWrapper').removeClass('swap');
			$('#memorySummaryWrapper').removeClass('swap');
			$('#memoryBgEdit').removeClass('swap');
			$('#memoryFooterTab').removeClass('swap');
			$('#memoryFooterTabTall').removeClass('swap');
		} // check conditions for updating bg
		var bg_src = $('#backstretch img').attr('src');
		var is_dark = !$('#memorySummaryWrapper').hasClass('light');
		var update_needed = memoryCreationWizard.layout + layout > 3;
		//var level_leap = Math.abs(parseInt((memoryCreationWizard.layout-1)/2, 10) - parseInt((layout-1)/2, 10));
		$('#layout'+memoryCreationWizard.layout).removeClass('selected');
		$('#layout'+memoryCreationWizard.layout+2).removeClass('selected');
		$('#layout'+layout).addClass('selected');
		memoryCreationWizard.layout = layout;
		
		// display and save
		if (bg_src && is_dark && update_needed) updateBgImage(bg_src, 'dark');
		createFutureSegment();
	}
}

function notifyFriend(fid) {
	if (!userProfileObj.perms.publish_stream) {
		getFacebookExtendedPermissions('publish_stream', function(response) {
			var session = getFacebookSession();
			if (session) {
				getFacebookPermissions(function (fb_perms) {
					if (fb_perms['publish_stream']) {
						userProfileObj.perms.publish_stream = 1;
						$.cookies.set("userPerms", null);
						notifyFriend(fid);
					}
				});
			}
		});
	} else {
		if (fid) {
			var notify_friend_wrapper = document.getElementById('f'+fid+'invite_wrapper');
			notify_friend_wrapper.onclick = '';
			notify_friend_wrapper.style.cursor = 'auto';
			var notify_friend_invite_btn = document.getElementById('f'+fid+'invite_btn');
			notify_friend_invite_btn.className = 'friend_posted_btn';
			notify_friend_invite_btn.innerHTML = 'Posted on wall!';
		} else {fid = [];
			$('#notifyFriendsSelector .friend_post_wrapper').each(function() {
				var fbid = this.id.replace('invite_wrapper', '').replace('f', '');
				fid.push(fbid);
			});
		}var img_src = document.getElementById('notifyPreviewThumb').src;
		var notifyFriendsMsg = document.getElementById('notifyPreviewStatus').value;
		if (notifyFriendsMsg == 'Add a comment') notifyFriendsMsg = '';
		var args = {'message':notifyFriendsMsg, 'title':memoryCreationWizard.shareTitle, 'desc':memoryCreationWizard.shareDesc, 'url':'?p=nw&sid='+memoryCreationWizard.sid+'&ref=friend_post', 'src':img_src, 'token':FB.getAccessToken(), 'target':fid};
		var feed_post_url = 'http://'+location.host+'?p=facebook_feed&args='+encodeURIComponent(JSON.stringify(args));
		jx.load(feed_post_url, '', '', 'POST');
	}
}

function editNotifyFriends(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;
		memoryCreationWizard.shareTitle = notifyPreviewTitleVal;
		memoryCreationWizard.shareDesc = notifyPreviewDescVal;
		notifyPreviewEditBtn.className = '';
		notifyPreviewSaveBtns.className = 'hidden';
	} else if (action == 2) {
		notifyPreviewTitle.innerHTML = memoryCreationWizard.shareTitle?memoryCreationWizard.shareTitle:'';
		notifyPreviewDesc.innerHTML = memoryCreationWizard.shareDesc?memoryCreationWizard.shareDesc:'';
		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;
		memoryCreationWizard.shareTitle = notifyPreviewTitleVal;
		memoryCreationWizard.shareDesc = notifyPreviewDescVal;
		notifyPreviewEditBtn.className = 'hidden';
		notifyPreviewSaveBtns.className = '';
	}
}

function updateShownFriends() {
	var friendFilter = document.getElementById('notifyFriendsSearch').value;
	if (friendFilter == 'Search Friends by Name') friendFilter = '';
	friendFilter = friendFilter.replace(/\s/g, '').toLowerCase();
	var friendFilterClear = document.getElementById('notifyFriendsSearchClear');
	if (!friendFilter) friendFilterClear.style.display = '';
	else friendFilterClear.style.display = 'block';
	$('.friend_post_wrapper .friend_wrapper_name_text').each(function() {
		var friend_link = this.parentNode.parentNode;
		if (!friendFilter) friend_link.style.display = '';
		else {
			try {
				var friend_node = this;
				var friend_name = friend_node.textContent;
				if (!friend_name) friend_name = friend_node.innerText;
				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) {}
		}
	});
}

function clearFriendFilter() {
	document.getElementById('notifyFriendsSearch').value = 'Search Friends by Name';
	document.getElementById('notifyFriendsSearchClear').style.display = 'none';
	updateShownFriends();
}

function showAlert(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:'';
}

function showHoverHint(div_id, hide) {
	var hoverElem = document.getElementById(div_id);
	var elemDisplay = (!hide? 'block' : '');
	hoverElem.style.display = elemDisplay;
}

function checkTriggerPaginate() {
	if (segmentFlags.cached && document.getElementById('photosTab').style.display == 'block') {
		if ($(document).scrollTop() + $(window).height() + 20 >= $(document).height()) {
			loadPage();
		}
	}
}

function addToFriendTab(uid, remove, first_name, last_name) {
	var attendee_id = 'attendee'+uid;
	var attendee_album_id = attendee_id+"_album";
	var attendee_wrapper = document.getElementById(attendee_id);
	var attendee_album_wrapper = document.getElementById(attendee_album_id);
	var friend_wrapper = document.getElementById('f'+uid);
	var attendee_div = document.getElementById('friendsTab');
	var attendee_album_div = document.getElementById('createMemoryAllPhotosFriendsList');
	var attendee_list_empty = document.getElementById('createMemoryAllPhotosFriendsListEmpty');
	if (attendee_div) {
		if (!remove) {
			if (!attendee_wrapper && (memoryCreationWizard.fb_owner && (uid != memoryCreationWizard.fb_owner || (editNight && uid == memoryCreationWizard.fb_owner))) || (!memoryCreationWizard.fb_owner && uid != loggedInUser)) {
				var full_name = getFullName(first_name, last_name);
				var load_fbml, fb_name_text = full_name;
				if (!full_name) {
					fb_name_text = '<fb:name uid="'+uid+'" capitalize="true" linked="false"></fb:name>';
					load_fbml = 1;
				}
				var friend_div_content = getPartnerLink(uid, 'profile_pic');//getLinkedProfilePic(uid, first_name, last_name);
				var new_attendee_div_wrapper = document.createElement('div');
				var new_attendee_album_div_wrapper = document.createElement('div');
				var new_attendee_div_html = '<a href="?p=f&fid='+uid+'"><div class="friend_wrapper" id="'+attendee_id+'"><div class="friend_wrapper_thumb"><img title="'+full_name+'" class="profile_pic" src="'+friend_div_content+'"></div><div class="friend_wrapper_name" style="color:white">'+fb_name_text+'</div>';
				// insert delete buttons
				if ((!editNight || userProfileObj.pairNewPoints) && uid != segmentData.fbOwner)	{
					new_attendee_div_html += '<div class="delete_btn" onclick="memoryCreationWizard.removeFriend(\''+uid+'\'); return false"></div>';
				}
				
				new_attendee_div_html += '</div></a>';
				new_attendee_div_wrapper.innerHTML = new_attendee_div_html;
				//if ((!editNight || userProfileObj.pairNewPoints) && uid != segmentData.fbOwner) friend_div_content += '<div class="small_delete_btn" onclick="addFbUserToNight(\''+uid+'\', 1)"></div>';
				new_attendee_album_div_wrapper.innerHTML = '<div id="'+attendee_album_id+'" class="friend_wrapper" onclick="memoryCreationWizard.unhideFriendAlbum(this, \'' + uid + '\')"><div class="friend_wrapper_thumb">' + '<img src="' + friend_div_content + '" class="profile_pic" title="'+ full_name +'"></div><div class="friend_wrapper_name">' + fb_name_text + '</div></div>';
				
				var new_attendee_div = new_attendee_div_wrapper.childNodes[0];
				var new_attendee_album_div = new_attendee_album_div_wrapper.childNodes[0];
				
				// insert and update elements
				if (!editNight || editNight && uid != loggedInUser) attendee_div.appendChild(new_attendee_div);
				if (attendee_album_div && (uid != segmentData.fbOwner && uid != loggedInUser) || (uid == segmentData.fbOwner && editNight)) attendee_album_div.appendChild(new_attendee_album_div);
				var wizardContributeCheck = !wizardMemoryData || (wizardMemoryData && segmentFlags.wizardShowContributeActive);
				//if (!editNight && wizardContributeCheck) updateAutoShowRemove('night_friend_pic_wrapper');
				if (!editNight) updateAutoShowRemove('friend_wrapper');
				if (friend_wrapper) friend_wrapper.className = 'friend_wrapper_selected';
				if (uid != segmentData.fbOwner) {
					segmentFriendFbIds[uid] = 1;
					memoryCreationWizard.selected_friends[uid] = 1;
				}
				if (load_fbml) {
					loadFBML(new_attendee_div);
					loadFBML(new_attendee_album_div);
				}
				updateTabStatus('friends', 1);
				if (attendee_list_empty) attendee_list_empty.style.display = 'none';
			}
		} else {
			if (attendee_wrapper) {
				attendee_div.removeChild(attendee_wrapper.parentNode); // remove the <a> wrapper instead of just the div
				if (attendee_album_div && attendee_album_wrapper) attendee_album_div.removeChild(attendee_album_wrapper);
				if (friend_wrapper) friend_wrapper.className = 'friend_wrapper';
				delete segmentFriendFbIds[uid];
				delete memoryCreationWizard.selected_friends[uid];
				updateTabStatus('friends', $('#friendsTab .friend_wrapper').length);
				if (attendee_album_div && !attendee_album_div.childNodes.length)
					attendee_list_empty.style.display = '';
			}
		}//updateFriendCount();
	}
}

/* 
 * voting functions
 */
 
function incrementVoteCount() {
	if (memoryCreationWizard.incrementVoteCount) {
		var vote_kptrid = memoryCreationWizard.vote_kptrid;
		if (vote_kptrid) writeToDB('deleteTag', [vote_kptrid], function() {createTagCount(parseInt(memoryCreationWizard.vote_count,10)+1)});
		delete memoryCreationWizard.incrementVoteCount;
	} else updateVoteCount(memoryCreationWizard.vote_count);
}

function getVoteCount(logged_off) {
	readFromDB('getTagsByObject', [{'objectType':'segment', 'objectIdValue':memoryCreationWizard.sid}], function(data) {showVoteCount(data, logged_off)});
}

function showVoteCount(data, logged_off) {
	var vote_count = parseVoteCount(data);
	if (vote_count) updateVoteCount(vote_count, logged_off);
	else createTagCount('1', logged_off);
}

function createTagCount(vote_count, logged_off) {
	writeToDB('createTag', [{'objectType':'segment', 'objectIdValue':memoryCreationWizard.sid,
		'name':memoryCreationWizard.app_id, 'partnerId_id':'18', 'partnerIdValue':vote_count}], function(data) {
			memoryCreationWizard.vote_kptrid = extractJSONid(data);
			updateVoteCount(vote_count, logged_off);
		});
}

function tagKapturAsWedding(sid){
	writeToDB('createTag',[{'objectType':'segment','objectIdValue':sid,'name':'wedding'}],null,false);
}

function updateVoteCount(vote_count, logged_off) {
	var voteWrapper = document.getElementById('voteWrapper');
	var voteCount = document.getElementById('voteCount');
	var voteBtn = document.getElementById('voteBtn');
	var vote_count_text = vote_count;
	if (!logged_off) {
		vote_count_text += ' Vote'+(vote_count!=1?'s':'');
		voteBtn.style.display = 'none';
	}voteCount.innerHTML = vote_count_text;
	voteWrapper.style.display = 'block';
	memoryCreationWizard.vote_count = vote_count;
}

function parseVoteCount(response) {
	response = JSON.parse(response);
	if (response['status'] == "ok") {
		var segment_tags = response['result'];
		if (segment_tags) {
			for (var i=0; i<segment_tags.length; i++) {
				var segment_tag = segment_tags[i];
				if (segment_tag['partnerId_id'] == '18' && segment_tag['name'] == memoryCreationWizard.app_id) {
					memoryCreationWizard.vote_kptrid = segment_tag['id'];
					return parseInt(segment_tag['partnerIdValue'], 10);
				}
			}
		}
	}return false;
}


function loadUserAlbums() {
	if (loggedInUser) {
		if (!memoryCreationWizard.userAlbumsLoaded) {
			memoryCreationWizard.loadAlbums(loggedInUser, memoryCreationWizard.displayUserAlbums);
			memoryCreationWizard.userAlbumsLoaded = 1;
		}
	}
}

/**
 * saves a bunch of photos in bulk.  all parameters are optional. all saved photos
 * must first be loaded in the memoryCreationWizard if they are to be saved
 * 
 * @param total_photos - (default memoryCreationWizard.new_photos) the number of photos
 *		being saved
 * @param photos_to_save - (default memoryCreationWizard.new_selected_photos) an
 *		array of pids for photos to save
 * @param callback - a function to call once the saving is finished
 */
function callBulkSave(total_photos, photos_to_save, callback) {
	// add photos
	total_photos = total_photos || memoryCreationWizard.new_photos;//+memoryCreationWizard.aviary_photos;
	if (total_photos) {
		//Temporary until we properly add points to slideshow on the fly
		//SlideShow.show_reload = true;
		readFromDB('getUniqueKapturIds', [2*total_photos, 'bulkIdsForAggregateCreatePointAndMedia|'+new Date().getTime()+'|'+memoryCreationWizard.sid], function(response) {
			response = JSON.parse(response);
			if (response['status'] == "ok") {
				var kptr_ids = response['result'];
				var num_kaptur_ids = arrayLength(kptr_ids);
				var photo_ids = [];
				var photo_times = [];
				var upload_photos = [];
				var photo_count = 0;
				var cookies_str = d_escape(JSON.stringify(parseCookies()));
				var point_ids = [];
				
				for (i = 0; i < num_kaptur_ids; i+=2) {
					point_ids.push(kptr_ids[i]);
				}
				
				photos_to_save = photos_to_save || memoryCreationWizard.new_selected_photos;
				for (var i in photos_to_save) {
					var upload_photo = 0;
					var media_content = memoryCreationWizard.loaded_photos[i];
					var photo_time = media_content['utc_time_second'];
					var owner_facebook_id = media_content['owner_facebook_id'] || loggedInUser;
					
					loadFacebookName(owner_facebook_id);
					
					if (!has_segment_point_table) {
						photo_time = memoryCreationWizard.adjustPointTime(photo_time);
					}
					
					photo_time = getUniqueTime(photo_time);
					photo_times.push(photo_time);
					memoryCreationWizard.loaded_photos[i]['utc_time_second'] = photo_time;
					var point_id = kptr_ids[2*photo_count];
					var media_id = kptr_ids[2*photo_count+1];
					fbPhotoPointIds[i] = point_id;
					if (media_content['uploaded']) {
						upload_photos.push(media_content);
						upload_photo = 1;
					} else photo_ids.push(i);
					//loadFacebookName(media_content['owner_facebook_id']);
					var point_args = {
						'user_id':userProfileObj.id,
						'utcTimeSec':photo_time,
						'description':media_content['description'],//d_escape()
						'partnerId_id':(upload_photo?16:4),
						'partnerIdValue': owner_facebook_id,
						'service':(upload_photo?SERVICE_TYPES.kaptur:SERVICE_TYPES.facebook),
						'timezoneOffset':memoryCreationWizard.timezone_offset,//-new Date().getTimezoneOffset()/60,
						'privacy':'public',
						'width':media_content['width'],
						'height':media_content['height'],
						'media_type_id':media_content['id'],
						'media_src':media_content['source'],
						'src_high_res':media_content['src_high_res'],
						'media_thumb':media_content['thumbnail'],
						'media_id':media_id
					};
					rmnPoints[point_id] = point_args;
					photo_count++;
					// set album cover if it's not set
					if (!memoryCreationWizard.weddingCover) setWeddingCover(media_content['id'], 0, point_id);
				}
				upload_photos = d_escape(JSON.stringify(upload_photos));
				
				var params = [{
					'kptr_ids':kptr_ids,
					'pids':photo_ids,
					'friend_ids':'',
					'utctimes':photo_times,
					'user_id':userProfileObj.id,
					'app_id':memoryCreationWizard.app_id,
					'tzoffset':memoryCreationWizard.timezone_offset,
					'segment_id':memoryCreationWizard.sid,
					'cookies':cookies_str,
					'memory_thumb':memoryCreationWizard.weddingCover,
					'aviary_photos':'',
					'upload_photos':upload_photos
				}];//-new Date().getTimezoneOffset()/60
			
				if (window.has_segment_point_table) {
					params[0]['use_segment_point_table'] = memoryCreationWizard.sid;
				}
				
				if (editNight) params[0]['contribute_rmnid'] = memoryCreationWizard.owner_id;
				writeToDB("addDataInBulkFromWizard", params, function () {
					addPointsToSegmentPointTable(memoryCreationWizard.sid, point_ids, photo_times);
					saveCompleteShowContribute();
					safeCall(callback);
				}, 1);
				wizardMemoryData = 1;
				setTimeout(function () {
					if (!segmentFlags.wizardShowContributeActive) {
						addPointsToSegmentPointTable(memoryCreationWizard.sid, point_ids, photo_times);
						saveCompleteShowContribute();
						safeCall(callback);
					}
				}, 45000);
				
				// insert items into canvas
				for (var i in photos_to_save) {
					var media_content = memoryCreationWizard.loaded_photos[i];
					insertCanvasItem({'id':i, 'title':media_content['description'], 'content':media_content['source'], 'grid_thumb': media_content['thumbnail'], 'utctime':media_content['utc_time_second'], 'service':SERVICE_TYPES.facebook});
				}
				
				// reset data in memory
				memoryCreationWizard.new_photos = 0;
				memoryCreationWizard.new_selected_photos = {};
			}
		});
	} else {
		safeCall(callback);
	}
	
	// delete photos
	var removed_points = [];
	var remove_selected_photos = memoryCreationWizard.remove_selected_photos;
	for (var i in remove_selected_photos) {
		var point_id = fbPhotoPointIds[i];
		if (point_id) removed_points.push(point_id);
	}
	
	if (removed_points.length) {
		kapturDb.removePointsFromSegment(memoryCreationWizard.sid, removed_points);
		writeToDB('deletePoints', [removed_points], '', 1);
	}
	
	for (var i in remove_selected_photos) {
		if (i == memoryCreationWizard.weddingCover) chooseClearAlbumCover();
		removeCanvasItem(i, {'no_write':1});
	}
	memoryCreationWizard.remove_selected_photos = {};
	
	// flag slideshow reload
	if (total_photos || removed_points.length) weddingCoverSlideshow.flagReload();
}

function chooseClearAlbumCover() {
	updateFromKapturPhotos();
	if ($('#createMemoryAllPhotosKapturPhotos').children().length)
		$('#createMemoryAllPhotosKapturPhotos').children()[0].onclick();
	else setWeddingCover('');
}

function mirrorDateField(part, adv, no_update) {
	var basic_field = document.getElementById('memoryStartBasic'+part);
	var adv_field = document.getElementById('memoryStart'+part);
	if (adv) {
		basic_field.value = adv_field.value;
		delete dataFlags.lastBasicDateEdit;
	} else {
		var basic_value = basic_field.value;
		adv_field.value = basic_value;
		if (!basic_value) document.getElementById('memoryEnd'+part).value = '';
		// update end date to be 36 hrs from start date
		updateStartEndDates(1);
		dataFlags.lastBasicDateEdit = 1;
	}
}

function showCallout(id, evt, left) {
	var calloutWrapper = document.getElementById('calloutOverlayWrapper');
	var calloutContents = document.getElementById('calloutOverlayContents');
	var calloutBlur = document.getElementById('calloutOverlayBlur');
	if (id) {
		if (memoryCreationWizard.lastCallout != id) {
			var hint_text = callout_text[id];
			if (hint_text) {
				if(id == 'date_alert'){
					if(!this.dataFlags.segmentCreated || window.has_segment_point_table){
						return;
					}
					else{
						if(!this.dateAlertFlag){
							this.dateAlertFlag = true;
							//setTimeout('showCallout()',1500);
							setTimeout('this.dateAlertFlag = false;',30000);
						}
						else{
							memoryCreationWizard.lastCallout = id;
							//showCallout();
							return;
						}
					}
				}
				if (!evt) evt = window.event;
				if (evt && evt.clientX && evt.clientY){
					calloutWrapper.style.left = evt.clientX+(left?-293:0)+'px';
					calloutWrapper.style.top = $(document).scrollTop()+6+evt.clientY+'px';
				}
				calloutContents.innerHTML = hint_text;
				calloutWrapper.className = (left?'left':'');
				calloutWrapper.style.display = 'block';
				if (!isMobile()) calloutBlur.focus();
			}memoryCreationWizard.lastCallout = id;
			if (memoryCreationWizard.calloutBlurTimer) {
				clearTimeout(memoryCreationWizard.calloutBlurTimer);
				delete memoryCreationWizard.calloutBlurTimer;
			}
		} else {
			showCallout();
			delete memoryCreationWizard.lastCallout;
		}
	} else {
		calloutWrapper.style.display = '';
		delete memoryCreationWizard.lastCallout;
	}
}

function showFirstCallout() {
	if (memoryCreationWizard.showFirstTimeCallouts) {
		var first_callout = $('#'+memoryCreationWizard.activeTab+' .callout_indicator:first');
		var first_callout_index = $('.callout_indicator').index(first_callout);
		if (!memoryCreationWizard.firstCalloutCalled) memoryCreationWizard.firstCalloutCalled = {};
		if (!memoryCreationWizard.firstCalloutCalled[first_callout_index]) {
			var offset = first_callout.offset();
			first_callout.click();
			$('#calloutOverlayWrapper').css('top', offset.top+7).css('left', offset.left+12);
			memoryCreationWizard.firstCalloutCalled[first_callout_index] = 1;
		}
	}
}

function calloutBlur() {
	memoryCreationWizard.calloutBlurTimer = setTimeout('showCallout()',100);
}

function toggleBeyonce(expand) {
	var memoryBgEdit = document.getElementById('memoryBgEdit');
	var memorySummaryWrapper = document.getElementById('memorySummaryWrapper');
	var memoryEditWrapper = document.getElementById('memoryEditWrapper');
	var memoryEditContents = document.getElementById('memoryEditContents');
	var topNavCenter = document.getElementById('topNavCenter');
	var topNavShareBtn = document.getElementById('topNavShareBtn');
	var tab_bg = document.getElementById('pageTabBg');
	var tab_wrapper = document.getElementById('pageTabWrapper');
	var tab = document.getElementById('beyonceTab');
	if (expand == null) expand = !tab.style.display;
	if (expand) {
		memoryBgEdit.style.height = '0';
		memoryBgEdit.style.overflow = 'hidden';
		memorySummaryWrapper.style.height = '0';
		memorySummaryWrapper.style.overflow = 'hidden';
		memoryEditWrapper.style.minHeight = '0';
		memoryEditContents.style.height = '0';
		memoryEditContents.style.overflow = 'hidden';
		topNavCenter.style.display = 'none';
		topNavShareBtn.style.display = 'none';
		tab_bg.style.display = 'block';
		tab_wrapper.style.display = 'block';
		tab.style.display = 'block';
	} else {
		memoryBgEdit.style.height = '';
		memoryBgEdit.style.overflow = '';
		memorySummaryWrapper.style.height = '';
		memorySummaryWrapper.style.overflow = '';
		topNavCenter.style.display = '';
		topNavShareBtn.style.display = '';
		tab_bg.style.display = '';
		tab_wrapper.style.display = '';
		tab.style.display = '';
		memoryEditWrapper.style.minHeight = '';
		memoryEditContents.style.height = '';
		memoryEditContents.style.overflow = '';
		$.scrollTo({top: '0px', left: '0px'}, 0);
	}
}

function toggleBeyonceAdSection(expand){
	if (expand){
		$("#beyonceAboutSectionAdWrapper").css("display","block");
	} else {
		if ($("#advancedSettingsWrapper").css("display")=="none"){
			$("#beyonceAboutSectionAdWrapper").css("display","block");
		} else {
			$("#beyonceAboutSectionAdWrapper").css("display","none");
		}
	}
}

function toggleQuickstart (expand) {
	var memoryBgEdit = document.getElementById('memoryBgEdit');
	var memorySummaryWrapper = document.getElementById('memorySummaryWrapper');
	var memoryEditWrapper = document.getElementById('memoryEditWrapper');
	var memoryEditContents = document.getElementById('memoryEditContents');
	var topNavCenter = document.getElementById('topNavCenter');
	var topNavShareBtn = document.getElementById('topNavShareBtn');
	var tab_bg = document.getElementById('pageTabBg');
	var tab_wrapper = document.getElementById('pageTabWrapper');
	var tab = document.getElementById('quickstartTab');
	if (expand == null) expand = !tab.style.display;
	if (expand) {
		memoryBgEdit.style.height = '0';
		memoryBgEdit.style.overflow = 'hidden';
		memorySummaryWrapper.style.height = '0';
		memorySummaryWrapper.style.overflow = 'hidden';
		memoryEditWrapper.style.minHeight = '0';
		memoryEditContents.style.height = '0';
		memoryEditContents.style.overflow = 'hidden';
		topNavCenter.style.display = 'none';
		topNavShareBtn.style.display = 'none';
		tab_bg.style.display = 'block';
		tab_wrapper.style.display = 'block';
		tab.style.display = 'block';
	} else {
		memoryBgEdit.style.height = '';
		memoryBgEdit.style.overflow = '';
		memorySummaryWrapper.style.height = '';
		memorySummaryWrapper.style.overflow = '';
		topNavCenter.style.display = '';
		topNavShareBtn.style.display = '';
		tab_bg.style.display = '';
		tab_wrapper.style.display = '';
		tab.style.display = '';
		memoryEditWrapper.style.minHeight = '';
		memoryEditContents.style.height = '';
		memoryEditContents.style.overflow = '';
		$.scrollTo({top: '0px', left: '0px'}, 0);
	}
}

function startMusic() {
	var bottomNavWrapper = document.getElementById('bottomNavWrapper');
	if (bottomNavWrapper) {
		bottomNavWrapper.style.display = 'block';
		startPartnerAudio();
		/*var so = new SWFObject('http://www.youtube.com/v/roLfyuXT9zA?version=3&enablejsapi=1&autoplay=1&playerapiid=musicPlayer', 'musicPlayer', 1, 1, "8", "#000000"); // e/mmBHs5vS3_s
		so.addParam("allowScriptAccess", "always");
		so.addParam("wmode", "transparent");
		so.write('musicPlayerContents');*/
		//document.getElementById('musicPlayer').innerHTML = embedVideo('http://www.youtube.com/e/mmBHs5vS3_s?version=3&enablejsapi=1&autoplay=1&playerapiid=musicPlayer', {'return_html':1})
	}
}

function togglePlayMusic(play) {
	/*var playPause = document.getElementById('musicPlayPause');
	var musicPlayer = document.getElementById('musicPlayer');
	if (musicPlayer) {
		var btn_class = 'play';
		if ((play != null && play === 0) || (play == null && playPause.className == 'pause')) {
			musicPlayer.pauseVideo();
		} else {
			musicPlayer.playVideo();
			btn_class = 'pause';
		} playPause.className = btn_class;
	}*/
	var musicPlayPause = document.getElementById('musicPlayPause');
	if (musicPlayPause && window.audioInitialized && audioInitialized) {
		var btn_class = 'play';
		if ((play != null && play === 0) || (play == null && musicPlayPause.className == 'pause')) {
			if (allowPartnerAudio) $("#jplayer").jPlayer("pause");
		} else {
			if (allowPartnerAudio) $("#jplayer").jPlayer("play");
			btn_class = 'pause';
		}musicPlayPause.className = btn_class;
	}
}

function toggleMuteMusic() {
	/*var muteBtn = document.getElementById('musicMute');
	var musicPlayer = document.getElementById('musicPlayer');
	var btn_class = 'unmute';
	if (muteBtn.className == 'mute') {
		musicPlayer.mute();
	} else {
		musicPlayer.unMute();
		btn_class = 'mute';
	} muteBtn.className = btn_class;*/
	var musicMute = document.getElementById('musicMute');
	var btn_class = 'unmute';
	if (allowPartnerAudio) {
		if ($("#jplayer").jPlayer("getData", "volume") != 0) {
			$("#jplayer").jPlayer("volumeMin");
		} else {
			$("#jplayer").jPlayer("volume", 75);
			btn_class = 'mute';
		}
	} else {
		SlideShow.toggleMute();
		if (musicMute.className != 'mute') btn_class = 'mute';
	}
	musicMute.className = btn_class;
	// else alertSongHasExpired();
}

function showHideMusicBar(hide) {
	if (memoryCreationWizard.musicBarState != hide) {
		if ($('#nightSlideShowWrapper').parent().hasClass('hidden') && hide) return;
		$('#bottomNavWrapper').animate({
			bottom: (hide?'-':'+')+'=42'
		}, {queue: true});
		memoryCreationWizard.musicBarState = hide;
	}
}

function startPartnerAudio() {
	allowPartnerAudio = true;
	$("#jplayer").jPlayer("play");
	document.getElementById('musicMute').className = 'mute';
}

function togglePhotosTimeline(update) {
	var photosTimelineBtn = document.getElementById('photosTimelineBtn');
	var photosTimeline = document.getElementById('photosTimeline');
	var photoBooksAd = document.getElementById('photoBooksAdWrapper');
	if (update) {
		var num_sections = 10, border_width = 2;
		var chrome_offset = (navigator.userAgent.indexOf('Safari') != -1)? 5 : 0;
		var start_time = parseInt(getAdjustedTimeWrap(memoryCreationWizard.start_time).getTime()/1000, 10);
		var end_time = parseInt(getAdjustedTimeWrap(memoryCreationWizard.end_time).getTime()/1000, 10);
		var memory_length = end_time - start_time;
		var section_length = memory_length / num_sections;
		var timeline_height = Math.max($(window).height() - 180, 425);
		var section_height = (timeline_height-((num_sections-1)*border_width))/num_sections;
		photosTimeline.style.height = timeline_height+'px';
		var timeline_html = '';
		for (var i=0; i<num_sections; i++) {
			var even_section = !(i%2);var last_section = (i == num_sections-1);
			var last_section_position = last_section?' style="position:relative;top:'+(parseInt(section_height,10)+parseInt(border_width,10)+chrome_offset)+'px"':'';
			var bar_time = even_section || last_section ? '<div class="photos_timeline_date"'+last_section_position+'>'+formatTimeStr(start_time + (!last_section?i:(i+1))*section_length, 'timeline')+'</div>' : '';
			timeline_html += '<div class="photos_timeline_bar" style="width:'+(even_section?'70':'35')+'%;height:'+section_height+'px">'+bar_time+'</div>';
		}photosTimeline.innerHTML = timeline_html;
	} else {
		if (!memoryCreationWizard.organizeActive) {
			photosTimeline.style.display = 'block';
			photosTimelineBtn.className = 'up';
			photoBooksAd.style.display = 'none';
			memoryCreationWizard.organizeActive = 1;
		} else {
			photosTimelineBtn.className = '';
			photosTimeline.style.display = '';
			photoBooksAd.style.display = '';
			delete memoryCreationWizard.organizeActive;
			clearOrganizeOutlines();
		}
	}
}

function showHideTimelineTime(evt, hide) {
	var photosTimelineBubble = document.getElementById('photosTimelineBubble');
	var display_style = '';
	if (!hide) {
		if (!evt) evt = window.event;
		var top_offset = 85, indicator_offset = 18, timeline_height = $('#photosTimeline').height();
		var scroll_top = $(document).scrollTop();
		//photosTimelineBubble.style.left = evt.clientX+'px';
		var bubble_offset = scroll_top + Math.min(top_offset+timeline_height+1, evt.clientY) - indicator_offset;
		photosTimelineBubble.style.top = bubble_offset+'px';
		var timeline_ratio = Math.max(0, Math.min(1, (evt.clientY - top_offset) / timeline_height));
		var start_time = parseInt(memoryCreationWizard.start_time.getTime(), 10);
		var end_time = parseInt(memoryCreationWizard.end_time.getTime(), 10);
		var memory_length = end_time - start_time;
		var cursor_time = start_time + (memory_length*timeline_ratio);
		memoryCreationWizard.timelineCursorTime = parseInt(cursor_time/1000, 10);
		cursor_time = parseInt(getAdjustedTimeWrap(new Date(cursor_time)).getTime()/1000, 10);
		photosTimelineBubble.innerHTML = formatTimeStr(cursor_time, 'timeline_indicator');
		display_style = 'block';
	}
	photosTimelineBubble.style.display = display_style;
}

function moveCanvasItemsTimeline() {
	var media_wrapper_ids = [];
	for (var i in memoryCreationWizard.organize_ids) {
		if (typeof i == 'string') media_wrapper_ids.push(i);
	}
	
	if (media_wrapper_ids.length) {
		var canvas_row = document.getElementById('nightCanvasRow');
		for (var i=0; i<media_wrapper_ids.length; i++) {
			var media_wrapper_id = media_wrapper_ids[i];
			var item = document.getElementById(media_wrapper_id);
			if (item) {
				var media_point_id = item.getAttribute('point_id');
				if (rmnPoints[media_point_id]) {
					rmnPoints[media_point_id].utcTimeSec = getUniqueTime(memoryCreationWizard.timelineCursorTime).toString();
					item.parentNode.removeChild(item);
					addStreamItemToStream(item, 'nightCanvasRow');
					saveTime(media_point_id);
				}
			}
		}
		var loading_img = TEMPLATE_VIEW_PATH+"images/canvas_loading.png"; // .night_img_big[src='"+loading_img+"'], 
		$(".night_img_thumb[src='"+loading_img+"']").lazyload({placeholder : loading_img, event:"updatecanvas"});
		$(".night_img_thumb[src='"+loading_img+"']").lazyload({placeholder : loading_img});
		clearOrganizeOutlines();
		
		// flag slideshow reload
		weddingCoverSlideshow.flagReload();
	}
}

function clearOrganizeOutlines() {
	for (var i in memoryCreationWizard.organize_ids) {
		if (typeof i == 'string') {
			document.getElementById(i).style.borderColor = '';
		}
	}
	memoryCreationWizard.organize_ids = {};
}

function initializeQuickstart() {
	if (dataFlags.quickstartInitialized) {
		return;
	}
	
	dataFlags.quickstartInitialized = true;
	kaptur_quickstart.user_kaptur_id = userProfileObj.id;
	kaptur_quickstart.user = {
		kaptur_id : userProfileObj.id,
		facebook_id : loggedInUser,
		first_name : userProfileObj.first_name,
		last_name : userProfileObj.last_name
	};
	kaptur_quickstart.onFacebookAndDocumentReady();
	
	//overwrite the event handler so that it can use this segment
	$('.create_segment_button').unbind('click', kaptur_quickstart.handleCreateSegmentClicked);
	$('.create_segment_button').bind('click', handleSaveQuickstart);
}

function handleSaveQuickstart() {
	var segment_id, kaptur_ids;
	bulkSaveQuickstart();
}

function bulkSaveQuickstart() {
	var segment_id = segmentData.id || memoryCreationWizard.sid,
		purpose = 'bulkIdsForAggregateCreatePointAndMedia|' + new Date().getTime() +
			'|' + segment_id,
		wedding_time_bounds = kaptur_quickstart.getWeddingTimeBounds(),
		start = wedding_time_bounds.start,
		end = wedding_time_bounds.end,
		num_ids, photos, num_photos;
	
	kaptur_quickstart.start = start;
	kaptur_quickstart.end = end;
	photos = kaptur_quickstart.collectPhotos();
	photos = kaptur_quickstart.removeDeletedPhotos(photos);
	num_photos = arrayLength(photos);
	num_ids = (num_photos * 2);// + arrayLength(kaptur_quickstart.users_array);
	
	kapturDb.getUniqueKapturIds(num_ids, purpose, function (kaptur_ids) {
		var memoryBulkSave = kaptur_quickstart.createMemoryBulkSave(segment_id, kaptur_ids, photos);
		
		//do not add the friend_ids via bulk because they will be added when
		//the user hits save on the add/edit lightbox
		//memoryBulkSave.friend_ids = [];
		
		//set quickstart to use the app id for beyonce
		kaptur_quickstart.app_id = 20;
		kaptur_quickstart.segment_id = segment_id;
		kaptur_quickstart.createNewSegment(function () {
			dataFlags.segmentCreated = 1;
			
			importQuickstartSegmentData();
			importQuickstartPhotos();
			importQuickstartFriends();
			setWeddingCover(memoryBulkSave.memory_thumb);
			toggleQuickstart(false);
			writeToDB("addDataInBulkFromWizard", [memoryBulkSave], onQuickstartSaved, 1);
		});
	});
}

function onQuickstartSaved () {
	
}

function importQuickstartFriends () {
	var kaptur_quickstart = window.kaptur_quickstart,
		memoryCreationWizard = window.memoryCreationWizard,
		friends = kaptur_quickstart.users_array,
		friends_length = friends.length,
		i, friend, facebook_id;
	for(i = 0; i < friends_length; i++) {
		friend = kaptur_quickstart.normalizeUser(friends[i]);
		facebook_id = friend['uid'];
		memoryCreationWizard.loaded_friends[facebook_id] = friend;
		memoryCreationWizard.selected_friends[facebook_id] = true;
		memoryCreationWizard.bulk_saved_friends[facebook_id] = true;
		toggleFriendSelected(facebook_id, false, friend.first_name, friend.last_name, true);
		addToAttendList(friend.facebook_id, false, friend.first_name, friend.last_name);
	};
}

function importQuickstartPhotos () {
	var photos = kaptur_quickstart.removeDeletedPhotos(kaptur_quickstart.collectPhotos()),
		normalizePhoto = kaptur_quickstart.normalizePhoto,
		photos_div = $('#nightCanvasRow'),
		i, photo, id, title, content, utc_time, service, num_photos, thumb;
	
	if ($.browser.msie) {
		photos = photos.slice(0,999);
	}
	
	num_photos = photos.length;
	
	//hide the row while it updates to make it more efficient
	photos_div.css('display', 'none');
	
	for (i = 0; i < num_photos; i++) {
		photo = normalizePhoto(photos[i]);
		
		memoryCreationWizard.loaded_photos[photo['pid']] = photo;
		memoryCreationWizard.togglePhotoSelected(null, photo['pid']);
		
		id = photo['pid'];
		title = photo['title'] || '';
		content = photo['source'];
		utc_time = photo['utc_time_second'];
		service = SERVICE_TYPES.facebook;
		thumb = photo['thumbnail'];
		
		insertCanvasItem({
			'id': id,
			'title': title,
			'content': content,
			'utctime': utc_time,
			'service': service
		}, true); //skip lazyloading
	};
	
	//redisplay the div
	photos_div.css('display', '');
	
	memoryCreationWizard.new_photos = 0;
	memoryCreationWizard.new_selected_photos = {};
}

function importQuickstartSegmentData () {
	var memory_title = $('#memoryTitle, .top_nav_title'),//#topNavTitle
		start_month = $('#memoryStartBasicMonth'),
		start_day = $('#memoryStartBasicDay'),
		start_year = $('#memoryStartBasicYear'),
		start_am_pm = $('#memoryStartAMPM'),
		memory_tzoffset = $('#nightSummaryTZ'),
		start_date = new Date(kaptur_quickstart.start * 1000),
		end_date = new Date(kaptur_quickstart.end * 1000),
		timezone_offset;
	
	memory_title.val(kaptur_quickstart.title);
	
	timezone_offset = start_date.getTimezoneOffset() / -60;
	memory_tzoffset.find('option[selected="selected"]').removeAttr('selected');
	memory_tzoffset.find('option[value="' + timezone_offset + '"]').attr('selected', 'selected');
	start_month.val(start_date.getMonth() + 1);
	mirrorDateField('Month', '');
	start_day.val(start_date.getDate());
	mirrorDateField('Day', '');
	start_year.val(start_date.getFullYear());
	mirrorDateField('Year', '');
	
	updateMemoryInfo();
}

function goToProfile() {
	var ref_param = '';
	var ref_regex = new RegExp('&(aff|ref)=([^&]*)');
	if (location.href.match(ref_regex)) ref_param += '&'+RegExp.$1+'='+RegExp.$2;
	var profilePage = function() {location.href = '?p=f&btn=mykapturs'+ref_param;}
	if (!loggedInUser) {
		loginToFacebook(profilePage);
	} else {
		profilePage();
	}
	//authAction('profile');
}

function updateFromKapturPhotos(point_id, remove) {
	if (!point_id && !dataFlags.fromKapturPhotosLoaded) {
		var kapturCoverHtml = '', photobookPhotoHtml = '';
		var unique_thumbs = {};
		for (var i in rmnPoints) {
			// handle duplicates
			if (rmnPoints[i]['partnerIdValue']) {
				var cover_thumb = addRemoveFromKapturCoverSelect(i, 1);
				var cover_thumb_id = cover_thumb[0];
				if (!unique_thumbs[cover_thumb_id]) {
					kapturCoverHtml += cover_thumb[1];
					photobookPhotoHtml += cover_thumb[2];
					unique_thumbs[cover_thumb_id] = 1;
				}
			}
		}
		var createMemoryAllPhotosKapturPhotos = document.getElementById('createMemoryAllPhotosKapturPhotos');
		createMemoryAllPhotosKapturPhotos.innerHTML = kapturCoverHtml;
		createMemoryAllPhotosKapturPhotos.style.display = kapturCoverHtml?'':'none';
		document.getElementById('createMemoryAllPhotosKapturPhotosEmpty').style.display = !kapturCoverHtml?'block':'';
		document.getElementById('photobookPhotoSelector').innerHTML = photobookPhotoHtml;
		dataFlags.fromKapturPhotosLoaded = 1;
	} else if (point_id && dataFlags.fromKapturPhotosLoaded) addRemoveFromKapturCoverSelect(point_id, 0, remove);
}

function addRemoveFromKapturCoverSelect(point_id, return_html, remove) {
	var kaptur_photo_thumb;
	var point_data = rmnPoints[point_id];
	var img_id = point_data['media_type_id'];
	var img_type = point_data['partnerId_id'];
	if (img_id && in_array(img_type, [1,4,14,16,17])) {
		var createMemoryAllPhotosKapturPhotos = document.getElementById('createMemoryAllPhotosKapturPhotos');
		var photobookPhotoSelector = document.getElementById('photobookPhotoSelector');
		var img_thumb_id = 'kapturPhotos'+img_id;
		var photobook_thumb_id = 'photobookPhotos'+img_id;
		var img_elem = document.getElementById(img_thumb_id);
		var photobook_img_elem = document.getElementById(photobook_thumb_id);
		if (!remove) {
			var img_src = point_data['media_thumb'];
			var photo_selected = memoryCreationWizard.weddingCover == img_id;
			var kaptur_photo_thumb_html = '<div id="'+img_thumb_id+'" onclick="setWeddingCover(\''+img_id+'\', 0, \''+point_id+'\')" class="create_memory_photo'+(photo_selected?' create_memory_photo_selected':'')+'"><img src="'+img_src+'"></div>';
			var photobook_photo_thumb_html = '<div id="'+photobook_thumb_id+'" onclick="changePhotobookPhoto({\'point_id\':\''+point_id+'\', \'src_elem\':this})" class="create_memory_photo"><img src="'+img_src+'"></div>';
			if (return_html) return [img_id, kaptur_photo_thumb_html, photobook_photo_thumb_html];
			kaptur_photo_thumb = document.createElement('div');
			kaptur_photo_thumb.innerHTML = kaptur_photo_thumb_html;
			if (!img_elem) createMemoryAllPhotosKapturPhotos.appendChild(kaptur_photo_thumb.childNodes[0]);
			kaptur_photo_thumb.innerHTML = photobook_photo_thumb_html;
			if (!photobook_img_elem) photobookPhotoSelector.appendChild(kaptur_photo_thumb.childNodes[0]);
		} else {
			if (img_elem) img_elem.parentNode.removeChild(img_elem);
			if (photobook_img_elem) photobook_img_elem.parentNode.removeChild(photobook_img_elem);
		}
		var num_photos = createMemoryAllPhotosKapturPhotos.childNodes.length;
		createMemoryAllPhotosKapturPhotos.style.display = num_photos?'block':'';
		document.getElementById('createMemoryAllPhotosKapturPhotosEmpty').style.display = !num_photos?'block':'';
	}return ['', '', ''];
}

weddingCoverSlideshow = {
	loaded : false, //  has the slideshow data been loaded yet
	music : null, resize_timer : null,
	container_id : 'memoryCoverWrapper',  // the id of the container for the slideshow
	music_container_id : 'slideshowMusic',
	
	/**
	 * Flags slideshow to reload when clicking start again
	 */
	flagReload : function(delayed) {
		if (delayed) {
			delete this.loaded;
			delete this.no_cover_skip;
			delete this.currentImg;
			this.reloadFlagged = 1;
		} else setTimeout('weddingCoverSlideshow.flagReload(1)', 1000);
	},
	
	/**
	 * Sets up slideshow as background 
	 */
	initBg : function() {
		this.initialize();
		this.initialize(); //this.display();
		//this.load(this.hideSlideshowStatuses); // hide statuses by default
		
		// load cover image
		var memory_cover = [{'type':'photo', 'metadata':{
			'src':memoryCreationWizard.thumb,
			'alt_src':memoryCreationWizard.thumb_big?memoryCreationWizard.thumb_big:'',
			'width':memoryCreationWizard.thumb_width,
			'height':memoryCreationWizard.thumb_height
		}}];
		this.load(null, memory_cover);
	},
	
	/**
	 * hides slideshow statuses by default
	 */
	hideSlideshowStatuses : function() {
		SlideShow.toggleHideSlideshowStatuses();
		$('#slideshowToggleHidden').css('display', 'none');
	},
	
	/**
	 * Sets up the initialization of the slideshow
	 */
	initialize : function () {
		SlideShow.json = "";
		SlideShow.slideshow_id = weddingCoverSlideshow.container_id;
		SlideShow.facebook_div_id = "nightSlideShowFacebookStatuses";
		SlideShow.display_facebook_video_width = 540;
		SlideShow.display_facebook_video_height = 480;
		SlideShow.display_youtube_video_width = 540;
		SlideShow.display_youtube_video_height = 480;
		SlideShow.display_spacing = 0;
		SlideShow.display_padding = 0;
		SlideShow.display_facebook_height = 54;
		SlideShow.autoscroll_speed = 2000;
		SlideShow.autoscroll_video_wait = 9000;
		SlideShow.autoscroll_photo_wait = 3000;
		SlideShow.autoscroll_facebook_wait = 4000;
		SlideShow.cross_fade_speed = 500;
		SlideShow.video_preload_amount = 1500;
		SlideShow.facebook_userpic_width = 50;
		SlideShow.facebook_userpic_height = 50;
		SlideShow.max_post_length = 120;
		SlideShow.video_offset = 0;
		SlideShow.auto_replay = true;
		SlideShow.replay_image = TEMPLATE_VIEW_PATH+"/images/replayimage.png";
		SlideShow.flashcover = TEMPLATE_VIEW_PATH+"/images/ieflashcover.png";
		SlideShow.ieflashcover = TEMPLATE_VIEW_PATH+"/images/ieflashcover.png";
		SlideShow.title_div_id = "slideshowTitle";
		SlideShow.initialize("movie");
		this.updateSlideshowSize();
		
		// set event handlers
		$('#memorySlideshowControls').css('display', 'block');
		$("#memoryCoverPageWrapper, #memoryBgEdit").unbind();
		if (isMobile()) $("#memoryCoverPageWrapper, #memoryBgEdit, #slideshowPlay").bind('click', function() { SlideShow.toggleAllControls() });
		else $("#memoryCoverPageWrapper, #memoryBgEdit").bind('mousemove', (SlideShow.mouseMoveControlsHandler)());
		
		
		$(window).resize(function () {
			clearTimeout(weddingCoverSlideshow.resize_timer);
			SlideShow.resize_timer = setTimeout(weddingCoverSlideshow.updateSlideshowSize, 250);
		}); //$("#memoryCoverPageWrapper").bind('click', function() {$('#slideshowPlay').click();});
	},
	
	/**
	 * resize and center slideshow
	 * done here.
	 */
	updateSlideshowSize : function () {
		var win_width = $(window).width();
		var win_height = $(window).height();
		SlideShow.updateImgRes(win_width, win_height);
		var width = Math.max(983, win_width);// - $('#memorySummaryWrapper').outerWidth(),
		var height = win_height;// - $('#topNavCenterWrapper').outerHeight();
		SlideShow.display_width = width;
		SlideShow.display_height = height;
		SlideShow.displaycase.css({'width':width, 'height':height});
		SlideShow.slideshow.css({'width':width, 'height':height});
		SlideShow.display_facebook_width = Math.max(0, width - 400);
		SlideShow.next();
		SlideShow.previous();
		
		// center slideshow controls
		$('#memorySlideshowControls, #musicPlayerWrapper').css('left', (width-$('#memorySlideshowControls').outerWidth())/2+'px');
	},
	
	/**
	 * Use this to adjust the display for the slideshow.  Some of the display
	 * is set up by initialize since the slideshow does that automatically.  Anything
	 * else related solely to manipulating how things are displayed should be
	 * done here.
	 */
	display : function () {
		var backstretch = $('#backstretch'),
			top_bar_height = 0,//$('#topNavCenterWrapper').height(),
			cover_image = $('#memoryCover'),
			slideshow_container = $('#' + weddingCoverSlideshow.container_id);
		
		cover_image.hide();
		backstretch.remove();
		slideshow_container.css({
			position: 'absolute',
			top: top_bar_height,
			left: 0
		});
	},
	
	/**
	 * loads the slideshow json from the database then passes the parsed result
	 * to a callback function
	 */
	loadFromDatabase : function (callback) {
		this.db_load_called = 1;
		jx.load("?p=slideshowJSON&sid="+memoryCreationWizard.sid+"&cache=true", function(data) {
			if (data == '{}') data = '[]';
			if (data) data = JSON.parse(data);
			weddingCoverSlideshow.loaded = true;
			safeCall(callback, [data]);
		});
	},
	
	/**
	 * Initializes the slideshow and fills it with data.  It does both because
	 * the slideshow needs to be initialized before it can have data loaded
	 * into it.
	 */
	load : function (callback, data) {
		if (!data) {
			weddingCoverSlideshow.loadFromDatabase(function (data) {
				weddingCoverSlideshow.initialize();
				if (!dataFlags.partnerMusic) {
					weddingCoverSlideshow.getMusic(data);
					weddingCoverSlideshow.displayMusic(weddingCoverSlideshow.music, weddingCoverSlideshow.musicThumb, weddingCoverSlideshow.musicTitle);
				}
				SlideShow.loadData(data);
				safeCall(callback);
			});
		} else SlideShow.loadData(data);
	},
	
	/**
	 * loads the slideshow if it is not loaded yet then executes the function
	 * that was attempted
	 * 
	 * returns true if it needed to be loaded
	 */
	checkInitialLoad : function (fn) {
		weddingCoverSlideshow.storeCurrentImgSrc();
		if (!weddingCoverSlideshow.loaded) {
			weddingCoverSlideshow.load(function () {
				//weddingCoverSlideshow.display();
				weddingCoverSlideshow.hideSlideshowStatuses();
				//weddingCoverSlideshow.addMusic();
				weddingCoverSlideshow[fn]();
			});
			return true;
		} else return false;
	},
	
	storeCurrentImgSrc : function() {
		// store img url to determine whether to skip cover photo on new load
		if (weddingCoverSlideshow.reloadFlagged && !weddingCoverSlideshow.currentImg)
			weddingCoverSlideshow.currentImg = $("."+SlideShow.slideshow_display_class+" img:first").attr('src');
	},
	
	determineCoverSkip : function() {
		if (weddingCoverSlideshow.reloadFlagged) {
			try { // skip first photo if it's the same as the one currently shown
				if (weddingCoverSlideshow.currentImg != SlideShow.slideshow_data[0]['metadata']['url'])
					weddingCoverSlideshow.no_cover_skip = 1;
			} catch(err) {}
			$("."+SlideShow.slideshow_display_class+":first").remove();
			delete weddingCoverSlideshow.reloadFlagged;
		}
	},
	
	/**
	 * Starts the slideshow.  If it is not loaded yet it will load the slideshow
	 * first.
	 */
	play : function () {
		if (weddingCoverSlideshow.checkInitialLoad('play')) {
			return;
		}
		if (!weddingCoverSlideshow.slideshowPlayed && (memoryCreationWizard.app_id == 28 || memoryCreationWizard.app_id == 30)) {
			startMusic();
		}
		weddingCoverSlideshow.determineCoverSkip();
		SlideShow.startAutoScroll();
		togglePause();
		SlideShow.autoscroll_playing = true;
		if (!weddingCoverSlideshow.no_cover_skip && SlideShow.slideshow_data[SlideShow.display_index].type !== 'video')
			weddingCoverSlideshow.next();
		var slideshowPlay = document.getElementById('slideshowPlay');
		slideshowPlay.style.backgroundPosition = '0 -255px';
		slideshowPlay.onclick = weddingCoverSlideshow.pause;
		SlideShow.toggleStatuses(true);
		weddingCoverSlideshow.slideshowPlayed = 1;
		
		// hide callout if it's visible
		var topCalloutsWrapper = document.getElementById('topCalloutsWrapper');
		if (topCalloutsWrapper.style.display == 'block') topCalloutsWrapper.style.display = '';
	},
	
	/**
	 * Pauses the slideshow if it was playing
	 */
	pause : function () {
		SlideShow.pauseAutoScroll();
		togglePause();
		var slideshowPlay = document.getElementById('slideshowPlay');
		slideshowPlay.style.backgroundPosition = '0 -102px';
		slideshowPlay.onclick = weddingCoverSlideshow.play;
	},
	
	/**
	 * goes to the next slide in the slideshow
	 */
	next : function () {
		if (weddingCoverSlideshow.checkInitialLoad('next')) return;
		weddingCoverSlideshow.determineCoverSkip();
		if (!weddingCoverSlideshow.no_cover_skip) SlideShow.next();
		else delete weddingCoverSlideshow.no_cover_skip;
	},
	
	/**
	 * goes to the previous slide in the slideshow
	 */
	previous : function () {
		/*if (weddingCoverSlideshow.checkInitialLoad('previous')) {
			return;
		}*/
		SlideShow.previous();
	},
	
	/**
	 * puts music into the slideshow if there is music
	 */
	addMusic : function () {
		var music = weddingCoverSlideshow.music;
		if (music) weddingCoverSlideshow.displayMusic(music);
	},
	
	/**
	 * embeds music at the given url into the specified destination using and
	 * embed that will have the passed in id, width, and height
	 */
	embedMusic : function (url, destination, id, width, height) {
		var so = new SWFObject(url, id, width, height, "8", "#000000");
		so.addParam("allowScriptAccess", "always");
		so.addParam("wmode", "transparent");
		so.write(destination);
		audioInitialized = 1;
	},
	
	/**
	 * places a song into the music player and modifies the slideshow to accommodate
	 * having music
	 */
	displayMusic : function (song, thumb, title) {
		if (song) {
			SlideShow.has_music = 1;
			song = song.replace("&fs=1", "");
			song = song.replace("&feature=player_embedded", "");
			song = song.replace("&version=3", "");
			song = song.replace("&autoplay=1", "");
			song += '&autoplay=1&enablejsapi=1&playerapiid=kapturmusic';
			weddingCoverSlideshow.embedMusic(song, weddingCoverSlideshow.music_container_id, "KapturMusicPlayer", 200, 25);
			$("#slideshowMusicBar").css({
				'display':'block',
				'bottom':'-25px'
			});
			try {
				document.getElementById('musicPlayerThumb').src = (thumb?thumb:'');
				document.getElementById('musicPlayerTitle').innerHTML = (title?title:'Now Playing...');
			} catch(err) {}
			$('#musicPlayerControls, #musicPlayerWrapper').css('display', 'block');
			//$("#nightSlideShowFacebookStatuses").addClass("with_music");
		}
	},
	
	/**
	 * gets the music from the dataset or that has already been found if data
	 * is not passed in
	 */
	getMusic : function (data) {
		var data_length = arrayLength(data),
			i;
		
		if (data_length) {
			for(i = 0; i < data_length; i++) {
				if (data[i]['type'] == 'music') {
					//music found so we stop searching
					var music_metadata = data[i]['metadata'];
					weddingCoverSlideshow.music = music_metadata['src'];
					weddingCoverSlideshow.musicTitle = music_metadata['rmnMediaTitle'];
					weddingCoverSlideshow.musicThumb = music_metadata['thumb'];
					break;
				}
			}
		}
		
		return [weddingCoverSlideshow.music, weddingCoverSlideshow.musicThumb, weddingCoverSlideshow.musicTitle];
	},
	
	/**
	 * returns a boolean determining whether the slideshow has music.  requires
	 * initialization first.
	 */
	hasMusic : function () {
		return !!weddingCoverSlideshow.music;
	},
	
	convertPointToSlideshowFormat : function (point) {
		var metadata = {
				alt_src: point.src_high_res,
				caption: point.description,
				height: point.media_height,
				width: point.media_width,
				photo_id: point.media_type_id,
				rmnMediaDesc: point.description,
				rmnMediaTitle: point.description,
				rmnMediaId: point.media_id,
				rmnOwnerId: point.user_id,
				rmnPointDesc: point.description,
				rmnPointId: point.id,
				rmnPartnerIdId: point.partnerId_id,
				rmnPartnerIdValue: point.partnerIdValue,
				src: point.media_src,
				thumb: point.media_thumb,
				timezoneOffset: point.timezoneOffset,
				url: point.src_high_res || point.media_src,
				utcLastModifiedSec: point.utcLastModifiedSec,
				utcTimeSec: point.utcTimeSec
			},
			type = 'photo',
			tags = null,
			item = {
				metadata: metadata,
				type: type,
				tags: tags
			};
		
		return item;
	},
	
	addPhotoPoint : function (point, index) {
		return; // function deprecated
		if (this.db_load_called) {
			if (!weddingCoverSlideshow.loaded) return;
			var item = weddingCoverSlideshow.convertPointToSlideshowFormat(point);
			if (item) SlideShow.addItem(item, index);
		}
	},
	
	removePhotoByPointId : function (point_id) {
		return; // function deprecated
		var point = rmnPoints[point_id], url, time;
		if (!weddingCoverSlideshow.loaded || !point_id) return;
		
		url = point['media_src'];
		time = point['utcTimeSec'];
		if(url) SlideShow.removeItemByUrl(url);
		else SlideShow.removeItemByTime(time);
	}
};

function removePartnerMusic() {
	document.getElementById('partnerMusicThumbs').style.display = 'none';
	document.getElementById('partnerPlayerInfoWrapper').style.display = 'none';
	document.getElementById('partnerMusicBuyLink').style.display = 'none';
	document.getElementById('musicPlayerWrapper').style.display = '';
	document.getElementById('memoryExtMusicWrapper').style.display = 'block';
	document.getElementById('musicPlayerInfoWrapper').style.display = 'block';
	document.getElementById('musicMute').className = 'mute';
	$("#jplayer").jPlayer("stop");
	delete dataFlags.partnerMusic;
	delete SlideShow.has_music;
	audioInitialized = false;
	allowPartnerAudio = false;
	// change segment app id
	var new_app_id = 5;
	if (memoryCreationWizard.app_id == 27) new_app_id = 10;
	if (memoryCreationWizard.app_id == 28) new_app_id = 14;
	else if (memoryCreationWizard.app_id == 30) new_app_id = 29;
	else if (memoryCreationWizard.app_id == 20) new_app_id = 10;
	memoryCreationWizard.app_id = new_app_id;
	writeToDB('editSegment', [{'app_id':new_app_id.toString()}, memoryCreationWizard.sid]);
}

function showNavBar(type, hide, no_toggle) {
	var targetTab, linkedTab;
	if (type == 'media') {
		targetTab = document.getElementById('topNavMedia');
		linkedTab = document.getElementById('topNavMain');
	} else if (type == 'buy') {
		targetTab = document.getElementById('topNavBuy');
		linkedTab = document.getElementById('topNav');
	} else if (type == 'photobook') {
		targetTab = document.getElementById('topNavPhotobook');
		linkedTab = document.getElementById('topNav');
		//linkedTab = document.getElementById('topNavBuy');
	}
	
	if (!hide) {
		linkedTab.style.display = 'none';
		targetTab.style.display = 'block';
	} else {
		if (!(type == 'buy' && no_toggle)) linkedTab.style.display = '';
		targetTab.style.display = '';
		if (type == 'media' && !no_toggle) toggleTab(memoryCreationWizard.lastTab, 0);
	}
}

/* mobile functions start */
function setInternetStatus(status) {
	currentInternetStatus = status;
}

function setCurrentEnv(env) {
	if (env != '(null)') currentEnv = env;
}

function chooseMobilePhoto() {
	if (isMobileApp()) {
		if (currentInternetStatus == 2) {
			var rmnid = document.getElementById('rmnid');
			if (rmnid) rmnid.innerHTML = userProfileObj.id;
			location.href = "http://choosePhoto/";
		} else alert('Please connect to WIFI to upload photos.');
	}
}

function setImage(imgSrc, imgJSON) {
	try {
		processUploadedFiles(imgJSON, 1, 1);
		/*var imgPreview = document.getElementById("resultImg");
		imgPreview.src = imgSrc;
		imgPreview.style.display = "block";*/
	} catch(e) {}
}

function getRMNId() {
	return userProfileObj.id;
}

function checkMobileFinish() {
	if (isMobileApp()) {
		alert('Please visit www.kaptur.com on your computer to download all photos, create a photo book, or send greeting cards.');
		return false;
	}return true;
}/* mobile functions end */

function seeNextPhotobookPages(prev) {
	var scroll_width = $('#pageFramesContents').width()/2; // 420
	$('#pageFramesContents').scrollTo({top: '0px', left: (prev?'-':'+')+'='+scroll_width+'px'}, 350);
}

function updateLayoutSet(set) {
	var prevLayoutSet = memoryCreationWizard.prevLayoutSet;
	if (set != prevLayoutSet) {
		showLayoutSet(prevLayoutSet, 1);
		showLayoutSet(set);
		memoryCreationWizard.prevLayoutSet = set;
	}
}

function showLayoutSet(set, hide) {
	document.getElementById('photobookPageLayouts'+set).style.display = !hide?'block':'';
}

function katurNewMemory() {
	var redirect_fn = function() {redirectKapturUser(getFacebookSession());};
	if (loggedInUser && checkSetPerms(['user_relationships'])) redirect_fn();
	else loginToFacebook(function() {$.cookies.set("userPerms", null);redirect_fn();}, {'homepage':1});
}

//////// start from kaptur homepage ////////
function redirectNewUser(session, kptr_app) {
	if (session && session.userID) {
		var uid = session.userID;
		if (uid) {
			queryFacebook("SELECT relationship_status FROM user WHERE uid = '"+uid+"'", [], function(data) {
				if (data && data[0]) {
					var relationship_status = data[0]['relationship_status'];
					if (relationship_status == 'Married') location.href = replaceUrlParam('p', 'quickstart').replace('guetta.','')+'&app_id='+(kptr_app?'10':'27')+'&ref=newinviteduser';
					else location.href = replaceUrlParam('p', 'kaptur_my_life').replace('guetta.','')+(!kptr_app?'&app_id=28':'')+'&ref=newinviteduser';
				}
			});
		}
	}
}

function redirectKapturUser(session) {
	if (session && session.userID) {
		var uid = session.userID;
		if (uid) {
			readFromDB('getRmnUserInfoByFacebookId', [uid], function(data) {
				if (data && data.indexOf('"app_id":"') != -1) location.href = replaceUrlParam('p', 'f').replace('guetta.','')+'&ref=newinviteduser';
				else redirectNewUser(session, 1);
			});
		}
	}
}
//////// end from kaptur homepage ////////

function toggleViewComments() {
	var comments = document.getElementById('memorySummaryWrapper'); 
	comments.style.display = comments.style.display != 'block'? 'block' : '';
	// hide the share callout if its visible
	$('#memoryFooterCallout').css('display', 'none');
}

function kmlSegmentNotActivated() {
	return (count(rmnPoints) < 2);
}

function showConfirmDatePopup(date) {
	var date_div = $('#kmlDateConfirmDate'),
		parsed_date = parseKmlDate(date),
		start_date, end_date, date_text;
	
	start_date = formatDateStr(parsed_date.start_date, 'slashed_full');
	start_date = start_date.split('/');
	
	$('#kmlDateConfirmMonth').val(start_date[0]);
	$('#kmlDateConfirmDay').val(start_date[1]);
	$('#kmlDateConfirmYear').val(start_date[2]);
	
	togglePopup('kmlConfirmDate', true);
	/*if (count(rmnPoints) < 2) {
		togglePopup('kmlConfirmDate', true);
	} else {
		showMemoryEdit('info');
	}*/
}

function togglePopup (div, show) {
	var popup_bg = $('#customPopupWrapper');
	div = $('#' + div)
	
	
	popup_bg.toggle(show);
	div.toggle(show);
}

/* photobook functions start */
var num_photobook_pages = 16;
var photobook_title_limit = 40;
var layout_alpha_map = ['a','b','c','d'];
var layout_configs = [
	[
	 	[ [[1,1],[1,1],[1,1]] ],
	 	[ [[1,2],[1,2],[1,2]] ],
	 	[ [[1,3],[1,3],[1,3]] ],
	 	[ [[1,4],[1,4],[1,4]] ]
	],
	
	[
	 	[ [[2,1],[2,1],[2,1]], [[2,1],[2,2],[2,1]] ],
	 	[ [[2,1],[2,1],[2,1]], [[1,4],[2,2],[2,2]] ],
	 	[ [[1,4],[2,1],[2,2]], [[2,1],[2,2],[2,1]] ],
	 	[ [[1,4],[2,1],[2,2]], [[1,4],[2,2],[2,2]] ]
	],
	
	[
	 	[ [[2,1],[2,1],[2,2]], [[2,1],[2,1],[3,1]], [[1,4],[2,2],[2,2]] ],
	 	[ [[3,1],[3,1],[3,2]], [[2,1],[3,3],[2,1]], [[3,1],[3,2],[3,2]] ],
	 	[ [[1,4],[2,1],[2,2]], [[2,1],[2,2],[2,2]], [[2,1],[2,2],[3,1]] ],
	 	[ [[3,2],[3,1],[3,3]], [[3,1],[3,4],[3,2]], [[3,2],[3,2],[3,3]] ]
	],
	
	[
	 	[ [[2,1],[2,1],[2,2]], [[2,1],[2,2],[2,2]], [[2,1],[2,1],[3,1]], [[2,1],[2,2],[3,1]] ],
	 	[ [[3,1],[4,1],[1,2]], [[3,1],[4,2],[1,2]], [[3,1],[4,1],[4,1]], [[3,1],[4,2],[4,1]] ],
	 	[ [[2,1],[2,1],[2,2]], [[3,1],[4,2],[1,2]], [[3,1],[4,1],[4,1]], [[2,1],[2,2],[3,1]] ],
	 	[ [[3,1],[4,1],[1,2]], [[2,1],[2,2],[2,2]], [[2,1],[2,1],[3,1]], [[3,1],[4,2],[4,1]] ]
	]
];

var layout_config_data = [
	[
	 	[ {'w':.97, 'h':.80875, 'x':.015, 'y':.09575} ],
	 	[ {'w':.5136, 'h':.9625, 'x':.2434, 'y':.01875} ],
	 	[ {'w':.6, 'h':.5, 'x':.2, 'y':.25} ],
	 	[ {'w':.4, 'h':.75, 'x':.3, 'y':.125} ]
	],
	
	[
	 	[ {'w':.4774, 'h':.39775, 'x':.015, 'y':.301}, {'w':.4774, 'h':.39775, 'x':.5074, 'y':.301} ],
	 	[ {'w':.4774, 'h':.39775, 'x':.015, 'y':.301}, {'w':.4774, 'h':.89475, 'x':.5074, 'y':.0525} ],
	 	[ {'w':.4774, 'h':.89475, 'x':.015, 'y':.0525}, {'w':.4774, 'h':.39775, 'x':.5074, 'y':.301} ],
	 	[ {'w':.4774, 'h':.89475, 'x':.015, 'y':.0525}, {'w':.4774, 'h':.89475, 'x':.5074, 'y':.0525} ]
	],
	
	[
	 	[ {'w':.4774, 'h':.39775, 'x':.015, 'y':.07675}, {'w':.4774, 'h':.39775, 'x':.015, 'y':.5255},
		 	{'w':.4516, 'h':.8465, 'x':.5336, 'y':.07675} ],
	 	[ {'w':.27, 'h':.50625, 'x':.015, 'y':.24675}, {'w':.4, 'h':.33325, 'x':.3, 'y':.33325},
		 	{'w':.27, 'h':.50625, 'x':.715, 'y':.24675} ],
	 	[ {'w':.4516, 'h':.8465, 'x':.015, 'y':.07675}, {'w':.4774, 'h':.39775, 'x':.5074, 'y':.07675},
		 	{'w':.4774, 'h':.39775, 'x':.5074, 'y':.5255} ],
	 	[ {'w':.335, 'h':.27925, 'x':.015, 'y':.36025}, {'w':.27, 'h':.50625, 'x':.365, 'y':.24675},
		 	{'w':.335, 'h':.27925, 'x':.65, 'y':.36025} ]
	],
	
	[
	 	[ {'w':.4774, 'h':.39775, 'x':.015, 'y':.0925}, {'w':.4774, 'h':.39775, 'x':.5074, 'y':.0925},
		 	{'w':.4774, 'h':.39775, 'x':.015, 'y':.50925}, {'w':.4774, 'h':.39775, 'x':.5074, 'y':.50925} ],
	 	[ {'w':.2516, 'h':.47175, 'x':.1278, 'y':.01875}, {'w':.2516, 'h':.47175, 'x':.6204, 'y':.01875},
		 	{'w':.2516, 'h':.47175, 'x':.1278, 'y':.50925}, {'w':.2516, 'h':.47175, 'x':.6204, 'y':.50925} ],
	 	[ {'w':.4774, 'h':.39775, 'x':.1278, 'y':.0925}, {'w':.2516, 'h':.47175, 'x':.6204, 'y':.01875},
		 	{'w':.2516, 'h':.47175, 'x':.1278, 'y':.50925}, {'w':.4774, 'h':.39775, 'x':.3944, 'y':.50925} ],
	 	[ {'w':.2516, 'h':.47175, 'x':.1278, 'y':.01875}, {'w':.4774, 'h':.39775, 'x':.3944, 'y':.0925},
		 	{'w':.4774, 'h':.39775, 'x':.1278, 'y':.50925}, {'w':.2516, 'h':.47175, 'x':.6204, 'y':.50925} ]
	]
];

var layout_orientations = [
	[ [0], [1], [0], [1] ],
	[ [0,0], [0,1], [1,0], [1,1] ],
	[ [0,0,1], [1,0,1], [1,0,0], [0,1,0] ],
	[ [0,0,0,0], [1,1,1,1,], [0,1,0,1], [1,0,1,0] ]
];

function setLayoutStyles() {
	for (var i=0; i<layout_config_data.length; i++) {
		var config_html = '';
		var layout_config = layout_config_data[i];
		var layout_num = i+1;
		for (var j=0; j<layout_config.length; j++) {
			config_html += setLayoutStyle({'config':i, 'layout':j});
		} document.getElementById('photobookPageLayouts'+layout_num).innerHTML = config_html;
	}
	
	// custom layouts
	$('.photobook_layouts_wrapper #photobookPageLayout2a1, .photobook_layouts_wrapper #photobookPageLayout2b1, .photobook_layouts_wrapper #photobookPageLayout2c1, .photobook_layouts_wrapper #photobookPageLayout2d1, ').css('width', '47%')
;	
	$('.photobook_layouts_wrapper #photobookPageLayout3b2').css({'left':'31%', 'width':'38%'});
	$('.photobook_layouts_wrapper #photobookPageLayout3d2').css({'left':'38%', 'width':'25.2%'});
	$('.photobook_layouts_wrapper #photobookPageLayout4a1, .photobook_layouts_wrapper #photobookPageLayout4a2, .photobook_layouts_wrapper #photobookPageLayout4c1, .photobook_layouts_wrapper #photobookPageLayout4d2').height('38%');
	$('.photobook_layouts_wrapper #photobookPageLayout4b1, .photobook_layouts_wrapper #photobookPageLayout4b2').height('47%');
	$('.photobook_layouts_wrapper #photobookPageLayout4c2, .photobook_layouts_wrapper #photobookPageLayout4d1').css({'top':'0%', 'height':'47%'});
	$('.photobook_layouts_wrapper #photobookPageLayout4c2').css('left', '59%');
	$('.photobook_layouts_wrapper #photobookPageLayout4c1').css('width', '45%');
	$('.photobook_layouts_wrapper #photobookPageLayout4d3').css('width', '47%');
	$('.photobook_layouts_wrapper #photobookPageLayout4d4').css({'left':'61%', 'width':'24%'});
}

function getPercent(dec) { return dec*100+'%'; }
function getLayoutCSS(elem) { return ' style="width:'+getPercent(elem.w)+';height:'+getPercent(elem.h)+';left:'+getPercent(elem.x)+';top:'+getPercent(elem.y)+';"'; }

function setLayoutStyle(args) {
	var layout_html = '';
	var config = args['config'];
	var layout = args['layout'];
	var load_layout = args['load_layout'];
	var change_layout = args['change_layout'];
	var load_crop = args['load_crop'];
	var current_page = parseInt(memoryCreationWizard.photobook_page, 10);
	var pageCanvasId = 'photobookPage'+current_page+'Canvas';
	var pageThumbId = 'photobookPage'+current_page+'Thumb';
	var pageCanvas = document.getElementById(pageCanvasId);
	var pageThumb = document.getElementById(pageThumbId);
	if (isNaN(config)) {
		// keep track of layout config in memory
		var layout_html = '';
		var layout_id = 'l-10x8-0-a';
		if (config == 'back_cover') {
			layout_id = 'l-10x8-c-b';
			var layout_html = '<div class="back_cover_logo"><img src="'+TEMPLATE_VIEW_PATH+'/images/photobooks/stamps/back_cover_logo.png"></div>';
		} else memoryCreationWizard.photobookLayouts[current_page+2] = {'template':layout_id, 'photos':[]};
		highlightLayoutThumb(0, 'a');
		
		//if (config == 'white') pageCanvas.style.backgroundColor = 'white';
		//else pageCanvas.style.backgroundColor = '';
		pageCanvas.innerHTML = layout_html;
		pageThumb.innerHTML = layout_html;
		
		pageCanvas.style.display = '';
		if (change_layout && !load_crop) $('#pageFramesWrapper .page_frame_wrapper.selected .page_frame_thumb').click();
	} else {
		var layout_num = parseInt(config, 10)+1;
		var layout_choice = layout_alpha_map[layout];
		var layout_id = layout_num+layout_choice;
		var layout_elements = layout_config_data[config][layout];
		for (var k=0; k<layout_elements.length; k++) {
			var layout_element = layout_elements[k];
			var layout_set_id = 'photobookPageLayout'+layout_id+(k+1);
			var style_param = getLayoutCSS(layout_element);
			layout_html += '<div id="'+layout_set_id+'" class="photobook_layout_item"'+style_param+'><div class="photobook_edit_btn" onclick="showPhotobookPhotoSelector(this)">Add Photo</div></div>';
			//layout_html += '<div id="'+layout_set_id+'" class="photobook_layout_item layout_size_'+layout_element[0][0]+'_'+layout_element[0][1]+' layout_x_'+layout_element[1][0]+'_'+layout_element[1][1]+' layout_y_'+layout_element[2][0]+'_'+layout_element[2][1]+'"><div class="photobook_edit_btn" onclick="showPhotobookPhotoSelector(this)">Add Photo</div></div>';
		} if (!load_layout) {
			return '<div id="photobookPageLayout'+layout_id+'" class="photobook_layout" onclick="setLayoutStyle({\'config\':\''+config+'\', \'layout\':\''+layout+'\', \'load_layout\':1, \'change_layout\':1})">'+layout_html+'</div>';
		} else {
			// append title on cover
			if (current_page == 0) {
				if (!memoryCreationWizard.photobook_title) {
					memoryCreationWizard.photobook_title = memoryCreationWizard.title.substr(0, photobook_title_limit);
					if (!memoryCreationWizard.photobook_title) memoryCreationWizard.photobook_title = 'Untitled';
				} layout_html += '<div class="photobook_title">'+memoryCreationWizard.photobook_title+'</div>';
			}
			
			highlightLayoutThumb(layout_num, layout_choice);
			pageCanvas.innerHTML = layout_html;
			pageThumb.innerHTML = layout_html;
			pageCanvas.style.backgroundColor = '';
			
			// back up current photos data
			var prev_photos; 
			if (memoryCreationWizard.photobookLayouts[current_page+2])
				prev_photos = memoryCreationWizard.photobookLayouts[current_page+2]['photos'];
			
			$(pageCanvas).css({position: "relative", visibility: "hidden", display: "block"});
			if (!load_crop) {
				// keep track of layout config in memory
				var layout_id = 'l-10x8-'+layout_num+'-'+layout_choice;
				memoryCreationWizard.photobookLayouts[current_page+2] = {'template':layout_id, 'photos':[]};
			} else if (!prev_photos) memoryCreationWizard.photobookLayouts[current_page+2]['photos'] = [];
			
			var layout_width = $(pageCanvas).width();
			var layout_height = $(pageCanvas).height();
			for (var i=0; i<layout_num; i++) {
				if (!load_crop || (!prev_photos || prev_photos && !prev_photos[i])) {
					var photobook_elem = $('#'+pageCanvasId+' .photobook_layout_item:eq('+i+')');
					var photobook_elem_pos = photobook_elem.position();
					var xStart = photobook_elem_pos.left/layout_width;
					var xEnd = (photobook_elem_pos.left+photobook_elem.width())/layout_width;
					var yStart = photobook_elem_pos.top/layout_height;
					var yEnd = (photobook_elem_pos.top+photobook_elem.height())/layout_height;
					xStart = xStart.toString().substr(0,7);
					yStart = yStart.toString().substr(0,7);
					xEnd = xEnd.toString().substr(0,7);
					yEnd = yEnd.toString().substr(0,7);
					memoryCreationWizard.photobookLayouts[current_page+2]['photos'][i] =
						{'layout': {'xStart':xStart, 'xEnd':xEnd, 'yStart':yStart, 'yEnd':yEnd} };
				}
			}
			
			// update title positioning
			if (current_page == 0) {
				displayPhotobookTitleTarget('thumb');
				displayPhotobookTitleTarget('canvas');
			} $(pageCanvas).css({position: "", visibility: "", display: ""});
			
			// update existing photos in new layout
			if (change_layout) {
				if (prev_photos) {
					for (var i in prev_photos) {
						var prev_photo = prev_photos[i];
						var point_id = prev_photo['point_id'];
						if (rmnPoints[point_id]) {
							var page_index = memoryCreationWizard.photobook_page;
							var photo_elem = $('#photobookPageEditMainWrapper #photobookPage'+page_index+'Canvas .photobook_layout_item:eq('+i+') img');
							changePhotobookPhoto({'point_id':point_id, 'photo_elem':photo_elem, 'page_index':page_index, 'layout_index':i, 'load_crop':load_crop?prev_photo['crop']:null});
							
							// update image crop
							/*if (load_crop) {
								var photo_crop = prev_photo['crop'];
								var thumb_elem = $('#photobookPage'+page_index+'Thumb .photobook_layout_item:eq('+i+') img');
								thumb_elem.css('left', -1*photo_crop['xStart']*thumb_elem.width()).css('top', -1*photo_crop['yStart']*thumb_elem.height());
								var canvas_elem = $('#photobookPage'+page_index+'Canvas .photobook_layout_item:eq('+i+') img');
								canvas_elem.css('left', -1*photo_crop['xStart']*canvas_elem.width()).css('top', -1*photo_crop['yStart']*canvas_elem.height());
							}*/
						}
					}
				} if (!load_crop) $('#pageFramesWrapper .page_frame_wrapper.selected .page_frame_thumb').click();
				//autoFlowPhotos();
			}
		}
	}
}

function displayPhotobookTitleTarget(target) {
	var target_id = ucfirst(target);
	var target_wrapper = (target == 'canvas')? 'photobookPageEditMainWrapper' : 'pageFramesWrapper';
	var page_canvas = $('#photobookPage0'+target_id);
	var cover_item = $('#photobookPage0'+target_id+' .photobook_layout_item');
	//if (target == 'canvas') $(page_canvas).css({position: "relative", visibility: "hidden", display: "block"});
	var canvas_width = page_canvas.width();
	var canvas_height = page_canvas.height();
	var cover_item_top = cover_item.position().top;
	var cover_item_bottom = cover_item.height() + cover_item_top;
	//if (target == 'canvas') $(page_canvas).css({position: "", visibility: "", display: ""});
	var font_height = .035*canvas_height;
	var cover_title_bottom = (canvas_height - cover_item_bottom - font_height)*.75;
	var photobook_title = $('#'+target_wrapper+' .photobook_title');
	
	// adjust page contents higher to account for title spacing
	var cover_item_adjust = (cover_item_top + cover_title_bottom)/2;
	cover_title_bottom += cover_item_top - cover_item_adjust;
	cover_item.css('top', cover_item_adjust+'px');
	photobook_title.css('font-size', font_height+'px').css('min-height', font_height+'px').css('bottom', cover_title_bottom+'px').css('display', 'block');
	
	// enable title edit
	if (target = 'canvas') {
		photobook_title.click(editPhotobookTitle);
		document.getElementById('photobookEditTitleWrapper').style.display = '';
	}
}

function editPhotobookTitle(action) {
	var photobookEditTitleWrapper = document.getElementById('photobookEditTitleWrapper');
	var photobookEditTitleField = document.getElementById('photobookEditTitleField');
	var photobookTitleCount = document.getElementById('photobookTitleCount');
	var photobookTitle = $('#photobookPageEditMainWrapper .photobook_title');
	if (action == 'save' || action == 'cancel') {
		if (action == 'save') {
			var photobook_title = photobookEditTitleField.value;
			memoryCreationWizard.photobook_title = photobook_title;
			$('.photobook_title').html(photobook_title);
		} photobookEditTitleWrapper.style.display = '';
		photobookTitle.css('display', 'block');
	} else {
		photobookEditTitleField.value = memoryCreationWizard.photobook_title;
		if (!photobookEditTitleField.getAttribute('maxLength'))
			photobookEditTitleField.setAttribute('maxLength', photobook_title_limit);
		photobookTitleCount.innerHTML = photobook_title_limit - memoryCreationWizard.photobook_title.length;
		photobookEditTitleWrapper.style.marginTop = photobookTitle.position().top - $('#photobookPage0Canvas').height() - 13 + 'px';
		photobookEditTitleWrapper.style.display = 'block';
		photobookTitle.css('display', '');
	}
}

function updatePhotobookTitleCount() {
	var photobook_title_count = photobook_title_limit - document.getElementById('photobookEditTitleField').value.length;
	var photobookTitleCount = document.getElementById('photobookTitleCount');
	photobookTitleCount.innerHTML = photobook_title_count;
	//if (photobook_title_count < 0) photobookTitleCount.style.color = 'red';
	//else photobookTitleCount.style.color = '';
}

function highlightLayoutThumb(config, layout) {
	$('.photobook_layouts_wrapper .photobook_layout.selected').removeClass('selected');
	if (config != null && layout != null)
		$('.photobook_layouts_wrapper #photobookPageLayout'+config+layout).addClass('selected');
}

function highlightSelectedPage(page) {
	$('.page_frame_wrapper.selected').removeClass('selected');
	if (page != null) $('#photobookPage'+page+'Thumb').parent().addClass('selected');
}

function showPhotobookPage(page, no_refocus) {
	if (!memoryCreationWizard.photobookCheckout) {
		var refocus_page_nav = !no_refocus?1:0;
		if (page == 'next') page = Math.min(parseInt(memoryCreationWizard.photobook_page,10)+1, num_photobook_pages-1);
		else if (page == 'prev') page = Math.max(parseInt(memoryCreationWizard.photobook_page,10)-1, 0);
		else refocus_page_nav = 0;
		document.getElementById('photobookPage'+memoryCreationWizard.photobook_page+'Canvas').style.display = '';
		document.getElementById('photobookPage'+page+'Canvas').style.display = 'block';
		memoryCreationWizard.photobook_page = page;
		highlightLayoutThumb();
		highlightSelectedPage(page);
		if (refocus_page_nav) {
			var page_frame_width = 145; // attempt to keep focus in the center
			var half_num_frames = Math.floor($('#pageFramesContents').width() / 2 / page_frame_width);
			$('#pageFramesContents').scrollTo($('.page_frame_wrapper.selected .page_frame_thumb'), 350, {offset:{top:0, left:-(page_frame_width*half_num_frames)}});
		}
		
		// update layout selector
		var edit_options = document.getElementById('photobookPageEditOptionsWrapper');
		var edit_elems = $('#photobookPageLayout1a, #photobookPageLayout1b, #photobookPageSelectLayoutCount');
		if (page == num_photobook_pages-1) {
			edit_options.style.display = 'none';
		} else {
			var page_template = memoryCreationWizard.photobookLayouts[parseInt(page,10)+2]['template'];
			var templage_data = page_template.split('-');
			var photos_count = templage_data[2]; // $('.page_frame_wrapper.selected .page_frame_thumb>.photobook_layout_item').length
			var layout_id = templage_data[3]; // layout_alpha_map.indexOf()
			$('#photobookPagePhotosCount').val(photos_count).change();
			highlightLayoutThumb(photos_count, layout_id);
			
			// update layout selector
			edit_elems.css('display', (page == 0?'none':''));
			edit_options.style.display = '';
		}
	}
}

function autoFlowLayouts() {
	if (dataFlags.photobookLoaded) return;
	dataFlags.photobookLoaded = 1;
	
	var unique_photos = {}, cover_index;
	memoryCreationWizard.photobook_photos = [];
	
	// aggregate array of photos
	for (var i in rmnPoints) {
		var point = rmnPoints[i];
		var type = parseInt(point['partnerId_id'], 10);
		if (in_array(type, [1,4,14,16,17])) {
			var partner_value = point['media_type_id'];
			if (!unique_photos[partner_value]) {
				if (!point['id']) point['id'] = i;
				if (cover_index == null && i == memoryCreationWizard.cover_point_id)
					cover_index = memoryCreationWizard.photobook_photos.length;
				memoryCreationWizard.photobook_photos.push(point);
				unique_photos[partner_value] = 1;
			}
		}
	}
	
	// prepend cover
	var reuse_cover, num_photos = memoryCreationWizard.photobook_photos.length;
	var num_inner_pages = num_photobook_pages-2;
	var low_num_photos = num_photos < num_inner_pages-1;
	if (cover_index && cover_index != 0 || low_num_photos) {
		if (!low_num_photos && (num_photos == num_inner_pages-1 || num_photos > num_inner_pages)) {
			memoryCreationWizard.photobook_photos.splice(cover_index, 1);
			num_photos--;
		} else reuse_cover = 1;
		memoryCreationWizard.photobook_photos.unshift(rmnPoints[memoryCreationWizard.cover_point_id]);
		num_photos++;
	}
	
	// init photobook layouts object stub in back cover and spine layouts
	var skip_inside_covers;
	var missing_back_cover = num_photos == num_inner_pages && !reuse_cover;
	memoryCreationWizard.photobookLayouts = [{'template':'l-10x8-c-b'}, {'template':'l-1x8-s-a'}];
	for (var i=0; i<num_photobook_pages; i++) {
		memoryCreationWizard.photobook_page = i;
		var config = parseInt((Math.random()*3)+1, 10);
		var layout_config = layout_config_data[config];
		var layout = parseInt(Math.random()*layout_config.length, 10);
		if (in_array(i, [0,1,num_inner_pages])) {
			if (i && (num_photos < num_inner_pages || missing_back_cover)) {
				config = 'blank'; layout = 'null';
				skip_inside_covers = 1;
			} else {
				var point = memoryCreationWizard.photobook_photos[i], portrait = 0;
				if (point) {
					var width = point['media_width']?point['media_width']:point['width'];
					var height = point['media_height']?point['media_height']:point['height'];
					portrait = height > width;
				} config = 0; layout = portrait?3:2;
			}
		} else if (i==num_photobook_pages-1) { config = 'back_cover'; layout = 'null'; }
		setLayoutStyle({'config':config, 'layout':layout, 'load_layout':1});
	}
	
	// update layouts between inside covers
	if (num_photos < num_photobook_pages && !missing_back_cover) { // fewer photos than pages
		var num_photos_left = Math.min(num_photos+1, num_inner_pages);
		for (var i=2; i<num_photos_left; i++) {
			var pbook_photo_lengths, width, height
			memoryCreationWizard.photobook_page = i;
			
			var page_start_i = i-(skip_inside_covers?1:0);
			pbook_photo_lengths = getPbookPhotoLengths(memoryCreationWizard.photobook_photos[page_start_i]);
			width = pbook_photo_lengths[0]; height = pbook_photo_lengths[1];
			var portrait = height > width;
			
			config = 0, layout = portrait?1:0;
			setLayoutStyle({'config':config, 'layout':layout, 'load_layout':1});
		}
	} else if (num_photos <= 2*num_inner_pages-1) { // up to 2 photos per page
		var num_photos_left = num_photos - (!skip_inside_covers?3:1);
		var num_dbl_pages = num_photos_left - (num_inner_pages - 2);
		var num_dbl_pages_processed = 0;
		for (var i=2; i<num_inner_pages; i++) {
			var pbook_photo_lengths, width, height, portrait_orientation = [];
			memoryCreationWizard.photobook_page = i;
			
			var dbl_pages_done = num_dbl_pages_processed >= num_dbl_pages;
			var page_start_i = i-(skip_inside_covers?1:0)+num_dbl_pages_processed;
			var page_end_i = page_start_i+(!dbl_pages_done?2:1);
			for (var j=page_start_i; j<page_end_i; j++) {
				pbook_photo_lengths = getPbookPhotoLengths(memoryCreationWizard.photobook_photos[j]);
				width = pbook_photo_lengths[0]; height = pbook_photo_lengths[1];
				portrait_orientation.push(height > width?1:0);
			}
			
			if (dbl_pages_done) {
				config = 0, layout = portrait_orientation[0]?1:0;
			} else {
				config = 1, layout_orientation = layout_orientations[config], portrait_config = portrait_orientation.join();
				for (var j=0; j<layout_orientation.length; j++) {
					if (portrait_config == layout_orientation[j].join()) {
						layout = j;
						break;
					}
				} num_dbl_pages_processed++;
			} setLayoutStyle({'config':config, 'layout':layout, 'load_layout':1});
		}
	} else { // more than 2 photos per page
		var num_slots = $('#pageFramesWrapper .photobook_layout_item').length;
		if (num_photos < num_slots) {
			var num_extra_slots = num_slots - num_photos, i = 2;
			while (num_extra_slots > 0) {
				if (i == 2) i = num_inner_pages; // loop to end of pages
				memoryCreationWizard.photobook_page = --i;
				
				var layout_item_count = $('#photobookPage'+i+'Thumb .photobook_layout_item').length;
				if (layout_item_count > 2) {
					config = layout_item_count - 1;
					num_extra_slots -= 1;
					/*if (num_extra_slots == 3 && layout_item_count > 3) {
						config = layout_item_count - 3;
						num_extra_slots -= 3;
					} else {
						if (layout_item_count % 2 || num_extra_slots == 1) { // odd layout
							config = layout_item_count - 1;
							num_extra_slots -= 1;
						} else { // even layout
							config = layout_item_count - 2;
							num_extra_slots -= 2;
						}
					}*/ config--; layout = parseInt(Math.random()*config, 10);
					setLayoutStyle({'config':config, 'layout':layout, 'load_layout':1});
				}
			}
		} else if (num_photos > num_slots) { // more photos than pages can hold
			// construct reduced photos set
			var start_i = 1; var skip_multiplier = 1; var num_reviewed = 0;
			var num_review_photos = num_photos - (start_i+1);
			var num_extra_photos = num_photos - num_slots + 1;
			var skip_interval = num_review_photos/num_extra_photos;
			var next_skip = Math.round(skip_interval);
			var current_photobook_photos = [];
			current_photobook_photos.push(memoryCreationWizard.photobook_photos[0]);
			for (var i=start_i; i<num_photos-1; i++) {
				if (num_reviewed++ == next_skip) {
					next_skip = Math.round(++skip_multiplier * skip_interval);
				} else current_photobook_photos.push(memoryCreationWizard.photobook_photos[i]);
			} current_photobook_photos.push(memoryCreationWizard.photobook_photos[num_photos-1]);
			memoryCreationWizard.photobook_photos = current_photobook_photos;
		}
		
		// fix up photos based on photo orientations
		
	}
	
	// flow in photos
	memoryCreationWizard.photobook_page = 0;
	autoFlowPhotos();
	$('#topNavBuyBtn').css('display', 'block');
}

function getPbookPhotoLengths(pbook_photo) {
	var width = pbook_photo['media_width']?pbook_photo['media_width']:pbook_photo['width'];
	var height = pbook_photo['media_height']?pbook_photo['media_height']:pbook_photo['height'];
	return [width?width:0, height?height:0];
}

function autoFlowPhotos() {
	var current_index = 0, photobook_photos = memoryCreationWizard.photobook_photos;
	for (var i=0; i<photobook_photos.length; i++) {
		var point = photobook_photos[i];
		var slot_filled = showUpdatedThumbDelayed(point, current_index);
		if (!slot_filled) break; // stop when all items have been filled
		current_index++;
	} $('#pageFramesWrapper .page_frame_wrapper.selected .page_frame_thumb').click();
	$('#photobookPageEditMainWrapper .photobook_layout_item img').draggable({'drag':handlePhotobookDrag, 'stop':handlePhotobookDragStop});
}

function showUpdatedThumbDelayed(point, current_index, delayed) {
	// check whether there are remaining slots to fill
	var pageThumbQuery = '#pageFramesWrapper .photobook_layout_item:eq('+(current_index)+')';
	var pageCanvasQuery = '#photobookPageEditMainWrapper .photobook_layout_item:eq('+(current_index)+')';
	var pageThumb = $(pageThumbQuery); var pageCanvas = $(pageCanvasQuery);
	if (!pageThumb.length) return false;
	
	// load data for thumb
	var point_id = point['id'];
	var width = point['media_width']?point['media_width']:point['width'];
	var height = point['media_height']?point['media_height']:point['height'];
	var thumb = point['media_thumb'];
	var src = point['media_src'];
	var src_hd = point['src_high_res'];
	var partner_id = point['partnerId_id'];
	var partner_value = point['media_type_id'];
	var media_id = point['media_id'];
	
	if (!delayed) {
		var thumb_html = '<img id="photobook_'+getMediaPartnerId(partner_value, partner_id)+'" src="'+src+'" style="position:relative"><div class="photobook_edit_btn" onclick="showPhotobookPhotoSelector(this, \''+partner_value+'\')">Change</div>';
		pageThumb.html(thumb_html);
		pageCanvas.html(thumb_html);
		
		// handle images with no width and height saved
		if (!width || !height) {
			var img_bg_download = new Image();
			img_bg_download.onload = function() {
				rmnPoints[point_id]['media_width'] = this.width;
				rmnPoints[point_id]['media_height'] = this.height;
				var point = rmnPoints[point_id];
				showUpdatedThumbDelayed(point, current_index, 1);
				$('#pageFramesWrapper .page_frame_wrapper.selected .page_frame_thumb').click();
				if (point['media_id']) writeToDB('editMedia', [{'width':this.width, 'height':this.height}, point['media_id']]);
			}; img_bg_download.src = thumb;
		}
	}
	
	// insert to precise location
	var photobook_indexes = getPhotobookElemIndex($(pageCanvasQuery+' img'));
	var page_index = photobook_indexes[0];
	var layout_elem_index = photobook_indexes[1];
	var media_elem = '.photobook_layout_item:eq('+layout_elem_index+')';
	var canvas_elem = '#photobookPage'+page_index+'Canvas '+media_elem;
	var img_elem = canvas_elem+' img';
	
	showUpdatedThumb({'width':width, 'height':height, 'partnerId_id':partner_id, 'partnerIdValue':partner_value, 'crop_src':src_hd?src_hd:src, 'crop_media_id':media_id, 'crop_point_id':point_id, 'elem':img_elem});
	return true;
}

function showPhotobookPhotoSelector(elem, partner_value) {
	updateFromKapturPhotos();
	memoryCreationWizard.current_photobook_photo = elem;
	$('#photobookPhotoSelectorWrapper .create_memory_photo_selected').removeClass('create_memory_photo_selected');
	$('#photobookPhotoSelectorWrapper #photobookPhotos'+partner_value).addClass('create_memory_photo_selected');
	$.colorbox({inline:true, href:'#photobookPhotoSelectorWrapper', innerWidth:680, innerHeight:550, onOpen:function() {toggleExpand('share', 0);}, onComplete:hideEmbed, onClosed:function(){hideEmbed(1)}, open:true});
}

function changePhotobookPhoto(args) {
	var point_id = args['point_id'];
	var src_elem = args['src_elem'];
	var photo_elem = args['photo_elem'];
	var page_index = args['page_index'];
	var layout_elem_index = args['layout_index'];
	var load_crop = args['load_crop'];
	if (!photo_elem) photo_elem = memoryCreationWizard.current_photobook_photo;
	if (page_index == null && layout_elem_index == null) {
		var photobook_indexes = getPhotobookElemIndex(photo_elem);
		page_index = photobook_indexes[0];
		layout_elem_index = photobook_indexes[1];
	} var media_elem = '.photobook_layout_item:eq('+layout_elem_index+')';// img
	var thumb_elem = '#photobookPage'+page_index+'Thumb '+media_elem;
	var canvas_elem = '#photobookPage'+page_index+'Canvas '+media_elem;
	var img_elem = canvas_elem+' img';
	var pageThumb = $(thumb_elem);
	var pageCanvas = $(canvas_elem);
	if (src_elem && !$(src_elem).hasClass('create_memory_photo_selected') || !src_elem) {
		var point = rmnPoints[point_id];
		var width = point['media_width']?point['media_width']:point['width'];
		var height = point['media_height']?point['media_height']:point['height'];
		var thumb = point['media_thumb'];
		var src = point['media_src'];
		var src_hd = point['src_high_res'];
		var partner_id = point['partnerId_id'];
		var media_id = point['media_id'];
		var partner_value = point['media_type_id'];
		
		var thumb_html = '<img id="photobook_'+partner_value+'" src="'+src+'" style="position:relative"><div class="photobook_edit_btn" onclick="showPhotobookPhotoSelector(this, \''+partner_value+'\')">Change</div>';
		pageThumb.html(thumb_html);
		pageCanvas.html(thumb_html);
		showUpdatedThumb({'width':width, 'height':height, 'partnerId_id':partner_id, 'partnerIdValue':partner_value, 'crop_src':src_hd?src_hd:src, 'crop_media_id':media_id, 'crop_point_id':point_id, 'elem':img_elem, 'load_crop':load_crop});
		if (!load_crop) $('#pageFramesWrapper .page_frame_wrapper.selected .page_frame_thumb').click();
		$(img_elem).draggable({'drag':handlePhotobookDrag, 'stop':handlePhotobookDragStop});
	} $.colorbox.close();
}

function savePhotobook() { toggleShowCheckoutIframe(1);
	var layout_data = d_escape(JSON.stringify(memoryCreationWizard.photobookLayouts));
	var memory_url = ''; // todo: generate a hash if one doesn't exist
	if (memoryCreationWizard.hash) memory_url = (CONTEXT!='www.'?CONTEXT:'')+'kptr.it/'+memoryCreationWizard.hash;
	writeToDB('createPhotobook', [{'user_id':userProfileObj.id, 'segment_id':memoryCreationWizard.sid, 'layout_data':layout_data, 'title':d_escape(memoryCreationWizard.photobook_title), 'url':d_escape(memory_url)}], function(data) {
		var photobook_ids = JSON.parse(data);
		photobook_ids = photobook_ids['result'];
		var order_id = photobook_ids['order_id'];
		//alert('http://'+location.host+'?p=download_photobook&oid='+order_id);
		//var aff_param = location.href.match(/([^\w])(aff=[^&]+)/)? '&'+RegExp.$2 : '';
		var order_confirm_url = '?p=pbook_checkout&oid='+order_id;//+aff_param;
		
		var ref_regex = new RegExp('&(aff|ref)=([^&]*)');
		if (location.href.match(ref_regex)) order_confirm_url += '&'+RegExp.$1+'='+RegExp.$2;
		
		document.getElementById('photobookCheckout').src = order_confirm_url;
		//alert(show_props(photobook_ids));
		//print_r(photobook_ids);
	}, 1);
}

function loadPhotobook() {
	if (!dataFlags.photobookLoaded) {
		dataFlags.photobookLoaded = 1;
		readFromDB('getLatestPhotobookOrderDataBySegmentAndUser', [memoryCreationWizard.sid, userProfileObj.id], function(data) {
			if (data) {
				var result = JSON.parse(data);
				result = result['result'];
				if (result) {
					var order_summary = result['summary'];
					var pbook_spreads = result['spreads'];
					var owner_id = order_summary['user_id'];
					var order_id = order_summary['order_id'];
					var orderline_id = order_summary['orderline_id'];
					memoryCreationWizard.photobookLayouts = [];
					
					var current_page = -2;
					for (var i=0; i<pbook_spreads.length; i++) {
						var spread_layouts = pbook_spreads[i]['layouts'];
						for (var j=0; j<spread_layouts.length; j++) {
							var spread_layout = spread_layouts[j];
							var layout_metadata = spread_layout['metadata'];
							if (layout_metadata) {
								layout_metadata = JSON.parse(layout_metadata);
								var layout_type = layout_metadata['type'];
								if (layout_type == 'front_cover') {
									var pbook_title = urldecode(layout_metadata['title']);
									memoryCreationWizard.photobook_title = pbook_title?pbook_title:'Untitled';
								}// else if (layout_type == 'back_cover') var vanity_url = urldecode(layout_metadata['url']);
							}
							
							// load photobook data in memory
							var template_id = spread_layout['photobookTemplate_id'];
							var layout_data = {'template':template_id};
							if (current_page >= 0) {
								var layout_photos = spread_layout['photos'];
								if (layout_photos) {
									for (var k in layout_photos) {
										var layout_photo = layout_photos[k];
										if (layout_photo) {
											layout_photos[k]['layout'] = {
												'xStart':layout_photo['xStart'],
												'yStart':layout_photo['yStart'],
												'xEnd':layout_photo['xEnd'],
												'yEnd':layout_photo['yEnd']
											}; delete layout_photo['xStart'];
											delete layout_photo['yStart'];
											delete layout_photo['xEnd'];
											delete layout_photo['yEnd'];
										}
									} layout_data['photos'] = layout_photos;
								}
							} memoryCreationWizard.photobookLayouts.push(layout_data);
							
							if (current_page == -2) { // back cover
								memoryCreationWizard.photobook_page = num_photobook_pages - 1;
								setLayoutStyle({'config':'back_cover'});
							} else if (current_page > -1) { // skip spine layout
								var layout_parts = template_id.split('-');
								var config = parseInt(layout_parts[2], 10)-1;
								var layout = layout_alpha_map.indexOf(layout_parts[3]);
								if (config < 0) { config = 'blank'; layout = null; }
								memoryCreationWizard.photobook_page = current_page;
								setLayoutStyle({'config':config, 'layout':layout, 'load_layout':1, 'change_layout':1, 'load_crop':1});
							} current_page++;
						}
					} $('#pageFramesWrapper .page_frame_wrapper.selected .page_frame_thumb').click();
					$('#topNavBuyBtn').css('display', 'block');
				} else { delete dataFlags.photobookLoaded; autoFlowLayouts(); }
			} else { delete dataFlags.photobookLoaded; autoFlowLayouts(); }
		});
	}
}

function toggleShowCheckoutIframe(hide) {
	var photobookCheckout = document.getElementById('photobookCheckout');
	var photobookCheckoutLoader = document.getElementById('photobookCheckoutLoader');
	if (!hide) {
		photobookCheckout.style.display = 'block';
		photobookCheckoutLoader.style.display = 'none';
	} else {
		photobookCheckout.style.display = 'none';
		photobookCheckoutLoader.style.display = 'block';
	}
}

function handlePhotobookDrag(event, ui) {
	var newTop, newLeft;
	var target_img = $(event.target);
	var target_img_crop = target_img.parent();
	var container_width = target_img_crop.width();
	var container_height = target_img_crop.height();
	var img_width = target_img.width();
	var img_height = target_img.height();
	var parentPos = target_img_crop.offset();
	if (ui.absolutePosition.top > parentPos.top) newTop = 0;
	if (ui.absolutePosition.left > parentPos.left) newLeft = 0;
	if (img_height + ui.absolutePosition.top < container_height + parentPos.top) newTop = container_height - img_height;
	if (img_width + ui.absolutePosition.left < container_width + parentPos.left) newLeft = container_width - img_width;
	if (newTop != null) ui.position.top = newTop;
	if (newLeft != null) ui.position.left = newLeft;
}

function handlePhotobookDragStop(event) {
	var target_img = $(event.target);
	var layout_div = target_img.parent();
	var layout_width = layout_div.width();
	var layout_height = layout_div.height();
	var photobook_img_width = target_img.width();
	var photobook_img_height = target_img.height();
	var photobook_img_left = parseInt(target_img.css('left'), 10);
	var photobook_img_top = parseInt(target_img.css('top'), 10);
	photobook_img_top = Math.abs(photobook_img_top);
	photobook_img_left = Math.abs(photobook_img_left);
	var xStart = photobook_img_left/photobook_img_width;
	var xEnd = (layout_width+photobook_img_left)/photobook_img_width;
	var yStart = photobook_img_top/photobook_img_height;
	var yEnd = (layout_height+photobook_img_top)/photobook_img_height;
	xStart = xStart.toString().substr(0,7);
	yStart = yStart.toString().substr(0,7);
	xEnd = xEnd.toString().substr(0,7);
	yEnd = yEnd.toString().substr(0,7);
	var elem_crop = {'xStart':xStart, 'yStart':yStart, 'xEnd':xEnd, 'yEnd':yEnd};
	updatePhotobookElem(target_img, elem_crop);
	
	// update thumb crop area
	var photobook_indexes = getPhotobookElemIndex(target_img);
	var page_index = photobook_indexes[0];
	var layout_elem_index = photobook_indexes[1];
	var thumb_elem = $('#photobookPage'+page_index+'Thumb .photobook_layout_item:eq('+layout_elem_index+') img');
	thumb_elem.css('left', -1*xStart*thumb_elem.width()).css('top', -1*yStart*thumb_elem.height());
}

function getAdjustedLengths(media_args) {
	var default_width = parseInt(media_args['width'], 10);
	var default_height = parseInt(media_args['height'], 10);
	var adj_width = default_width;
	var adj_height = default_height;
	var adj_width_big = default_width;
	var adj_height_big = default_height;
	
	var max_lengths = getMaxLengths(media_args);
	var max_width = max_lengths[0];
	var max_height = max_lengths[1];
	var max_width_big = max_lengths[2];
	var max_height_big = max_lengths[3];
	
	// adjust dimensions based on dimensions of layout element
	var ratio = 1, ratio_big = 1;//, zoom_to_fit = 1;
	/* -- photo orientation is irrelevant --
	if (default_width >= default_height) { // landscape photos
		if (max_width >= max_height) { // landscape layout
			if (default_width > max_width || zoom_to_fit) ratio = max_width/default_width;
			if (default_width > max_width_big || zoom_to_fit) ratio_big = max_width_big/default_width;
		} else { // portrait layout
			if (default_height > max_height || zoom_to_fit) ratio = max_height/default_height;
			if (default_height > max_height_big || zoom_to_fit) ratio_big = max_height_big/default_height;
		}
	} else { // portrait photos
		if (max_width >= max_height) { // landscape layout
			if (default_width > max_width || zoom_to_fit) ratio = max_width/default_width;
			if (default_width > max_width_big || zoom_to_fit) ratio_big = max_width_big/default_width;
		} else { // portrait layout
			if (default_height > max_height || zoom_to_fit) ratio = max_height/default_height;
			if (default_height > max_height_big || zoom_to_fit) ratio_big = max_height_big/default_height;
		}
	}*/
	if (max_width >= max_height) { // landscape layout
		ratio = max_width/default_width;
		ratio_big = max_width_big/default_width;
	} else { // portrait layout
		ratio = max_height/default_height;
		ratio_big = max_height_big/default_height;
	} adj_width = default_width*ratio;
	adj_height = default_height*ratio;
	adj_width_big = default_width*ratio_big;
	adj_height_big = default_height*ratio_big;
	
	// if photo doesn't fill layout area, adjust accordingly
	var readjust_lengths = 1;
	if (adj_height_big < max_height_big && max_width >= max_height) { // landscape layout
		ratio = max_height/default_height;
		ratio_big = max_height_big/default_height;
	} else if (adj_width_big < max_width_big && max_width < max_height) { // portrait layout
		ratio = max_width/default_width;
		ratio_big = max_width_big/default_width;
	} else readjust_lengths = 0;
	if (readjust_lengths) {
		adj_width = default_width*ratio;
		adj_height = default_height*ratio;
		adj_width_big = default_width*ratio_big;
		adj_height_big = default_height*ratio_big;
	}
	
	return [Math.round(adj_width), Math.round(adj_height), Math.round(adj_width_big), Math.round(adj_height_big)];
}

function adjustRatio(width, height) {
	// returns better-rounded dimensions
	if (height > width) {
		var height_intervals = Math.ceil(height/6, 10);
		height = height_intervals*6;
		width = height_intervals*4;
	} else {
		var width_intervals = Math.ceil(width/6, 10);
		width = width_intervals*6;
		height = width_intervals*4;
	}
	return [width, height];
}

function getMaxLengths(media_args) {
	var media_elem = media_args['elem'];
	if (media_elem) media_elem = media_elem.replace(' img', '');
	
	var media_id = getMediaPartnerId(media_args['partnerIdValue'], media_args['partnerId_id']);
	var photobook_layout_item = media_elem? $(media_elem.replace('Canvas', 'Thumb')):$('#pageFramesWrapper #photobook_'+media_id).parent();
	var photobook_layout_item_big = media_elem? $(media_elem) : $('#photobookPageEditMainWrapper #photobook_'+media_id).parent();
	var max_width = photobook_layout_item.width();
	var max_height = photobook_layout_item.height();
	var max_lengths_adj = adjustRatio(max_width, max_height);
	max_width = max_lengths_adj[0];
	max_height = max_lengths_adj[1];
	
	photobook_layout_item_big.parent().css({position: "relative", visibility: "hidden", display: "block"});
	var max_width_big = photobook_layout_item_big.width();
	var max_height_big = photobook_layout_item_big.height();
	photobook_layout_item_big.parent().css({position: "", visibility: "", display: ""});
	
	return [max_width, max_height, max_width_big, max_height_big];
}

function getMediaPartnerId(media_id, partner_id) {
	return media_id+(partner_id==14?'flickr':partner_id==16?'kaptur':'');
}

function showUpdatedThumb(media_args) {
	var adj_lengths = getAdjustedLengths(media_args);
	var imgWidth = adj_lengths[0];
	var imgHeight = adj_lengths[1];
	var imgWidthBig = adj_lengths[2];
	var imgHeightBig = adj_lengths[3];
	var imgTrueWidth = media_args.width;
	var imgTrueHeight = media_args.height;
	
	var max_lengths = getMaxLengths(media_args);
	var max_width = max_lengths[0];
	var max_height = max_lengths[1];
	var max_width_big = max_lengths[2];
	var max_height_big = max_lengths[3];
	var aspect_ratio = 6/4;
	
	media_args['max_width'] = imgWidth;
	media_args['max_height'] = imgHeight;
	var coords = getCropBoundsTarget(media_args, max_width, max_height);
	showUpdatedThumbTarget(media_args, max_width, max_height, aspect_ratio, coords, 'pageFramesWrapper');
	media_args['max_width'] = imgWidthBig;
	media_args['max_height'] = imgHeightBig;
	coords = getCropBoundsTarget(media_args, max_width_big, max_height_big);
	showUpdatedThumbTarget(media_args, max_width_big, max_height_big, aspect_ratio, coords, 'photobookPageEditMainWrapper');
}

function showUpdatedThumbTarget(media_args, max_width, max_height, aspect_ratio, coords, target) {
	var media_id = getMediaPartnerId(media_args['partnerIdValue'], media_args['partnerId_id']);
	var crop_media_id = media_args['crop_media_id'];
	var crop_point_id = media_args['crop_point_id'];
	var media_width = media_args['max_width'];
	var media_height = media_args['max_height'];
	var media_elem = media_args['elem'];
	if (media_elem && target == 'pageFramesWrapper') media_elem = media_elem.replace('Canvas', 'Thumb');
	var load_crop = media_args['load_crop'];
	var thumb_width = max_width;//max_height*aspect_ratio;
	var thumb_height = max_height;
	var orientation = 'landscape';
	if (coords.h > coords.w) {/*thumb_width = max_width;thumb_height = max_width*aspect_ratio;*/orientation = 'portrait';}
	var rx = thumb_width / coords.w;
	var ry = thumb_height / coords.h;
	var photobook_img = $(media_elem?media_elem:'#'+target+' #photobook_'+media_id);
	var photobook_img_width = Math.round(rx * media_width);
	var photobook_img_height = Math.round(ry * media_height);
	var photobook_img_left = '-'+Math.round(rx * coords.x);
	var photobook_img_top = '-'+Math.round(ry * coords.y);
	if (load_crop) {
		photobook_img_left = -1*photobook_img_width*load_crop['xStart'];
		photobook_img_top = -1*photobook_img_height*load_crop['yStart'];
	} photobook_img.css({
		width: photobook_img_width+'px',
		height: photobook_img_height+'px',
		left: photobook_img_left+'px',
		top: photobook_img_top+'px'
	});
	
	if (!load_crop && photobook_img.length && target == 'photobookPageEditMainWrapper') {
		var layout_width = media_width;
		var layout_height = media_height;
		photobook_img_top = Math.abs(photobook_img_top);
		photobook_img_left = Math.abs(photobook_img_left);
		var xStart = photobook_img_left/photobook_img_width;
		var xEnd = (layout_width-photobook_img_left)/photobook_img_width;
		var yStart = photobook_img_top/photobook_img_height;
		var yEnd = (layout_height-photobook_img_top)/photobook_img_height;
		xStart = xStart.toString().substr(0,7);
		yStart = yStart.toString().substr(0,7);
		xEnd = xEnd.toString().substr(0,7);
		yEnd = yEnd.toString().substr(0,7);
		var elem_crop = {'width':media_args['width'], 'height':media_args['height'], 'xStart':xStart, 'yStart':yStart, 'xEnd':xEnd, 'yEnd':yEnd, 'src':media_args['crop_src']};
		updatePhotobookElem(photobook_img, elem_crop, crop_media_id, crop_point_id);
	}
	
	var thumb_class = 'photobook_thumb_'+orientation;
	photobook_img.parent().addClass(thumb_class);
}

function getCropBoundsTarget(media_args, layout_width, layout_height) {
	var imgWidth = media_args['max_width'];
	var imgHeight = media_args['max_height'];
	var cropBounds = getCropBounds({'imgWidth':imgWidth, 'imgHeight':imgHeight, 'layoutWidth':layout_width, 'layoutHeight':layout_height});
	xStart = cropBounds[0]/imgWidth;
	yStart = cropBounds[1]/imgHeight;
	xEnd = cropBounds[2]/imgWidth;
	yEnd = cropBounds[3]/imgHeight;
	var coords = {'x':cropBounds[0],'y':cropBounds[1],'w':cropBounds[2]-cropBounds[0],'h':cropBounds[3]-cropBounds[1]};
	return coords;
}

function getPhotobookElemIndex(photobook_img) {
	var photobook_page = $(photobook_img).parent().parent();
	var page_index = $('#photobookPageEditMainWrapper .photobook_page').index(photobook_page);
	var photobook_layout_items_id = '#photobookPage'+page_index+'Canvas .photobook_layout_item';
	var layout_elem_index = $(photobook_layout_items_id).index($(photobook_img).parent());
	return [page_index, layout_elem_index];
}

function updatePhotobookElem(photobook_img, elem_crop, crop_media_id, crop_point_id) {
	var photobook_indexes = getPhotobookElemIndex(photobook_img);
	var page_index = photobook_indexes[0];
	var layout_elem_index = photobook_indexes[1];
	if (memoryCreationWizard.photobookLayouts[page_index+2]['photos'][layout_elem_index]['crop']) {
		for (var i in elem_crop)
			memoryCreationWizard.photobookLayouts[page_index+2]['photos'][layout_elem_index]['crop'][i] = elem_crop[i];
	} else memoryCreationWizard.photobookLayouts[page_index+2]['photos'][layout_elem_index]['crop'] = elem_crop;
	
	if (crop_media_id) memoryCreationWizard.photobookLayouts[page_index+2]['photos'][layout_elem_index]['media_id'] = crop_media_id;
	
	if (crop_point_id) memoryCreationWizard.photobookLayouts[page_index+2]['photos'][layout_elem_index]['point_id'] = crop_point_id;
}

function getCropBounds(args) {
	var imgWidth = args['imgWidth']; 
	var imgHeight = args['imgHeight'];
	var layoutWidth = cropWidth = args['layoutWidth'];
	var layoutHeight = cropHeight = args['layoutHeight'];
	var aspectRatio = args['aspectRatio'];
	var rotate = args['rotate'];
	if (!aspectRatio) aspectRatio = 6/4;
	var startX = (imgWidth-cropWidth)/2;
	var startY = (imgHeight-cropHeight)/2;
	var endX = cropWidth+startX;
	var endY = cropHeight+startY;
	return [startX, startY, endX, endY];
}

function swapPhotobookLayout(page, neighborPage, thumb) {
	var thumbBig = thumb?'Thumb':'Canvas';
	var pageLayout = document.getElementById('photobookPage'+page+thumbBig);
	var neighborLayout = document.getElementById('photobookPage'+neighborPage+thumbBig);
	var neighborContent = neighborLayout.innerHTML;
	neighborLayout.innerHTML = pageLayout.innerHTML;
	pageLayout.innerHTML = neighborContent;
}

function shiftPhotobookPage(page, left) {
	var neighborPage = parseInt(page,10)+(left?-1:1);
	memoryCreationWizard.photobookLayouts[page+2] = memoryCreationWizard.photobookLayouts.splice(neighborPage+2, 1, memoryCreationWizard.photobookLayouts[page+2])[0];
	swapPhotobookLayout(page, neighborPage);
	swapPhotobookLayout(page, neighborPage, 1);
	if (page == memoryCreationWizard.photobook_page) showPhotobookPage(left?'prev':'next', 1);
	$('#photobookPageEditMainWrapper #photobookPage'+page+'Canvas .photobook_layout_item img, #photobookPageEditMainWrapper #photobookPage'+neighborPage+'Canvas .photobook_layout_item img').draggable({'drag':handlePhotobookDrag, 'stop':handlePhotobookDragStop});
}
/* photobook functions end */

function parseKmlDate(date) {
	var parsed_date = date.split('-'),
		start_date = parsed_date[0],
		end_date = parsed_date[1],
		start_day,start_month,start_year,end_day,end_month,end_year;
	
	if (start_date) start_date = new Date(start_date * 1000);
	if (end_date) end_date = new Date(end_date * 1000);
	
	return {
		start_date : start_date,
		end_date : end_date
	};
}

function clearMemoryTime() {
	$('#memoryStartMonth').val('');
	$('#memoryStartDay').val('');
	$('#memoryStartYear').val('');
	$('#memoryStartHour').val('');
	$('#memoryStartMinute').val('');
	$('#memoryStartAMPM').val('');
	$('#memoryEndMonth').val('');
	$('#memoryEndDay').val('');
	$('#memoryEndYear').val('');
	$('#memoryEndHour').val('');
	$('#memoryEndMinute').val('');
	$('#memoryEndAMPM').val('');
}

function getCoverPoint () {
	var cover_point_id = memoryCreationWizard.cover_point_id,
		cover_point = null;
	
	cover_point = rmnPoints[cover_point_id];
	
	return cover_point;
}

function getKmlUsersForPhoto(photo_facebook_id, callback) {
	var get_album_fql, get_photos_fql, get_users_fql, get_subjects_fql, get_album_query,
		get_users_query, get_photos_query;
	if (!photo_facebook_id) {
		return;
	}
		
	get_album_fql = "SELECT aid FROM photo WHERE pid='" + photo_facebook_id + "'";
	get_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 aid IN (" + get_album_fql + ")";
	get_subjects_fql = "SELECT subject FROM photo_tag WHERE pid IN (" + get_photos_fql + ")";
	get_users_fql = "SELECT uid, first_name, last_name FROM user WHERE uid IN (" + get_subjects_fql + ")";
	
	get_album_query = {
		fql : get_album_fql,
		args : []
	};
	
	get_photos_query = {
		fql : get_photos_fql,
		args : []
	}
	
	get_users_query = {
		fql : get_users_fql,
		args : []
	};
	
	multipleQueryFacebook([get_album_query, get_users_query, get_photos_query], function (facebook_response) {
		var album_id, users, photos;
		
		if (facebook_response) {
			album_id = (facebook_response[0] && facebook_response[0][0] && facebook_response[0][0]['aid']) || null;
			users = facebook_response[1] || [];
			photos = facebook_response[2] || [];
			
			callback(users, album_id, photos);
		}
	});
}

function saveKmlPhotos (photos, callback) {
	var photo_ids_obj = {},
		photo_ids, cover_id, num_photo_ids, i, photo_id;
	memoryCreationWizard.processAlbumPhotos([photos]);
	photo_ids = extractValuesByField(photos, 'pid');
	cover_id = getCoverPoint();
	if (cover_id) {
		cover_id = cover_id['media_type_id'];
		removeFromArray(cover_id, photo_ids);
	}
	
	num_photo_ids = arrayLength(photo_ids);
	for (i = 0; i < num_photo_ids; i++) {
		photo_id = photo_ids[i];
		photo_ids_obj[photo_id] = 1;
		memoryCreationWizard.selected_photos[photo_id] = 1;
	}
	
	callBulkSave(num_photo_ids, photo_ids_obj, callback);
}

function saveKmlDate(date) {
	var cover_point = getCoverPoint(),
		cover_point_id = cover_point['id'],
		edit_segment_args, claimed_app_id;
	
	//change the time of the cover otherwise stuff breaks when changing the date
	cover_point['utcTimeSec'] = (date.getTime() / 1000);
	saveTime(cover_point_id);
	
	//set the segment date
	segmentData.start = (memoryCreationWizard.start_time.getTime() / 1000);
	segmentData.end = (memoryCreationWizard.end_time.getTime() / 1000);
	
	//guetta needs a different app id
	claimed_app_id = (segmentData.app_id == 28) ? 30 : 29;
	
	edit_segment_args = {
		app_id : claimed_app_id, //claim the app
		utcStartSec : segmentData.start,
		utcEndSec : segmentData.end
	};
	
	//kapturDb.saveSegment(segmentData.id, edit_segment_args);
	kapturDb.saveSegment(memoryCreationWizard.sid, edit_segment_args);
	memoryCreationWizard.app_id = claimed_app_id;
}

function saveKmlMemory (date, callback) {
	var cover_point = getCoverPoint(),
		segmentData = window.segmentData,
		cover_facebook_id;
	
	//this ensures that the segment has loaded
	if (!segmentData || !segmentData.fbOwner) {
		setTimeout(function () {
			saveKmlMemory(date, callback);
		}, 500);
	}
	
	if (cover_point) {
		cover_facebook_id = cover_point['media_type_id'];
		getKmlUsersForPhoto(cover_facebook_id, function(users, album_id, photos) {
			var uids = [],
				num_users, i, user, uid, first_name, last_name, cookies_str;
			if (album_id) {
				memoryCreationWizard.suggested_album_id = album_id;
			}
			
			removeFromArray(loggedInUser, users);
			num_users = arrayLength(users);
			cookies_str = d_escape(JSON.stringify(parseCookies()));
			for (i = 0; i < num_users; i++) {
				user = users[i];
				uid = user['uid'];
				uids.push(uid);
				first_name = user['first_name'];
				last_name = user['last_name'];
				fbidsToNames[uid] = first_name + ' ' + last_name;
				memoryCreationWizard.selected_friends[user['uid']] = 1;
				addToAttendList(uid, false, first_name, last_name);
			}
			memoryCreationWizard.suggested_album_id = album_id;
			memoryCreationWizard.loadExtendedSuggestions();
			kapturDb.addUsersInBulk(segmentData.id, userProfileObj.id, uids, cookies_str);
			saveKmlDate(date);
			saveKmlPhotos(photos, callback);
			
			 /*
			memoryCreationWizard.loadFriends(function () {
				for (i = 0; i < num_users; i++) {
					user = users[i];
					if (!memoryCreationWizard.selected_friends[user]) {
						$('#f' + user).click();
					}
				}
			}); // */
		});
	} else {
		safeCall(callback);
	}
}

function displayKmlMemorySaving () {
	var choose_date_div = $('#kmlDateConfirmText, #kmlDateConfirmDate, #kmlConfirmButtons'),
		saving_div = $('#kmlDateConfirmSaving');
	
	choose_date_div.hide();
	saving_div.show();
}

function confirmKmlDate() {
	var selected_month = $('#kmlDateConfirmMonth'),
		selected_day = $('#kmlDateConfirmDay'),
		selected_year = $('#kmlDateConfirmYear'),
		basic_month = $('#memoryStartBasicMonth'),
		basic_day = $('#memoryStartBasicDay'),
		basic_year = $('#memoryStartBasicYear'),
		confirmed_date = new Date();
		
	basic_month.val(selected_month.val());
	basic_day.val(selected_day.val());
	basic_year.val(selected_year.val());
	// check date
	var old_start_time = memoryCreationWizard.start_time.getTime();
	var old_end_time = memoryCreationWizard.end_time.getTime();

	mirrorDateField('Month');
	mirrorDateField('Day');
	mirrorDateField('Year');
	//reload the stream if the date has changed
	if ((memoryCreationWizard.start_time.getTime() != old_start_time) || (memoryCreationWizard.end_time.getTime() != old_end_time)) {
		segmentData.start = memoryCreationWizard.start_time.getTime() / 1000;
		segmentData.end = memoryCreationWizard.end_time.getTime() /1000;
		reloadFacebookStream();
	}
	
	//constuct the date confirmed for the segment (midnight of the selected day)
	confirmed_date.setUTCFullYear(selected_year.val(), selected_month.val() - 1, selected_day.val());
	confirmed_date.setUTCHours(confirmed_date.getTimezoneOffset() / 60, 0, 0, 0);
	
	displayKmlMemorySaving();
	
	//load stream items
	saveKmlMemory(confirmed_date, function () {
		weddingCoverSlideshow.flagReload(true);
		togglePopup('kmlConfirmDate', false);
		reloadFacebookStream(false);
		setTimeout(function () {
			$("#topCalloutsWrapper").fadeIn();
			animateMemoryHeaderCallout('down');
		},1500);
		//showMemoryEdit('addPhotos');
	});
}

function forceReflow(id) {
	$(id).append('<div id="forcedReflowElement"></div>');
	setTimeout(function () {
		$("#forcedReflowElement").remove()
	}, 10);
}

function toggleEditPhotos () {
	var edit_buttons = ".delete_btn, .move_left_btn, .move_right_btn",
		edit_mode_button = $('#topNavEditModeBtn'),
		edit = !edit_mode_button.hasClass('edit_mode') && checkPermsForContribute();
		
	if (edit) {
		$("#photosTabContents").addClass("edit_mode");
		edit_mode_button.addClass('edit_mode').html('Done');
		$(".night_img_wrapper_thumb").find(edit_buttons).show();
		enableDragAndDrop();
		if (loggedInUser == segmentData.fbOwner) {
			$("#photosTimelineWrapper").show();
			togglePhotosTimeline();
			forceReflow('#nightCanvasRow');
		}
	} else {
		$("#photosTabContents").removeClass("edit_mode");
		edit_mode_button.removeClass('edit_mode').html('Edit');
		$(".night_img_wrapper_thumb").find(edit_buttons).hide();
		disableDragAndDrop();
		if (loggedInUser == segmentData.fbOwner) {
			$("#photosTimelineWrapper").hide();
			togglePhotosTimeline();
			forceReflow('#nightCanvasRow');
		}
	}
}


