var loggedInUser, userProfileObj = new Object(); // holds user profile data
var dataFlags = new Object(); // data loading flags
var fbAlbums = new Object(); // fb album data
var fbPhotos = new Object(); // fb photo data
var fbVideos = new Object(); // fb video data
var rmnIdsToFbids = new Object();
var fbidsToNames = new Object();
fbVideos.yt = new Object(); // youtube video data
fbVideos.vim = new Object(); // vimeo video data
var fbFriendIds = new Object(); // fb-rmn ids array
var event_suggestions_list = new Object(); // fb event data
var profileData = new Object(); // user profile data

//segment specific variables
var segmentData;
var fbPhotoPointIds;
var fbVideoPointIds;
var flickrPhotoPointIds;
var rmnPoints;
var rmnPointTimes;
var rmnPointFriendFilters;
var segmentFriendFbIds;
var segmentFriendIds;
var segmentPairingIds;
var segmentFbPosts;
var segmentFlags;
var wizardMemoryData;
var wizardMemoryThumb;
var wizardMemoryFriends;

var night_info_cleared = 1;
var min_posts_shown = 3, min_desc_chars = 225, max_desc_chars = 500;
var last_shown_owner_album, last_shown_friend_album, last_shown_friend_id;
var slideshow_initialized, slideshow_data_loaded, facebook_ids_loaded, rmn_ids_loaded;

var ajax_loader_small = '<img src="'+TEMPLATE_VIEW_PATH+'images/ajax_loader_small.gif">';
var ajax_loader = '<img src="'+TEMPLATE_VIEW_PATH+'images/ajax_loader.gif">';
if (location.href.match('kaptur')) {
	ajax_loadersmall = '<img src="'+TEMPLATE_VIEW_PATH+'images/ajax_loader_small_orange.gif">';
	ajax_loader = '<img src="'+TEMPLATE_VIEW_PATH+'images/ajax_loader_orange.gif">';
}

var SERVICE_TYPES = {
	"facebook":1,
	"twitter":2,
	"flickr":3,
	"kaptur": 4,
	"aviary":5
}

var PARTNER_TYPES = {
	"facebook_user" : 1,
	"facebook_event" : 2,
	"facebook_post" : 3,
	"facebook_photo" : 4,
	"facebook_album" : 5,
	"rmn_user_log_entry" : 6,
	"rmn_guest_list" : 7,
	"facebook_link" : 8,
	"facebook_video" : 9,
	"youtube_video" : 10,
	"vimeo_video" : 11,
	"youtube_music" : 12,
	"vimeo_music" : 13,
	"flickr_photo" : 14,
	"facebook_tag": 15,
	"kaptur_photo": 16,
	"aviary_photo": 17
}

var MEDIA_TYPES = {
	"photo" : 1,
	"video" : 2,
	"voicemail" : 3,
	"text_message" : 4,
	"link" : 5,
	"photo_album" : 6,
	"music": 7
}

var contributeElements = {'nightCanvasAdd':'photos', 'canvasAddMoreBtn':'photos', 'nightCanvasAddLinkWrapper':'photos', 'addCanvasPhotoSmall':'photos', 'newNightCreateAddPhotos':'photos', 'newNightCreateAddFriendPhotos':'photos', 'newNightCreateAddIcons':'photos', 'addCanvasPhotoBig':'photos', 'addCanvasMediaIcons':'photos', 'attendBtn':'attend', 'addFriendsBtn':'friends', 'nightFriendsAdd':'friends', 'addCanvasFriendSmall':'friends', 'newNightCreateAddFriends':'friends', 'addCanvasFriendBig':'friends', 'addVideosBtn':'music', 'nightVideosAdd':'music', 'addCanvasMusicSmall':'music', 'addCanvasMusicBig':'music', 'nightCanvasAddVideos':'videos', 'nightCanvasAddVideosLinkWrapper':'videos', 'addCanvasVideoSmall':'videos', 'addCanvasVideoBig':'videos', 'retroDiaryAddBtn':'posts', 'retroDiaryAddLink':'posts', 'retroDiaryEmptyLink':'posts', 'addCanvasStatusSmall':'posts', 'addCanvasStatusBig':'posts', 'filterMediaByPersonReload':''}; // 'nightCanvasAddMedia':'photos', 
var contributeSavingElements = {'addCanvasMediaIcons':'photos', 'addVideosBtn':'music', 'nightVideosAdd':'music', 'addCanvasMusicSmall':'music', 'addCanvasMusicBig':'music', 'nightCanvasAddVideos':'videos', 'nightCanvasAddVideosLinkWrapper':'videos', 'addCanvasVideoSmall':'videos', 'addCanvasVideoBig':'videos', 'retroDiaryAddBtn':'posts', 'retroDiaryAddLink':'posts', 'retroDiaryEmptyLink':'posts', 'addCanvasStatusSmall':'posts', 'addCanvasStatusBig':'posts', 'filterMediaByPersonReload':''};

function loginToFacebook(postAuth, args) {
	var login = FB.login,
		handleFacebookLoginResponse = function (response) {
		var session = getFacebookSession(response);
		if (session) {
			// refresh the page on login
			if (typeof postAuth != 'function') {
				var currentUrl = removeUrlParam('fbDown', location.href).replace(/#$/g, '');
				var trackLoggedIn = '&loggedIn=1';
				try {if (editNight) trackLoggedIn = '&contributeClicked=1';} catch (err) {}
				if (currentUrl.indexOf('p=') == -1) location.href = '?p=f'+trackLoggedIn; // default case; redirect to homepage
				else if (currentUrl.indexOf('p=h') != -1 && currentUrl.indexOf('sts=') == -1 && currentUrl.indexOf('sid=') == -1) location.href = getNewPageUrl('f')+trackLoggedIn; // case where p=h is present, but no segment or time has been specified
				else if (currentUrl.indexOf('p=n') != -1 && currentUrl.indexOf('sts=') == -1 && currentUrl.indexOf('sid=') == -1 && segmentData.start && segmentData.end) location.href = currentUrl + '&sts=' + segmentData.start + '&ets=' + segmentData.end + trackLoggedIn; // preserve date for new nights
				else {
					var wizard_params = '';
					try {
						var end_month = document.getElementById('createMemoryEndTimeMonth').value;
						var end_day = document.getElementById('createMemoryEndTimeDay').value;
						var end_year = document.getElementById('createMemoryEndTimeYear').value;
						var end_date = end_month+'/'+end_day+'/'+end_year;
						var start_date = document.getElementById('createMemoryStartTimeMonth').value+'/'+document.getElementById('createMemoryStartTimeDay').value+'/'+document.getElementById('createMemoryStartTimeYear').value;
						var createMemoryStartTimeCanvas = document.getElementById('createMemoryStartTimeCanvas');
						var createMemoryEndTimeCanvas = document.getElementById('createMemoryEndTimeCanvas');
						if (createMemoryStartTimeCanvas) start_date = createMemoryStartTimeCanvas.value;
						if (createMemoryEndTimeCanvas) end_date = createMemoryEndTimeCanvas.value;
						var end_date_param = ((end_month&&end_day&&end_year)||createMemoryEndTimeCanvas)? '&end_date='+end_date:'';
						wizard_params += '&start_date='+start_date+end_date_param+(memoryCreationWizard.title?'&title='+encodeURIComponent(memoryCreationWizard.title):'');
						if (dataFlags.proceedStep2) wizard_params += '&step='+dataFlags.proceedStep2;//'&proceed=1';
						if (memoryCreationWizard.storedWeddingEmail) wizard_params += '&storedEmail=1';
					} catch (err) {}
					location.href = currentUrl+wizard_params+trackLoggedIn; // for everything else
				}

			} else postAuth();
		} else {
			// user is not logged in
		}
	};

	try {
		login = FacebookProxy.login;
	}catch (err) {
		login = FB.login;
	}
	
	var params = {scope:'email, friends_photos, user_photos, friends_videos, user_videos, friends_relationships, friends_relationship_details, read_stream'};//user_photo_video_tags, friends_photo_video_tags, 
	if (location.href.indexOf('perms=more') != -1) {
		params = {scope:'read_stream, publish_stream, user_events, friends_photos, user_photos, friends_videos, user_videos, email, user_relationships, user_relationship_details, friends_relationships, friends_relationship_details, read_friendlists'};//user_photo_video_tags, friends_photo_video_tags, 
	}if (args && args['homepage']) params = {scope:'email, friends_photos, user_photos, user_relationships, friends_videos, user_videos, friends_relationships, friends_relationship_details, read_stream'};
	login(handleFacebookLoginResponse, params);//user_relationships, user_relationship_details, 
	
	try {$.cookies.set("fbDownMsg", null);}
	catch (err) {}
}

function logout() {
	var onlogout = function() {
		$.cookies.set("userPerms", null);
		if (isMobileApp()) location.href = 'http://localhost/index.html';
		else location.href = '.';
	};
	try {
		FacebookProxy.logout(onlogout);
	} catch (err) {
		FB.logout(onlogout);
	}
	return false;
}

function loadOfflineView() {
	try {
		if (!dataFlags.offlineView) {
			// load rmn segment and points
			loadRmnSegment();
			dataFlags.offlineView = 1;
		}
	} catch(err) {}
}

function welcomeFBUser(initFn) {
	var fb_down;
	clearLoginTimeout();
	setLoginTimeout();
	
	// retrieve fb session
	try {
		var session = getFacebookSession(),
			sessionUser;
		
		if (session) {
			sessionUser = getFacebookUserId(session);
		}
		
		if (!sessionUser) {
			fb_down = 1;
		}
		//FB.getLoginStatus(function(response) {
		var fb_down;
		dataFlags.fbDown = null;
		if (!dataFlags.offlineView) {
			showLogoutBtn(1);
		}
		clearLoginTimeout();
		
		if (location.href.indexOf('fbDown=1') != -1 || dataFlags.fbDown) {
			fb_down = 1;
			if (!dataFlags.bypassDown) loggedInUser = null;
		}
		if (!fb_down || dataFlags.bypassDown) {
			//if (response.session) {
			//loggedInUser = response.session.uid;
			loggedInUser = sessionUser;
			if (loggedInUser) {
				loadRmnUserInfo(initFn); // load rmn user info
			} else {
				fb_down = 1;
			}
			//} else fb_down = 1; // no user session available, someone you dont know
		}
		if (fb_down && !dataFlags.fbDown && !dataFlags.bypassDown) {
			handleFBDown();
		} else if ($.cookies.get("fbDownMsg")) {
			$.cookies.set("fbDownMsg", null);
		}
		//});
		
		// check for fb permissions
		userProfileObj.perms = {};
		var user_perms = $.cookies.get("userPerms");
		if (!user_perms) {
			FB.api('/me/permissions', function(response) {
				if (response && response.data && response.data.length) {
					userProfileObj.perms = response.data[0];user_perms = '';
					for (var i in userProfileObj.perms) user_perms += (user_perms?',':'')+i;
					$.cookies.set("userPerms", user_perms);
				}
			});
		} else { // load user permissions
			user_perms = user_perms.split(',');
			for (var i=0; i<user_perms.length; i++) {
				if (user_perms[i]) {
					userProfileObj.perms[user_perms[i]] = 1;
				}
			}
		}
		
		
		// *hack* use extra check to ensure new user has properly authenticated
		// problem: fql query functions don't work right after certain new users authenticate (or remove app)
		if (typeof dataFlags.initCallback == 'function') {
			var initFnTimeout = setTimeout('dataFlags.initCallback()', 7000);
			queryFacebook('SELECT is_app_user FROM user WHERE uid={0}', [sessionUser.toString()], function() {
				clearTimeout(initFnTimeout);
			});
		}
	} catch (err) {handleFBDown();}
}

function claimSegment() {
	/*if (segmentFlags && !segmentFlags.claimed && loggedInUser) {
		$.colorbox({
			inline:true,
			href:"#claimSegmentMessage"
		});
	} else {
		alert('already claimed');
	}*/
}

function getEventsPermission() {
	if (!userProfileObj.perms['user_events']) {
		FB.login(function(response) {
			var session = getFacebookSession();
			if (session) { 
				userProfileObj.perms['user_events'] = 1;
				$.cookies.set("userPerms", null);
				segmentFlags.eventsLoaded = false;
				loadFbEvents();
			}
		}, {scope:'user_events'});
	}
}

function getReadStreamPermission() {
	if (!userProfileObj.perms['read_stream']) {
		FB.login(function(response) {
			var session = getFacebookSession();
			if (session) {
				getFacebookPermissions(function (perms) {
					if (perms['read_stream']) {
						userProfileObj.perms['read_stream'] = 1;
						$.cookies.set("userPerms", null);
						reloadFacebookStream();
					}
				});
			}
		}, {scope:'read_stream'});
	}
}

function handleFBDown() {
	dataFlags.fbDown = 1;
	clearLoginTimeout();showLogoutBtn();
	if (!$.cookies.get("fbDownMsg") && !dataFlags.bypassDown) {
		showError('Oops! Facebook is not responding. You may have been logged out or Facebook might be down.<br>Click <a href="javascript:loginToFacebook()">here</a> to sign in again or click <a href="javascript:$.colorbox.close()">here</a> to view the site in offline mode.', handleFBDownConfirmed);//<div style="width:855px">
		$.cookies.set("fbDownMsg", 1);
	} else handleFBDownConfirmed();
}

function handleFBDownConfirmed() {
	if (location.href.indexOf('p=n') != -1) {
		if (location.href.indexOf('sid=') == -1) clearLoadingAnimations();
		loadOfflineView();
	} else if (location.href.indexOf('p=f') != -1) {
		if (location.href.indexOf('fid=') != -1 || dataFlags.bypassDown) loadProfilePage();
		else location.href = '/';
	}
}

function setLoginTimeout() {
	if (!dataFlags.bypassDown) {
		if (!$.cookies.get("fbDownMsg")) dataFlags.loginTimeout = setTimeout('handleFBDown()', 10000);
		else $(document).ready(function() {handleFBDown();});
	}
}

function clearLoginTimeout() {
	if (dataFlags.loginTimeout) {
		clearTimeout(dataFlags.loginTimeout);
		dataFlags.loginTimeout = null;
	}
}

function userProfileObjDataSet() {
	//return (userProfileObj.name && (userProfileObj.first_name != 'not_set') && userProfileObj.email && (userProfileObj.email != 'not_set'));
	return (userProfileObj.first_name && (userProfileObj.first_name != 'not_set') && userProfileObj.email && (userProfileObj.email != 'not_set'));
}

function welcomeRmnUser(initFn) {
	if (userProfileObjDataSet()) {
		displayWelcomeMsg(initFn);
	} else {
		queryFacebook('select first_name, last_name, name, pic_square, email from user where uid={0}',
			[loggedInUser.toString()],
			function(users) {
				userProfileObj.name = urldecode(users[0].name);
				userProfileObj.first_name = urldecode(users[0].first_name);
				userProfileObj.last_name = urldecode(users[0].last_name);
				userProfileObj.thumbnail = urldecode(users[0].pic_square);
				userProfileObj.email = urldecode(users[0].email);
				// store fb data in db - 'http://graph.facebook.com/'+loggedInUser+'/picture'
				// note:: d_escape names as well
				writeToDB('setRmnUserInfo', [{'firstName':d_escape(userProfileObj.first_name), 'lastName':d_escape(userProfileObj.last_name), 'thumb':d_escape(userProfileObj.thumbnail), 'emailAddress':d_escape(userProfileObj.email)}, userProfileObj.id]);
				displayWelcomeMsg(initFn); // display welcome message
			}
		);
	}
	
	// store email address
	if (!userProfileObj.email || userProfileObj.email == 'null' || userProfileObj.email == 'not_set' || $.cookies.get("emailLoginId")) {
		queryFacebook('select email from user where uid={0}',
			[loggedInUser], function(users) {
				userProfileObj.email = users[0].email;
				writeToDB('setRmnUserInfo', [{'emailAddress':d_escape(userProfileObj.email)}, userProfileObj.id]);
			});
	}
	
	// store gender and locale
	if (!userProfileObj.gender || !userProfileObj.locale) {
		queryFacebook('select sex, locale from user where uid="{0}"',
			[loggedInUser], function(users) {
				var userInfo = {};
				if (!userProfileObj.gender) {
					userProfileObj.gender = users[0].sex;
					userInfo['gender'] = d_escape(userProfileObj.gender);
				}if (!userProfileObj.locale) {
					userProfileObj.locale = users[0].locale;
					userInfo['locale'] = d_escape(userProfileObj.locale);
				}
				
				writeToDB('setRmnUserInfo', [userInfo, userProfileObj.id]);
			});
	}
	
	// set app id if null (users that were originally added as friends)
	if (!userProfileObj.app_id) {
		writeToDB("setRmnUserInfo",[{"app_id":rmnAppId},userProfileObj.id]);
	}
	
	// store updated relationship status
	if (!$.cookies.get("setRelationshipStatus"+loggedInUser)) {
		setRelationshipStatus(loggedInUser, userProfileObj.id);
	}
	
	// remove any existing email login cookie
	$.cookies.set("emailLoginId", null);
}

function setRelationshipStatus(fbid, rmnid) {
	var relationship_status = {
		fql: 'SELECT relationship_status, significant_other_id FROM user WHERE uid="{0}"',
		args: [fbid]
	};
	var significant_other_info = {
		fql: 'SELECT first_name, last_name FROM user WHERE uid IN (SELECT significant_other_id FROM user WHERE uid="{0}")',
		args: [fbid]
	};
	multipleQueryFacebook([relationship_status, significant_other_info], function() {
		if (fbid == loggedInUser) $.cookies.set("setRelationshipStatus"+loggedInUser, 1, {expiresAt: new Date(new Date().getTime()+7*24*60*60*1000)}); // update every 7 days
		relationship_status = relationship_status.value;
		if (relationship_status) relationship_status = relationship_status[0];
		significant_other_info = significant_other_info.value;
		if (significant_other_info) significant_other_info = significant_other_info[0];
		var relationship_status_val, significant_other_id;
		if (relationship_status) {
			relationship_status_val = relationship_status['relationship_status'];
			significant_other_id = relationship_status['significant_other_id'];
		}var significant_other_fname = '', significant_other_lname = '';
		if (significant_other_id) {
			significant_other_fname = significant_other_info['first_name'];
			significant_other_lname = significant_other_info['last_name'];
		}
		if (fbid == loggedInUser || relationship_status_val) writeToDB('setSignificantOtherInfo', [{'loggedInUserId':rmnid, 'status':relationship_status_val, 'soFbId':significant_other_id, 'soFirstName':significant_other_fname, 'soLastName':significant_other_lname}]);//, 'soAppId':rmnAppId
	});
}

var pageOnloadFn;
function runOnPageLoad(fn) {
	var session = getFacebookSession();
	if (typeof pageOnloadFn == 'function') {
		/*
		 * the new oauth methods do not give FB.getAuthResponse() a value right
		 * away so we may need to wait.  Getting the login Status returns quickly
		 * and will ensure FB.getAuthResponse has a value.
		 */
		if (session) {
			pageOnloadFn();
		} else {
			FB.getLoginStatus(function (response) {
				pageOnloadFn();
			});
		}
	} else {
		pageOnloadFn = fn;
	}
}

function displayWelcomeMsg(initFn) {
	var user_first_name = userProfileObj.first_name;
	var userProfileThumb = document.getElementById('userProfileThumb');
	if (userProfileThumb) {
		userProfileThumb.src = userProfileObj.thumbnail;
		userProfileThumb.alt = user_first_name;userProfileThumb.title = user_first_name;
	}
	
	try {
		document.getElementById('userProfileInfo').innerHTML = 'Welcome, '+user_first_name;
		document.getElementById('headerBarRightOn').style.display = 'block';
	} catch (err) {}
	
	try {
		document.getElementById('newNightCreateName').innerHTML = user_first_name;
	} catch (err) {}
	
	// call initialization function
	if (typeof initFn == 'function') {
		initFn();
	}
}

var date_selected;
var fbEventStats = new Object();

function loadFbInfo(start_time) {
	if (!start_time) {
		// load fb event info for today
		start_time = new Date();
		start_time.setHours(0, 0, 0, 0);
		start_time = start_time.getTime() / 1000;
	}
	
	// update recreate button event handler
	//eval("document.getElementById('recreateBtni').onclick = function() { location.href = '?p=n&fid="+loggedInUser+"&sts="+start_time+"'; } ");
	if (!segmentData) {
		segmentData = {}
	}
	segmentData.start = start_time;
	if (!segmentData.location) {
		segmentData.location = {};
	}
	segmentData.location.eid = '';
	
	// update active date
	date_selected = start_time;
	
	// initialize fb events object for selected date
	if (!fbEventStats[start_time]) fbEventStats[start_time] = new Object();
	
	// calculate time range end
	var end_time = start_time + 36*60*60;
	
	if (loggedInUser) {
		if (loggedInUser == getFid) {
			// query fb events count
			loadFbEventCount(start_time, end_time);
			
			// query other fb resource counts
			loadFbResourceCount('posts', start_time, end_time);
			loadFbResourceCount('photos', start_time, end_time);
			loadFbResourceCount('videos', start_time, end_time);
		}
	} else {
		document.getElementById('fbEventsCount').innerHTML = 0;
		document.getElementById('fbPostsCount').innerHTML = 0;
		document.getElementById('fbPhotosCount').innerHTML = 0;
		document.getElementById('fbVideosCount').innerHTML = 0;
	}
}

function recreateNight() {
	var start_date_string = '',
		start_date, start_day, start_month, start_year, start_date_string;
	if (segmentData.start) {
		start_date = new Date(segmentData.start * 1000);
		start_day = start_date.getUTCDate();
		start_month = start_date.getUTCMonth() + 1;
		start_year = start_date.getUTCFullYear();
		start_date_string = '&start_date=' + start_month + '/' + start_day + '/' + start_year;
	}
	
	location.href = '?p=nw' + start_date_string;//p=create
	//old version
	/*var fid = (loggedInUser) ? ('&fid='+loggedInUser) : '';
	var sts = (segmentData.start) ? ('&sts='+segmentData.start) : '';
	var eid = (segmentData.location.eid) ? ('&event_id='+segmentData.location.eid) : '';
	location.href = '?p=n'+fid+sts+eid;*/
}

function loadFbEventCount(start_time, end_time) {
	var fbEventsCount = document.getElementById('fbEventsCount');
	var fbEventTitles = document.getElementById('fbEventsList');
	var saved_events_count = fbEventStats[start_time]['events'];
	fbEventTitles.innerHTML = '';
	if (saved_events_count == null) {
		fbEventsCount.innerHTML = ajax_loader_small;
		queryFacebook('SELECT name, eid FROM event WHERE (eid IN (SELECT eid FROM event_member WHERE uid={0})) AND ((start_time >= {1} AND start_time <= {2}) OR (end_time >= {1} AND end_time <= {2}) OR (start_time <= {1} AND end_time >= {2}))',
			[loggedInUser, start_time, end_time], // tagline, description, pic, start_time, end_time, location, venue]
			function(events) {
				var event_titles = '';
				var events_count = 0;
				if (events && events.length) {
					events_count = events.length;
					event_titles = generate_event_titles(events);

					// don't update if user has already selected another date
					if (date_selected == start_time) {
						fbEventsCount.innerHTML = events_count;
						fbEventTitles.innerHTML = event_titles;
					}
				} else {
					fbEventsCount.innerHTML = 0;
					fbEventTitles.innerHTML = '';
				}
				fbEventStats[start_time]['events'] = events_count;
				fbEventStats[start_time]['eventsList'] = event_titles;
			}
		);
	} else {
		fbEventsCount.innerHTML = saved_events_count;
		fbEventTitles.innerHTML = fbEventStats[start_time]['eventsList'];
	}
}

function generate_event_titles(events) {
	var event_titles = '';
	if (!segmentData) {
		segmentData = {};
	}
	if (!segmentData.location) {
		segmentData.location = {};
	}
	for (var i=0; i<events.length; i++) {
		var event_name = events[i].name;
		var event_name_short = limitLen(event_name, 35);
		var event_id = events[i].eid;
		var event_click = "segmentData.location.eid='"+event_id+"'";
		event_titles += '<div><input type="radio" name="fbEvent" id="fbEvent'+event_id+'" onclick="'+event_click+'" value="'+events[i].eid+'"> <label for="fbEvent'+event_id+'" title="'+event_name+'">'+event_name_short+'</label></div>';
	}
	return event_titles;
}

var resource_count_fql = {
	'posts':'SELECT post_id FROM stream WHERE source_id={0} AND (created_time >= {1} AND created_time <= {2})',
	// created_time, actor_id, target_id, message, attachment, tagged_ids
	'photos':'SELECT pid, src FROM photo WHERE (pid IN (SELECT pid FROM photo_tag WHERE subject={0}) OR aid IN (SELECT aid FROM album where owner={0})) AND (created >= {1} AND created <= {2})',
	// aid, owner, src, src_big, src_small, link, caption, created, modified
	'videos':'SELECT vid FROM video WHERE (owner={0} OR vid IN (SELECT vid FROM video_tag WHERE subject={0}))  AND (created_time >= {1} AND created_time <= {2})' // owner, title, description, thumbnail_link, embed_html, created_time
}

function loadFbResourceCount(resource, start_time, end_time) {
	var resource_capped = ucfirst(resource);
	var fbResourceCount = document.getElementById('fb'+resource_capped+'Count');
	var saved_resource_count = fbEventStats[start_time][resource];
	if (saved_resource_count == null) {
		fbResourceCount.innerHTML = ajax_loader_small;
		queryFacebook( resource_count_fql[resource],
			[loggedInUser, start_time, end_time],
			function(data) {
				var resource_count = 0;
				if (data && data.length) {
					resource_count = data.length;
					if (date_selected == start_time) fbResourceCount.innerHTML = resource_count;
				} else fbResourceCount.innerHTML = 0;
				fbEventStats[start_time][resource] = resource_count;
			}
		);
	} else fbResourceCount.innerHTML = saved_resource_count;
}

function selectDate(dateText, nightPage, homePage) {
	var selectedDate = new Date(Date.parse(dateText));
	if (!nightPage) {
		document.getElementById('dateSelected').innerHTML = formatDateStr(selectedDate);
		loadFbInfo(selectedDate.getTime()/1000);
	} else {
		selectedDate.setHours(0,0,0,0); // naturalize date
		var segment_start = selectedDate.getTime()/1000;
		if (homePage) {
			try {document.getElementById('recreateBtn').onclick = function() {location.href = '?p=n&sts='+segment_start;}} catch (err) {}
		} else {
			var segment_end = segment_start+36*60*60;
			if (!segmentData) segmentData = new Object();
			segmentData['start'] = segment_start;
			segmentData['end'] = segment_end;
			segmentData['tzoffset'] = -selectedDate.getTimezoneOffset()/60;
			setSegmentTense();updateDateDisplays();surfaceCalendar(1);
		}
	}
}

var prev_index_val = {'featured':1, 'recent':1};
function jumpToSlide(index, section, delayed) {
	var prev_index = prev_index_val[section];
	// introduce delay to apply changes after jquery handlers
	if (!delayed) setTimeout('jumpToSlide('+index+', \''+section+'\', 1)', 0);
	else if (index != prev_index) {
		var section_short = section.charAt(0);
		document.getElementById(section_short+'l'+index).childNodes[0].className = section+'NightBulletSelected';
		document.getElementById(section_short+'l'+prev_index).childNodes[0].className = section+'NightBullet';
		prev_index_val[section] = index;
		
		var prev_link_img = document.getElementById(section+'NightPrev');
		var next_link_img = document.getElementById(section+'NightNext');
		var prev_link = prev_link_img.parentNode;
		var next_link = next_link_img.parentNode;
		if (index != 1) {
			prev_link.href = '#'+section_short+(index-1);
			prev_link_img.className = '';
			eval('document.getElementById("'+section+'NightPrev").parentNode.onclick = function() { jumpToSlide('+(index-1)+', "'+section+'") }');
		} else {
			prev_link.href = 'javascript:void(0)';
			prev_link_img.className = 'disabled_btn';
		}
		var num_nigts = document.getElementById(section+'NightBullets').getElementsByTagName('a').length;
		if (index < num_nigts) {
			next_link.href = '#'+section_short+(index+1);
			next_link_img.className = '';
			eval('document.getElementById("'+section+'NightNext").parentNode.onclick = function() { jumpToSlide('+(index+1)+', "'+section+'") }');
		} else {
			next_link.href = 'javascript:void(0)';
			next_link_img.className = 'disabled_btn';
		}
	}
}

function updateAutoShowRemove(classname, delayed) {
	// use delay to spread out consecutive updates
	if (!delayed) {setTimeout('updateAutoShowRemove("'+classname+'", 1)', 0);return;}
	
	if (in_array(classname, ['recent_night_wrapper', 'night_friend_pic_wrapper', 'video_thumb_wrapper', 'friend_wrapper'])) {
		$('.'+classname).bind('mouseenter mouseleave', function(e) {
			var fade_type = e.type == 'mouseenter' ? 'fadeIn' : 'fadeOut';
			var binding = e.type == 'mouseenter' ? 'bind' : 'unbind';
			if (e.type == 'mouseenter') $(this).find('.delete_btn, .small_delete_btn').show();
			else $(this).find('.delete_btn, .small_delete_btn').hide();
			/*if (e.type == 'mouseleave' || !isLastChild(this)) {
				if (e.type == 'mouseenter') $(this).find('.move_right_btn').show();
				else $(this).find('.move_right_btn').hide();
			}
			if (e.type == 'mouseleave' || !isFirstChild(this)) {
				if (e.type == 'mouseenter') $(this).find('.move_left_btn').show();
				else $(this).find('.move_left_btn').hide();
			} */ // switched to show/hide because fade causes recursion errors
			/* $(this).find('.delete_btn, .small_delete_btn')[fade_type](50);
			if (e.type == 'mouseleave' || !isLastChild(this)) {
				$(this).find('.move_right_btn')[fade_type](50);
			} if (e.type == 'mouseleave' || !isFirstChild(this)) {
				$(this).find('.move_left_btn')[fade_type](50);
			}*/
		}); // .night_img_wrapper_big, .night_friend_pic_wrapper, .video_thumb_wrapper
	}
	
	// update colorbox for edit videos
	if (classname == 'video_thumb_wrapper') $(".edit_video_btn").colorbox({opacity:.75, maxWidth:'85%', maxHeight:'85%', inline:true, title:'&nbsp;', href:"#editVideosWrapper", onComplete:updateColorboxScrollbars});
}

function preload_next_prev(elem) {
	try { // preload next and prev images
		var prev_elem = $(elem).parent().prev().find('.night_img_big'); //.parent().parent()
		if (prev_elem.length) prev_elem.trigger("appear");
		else {
			$('.night_img_big:eq('+($('.night_img_big').size()-1)+')').trigger("appear");
			$('.night_img_big:eq('+($('.night_img_big').size()-2)+')').trigger("appear");
		}
		var prev_prev_elem = $(elem).parent().next().find('.night_img_big');//.trigger("appear");
		if (prev_prev_elem.length) prev_prev_elem.trigger("appear");
		var next_elem = $(elem).parent().prev().prev().find('.night_img_big');
		if (next_elem.length) next_elem.trigger("appear");
		else {$('.night_img_big:eq(0)').trigger("appear");$('.night_img_big:eq(1)').trigger("appear");}
		var next_next_elem = $(elem).parent().next().next().find('.night_img_big');
		if (next_next_elem.length) next_next_elem.trigger("appear");
		
		// preload for grid view
		var prev_elem_thumb = $(elem).parent().prev().find('.night_img_thumb');
		if (prev_elem_thumb.length) {
			prev_elem_thumb.trigger("appear");
			prev_elem_thumb.attr('src', prev_elem_thumb.attr('grid_thumb'));
		} else {
			var night_img_thumb1 = $('.night_img_thumb:eq('+($('.night_img_thumb').size()-1)+')');
			var night_img_thumb2 = $('.night_img_thumb:eq('+($('.night_img_thumb').size()-2)+')');
			night_img_thumb1.trigger("appear");night_img_thumb2.trigger("appear");
			night_img_thumb1.attr('src', night_img_thumb1.attr('grid_thumb'));
			night_img_thumb2.attr('src', night_img_thumb2.attr('grid_thumb'));
		}
		var prev_prev_elem_thumb = $(elem).parent().next().find('.night_img_thumb');
		if (prev_prev_elem_thumb.length) {
			prev_prev_elem_thumb.trigger("appear");
			prev_prev_elem_thumb.attr('src', prev_prev_elem_thumb.attr('grid_thumb'));
		}
		var next_elem_thumb = $(elem).parent().prev().prev().find('.night_img_thumb');
		if (next_elem_thumb.length) {
			next_elem_thumb.trigger("appear");
			next_elem_thumb.attr('src', next_elem_thumb.attr('grid_thumb'));
		} else {
			$('.night_img_thumb:eq(0)').trigger("appear");
			$('.night_img_thumb:eq(1)').trigger("appear");
			$('.night_img_thumb:eq(0)').attr('src', $('.night_img_thumb:eq(0)').attr('grid_thumb'));
			$('.night_img_thumb:eq(1)').attr('src', $('.night_img_thumb:eq(1)').attr('grid_thumb'));
		}
		var next_next_elem_thumb = $(elem).parent().next().next().find('.night_img_thumb');
		if (next_next_elem_thumb.length) {
			next_next_elem_thumb.trigger("appear");
			next_next_elem_thumb.attr('src', next_next_elem_thumb.attr('grid_thumb'));
		}
	} catch(err) {}
}

function loadTagEditor(elem_id, point_id, owned) {
	var rmn_point = rmnPoints[point_id];
	var elem = document.getElementById(elem_id);
	var elem_type = rmn_point['partnerId_id'];
	
	// insert thumb
	document.getElementById('fbTaggedMediaThumb').src = elem.getAttribute('grid_thumb');
	// generate list of tagged names
	var taggedFriendHtml = '';var fbMediaFriendsList = document.getElementById('fbMediaFriendsList');
	for (var i in rmn_point['tags']) {
		taggedFriendHtml += '<div id="mediaTag'+i+'"><fb:name uid="'+i+'" capitalize="true" linked="false"></fb:name></div>';
		var fbMediaFriendsList = document.getElementById('fbMediaFriendsList');
	}
	fbMediaFriendsList.innerHTML = taggedFriendHtml;
	document.getElementById('addMediaTagsDone').onclick = function() {$(elem).colorbox({'open':true});};
	var mediaFriendTagsReload = document.getElementById('mediaFriendTagsReload');
	mediaFriendTagsReload.onclick = function() {reloadMediaTags(elem.id.substr(1), elem_type, point_id);};
	if (owned && in_array(elem_type, [4,9])) mediaFriendTagsReload.style.display = 'inline';
	else mediaFriendTagsReload.style.display = '';
	loadFBML(fbMediaFriendsList);
	var div_name = 'addMediaTagsWrapper';
	var fbMediaFriendsWrapper = document.getElementById('fbMediaFriendsWrapper');
	if (owned) {loadUserFriends(0, [elem, point_id]);fbMediaFriendsWrapper.style.display = '';}
	else {fbMediaFriendsWrapper.style.display = 'none';div_name += 'Small';}
	clearFriendFilter(0, 1); // clear friend filter
	initColorbox('', div_name, updateTaggedFilterHTML);
}

function updatePreloadLightboxSize(id, delayed) {
	if (!id) id = 'photoImg';
	if (!delayed) {
		if (dataFlags.lightboxLoaded) clearTimeout(dataFlags.lightboxLoaded);
		dataFlags.lightboxLoaded = setTimeout('updatePreloadLightboxSize(\''+id+'\', 1); dataFlags.lightboxLoaded = null', 250);
		return;
	}
	try {
		document.getElementById(id+'Wrapper').style.height='';
		$.colorbox.resize({'innerWidth':Math.max(document.getElementById(id).width, 567)+(id=='aviaryImg'?30:0)});
	} catch(err) {}
}

/**
 * use closures so that the inner functions do not pollute the global namespace
 * and they are only created once.
 */
updateLightboxPhotos = function () {
	var generateTagHtml = function (rmn_point, img_point_id, img_elem_id, offline_click_handler, wizardContributeCheck) {
		var refresh_btn = '',
			tag_data = rmn_point['tags'],
			tag_count = 0,
			media_tags = '',
			click_handler, i, tag_head;
		if (segmentFlags.contribute && in_array(rmn_point['partnerId_id'], [4,9]) && wizardContributeCheck) {
			if (offline_click_handler) click_handler = offline_click_handler;
			else click_handler = 'reloadMediaTags(\''+img_elem_id.substr(1)+'\', \''+rmn_point['partnerId_id']+'\', \''+img_point_id+'\')';
			refresh_btn = '<img id="mediaFriendTagNamesReload" title="Reload Tags" '+
				'src="'+TEMPLATE_VIEW_PATH+'images/btn/reload.png" '+
				'style="display:inline" '+
				'onclick="'+click_handler+'">';
		}
		for (i in tag_data) {
			if (tag_count++ == 2) break;
			media_tags += '<fb:name uid="'+i+'" capitalize="true" linked="false"></fb:name>, ';
		}
		if (offline_click_handler) {
			click_handler = offline_click_handler;
		} else {
			click_handler = 'loadTagEditor(\''+img_elem_id+'\', \''+img_point_id+'\', '+(segmentFlags.contribute && !dataFlags.offlineView)+')';//$(this).attr('id')
		}
		
		tag_head = '<a href="#" style="color:#cc6600" onclick="'+
			click_handler+'; return false;">';//(!!edit_tag)
		media_tags = '<div id="mediaTags">In this picture: <span id="mediaTagNames">'+
		media_tags.slice(0,media_tags.length-2)+(!tag_count?'No one':'')+
			'</span> '+(tag_count==3?tag_head+'more</a> ':'')+
			(segmentFlags.contribute?tag_head+'[ tag more people ]</a>'+refresh_btn:'')+
			'</div>';
		var futureWeddings = $('#pageTabWrapper #nightCanvasRow').length;
		if (futureWeddings) media_tags = '';
		
		return media_tags;
	},
	generateHtml = function () {
		var onload_handler = '',
			min_height = '',
			current_element = $(this),
			img_src = current_element.attr('src'),
			grid_thumb = current_element.attr('grid_thumb'),
			img_caption, img_elem_id, img_point_id, rmn_point, contributed_html,
			edit_tag, offline_click_handler, msg, point_owner,
			point_owner_fbid, point_owner_name, album_owner, album_owner_name,
			album_type, album_owner_text, point_high_res_url,
			wizardContributeCheck, download_button, print_button, photo_link_url,
			photo_link_text,share_photo_email, share_photo_facebook,
			photo_actions, media_tags,
			lightbox_html, i;
		preload_next_prev(this);
		if (current_element.hasClass('night_img_thumb') && img_src != grid_thumb) {
			img_src = grid_thumb;
			current_element.trigger("appear");
			onload_handler = ' onload="$(\'#'+current_element.attr('id')+'\').attr(\'src\', \''+grid_thumb+'\');updatePreloadLightboxSize();this.removeAttribute(\'onload\')"';
			min_height = ' style="height:430px"';
		} else if (!img_src || img_src.indexOf('loading') != -1) {
			img_src = current_element.attr('preload_src');current_element.trigger("appear");
			onload_handler = ' onload="updatePreloadLightboxSize();this.removeAttribute(\'onload\')"';
			min_height = ' style="height:430px"';
		}
		img_caption = current_element.attr('title');
		img_elem_id = current_element.attr('id');
		img_point_id = $(this.parentNode).attr('point_id');//.parentNode
		rmn_point = rmnPoints[img_point_id];
		contributed_html = '';
		edit_tag = '';
		offline_click_handler = '';
		if (dataFlags.offlineView) {
			msg = "Please <a href=\\\'javascript:loginToFacebook()\\\'>sign in</a> to contribute."; // function() { propagateContributeAction(\'tag\') }
			if (segmentData.privacy && segmentData.privacy.contribute == 'cfr') {
				msg += ' Only friends can contribute to this memory.';
			}
			offline_click_handler = "showError('"+msg+"');";
		}
		if (rmn_point) {
			point_owner = rmn_point['user_id'];
			point_owner_fbid = rmnIdsToFbids[point_owner];
			point_owner_name = fbidsToNames[point_owner_fbid];
			album_owner = urldecode(rmn_point['partnerIdValue']);
			album_owner_name = album_owner;
			album_type = "flickr";
			var partnerId_id = parseInt(rmn_point['partnerId_id'], 10);
			if (in_array(partnerId_id, [PARTNER_TYPES.facebook_photo, PARTNER_TYPES.aviary_photo])) {
				album_owner_name = fbidsToNames[album_owner];
				album_type = "facebook";
			}
			album_owner_text = '';
			if (point_owner_name) {
				switch (partnerId_id) {
					case PARTNER_TYPES.kaptur_photo :
						contributed_html = '<div id="photoOwnerText">[Uploaded by ' + point_owner_name + ']</div>';
						break;
					case PARTNER_TYPES.facebook_photo :
						contributed_html = '<div id="photoOwnerText">[From ' + album_owner_name + '\'s ' + album_type + ' album]</div>';
						break;
					case PARTNER_TYPES.aviary_photo :
						contributed_html = '<div id="photoOwnerText">[Edited by ' + point_owner_name + ']</div>';
						break;
					default :
						contributed_html = '<div id="photoOwnerText">[Added by ' + point_owner_name + ' from ' + album_owner_name + '\'s ' + album_type + ' album]</div>';
				}
			}
			point_high_res_url = urldecode(rmn_point['src_high_res']);

			// only show edit tag if user is owner of point
			point_owner = rmn_point['user_id'];
			wizardContributeCheck = !wizardMemoryData || (wizardMemoryData && segmentFlags.wizardShowContributeActive);
			var futureWeddings = $('#pageTabWrapper #nightCanvasRow').length;
			//if ((!editNight || point_owner == userProfileObj.id) && wizardContributeCheck && !futureWeddings) {
			if ((!editNight || point_owner == userProfileObj.id) && (wizardContributeCheck || futureWeddings)) {
				//edit_tag = '<img src="'+TEMPLATE_VIEW_PATH+'images/btn/edit_o.png" id="photoCaptionEdit" title="Edit" onclick="editMediaDetails({\'action\':\'edit\', \'point_id\':\''+img_point_id+'\', \'elem_id\':\''+img_elem_id+'\'})" />';
				edit_tag += '<input type="image" id="photoCaptionEdit" src="'+TEMPLATE_VIEW_PATH+'images/btn/caption_edit.png" title="Edit Caption" onclick="editMediaDetails({\'action\':\'edit\', \'point_id\':\''+img_point_id+'\', \'elem_id\':\''+img_elem_id+'\'}); return false;" />';//||1
				if (navigator.userAgent.indexOf("MSIE") == -1) {
					edit_tag += '<input type="image" id="photoImgEdit" src="'+TEMPLATE_VIEW_PATH+'images/btn/aviary_edit.png" title="Edit Photo" onclick="launchEditor(\'photoImg\'); return false;" />';
				}
			}
			download_button = '<img src="'+TEMPLATE_VIEW_PATH+'images/btn/download_o.png" id="photoDownload" class="photoAction" title="Download" onclick="downloadPhoto(\''+img_src+'\',\''+rmn_point['media_type_id']+(point_high_res_url&&point_high_res_url!='undefined'?'\',\''+point_high_res_url:'')+'\')" />';
			print_button = '<img src="'+TEMPLATE_VIEW_PATH+'images/btn/print_o.png" id="photoPrint" class="photoAction" title="Print" onclick="printPhoto(\''+img_src+'\')" />';
			var segment_id = segmentData.id;
			if (window.memoryCreationWizard) {
				segment_id = memoryCreationWizard.sid;
			}
			photo_link_url = "http://" + location.host + "/?p=nw&sid=" + segment_id + "&photo=" + img_point_id; //(location.href + "").replace(/&ref=\w*/g, '&');
			//photo_link_url = photo_link_url.replace(/&photo=\w*/g, '') + "&photo=" + img_point_id;
			photo_link_text = '<div id="photoLinkText" class="photoAction" >Link: <input id="photoLinkTextInput" value="'+photo_link_url+'" onclick="this.select()" readonly="readonly" /></div>';
			share_photo_email = '<div id="sharePhotoEmail" class="photoAction" onclick="sharePhoto(\''+img_point_id+'\', \'email\')"><img title="Share via email" alt="Share via email" width="16" heigh="16" src="'+TEMPLATE_VIEW_PATH+'images/share/email.png" /></div>';
			share_photo_facebook = '<div id="sharePhotoFacebook" class="photoAction" onclick="sharePhoto(\''+img_point_id+'\', \'facebook\')"><img title="Share on facebook" alt="Share on facebook" width="16" height="16" src="'+TEMPLATE_VIEW_PATH+'images/share/facebook.png" /></div>';
			photo_actions = '<div id="photoActions">' + (!isMobileApp()? (download_button + print_button + share_photo_email + share_photo_facebook):'') + photo_link_text + '</div>';
			media_tags = generateTagHtml(rmn_point, img_point_id, img_elem_id, offline_click_handler, wizardContributeCheck);
		}
		lightbox_html = '<div class="lightbox_photo_wrapper"><center><div id="photoImgWrapper"'+min_height+'><img src="'+img_src+'" id="photoImg"'+(point_high_res_url&&point_high_res_url!='undefined'?' src_high_res="'+point_high_res_url+'"':'')+' point_id="'+img_point_id+'" class="lightbox_photo"'+onload_handler+'></div><div id="photoCaptionWrapper"><span id="photoCaptionText">'+img_caption+'</span>'+edit_tag+contributed_html+photo_actions+media_tags+'</div><div id="photoEditWrapper">'+buildEditTimeHTML('photoEdit')+'<div class="clear" style="padding-bottom:5px"></div><input id="photoEditCaptionField" class="input_field"><div class="cancel_done_btn" onclick="editMediaDetails()"></div><div class="done_btn" onclick="editMediaDetails({\'action\':\'save\', \'point_id\':\''+img_point_id+'\', \'elem_id\':\''+img_elem_id+'\'})"></div><div class="clear"></div></div></center></div>';
		return lightbox_html;
	},
	generateTitle = function () {
		return '&nbsp;';
	},
	loadPageBuffer = 10,
	doOnComplete = function () {
		var current_index, total, images;
		hideEmbed();
		loadFBML(document.getElementById('mediaTagNames'));
		$.colorbox.resize();
		updateColorboxScrollbars();
		if (totalSegmentPoints) {
			images = $("img[rel='lightbox']");
			current_index = images.index($(this)) + 1;
			total = images.length;
			if (current_index > (total - loadPageBuffer)) {
				loadPage();
			}
		}
		$('#cboxClose').width('25px').height('25px');
	},
	doOnClosed = function () {
		hideEmbed(1);$('#cboxClose').width('0px').height('0px');
	},
	reload = true,
	/**
	 * Reloads the image once every time.  this is done to refresh the group the
	 * photos are taken from as they are being loaded.  Without this it loops
	 * around the photos that existed when the colorbox was first opened.
	 */
	doOnLoad = function () {
		if (reload) {
			reload = false;
			$(this).click();
		} else {
			reload = true;
		}
	};
	
	return function (delayed) {
		var current = ('{current} of '+ (totalSegmentPoints || '{total}'));
		if (!delayed) {
			setTimeout('updateLightboxPhotos(1)', 0);
			return;
		}/*$("img[rel='lightbox']").colorbox({opacity:.75, maxWidth:'95%', maxHeight:'95%', rel:'lightbox',
			href:function() { return $(this).attr('src'); }, title:function() { return '&nbsp;'; }
		});*/
		
		$("img[rel='lightbox']").colorbox({
			opacity:0.75,
			maxWidth:'95%',
			maxHeight:'95%',
			rel:'lightbox',
			href:'html',
			scrolling:false,
			html: generateHtml,
			title: generateTitle,
			current:current,
			onComplete: doOnComplete,
			onClosed: doOnClosed,
			onLoad: doOnLoad
		}); //{'innerWidth':$('#photoImgWrapper>img').width()?$('#photoImgWrapper>img').width():''}
	};
}();

function updateLightboxVideos(delayed) {
	// use delay to spread out consecutive updates
	if (!delayed) {setTimeout('updateLightboxVideos(1)', 0);return;}
	$("img[rel='lightbox_video']").colorbox({opacity:.75, rel:'lightbox', href:'html', scrolling:'false',// maxWidth:'95%', maxHeight:'95%', 
		html:function() {
			var img_src = $(this).attr('src');preload_next_prev(this);
			if (!img_src || img_src.indexOf('loading') != -1) $(this).trigger("appear");
			var img_caption = $(this).attr('title');
			var img_elem_id = $(this).attr('id');
			var img_point_id = $(this.parentNode).attr('point_id');//.parentNode
			var rmn_point = rmnPoints[img_point_id];var edit_tag = '', refresh_btn = '';
			var contributed_html = '', offline_click_handler = '';
			if (dataFlags.offlineView) {
				var msg = "Please <a href=\\\'javascript:loginToFacebook()\\\'>sign in</a> to contribute."; // function() { propagateContributeAction(\'tag\') }
				if (segmentData.privacy && segmentData.privacy.contribute == 'cfr') {
					msg += ' Only friends can contribute to this memory.';
				}
				offline_click_handler = "showError('"+msg+"');";
			}
			if (rmn_point) { // only show edit tag if user is owner of point
				var point_owner = rmn_point['user_id'];
				var point_owner_fbid = rmnIdsToFbids[point_owner];
				var point_owner_name = fbidsToNames[point_owner_fbid];
				var media_creator = rmn_point['partnerIdValue']
				var media_creator_name = fbidsToNames[media_creator];
				var creator_text = '';//(point_owner_fbid == media_creator || !media_creator_name)? "" : " originally posted by "+media_creator_name;
				if (point_owner_name) {
					contributed_html = " <div id=\"photoOwnerText\">[From " + point_owner_name + creator_text + "]</div>"; // && point_owner != userProfileObj.id
				}
				var futureWeddings = $('#pageTabWrapper #nightCanvasRow').length;
				if ((!editNight || point_owner == userProfileObj.id)) {// && !futureWeddings
					//edit_tag = '<img src="'+TEMPLATE_VIEW_PATH+'images/btn/edit_o.png" id="photoCaptionEdit" title="Edit" onclick="editMediaDetails({\'action\':\'edit\', \'point_id\':\''+img_point_id+'\', \'elem_id\':\''+img_elem_id+'\'})" />';
					edit_tag += '<input type="image" id="photoImgEdit" src="'+TEMPLATE_VIEW_PATH+'images/btn/caption_edit.png" title="Edit Caption" onclick="editMediaDetails({\'action\':\'edit\', \'point_id\':\''+img_point_id+'\', \'elem_id\':\''+img_elem_id+'\'}); return false;" />';	
				}
				if (segmentFlags.contribute && in_array(rmn_point['partnerId_id'], [4,9])) {
					refresh_btn = '<img id="mediaFriendTagNamesReload" title="Reload Tags" src="'+TEMPLATE_VIEW_PATH+'images/btn/reload.png" style="display:inline" onclick="'+(offline_click_handler?offline_click_handler:'reloadMediaTags(\''+img_elem_id.substr(1)+'\', \''+rmn_point['partnerId_id']+'\', \''+img_point_id+'\')')+'">';
				}
				var tag_head = '<a href="#" style="color:#cc6600" onclick="'+(offline_click_handler?offline_click_handler:'loadTagEditor(\''+$(this).attr('id')+'\', \''+img_point_id+'\', '+(segmentFlags.contribute && !dataFlags.offlineView)+')')+'; return false;">';//(!!edit_tag)
				var media_tags = '';
				var tag_data = [];//rmn_point['tags'];
				var tag_count = 0;
				for (var i in tag_data) {
					if (tag_count++ == 2) break;
					media_tags += '<fb:name uid="'+i+'" capitalize="true" linked="false"></fb:name>, ';
				}
				if (!futureWeddings) {
					media_tags = '<div id="mediaTags">In this video: <span id="mediaTagNames">'+media_tags.slice(0,media_tags.length-2)+(!tag_count?'No one':'')+'</span> '+(tag_count==3?tag_head+'more</a> ':'')+(segmentFlags.contribute?tag_head+'[ tag more people ]</a>'+refresh_btn:'')+'</div>';
				}
			}
			var lightbox_html = '<div class="lightbox_photo_wrapper"><center><div id="editLightboxVideoWrapper" vid="'+img_elem_id+'"></div><div id="photoCaptionWrapper"><span id="photoCaptionText">'+img_caption+'</span>'+edit_tag+contributed_html+media_tags+'</div><div id="photoEditWrapper">'+buildEditTimeHTML('photoEdit')+'<div class="clear" style="padding-bottom:5px"></div><input id="photoEditCaptionField" class="input_field"><div class="cancel_done_btn" onclick="editMediaDetails()"></div><div class="done_btn" onclick="editMediaDetails({\'action\':\'save\', \'point_id\':\''+img_point_id+'\', \'elem_id\':\''+img_elem_id+'\'})"></div><div class="clear"></div></div></center></div>';
			return lightbox_html;
		},
		title:function() {
			return '&nbsp;';
		},
		onComplete:function() { //updateColorboxScrollbars
			hideEmbed();
			loadFBML(document.getElementById('mediaTagNames'));
			var img_elem_id = $(this).attr('id');
			if (!img_elem_id) img_elem_id = document.getElementById('editLightboxVideoWrapper').getAttribute('vid');
			var img_media_id = img_elem_id.replace('_wrapper', '').substr(1);
			var video_src = $(this.parentNode).attr('media_content'); // fbVideos[img_media_id]['src'];
			embedVideo(video_src, {'edit':1, 'vid':img_media_id});
			removeYtAutoplay();$('#cboxClose').width('25px').height('25px');
		},
		onClosed:function() {
			hideEmbed(1);$('#cboxClose').width('0px').height('0px');
		},
		current: '{current} of {total}'
	});
}

function updateStdLightboxPhotos() {
	$("img[rel='lightbox']").colorbox({opacity:.75, maxWidth:'85%', maxHeight:'85%', rel:'lightbox', href:function() {
		return $(this).attr('media_content');}, title:function() {return '&nbsp;';}, onComplete:updateColorboxScrollbars
	});
}

function updateStdLightboxVideos() {
	$("img[rel='lightbox_video']").colorbox({opacity:.75, maxWidth:'85%', maxHeight:'85%', rel:'lightbox_video', current:"video {current} of {total}", title:function(){return '&nbsp;';}, html:function() {
			var media_id = $(this).attr('media_id');
			var media_content = $(this).attr('media_content');
			var args = {'return_html':1};
			if (media_id) args['vid'] = media_id;
			return embedVideo(media_content, args);
		}, href:function() {return '';}, onComplete:updateColorboxScrollbars
	});
}

function showNewNightHints() {
	$.colorbox({opacity:.75, maxWidth:'85%', maxHeight:'85%', inline:true, title:'&nbsp;', href:"#newNightHintsWrapper", onClosed:queryExistingNights, onComplete:updateColorboxScrollbars});
	showNewNightDiaryText();
	segmentFlags.newNight = 1;
	
	// start with today's date if none specified
	var nightDatePicker = document.getElementById('nightDatePicker');
	if (!nightDatePicker.value) nightDatePicker.value = formatDateStr(new Date(), 'slashed_full');
	
	// init page exit handler for new nights
	if (dataFlags.offlineView) window.onbeforeunload = setUnsavedExitHandler;
}

function showNewNightDiaryText() {
	if (segmentFlags.newNight) {
		document.getElementById('retroDiaryEmpty').style.display = 'block';
		document.getElementById('retroDiaryAddLink').style.display = 'none';
	}
}

function showNewUserHints() {return;
	$(document).ready(function() {
		$.colorbox({opacity:.40, maxWidth:'85%', maxHeight:'85%', inline:true, title:'&nbsp;', href:"#newUserHintsWrapper", onComplete:updateColorboxScrollbars});
	});
}

function queryExistingNights() {
	var rmn_user = userProfileObj.id;
	if (rmn_user) {
		var start_time = segmentData.start - 24*60*60;
		var end_time = segmentData.end + 36*60*60;
		var user_tzoffset = -new Date().getTimezoneOffset()/60;
		loadRmnSegmentFromDB(rmn_user, segmentData.start, segmentData.end, user_tzoffset, {'start':start_time, 'end':end_time});
	}
}

function initContributeElements() {
	initColorbox('summaryEditBtn, #nightDescEdit, .edit_summary', 'nightSummaryEditWrapper'); // , #fbEventFriendEventsEdit
    initColorbox('canvasAddMoreBtn, #nightCanvasAdd, #nightCanvasAddLink, .back_to_photos_link, #addCanvasPhotoBig, #addCanvasPhotoSmall', 'addPhotosWrapper');
    initColorbox('nightCanvasAddVideos, #nightCanvasAddVideosLink, #addCanvasVideoBig, #addCanvasVideoSmall', 'addVideosWrapper');
    initColorbox('addVideosBtn, #nightVideosAdd, #addCanvasMusicBig, #addCanvasMusicSmall', 'addMusicWrapper');
    initColorbox('addFriendsBtn, #nightFriendsAdd, #addCanvasFriendBig, #addCanvasFriendSmall', 'addFriendsWrapper'); // , #fbFriendSelectAdd
	$(document).bind('cbox_closed', function() {
		$('.back_to_photos_link').css({"display":"none"});
		$('.back_to_friends_link').css({"display":"none"});
	});
}

function editVideoDetails(media_id, media_type, media_src, media_id) {
	var media_id_type = 'm'+media_id+(media_type=='fb'?'':media_type);
	media_id_type += 'music'; // this function is currently only used by musics
	var media_elem = document.getElementById(media_id_type);
	var media_elem_wrapper = media_elem.parentNode;//.parentNode
	var media_point_id = media_elem_wrapper.getAttribute('point_id');
	var rmn_point = rmnPoints[media_point_id];
	editMediaDetails({'action':'edit', 'point_id':media_point_id, 'elem_id':media_id_type, 'video':media_src, 'vid':media_id});
}

function editMediaDetails(args) {
	var action, point_id, elem_id, video, video_id;
	if (args) {
		action = args['action'];
		point_id = args['point_id'];
		elem_id = args['elem_id'];
		video = args['video'];
		video_id = args['vid'];
	}var mediaEditType = 'photo';
	if (video) mediaEditType = 'video';
	
	// set variables
	var mediaEditMonth = document.getElementById(mediaEditType+'EditMonth');
	var mediaEditDay = document.getElementById(mediaEditType+'EditDay');
	var mediaEditYear = document.getElementById(mediaEditType+'EditYear');
	var mediaEditHours = document.getElementById(mediaEditType+'EditHours');
	var mediaEditMinutes = document.getElementById(mediaEditType+'EditMinutes');
	var mediaEditAMPM = document.getElementById(mediaEditType+'EditAMPM');
	var mediaEditTZ = document.getElementById(mediaEditType+'EditTZ');
	var mediaEditWrapper = document.getElementById(mediaEditType+'EditWrapper');
	var mediaEditCaptionField = document.getElementById(mediaEditType+'EditCaptionField');
	var mediaCaptionWrapper = document.getElementById(mediaEditType+'CaptionWrapper');
	var mediaCaptionText = document.getElementById(mediaEditType+'CaptionText');
	
	if (point_id) {
		var rmn_point = rmnPoints[point_id];
		var media_elem = document.getElementById(elem_id);
		if (action == 'edit') {
			var point_tzoffset = rmn_point['timezoneOffset'];
			var point_tzindex = getTzIndex(point_tzoffset);
			//var point_time = getAdjustedTime(roundOffSec(rmn_point['utcTimeSec']), point_tzoffset);
			var point_time = getAdjustedTime(rmn_point['utcTimeSec'], point_tzoffset);
			var point_desc = unescapeQuotes(urldecode(rmn_point['description']));
			// update text fields
			if (!video) {
				mediaCaptionWrapper.style.display = 'none';
				mediaEditWrapper.style.display = 'block';
			} else {
				embedVideo(removeAutoplay(video), {'music':1, 'vid':video_id, 'no_autoplay':1});
				removeYtAutoplay();
				eval("document.getElementById('editVideosDone').onclick = function() { editMediaDetails({'action':'save', 'point_id':'"+point_id+"', 'elem_id':'"+elem_id+"', 'video':1}); }");
			}var media_date = new Date(point_time*1000);
			mediaEditMonth.value = media_date.getMonth()+1;
			mediaEditDay.value = media_date.getDate();
			mediaEditYear.value = media_date.getFullYear();
			var end_hour = media_date.getHours();
			if (end_hour > 11) {
				end_hour -= 12;
				mediaEditAMPM.selectedIndex = 1;
			} else mediaEditAMPM.selectedIndex = 0;
			if (!end_hour) end_hour = 12;
			mediaEditHours.value = end_hour;
			var end_minutes = media_date.getMinutes();
			mediaEditMinutes.value = end_minutes < 10? '0'+end_minutes : end_minutes;
			mediaEditTZ.selectedIndex = point_tzindex;
			mediaEditCaptionField.value = (point_desc && point_desc != 'undefined')? point_desc : '';
		} else if (action == 'save') {
			var error_msg = '', time_modified, desc_modified;
			var editParams = new Object();
			
			// check for updated timezone
			var mediaEditTzoffset = mediaEditTZ.value;
			if (parseFloat(mediaEditTzoffset) != parseFloat(rmn_point['timezoneOffset'])) { // segmentData.tzoffset
				editParams['timezoneOffset'] = mediaEditTzoffset;
				rmn_point['timezoneOffset'] = mediaEditTzoffset;
				time_modified = 1;
			}
			
			// validate date
			var dateInfo = validateDate(mediaEditType+'Edit');
			var mediaEditTime = dateInfo['time'];
			error_msg = dateInfo['error'];
			
			if (!error_msg) {
				var mediaCaptionValue = removeHtmlTags(mediaEditCaptionField.value);
				var mediaEditCaption = removeHtmlTags(mediaCaptionValue);
				//if (parseInt(mediaEditTime/1000, 10) != parseInt(rmn_point['utcTimeSec']/1000, 10)) {
				if (mediaEditTime != rmn_point['utcTimeSec']) {
					mediaEditTime = getUniqueTime(mediaEditTime);
					editParams['utcTimeSec'] = mediaEditTime;
					rmn_point['utcTimeSec'] = mediaEditTime;
					time_modified = 1;
				}
				if (mediaEditCaption != urldecode(rmn_point['description'])) {
					editParams['description'] = d_escape(mediaEditCaption);
					rmn_point['description'] = mediaCaptionValue;
					media_elem.alt = mediaCaptionValue;
					media_elem.title = mediaCaptionValue;
					desc_modified = 1;
				}
				
				// write to db
				if (point_id && (time_modified || desc_modified))
					writeToDB('editPoint', [editParams, point_id]);
				
				// update values in memory
				if (!video) {
					if (desc_modified) mediaCaptionText.innerHTML = mediaCaptionValue;
					mediaCaptionWrapper.style.display = '';
					mediaEditWrapper.style.display = '';
				} else $.colorbox.close();
				
				// reinsert updated media item
				if (time_modified) {
					var media_elem_wrapper = media_elem.parentNode;
					var media_row_id = 'nightCanvasRow';
					if (video) media_row_id = 'videoThumbRow';
					document.getElementById(media_row_id).removeChild(media_elem_wrapper);
					addStreamItemToStream(media_elem_wrapper, media_row_id);
					updateScrollbarTime();
				}
				
				// resize colorbox to fit longer captions
				$.colorbox.resize();
			} else alert(error_msg);
		}
	} else {
		if (!video) {
			mediaCaptionWrapper.style.display = '';
			mediaEditWrapper.style.display = '';
		} else $.colorbox.close();
	}
}

function closeLightBox(type) {
	var colobox_grp = '';
	if (type == 'photo') colobox_grp = 'img[rel="lightbox"]';
	else if (type == 'photoAdd') colobox_grp = '#canvasAddMoreBtn';
	$(colobox_grp).colorbox.close();
}

function loadLocationInfo(data) {
	var response = JSON.parse(data);
	if (response["status"] == "ok") {
		var result = response["result"];
		if (result && result.length) {
			result = result[0];
			if (!segmentData.location) {
				segmentData.location = {};
			}
			segmentData.location.id = result['id'];
			segmentData.location.name = urldecode(result['name']);
			segmentData.location.desc = urldecode(result['description']);
			segmentData.location.city = urldecode(result['city']);
			segmentData.location.eid = result['partnerIdValue'];
			segmentData.location.thumb = urldecode(result['thumb']);
			if (result['partnerId_id'] == 2) {
				var fbEventId = result['partnerIdValue'];
				if (fbEventId) {
					//query event table
					queryFacebook('SELECT eid, name, tagline, description, pic, start_time, end_time, location, venue FROM event WHERE eid = \''+fbEventId+'\'',
						[],
						function(fb_event) {
							if (fb_event) {
								var fb_event = fb_event[0];
								if (fb_event) {
									var eid = fb_event['eid'];
									var name = fb_event['name'];
									var desc = fb_event['desc'];
									var start_time = fb_event['start_time'];
									var end_time = fb_event['end_time'];
									var location = fb_event['location'];
									var pic = fb_event['pic'];
									event_suggestions_list[eid] = {'name':name,'desc':desc,'start_time':start_time,'end_time':end_time,'location':location,'thumb':pic};
								}
							}updateNightInfo();
						}
					);
				}else updateNightInfo();
			} else updateNightInfo();
		} else updateNightInfo();
	} else updateNightInfo();
}

function updateNightInfo() {
	// load rmn segment data
	var segment_event_id, segment_event_thumb, segment_title, segment_desc, segment_location, segment_city, segment_location_desc;
	if (segmentData.id) {
		segment_title = segmentData.title, segment_desc = segmentData.desc;
		if (segmentData.location) {
			segment_event_id = segmentData.location.eid;
			segment_event_thumb = segmentData.location.thumb;
			segment_location = segmentData.location.name;
			segment_location_desc = segmentData.location.desc;
			segment_city = segmentData.location.city;
		}
		if (segmentData.cover.thumb) segment_event_thumb = segmentData.cover.thumb;
		if (!segment_title || segment_title == 'null') {
			segment_title = segment_location;
			segmentData.title = segment_title;
			segmentData.location.name = segment_title;
		} else if ((!segment_location_desc || segment_location_desc == 'null') && segment_title != segment_location) {
			segment_location_desc = segment_location;
			segmentData.location.desc = segment_location_desc;
		}
	}
	
	// load fb event data
	/*if (segment_event_id) {
		var fbEventInfo = event_suggestions_list[segment_event_id];
		if (!segment_title || segment_title == 'null') {
			segment_title = fbEventInfo['name'];
			if (segment_location) segment_title = segment_location; // override segment title with rmn data
		} if (!segment_desc) segment_desc = fbEventInfo['desc'];
		
		// determine what to display for location
		if (!segment_location_desc) segment_location_desc = fbEventInfo['location'];
		if (!segment_location_desc) segment_location_desc = segment_location;
	}*/
	
	// clear night data
	if (!night_info_cleared) clearNightInfo();
	
	// don't show edit button and links on edit night
	var editSummaryDisplay = 'inline', editSummaryDisplayDiv = 'block', segmentThumbDisplay = 'block';
	var hideEditMemory = editNight;// || (wizardMemoryData && !segmentFlags.wizardShowContributeActive);
	if (hideEditMemory) {editSummaryDisplay = '';editSummaryDisplayDiv = '';}
	if (!segment_event_thumb || segment_event_thumb == 'null') {
		segmentThumbDisplay = '';
		segment_event_thumb = '';//TEMPLATE_VIEW_PATH+'images/placeholders/night_thumb.png';
	}
	
	// display data on page
	try {
		if (segment_title && segment_title != 'null') {
			document.getElementById('nightSummaryTitleText').innerHTML = segment_title;
			document.getElementById('nightTitleText').innerHTML = segment_title;//': '+segment_title;
		} else {
			document.getElementById('nightTitleTextEmpty').style.display = editSummaryDisplay;
			document.getElementById('nightSummaryTitleEmpty').style.display = editSummaryDisplay;
		}//if (!editNight) document.getElementById('nightDescEdit').style.visibility = 'visible';
		if (segment_desc && segment_location_desc != 'null') {
			var nightSummaryDescText = document.getElementById('nightSummaryDescText');
			if (segment_desc.length > max_desc_chars) {
				nightSummaryDescText.innerHTML = limitLen(segment_desc, min_desc_chars);
				document.getElementById('nightSummaryExpand').style.display = 'block';
			} else nightSummaryDescText.innerHTML = segment_desc;
		} else document.getElementById('nightSummaryDescEmpty').style.display = editSummaryDisplay;
		if (segment_location_desc && segment_location_desc != 'null') {
			document.getElementById('nightSummaryLocation').style.display = 'block';
			document.getElementById('nightSummaryLocationText').innerHTML = segment_location_desc;
		} else {
			document.getElementById('nightSummaryLocation').style.display = editSummaryDisplayDiv;
			document.getElementById('nightSummaryLocationEmpty').style.display = editSummaryDisplay;
		}
		if (segment_city && segment_city != 'null') {
			document.getElementById('nightSummaryCity').style.display = 'block';
			document.getElementById('nightSummaryCityText').innerHTML = segment_city;
		} else {
			document.getElementById('nightSummaryCity').style.display = editSummaryDisplayDiv;
			document.getElementById('nightSummaryCityEmpty').style.display = editSummaryDisplay;
		}document.getElementById('summaryEditBtn').style.display = editSummaryDisplay;
		document.getElementById('addVideosBtn').style.display = editSummaryDisplay;
		document.getElementById('addCanvasMusicSmall').style.display = editSummaryDisplayDiv;
		document.getElementById('addCanvasMusicBig').style.display = editSummaryDisplayDiv;
		if (document.getElementById("videoThumbRow").childNodes.length == 0) {
			if (editSummaryDisplayDiv) {
				document.getElementById('nightVideosWrapper').style.display = '';
				document.getElementById("nightVideosAdd").style.display = 'block';
			} else document.getElementById('nightVideosWrapper').style.display = 'none';
		}
		if (loggedInUser) {
			if (segmentData.privacy.autoimport) {
				// don't interrupt fade-out transition when refreshing stream
				var retroDiaryAdd = document.getElementById('retroDiaryAdd');
				if (retroDiaryAdd.style.display != 'block') {
					var editSummaryDisplayDivPerm = editSummaryDisplayDiv;
					if (editSummaryDisplayDiv == 'block' && !userProfileObj.perms['read_stream']) {
						document.getElementById('retroDiaryFbStreamPermission').style.display = 'block';
						editSummaryDisplayDivPerm = '';
					}retroDiaryAdd.style.display = editSummaryDisplayDivPerm;
				}
			} //document.getElementById('filterMediaByPersonReload').style.display = editSummaryDisplay;
			//document.getElementById('addFriendPhotosSelectorWrapper').style.display = editSummaryDisplayDiv;
			document.getElementById('fbEventFriendsHeader').style.display = editSummaryDisplayDiv; 
		}document.getElementById('nightSummaryThumb').src = segment_event_thumb;
		document.getElementById('nightSummaryThumbWrapper').style.display = segmentThumbDisplay;
		document.getElementById('viewSlideshowBtn').style.display = 'block'; // show view slideshow button
		document.getElementById('downloadAllBtn').style.display = 'block';
		night_info_cleared = 0;
	} catch(err) {}
}

function saveCompleteShowContribute() {
	if (segmentFlags.wizardShowContributeReady) {
		if (!segmentFlags.wizardShowContributeActive) {
			segmentFlags.wizardShowContributeActive = 1;
			if (!document.getElementById('memoryEditWrapper')) {
				showContributeElements();updateAutoShowRemove('night_friend_pic_wrapper');
				//enableDragAndDrop(); // updateNightInfo();
			}
		}
	} else segmentFlags.wizardShowContributeCalled = 1;
}

function clearNightInfo() {
	document.getElementById('nightSummaryTitleText').innerHTML = '';
	document.getElementById('nightTitleText').innerHTML = '';
	document.getElementById('nightTitleTextEmpty').style.display = '';
	document.getElementById('nightSummaryTitleText').innerHTML = '';
	document.getElementById('nightSummaryTitleEmpty').style.display = '';
	document.getElementById('nightSummaryDescText').innerHTML = '';
	document.getElementById('nightSummaryDescEmpty').style.display = '';
	document.getElementById('nightSummaryLocation').style.display = '';
	document.getElementById('nightSummaryLocationText').innerHTML = '';
	document.getElementById('nightSummaryLocationEmpty').style.display = '';
	document.getElementById('nightSummaryCityText').innerHTML = '';
	document.getElementById('nightSummaryCityEmpty').style.display = '';
	document.getElementById('nightDescEdit').style.visibility = '';
	document.getElementById('summaryEditBtn').style.display = '';
	night_info_cleared = 1;
}

function editNightSummary(action, go_to_friends) {
	loadFbEvents(); // load fb events
	
	var summaryEditBtn = document.getElementById('summaryEditBtn');
	var summarySaveBtns = document.getElementById('summarySaveBtns');
	var nightSummaryText = document.getElementById('nightSummaryText');
	var nightSummaryEditFields = document.getElementById('nightSummaryEditFields');
	
	// time input fields
	var summaryStartMonth = document.getElementById('summaryStartMonth');
	var summaryStartDay = document.getElementById('summaryStartDay');
	var summaryStartYear = document.getElementById('summaryStartYear');
	var summaryStartHours = document.getElementById('summaryStartHours');
	var summaryStartMinutes = document.getElementById('summaryStartMinutes');
	var summaryStartAMPM = document.getElementById('summaryStartAMPM');
	var summaryEndMonth = document.getElementById('summaryEndMonth');
	var summaryEndDay = document.getElementById('summaryEndDay');
	var summaryEndYear = document.getElementById('summaryEndYear');
	var summaryEndHours = document.getElementById('summaryEndHours');
	var summaryEndMinutes = document.getElementById('summaryEndMinutes');
	var summaryEndAMPM = document.getElementById('summaryEndAMPM');
	var editSummaryError = document.getElementById('editSummaryError');
	
	// title, location, thumbnail, and desc
	var nightTitleText = document.getElementById('nightTitleText');
	var nightTitleTextEmpty = document.getElementById('nightTitleTextEmpty');
	var nightSummaryTitleText = document.getElementById('nightSummaryTitleText');
	var nightSummaryTitleEmpty = document.getElementById('nightSummaryTitleEmpty');
	var nightSummaryLocationText = document.getElementById('nightSummaryLocationText');
	var nightSummaryLocationEmpty = document.getElementById('nightSummaryLocationEmpty');
	var nightSummaryCityText = document.getElementById('nightSummaryCityText');
	var nightSummaryCityEmpty = document.getElementById('nightSummaryCityEmpty');
	var nightSummaryDescText = document.getElementById('nightSummaryDescText');
	var nightSummaryDescEmpty = document.getElementById('nightSummaryDescEmpty');
	var nightSummaryExpand = document.getElementById('nightSummaryExpand');
	var nightSummaryTitleField = document.getElementById('nightSummaryTitleField');
	var nightSummaryLocationField = document.getElementById('nightSummaryLocationField');
	var nightSummaryCityField = document.getElementById('nightSummaryCityField');
	var nightSummaryDescField = document.getElementById('nightSummaryDescField');
	var nightSummaryTZ = document.getElementById('nightSummaryTZ');
	var nightSummaryViewPrivacy = document.getElementById('nightSummaryViewPrivacy');
	var nightSummaryContributePrivacy = document.getElementById('nightSummaryContributePrivacy');
	var nightSummaryAutoImportPrivacy = document.getElementById('nightSummaryAutoImportPrivacy');
	var nightSummaryThumbWrapper = document.getElementById('nightSummaryThumbWrapper');
	var nightSummaryThumb = document.getElementById('nightSummaryThumb');
	if (!action) {
		/*summaryEditBtn.style.display = 'none';
		summarySaveBtns.style.display = 'inline';
		nightSummaryText.style.display = 'none';
		nightSummaryEditFields.style.display = 'block';*/
		
		// load time values
		var start_date = new Date(getAdjustedTime(segmentData.start)*1000);
		var end_date = new Date(getAdjustedTime(segmentData.end)*1000);
		summaryStartMonth.value = start_date.getMonth()+1;
		summaryStartDay.value = start_date.getDate();
		summaryStartYear.value = start_date.getFullYear();
		var start_hour = start_date.getHours();
		if (start_hour > 11) {
			start_hour -= 12;
			summaryStartAMPM.selectedIndex = 1;
		} else summaryStartAMPM.selectedIndex = 0;
		if (!start_hour) start_hour = 12;
		summaryStartHours.value = start_hour;
		var start_minutes = start_date.getMinutes();
		summaryStartMinutes.value = start_minutes < 10? '0'+start_minutes : start_minutes;
		// end range
		summaryEndMonth.value = end_date.getMonth()+1;
		summaryEndDay.value = end_date.getDate();
		summaryEndYear.value = end_date.getFullYear();
		var end_hour = end_date.getHours();
		if (end_hour > 11) {
			end_hour -= 12;
			summaryEndAMPM.selectedIndex = 1;
		} else summaryEndAMPM.selectedIndex = 0;
		if (!end_hour) end_hour = 12;
		summaryEndHours.value = end_hour;
		var end_minutes = end_date.getMinutes();
		summaryEndMinutes.value = end_minutes < 10? '0'+end_minutes : end_minutes;
		
		// load main segment values into text fields
		if (segmentData.id) {
			var segment_title = segmentData['title'];var segment_desc = segmentData['desc'];
			var segment_location = segmentData['location']['desc'];
			var segment_city = segmentData['location']['city'];
			nightSummaryTitleField.value = (segment_title && segment_title != 'null')? segment_title : '';
			nightSummaryLocationField.value = (segment_location && segment_location != 'null')? segment_location : '';
			nightSummaryCityField.value = (segment_city && segment_city != 'null')? segment_city : '';
			nightSummaryDescField.value = (segment_desc && segment_desc != 'null')? segment_desc : '';
			setIndexByValue(nightSummaryViewPrivacy, segmentData['privacy']['view']);
			setIndexByValue(nightSummaryContributePrivacy, segmentData['privacy']['contribute']);
			nightSummaryAutoImportPrivacy.checked = segmentData['privacy']['autoimport'];
		}nightSummaryTZ.selectedIndex = segmentData['tzindex'];
		// nightSummaryTitleField.focus();
	} else {
		if (action == 'save') {
			// remove html from contents
			var night_title = removeHtmlTags(nightSummaryTitleField.value);
			var night_location = removeHtmlTags(nightSummaryLocationField.value);
			var night_city = removeHtmlTags(nightSummaryCityField.value);
			var night_desc = removeHtmlTags(nightSummaryDescField.value);
			var night_tzoffset = nightSummaryTZ.value;
			var night_view_privacy = nightSummaryViewPrivacy.value;
			var night_contribute_privacy = nightSummaryContributePrivacy.value;
			var night_auto_import_privacy = nightSummaryAutoImportPrivacy.checked;
			var night_fb_event = $('input:radio[name=segmentFbEvent]:checked').val();
			var night_thumb = '';var night_event_data = event_suggestions_list[night_fb_event];
			if (night_event_data) night_thumb = night_event_data['thumb'];
			
			// set data modified flags
			var segment_info_modified, title_modified, location_modified, city_modified, fb_event_modified;
			var editParams = new Object();
			if (segmentData.id) {
				if (night_title != segmentData.title || night_desc != segmentData.desc || night_view_privacy != segmentData.privacy.view || night_contribute_privacy != segmentData.privacy.contribute || night_auto_import_privacy != segmentData.privacy.autoimport) segment_info_modified = 1;
				if (night_location != segmentData.location.desc) location_modified = 1;
				if (night_city != segmentData.location.city) city_modified = 1;
				if (night_event_data && night_fb_event != segmentData.location.eid) {
					// auto add event members to attendee list
					var event_members = night_event_data['members'];
					if (event_members) { // && event_members.length
						//for (var i=0; i<Math.min(20,event_members.length); i++) {
						var member_count = 0;
						for (var i in event_members) {
							var event_member = event_members[i];
							if (event_member && !document.getElementById('attendee'+event_member) && event_member != loggedInUser) {
								addFbUserToNight(i, 0, event_member[0], event_member[1]);
								member_count++;
							}
							if (member_count > 19) break;
						}
					}fb_event_modified = 1;
				}
				
				// set mq request params
				if (night_title != segmentData.title) {
					editParams['title'] = d_escape(night_title);
					title_modified = 1;
				}
				if (night_desc != segmentData.desc) editParams['description'] = d_escape(night_desc);
				if (night_view_privacy != segmentData.privacy.view || night_contribute_privacy != segmentData.privacy.contribute || night_auto_import_privacy != segmentData.privacy.autoimport) {
					editParams['privacy_ids'] = night_view_privacy+','+night_contribute_privacy+(!night_auto_import_privacy?',nai':'');
					if (night_auto_import_privacy != segmentData.privacy.autoimport) document.getElementById("retroDiaryAdd").style.display = (night_auto_import_privacy?'block':'');
				}
			}
			
			// check if timezone changed
			var time_modified, start_time, end_time;
			if (parseFloat(night_tzoffset) != parseFloat(segmentData.tzoffset)) {
				editParams['timezoneOffset'] = night_tzoffset;
				time_modified = 1;
			}
			
			// validate start date
			var date_info = validateDate('summaryStart');
			var err_msg = date_info['error'];
			if (!err_msg) {

				start_time = date_info['time'];
				if (start_time != segmentData.start) {
					editParams['utcStartSec'] = start_time;
					time_modified = 1;
				}
				
				// validate end date
				date_info = validateDate('summaryEnd');
				err_msg = date_info['error'];
				if (err_msg) editSummaryError.innerHTML = err_msg;
				else {
					end_time = date_info['time'];
					if (end_time != segmentData.end) {
						editParams['utcEndSec'] = end_time;
						time_modified = 1;
					}
					
					// make sure end time is greater than start time
					if (end_time <= start_time) err_msg = 'The end time should come past your start time!';
				}

				if ((start_time != segmentData.start) || (end_time != segmentData.end)) {
					reloadFacebookStream();
				}
			}editSummaryError.innerHTML = err_msg;
			
			// write to db
			if (!err_msg) { 
				if (!dataFlags.offlineView) {
					if (segmentData.id && (segment_info_modified || time_modified))
						writeToDB('editSegment', [editParams, segmentData.id], function() {if (time_modified) updateSegmentUrl();});
					if (segmentData.location.id && (title_modified || location_modified || city_modified || fb_event_modified)) {
						var editLocationParams = new Object();
						if (title_modified) editLocationParams['name'] = d_escape(night_title);
						if (location_modified) editLocationParams['description'] = d_escape(night_location);
						if (city_modified) editLocationParams['city'] = d_escape(night_city);
						if (fb_event_modified) {
							editLocationParams['partnerId_id'] = 2;
							editLocationParams['partnerIdValue'] = night_fb_event;
							editLocationParams['thumb'] = d_escape(night_thumb);
						}writeToDB('editLocation', [editLocationParams, segmentData.location.id]);
					}
				}
				
				// update values in memory
				segmentData['start'] = start_time;
				segmentData['end'] = end_time;
				segmentData['title'] = night_title;
				segmentData['desc'] = night_desc;
				segmentData['tzoffset'] = night_tzoffset;
				segmentData['location']['name'] = night_title;
				segmentData['location']['desc'] = night_location;
				segmentData['location']['city'] = night_city;
				segmentData['location']['eid'] = night_fb_event;
				segmentData['privacy']['view'] = night_view_privacy;
				segmentData['privacy']['contribute'] = night_contribute_privacy;
				segmentData['privacy']['autoimport'] = night_auto_import_privacy;
				
				// update calendar dates
				if (time_modified) updateDateDisplays();
				
				// load updated values into page
				nightTitleText.innerHTML = night_title;//(night_title?': ':'')+night_title;
				nightSummaryTitleText.innerHTML = night_title;
				nightSummaryLocationText.innerHTML = night_location;
				nightSummaryCityText.innerHTML = night_city;
				if (night_desc.length > max_desc_chars) {
					nightSummaryExpand.style.display = 'block';
					nightSummaryDescText.innerHTML = limitLen(night_desc, min_desc_chars);
				} else {
					nightSummaryDescText.innerHTML = night_desc;
					nightSummaryExpand.style.display = '';
				}
				if (!segmentData.cover.thumb) {
					if (night_thumb) {
						nightSummaryThumb.src = night_thumb;
						nightSummaryThumbWrapper.style.display = 'block';
					} else nightSummaryThumbWrapper.style.display = 'none';
				}
				
				// update segment tags
				updateSegmentTags();
				
				// show or hide hint links
				if (night_title) {
					nightTitleTextEmpty.style.display = '';
					nightSummaryTitleEmpty.style.display = '';
				} else {
					nightTitleTextEmpty.style.display = 'inline';
					nightSummaryTitleEmpty.style.display = 'inline';
				}
				if (night_location) nightSummaryLocationEmpty.style.display = '';
				else nightSummaryLocationEmpty.style.display = 'inline';
				if (night_city) nightSummaryCityEmpty.style.display = '';
				else nightSummaryCityEmpty.style.display = 'inline';
				if (night_desc) nightSummaryDescEmpty.style.display = '';
				else nightSummaryDescEmpty.style.display = 'inline';
			}
		}
		
		// close lightbox 
		if (!err_msg) { 
			if (!go_to_friends) $.colorbox.close(); 
			else { 
				$('#addFriendsBtn').colorbox({'open':true}); 
				$('.back_to_friends_link').css('display', 'none'); 
			}loadEventFriends(); 
		} // swap out buttons
		/*summaryEditBtn.style.display = 'inline';
		summarySaveBtns.style.display = '';
		nightSummaryText.style.display = '';
		nightSummaryEditFields.style.display = '';*/
	}
}

function loadUserAlbums(uid) {
	var addPhotosSelectorWrapper = document.getElementById('addPhotosSelectorWrapper');
	if (loggedInUser && (!dataFlags.photosLoaded || uid)) {
		if (!uid) {uid = loggedInUser;dataFlags.photosLoaded = 1;}
		else { // highlight friend icon
			if (last_shown_friend_id) {
				var profile_album_pic = document.getElementById('attendee'+last_shown_friend_id+'_album');
				if (profile_album_pic) profile_album_pic.className = 'profile_album_pic';
			}document.getElementById('attendee'+uid+'_album').className = 'profile_album_pic_selected';
			last_shown_friend_id = uid;
			showAlbumSelector('Friend');
		} // clear album / photos html
		var user = (uid != loggedInUser)? 'Friend' : 'Owner';
		var userAddPhotosWrapper = document.getElementById('add'+user+'PhotosWrapper');
		var userPhotosStatus = document.getElementById('add'+user+'PhotosStatus');
		var userAlbumsDiv = document.getElementById('fb'+user+'AlbumContents');
		userAlbumsDiv.innerHTML = '';userAddPhotosWrapper.style.display = '';
		document.getElementById('fb'+user+'PhotoContents').innerHTML = '';
		if (uid != loggedInUser) {
			userPhotosStatus.innerHTML = ajax_loader;
			userPhotosStatus.style.display = 'block';
		}
		var tagged_photos = {
			fql: 'SELECT pid, aid, owner, images, src, src_big, src_big_width, src_big_height, src_small, link, caption, created, modified FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject="{0}") AND owner != "{0}" ORDER BY created DESC',
			args: [uid]
		};
		var tagged_photos_tags = {
			fql: 'SELECT pid, subject, text FROM photo_tag WHERE pid IN (SELECT pid FROM {0})',
			args: [tagged_photos]
		};
		var albums = {
			fql: 'SELECT aid, cover_pid, owner, name, created, modified, description, location, link, size, visible FROM album WHERE owner={0} ORDER BY modified DESC',
			args: [uid]
		};
		var album_covers = {
			fql: 'SELECT aid, src FROM photo WHERE pid IN (SELECT cover_pid FROM {0})',
			args: [albums]
		};

		multipleQueryFacebook([tagged_photos, tagged_photos_tags, albums, album_covers], function() {
			// load user albums
			var albums_html = '';if (!uid) last_shown_owner_album = null; else last_shown_friend_album = null;
			if (albums) albums = albums.value;if (tagged_photos) tagged_photos = tagged_photos.value;
			if (tagged_photos_tags) tagged_photos_tags = tagged_photos_tags.value;
			if ((albums && albums.length) || (tagged_photos && tagged_photos.length)) {
				if (uid == loggedInUser || uid == last_shown_friend_id) {
					var albums_loaded = 0, first_album_id = 0;
					// convert album cover indexing
					album_covers = album_covers.value;
					album_covers_hash = new Object();
					if (album_covers && album_covers.length) {
						for (var i=0; i<album_covers.length; i++) {
							var album_cover = album_covers[i];
							var album_id = album_cover['aid'];
							album_covers_hash[album_id] = album_cover['src'];
						}
					}
					
					for (var i=-1; i<albums.length; i++) {
						var album_id = '', album_title, album_cover;
						if (i == -1) { // for tagged photos
							if (tagged_photos && tagged_photos.length) {
								// pid is used instead of aid to avoid highlighting user's albums by default
								album_id = tagged_photos[tagged_photos.length-1]['pid']+'tagged';
								album_cover = tagged_photos[0]['src'];
								album_title = 'Tagged Photos';
								storeMediaTags(tagged_photos_tags);
							}
						} else { // for normal albums
							var album = albums[i];
							album_id = album['aid'];
							album_title = escapeQuotes(album['name']);
							var album_cover = album_covers_hash[album_id];
							if (!album_cover) album_id = null; // skip this album
							//album_cover = TEMPLATE_VIEW_PATH+'/images/placeholders/night_thumb.png';
						}

						// construct albums html
						if (album_id) {
							if (!first_album_id) first_album_id = album_id;
							//if (albums_loaded++ % 5 == 0) albums_html += '<div class="clear"></div>';
							albums_html += '<div class="album_wrapper" onclick="showAlbumDiv(\''+album_id+'\', \''+uid+'\')"><div class="album_wrapper_inner"><img src="'+album_cover+'" class="photo_thumb" id="a'+album_id+'" alt="'+album_title+'" title="'+album_title+'" /></div><div class="album_title">'+album_title+'</div></div>';
							// create and insert photo wrapper div
							var album_wrapper_div = document.createElement('div');
							album_wrapper_div.id = 'a'+album_id+'wrapper';
							album_wrapper_div.style.display = 'none';
							document.getElementById('fb'+user+'PhotoContents').appendChild(album_wrapper_div);
						}

						// load photos
						if (i == -1) loadAlbumPhotos(tagged_photos);
						//else getFBPhotos(album_id);
						// space out and query album for photos
						//setTimeout("var getPhotosFQL = FB.Data.query('SELECT pid, aid, owner, src, src_big, src_big_width, src_big_height, src_small, link, caption, created, modified FROM photo WHERE aid = \\'"+album_id+"\\' ORDER BY created DESC'); getPhotosFQL.wait(loadAlbumPhotos);", (i+1)*100);
					}albums_html += '<div class="clear"></div>';
					userAlbumsDiv.innerHTML = albums_html;
					//showAlbumDiv(first_album_id, uid); // show first album
					userAddPhotosWrapper.style.display = 'block';
				}userPhotosStatus.style.display = 'none';
				addPhotosSelectorWrapper.style.display = 'block';
				//updateCustomScrollbar('fbAlbumContents'); updateCustomScrollbar('fbPhotoContents');
			} else {
				userPhotosStatus.innerHTML = '<div class="createMemoryAllPhotosFriendsAlbumsEmpty">' +
					'Your friend doesn\'t have any Facebook photos, or they are ' +
					'unavailable due to privacy settings.<br /><br />' +
					'Click <a href="#" style="color:#f96" ' +
					'onclick="inviteFriend(\'' + uid + '\');' +
					'return false">here</a> to invite them to use Kaptur!</div>';
			}
		});
	}
	if (dataFlags.offlineView) {
		var addOwnerPhotosStatus = document.getElementById('addOwnerPhotosStatus');
		if (addOwnerPhotosStatus) {
			addOwnerPhotosStatus.style.display = 'none';
			document.getElementById('addOwnerPhotosSelectorWrapper').style.display = 'none';
		}addPhotosSelectorWrapper.style.display = 'block';
		handleAddPhotoExpandClick('Flickr');
	}
}

function inviteFriend(uid) {
	var post_msg = segmentData.title;
	var post_thumb = DOMAIN_URL+TEMPLATE_VIEW_PATH+"images/fb_thumb.jpg";
	var night_owner = userProfileObj.first_name;
	var post_title = night_owner?night_owner+" invited you to check out "+(post_msg?post_msg+' on ':'')+"Kaptur!":'';
	var post_desc = memoryCreationWizard.shareDesc;//META_DESCRIPTION;
	var action_link_text = "Kaptur";
	var night_url = DOMAIN_URL+'?ref=fb_invite';
	var ui_args = { // show fb prompt
		method: 'stream.publish',
		message: post_msg,
		attachment: {
			name: post_title,
			caption: location.host,
			description: post_desc,
			href: night_url,
			media: [{type:"image", src:post_thumb, href:night_url}]
		}, target_id: uid,
		action_links: [{text:action_link_text, href:night_url}]
	};

	FB.ui(ui_args);
}

function getFBPhotos(album_id, uid) {
	var ownership = uid==loggedInUser?'Owner':'Friend';
	var addPhotosStatus = document.getElementById('add'+ownership+'PhotosPhotoStatus');
	if (!addPhotosStatus.style.display) {
		var addPhotosSelector = document.getElementById('add'+ownership+'PhotosPhotoSelector');
		addPhotosSelector.style.display = 'none';addPhotosStatus.style.display = 'block';
		var getPhotosFQL = {
			fql: 'SELECT pid, aid, owner, images, src, src_big, src_big_width, src_big_height, src_small, link, caption, created, modified FROM photo WHERE aid = "'+album_id+'" ORDER BY created DESC',
			args: []
		};
		var getPhotoTagsFQL = { // , xcoord, ycoord, created 
			fql: 'SELECT pid, subject, text FROM photo_tag WHERE pid IN (SELECT pid FROM {0})',
			args: [getPhotosFQL]
		};
		multipleQueryFacebook([getPhotosFQL, getPhotoTagsFQL], function() {
			var photos = getPhotosFQL.value;
			var photo_tags = getPhotoTagsFQL.value;
			storeMediaTags(photo_tags);
			loadAlbumPhotos(photos);
			if (!photos || !photos.length) {
				var album_wrapper_div = document.getElementById('a'+album_id+'wrapper');
				if (album_wrapper_div) album_wrapper_div.innerHTML = 'No photos found<div class="clear"></div>';
			}addPhotosStatus.style.display = '';
			showAlbumDiv(album_id, uid);
			addPhotosSelector.style.display = 'block';
		});
	}
}

function storeMediaTags(media_tags, media_tag_users) {
	if (media_tags && media_tags.length) {
		// generate fb names hash
		var media_tag_users_list = new Object();
		if (media_tag_users && media_tag_users.length) {
			for (var i=0; i<media_tag_users.length; i++) {
				var user_info = media_tag_users[i];
				var full_name = user_info['first_name']+' '+user_info['last_name'];
				media_tag_users_list[user_info['uid']] = full_name;
			}
		}for (var i=0; i<media_tags.length; i++) {
			var tag = media_tags[i];
			var tag_id = tag['pid'];
			var tag_uid = tag['subject'];
			var tag_name = tag['text'];
			if (media_tag_users) media_tag_users_list[tag_uid];
			var fb_media = fbPhotos;
			if (media_tag_users) {tag_id = tag['vid'];fb_media = fbVideos;}
			if (!fb_media[tag_id]) fb_media[tag_id] = {};
			if (!fb_media[tag_id]['tags']) fb_media[tag_id]['tags'] = {};
			fb_media[tag_id]['tags'][tag_uid] = tag_name;
		}
	}
}

function loadAlbumPhotos(photos) {
	if (photos && photos.length) {
		var photos_html = '';
		// derive tagged photos album id
		var album_id = photos[photos.length-1]['pid']+'tagged';
		var album_wrapper_div = document.getElementById('a'+album_id+'wrapper');
		if (!album_wrapper_div) {
			album_id = photos[photos.length-1]['aid'];
			album_wrapper_div = document.getElementById('a'+album_id+'wrapper');
		}
		
		if (album_wrapper_div) {
			fbAlbums[album_id] = [];
			for (var i=0; i<photos.length; i++) {
				var photo = photos[i];
				var photo_id = photo['pid'];
				var photo_thumb = photo['src'];
				try {
					var high_res_url = photo['images'][0]['source'];
					if (photo['src_big'] != high_res_url) {
						photo['src_high_res'] = high_res_url;
					}
				} catch (err) {}
				var photo_caption = escapeQuotes(photo['caption']);
				var photo_thumb_id = 'm'+photo_id+'thumb';
				//if (!document.getElementById(photo_thumb_id)) {
					var fbPhotoTags = new Object();
					if (fbPhotos[photo_id]) {
						fbPhotoTags = fbPhotos[photo_id]['tags'];
					}
					fbPhotos[photo_id] = photo; // store photo data in memory
					if (fbPhotoTags) {
						fbPhotos[photo_id]['tags'] = fbPhotoTags;
					}
					else fbPhotos[photo_id]['tags'] = null;
					fbAlbums[album_id].push(photo_id); // aggregate album photo ids
					photos_html += '<div class="photo_wrapper"><img src="'+photo_thumb+'" class="photo_thumb'+(fbPhotoPointIds[photo_id]?'_selected':'')+'" id="'+photo_thumb_id+'" alt="'+photo_caption+'" title="'+photo_caption+'" media_id="'+photo_id+'" onclick="addToCanvas(\''+photo_id+'\')"></div>';
				//}
			}photos_html += '<div class="clear"></div>';
			album_wrapper_div.innerHTML = photos_html;
		}
	}
}

function loadUserVideos() {
	if (!dataFlags.videosLoaded) {
		if (loggedInUser) {
			dataFlags.videosLoaded = 1;
			var getVideosFQL = {
				fql: 'SELECT vid, owner, title, description, embed_html, thumbnail_link, src, created_time FROM video WHERE owner="{0}" OR vid IN (SELECT vid FROM video_tag WHERE subject="{0}") ORDER BY created_time DESC',
				args: [loggedInUser]
			};
			var getVideoTagsFQL = {//, updated_time, created_time
				fql: 'SELECT vid, subject FROM video_tag WHERE vid IN (SELECT vid FROM {0})',
				args: [getVideosFQL]
			};
			var getVideoTagsUsersFQL = {
				fql: 'SELECT uid, name FROM user WHERE uid IN (SELECT subject FROM {0})',
				args: [getVideoTagsFQL]
			};
			var fbVideoStatus = document.getElementById('fbVideoStatus');
			fbVideoStatus.innerHTML = ajax_loader;
			multipleQueryFacebook([getVideosFQL, getVideoTagsFQL, getVideoTagsUsersFQL], function() {
				var videos = getVideosFQL.value;
				var video_tags = getVideoTagsFQL.value;
				var video_tag_users = getVideoTagsUsersFQL.value;
				var fbVideosWrapper = document.getElementById('fbVideosWrapper');
				if (videos && videos.length) {
					var videos_html = '';
					for (var i=0; i<videos.length; i++) {
						var video = videos[i];
						var video_id = video['vid'];
						var video_title = escapeQuotes(video['title']);
						var video_thumb = video['thumbnail_link'];
						var video_uploaded = video['created_time'];
						var video_src = video['src'];
						var video_size = extractFbVideoSize(video['embed_html']);
						var video_width = '', video_height = '';
						if (video_size) {
							video_width = video_size[0];
							video_height = video_size[1];
							video['width'] = video_width;
							video['height'] = video_height;
							var video_aspect = video_width / video_height;
							if (video_width > 121) {
								video_width = 121;
								video_height = Math.floor(video_width / video_aspect);
							}
							if (video_height > 88) {
								video_height = 88;
								video_width = Math.floor(video_height * video_aspect);
							}
						}var video_date = formatDateStr(new Date(video_uploaded*1000), 'slashed');
						fbVideos[video_id] = video; // store video data in memory
						var sizing_html = (video_width && video_height) ? 'width="' + video_width + '" height="' + video_height + '" style="width:' + video_width + 'px;height:' + video_height + 'px;"': "";
						videos_html += '<div onmouseover="previewVideo(\''+video_src+'\', \''+video_id+'\', 1);"><div class="photo_wrapper"><img id="m'+video_id+'thumb" src="'+video_thumb+'" class="photo_thumb'+(fbVideoPointIds[video_id]?'_selected':'')+'" '+sizing_html+' alt="'+video_title+'" title="'+video_title+'" onclick="addToCanvas(\''+video_id+'\', {\'video\':\'fb\', \'preview\':1})"></div><div class="video_desc_wrapper"><div class="video_desc_title">'+video_title+'</div><div>Uploaded: '+video_date+'</div><div><a href="#" onClick="previewVideo(\''+video_src+'\', \''+video_id+'\'); return false;" class="yellow">preview</a> &bull; <a href="#" onClick="addToCanvas(\''+video_id+'\', {\'video\':\'fb\'}); return false;" class="yellow" id="m'+video_id+'add">'+(fbVideoPointIds[video_id]?'remove':'add')+'</a></div></div><div class="clear"></div></div></div>';
					}document.getElementById('fbVideoContents').innerHTML = videos_html;
					fbVideoStatus.style.display = 'none';
					fbVideosWrapper.style.display = 'block';
				} else {
					fbVideoStatus.innerHTML = 'No videos retrieved.';
					fbVideosWrapper.style.display = '';
				}
				
				//updateCustomScrollbar('fbVideoContents');
				storeMediaTags(video_tags, video_tag_users);
			});
		}
		if (dataFlags.offlineView) {
			var fbVideoStatus = document.getElementById('fbVideoStatus');
			if (fbVideoStatus) fbVideoStatus.innerHTML = 'No videos retrieved.';
		}
	}
}

function loadUserFriends(profile, media_tags) {
	if ((!dataFlags.friendsLoaded || media_tags) && (!dataFlags.offlineView || (dataFlags.offlineView && dataFlags.fbDown))) {
		if (loggedInUser) {
			if (!media_tags) {
				dataFlags.friendsLoaded = 1;
				document.getElementById('fbFriendContents').innerHTML = '<div id="fbFriendStatus">'+ajax_loader+'</div>';
				document.getElementById('fbFriendsNav').innerHTML = '';
			} else {
				document.getElementById('fbMediaFriendContents').innerHTML = '<div id="fbMediaFriendStatus">'+ajax_loader+'</div>';
				document.getElementById('fbMediaFriendsNav').innerHTML = '';
			}
			
			//query logged in users friends
			queryFacebook('SELECT uid, first_name, middle_name, last_name, pic_square, sex, locale FROM user WHERE uid="'+loggedInUser+'" OR uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY lower(last_name) ASC',
				[loggedInUser],
				function (friends) {
					renderFriendNav(friends, profile, 0, media_tags);
				}
			);
		} else renderFriendNav(null, profile);
	}
}

function loadEventFriends(page) {
	var init_page;
	if (!page && page !== 0) {page = 0;init_page = 1;}
	var event_id = segmentData.location.eid;
	if (event_id && loggedInUser) {
		var pageChanged = !init_page && dataFlags.eventFriendsPageLoaded != page;
		if (!dataFlags.eventFriendsLoaded || dataFlags.eventFriendsLoaded != event_id || pageChanged) {
			dataFlags.eventFriendsLoaded = event_id;
			dataFlags.eventFriendsPageLoaded = page;
			document.getElementById('fbEventFriendContents').innerHTML = '<div id="fbEventFriendStatus">'+ajax_loader+'</div>';
			document.getElementById('fbEventFriendsNav').innerHTML = '';
			if (!userProfileObj.friends) {
				//query the users friends
				queryFacebook('SELECT uid2 FROM friend WHERE uid1={0}',
					[loggedInUser],
					function (friends) {
						userProfileObj.friends = friends;renderEventFriends(friends, event_id, page);
					}
				);
			} else renderEventFriends(userProfileObj.friends, event_id, page);
		}
	}
}

function renderEventFriends(friends, event_id, page) {
	var page_size = 75;
	//query the event members
	queryFacebook('SELECT uid from event_member WHERE eid = {0} AND rsvp_status = "attending" LIMIT '+page_size+' OFFSET '+(page*page_size),
		[event_id],
		function (event_members) {
			var friends_hash = new Object();
			var event_members_list = [];
			// generate friends hash and non-friend event members list
			if (friends && friends.length) {friends_hash[loggedInUser] = 1;for (var i=0; i<friends.length; i++) friends_hash[friends[i]['uid2']] = 1;}
			if (event_members && event_members.length) for (var i=0; i<event_members.length; i++) {
				var event_member = event_members[i]['uid'];
				if (!friends_hash[event_member]) event_members_list.push(event_member);
			} // get non-friend members list user data
			var eventFriendAddAll = document.getElementById('eventFriendAddAll');
			var navLinks = '';if (page) navLinks = '<a href="#" onClick="loadEventFriends('+(page-1)+');return false"><< prev</a>';
			if (event_members_list.length) {
				//query info (names, profile picture) on event members
				queryFacebook('SELECT uid, first_name, middle_name, last_name, pic_square FROM user WHERE uid IN ("'+event_members_list.join('","')+'") ORDER BY lower(last_name) ASC',
					[],
					function (friends) {
						renderFriendNav(friends, 0, 1);
					}
				);
				if (event_members.length == page_size) navLinks += (navLinks?' &bull; ':'') + '<a href="#" onClick="loadEventFriends('+(page+1)+');return false">next >></a>';
				document.getElementById('eventFriendNav').innerHTML = navLinks;
				if (eventFriendAddAll) eventFriendAddAll.style.display = '';
			} else {
				renderFriendNav(null, 0, 1);
				if (eventFriendAddAll) eventFriendAddAll.style.display = 'none';
			}
		}
	); //end queryFacebook
}

function renderFriendNavChunked(friends, current_letter, event_div, profile, event_friends, media_tags, start, size, fbFriendsNav, fbFriends, fbFriendsFilterWrapper) {
	var last_item_index = ((start + size) < friends.length) ? start + size : friends.length,
		navHTML = '',
		friendsHTML = '',
		i, html, friend;
	for (i = start; i < last_item_index; i++) {
		friend = friends[i];
		html = renderFriendAndNavHtml(friend, current_letter, event_div, profile, event_friends, media_tags);
		current_letter = html.current_letter;
		navHTML += html.nav;
		friendsHTML += html.friends;
	}
	if (navHTML) {
		fbFriendsNav.innerHTML += navHTML;
	}
	fbFriends.innerHTML += friendsHTML;

	if (last_item_index < friends.length) {
		setTimeout((function (friends, current_letter, event_div, profile, event_friends, media_tags, start, size, fbFriendsNav, fbFriends) {
			return function () {
				renderFriendNavChunked(friends, current_letter, event_div, profile, event_friends, media_tags, start, size, fbFriendsNav, fbFriends, fbFriendsFilterWrapper);
			};
		})(friends, current_letter, event_div, profile, event_friends, media_tags, start+size, size, fbFriendsNav, fbFriends), 10);
	} else {
		//$(fbFriendsFilterWrapper).css("display", "block");
		fbFriendsFilterWrapper.style.display = 'block';
	}
}

function renderFriendAndNavHtml(friend, current_letter, event_div, profile, event_friends, media_tags) {
	var first_name = friend['first_name'],
		middle_name = friend['middle_name'],
		last_name = friend['last_name'],
		gender = friend['sex'],
		locale = friend['locale'],
		uid = friend['uid'],
		profile_thumb = friend['pic_square'],
		navHtml = '',
		friendsHtml = '',
		media_id, media_point_id, tag_data;
	if (!first_name) first_name = '';
	if (!last_name) {
		if (middle_name) {
			last_name = middle_name;
		} else {
			last_name = first_name;first_name = '';
		}
	}

	if (uid && (first_name || last_name || profile_thumb) && (((!segmentData || !segmentData.fbOwner || segmentData.fbOwner != uid) && (!profile || (profile && loggedInUser != uid))) || media_tags)) {
		var new_letter = last_name?last_name.charAt(0).toUpperCase():'';

		if (current_letter != new_letter && new_letter.match(/[A-Z]/) && (!current_letter || current_letter < new_letter)) {
			// append nav link
			current_letter = new_letter;
			/*var fbFriendsNavLink = document.createElement('div');
			fbFriendsNavLink.innerHTML = '<a href="#'+new_letter+event_div+'" onClick="clearFriendFilter('+(event_friends?event_friends:'')+')">'+new_letter+'</a>';
			fbFriendsNav.appendChild(fbFriendsNavLink);*/
			navHtml += '<div><a href="#'+new_letter+event_div+'" onClick="clearFriendFilter('+
				(event_friends?event_friends:'')+');fixPageScroll('+profile+')">'+new_letter+'</a></div>';

			// append anchor mark
			/*var fbFriendsNavMarker = document.createElement('div');
			fbFriendsNavMarker.className = 'float_left';
			fbFriendsNavMarker.innerHTML = '<a name="'+new_letter+event_div+'"></a>';
			fbFriends.appendChild(fbFriendsNavMarker);*/
			friendsHtml += '<a name="'+new_letter+event_div+'" class="float_left"></a>';
		}

		// create and extract link element using a div wrapper (ensures proper onclick hanlder for html caching)
		var friend_selected = !profile && segmentFriendFbIds[uid];
		var onclick_handler = "toggleAttend('"+uid+"', '"+first_name.replace(/'/g, "\\'")+"', '"+last_name.replace(/'/g, "\\'")+"', '"+gender+"', '"+locale+"')";
		if (media_tags) {
			media_id = unwrapPhotoId(media_tags[0].id);
			media_point_id = media_tags[1];
			tag_data = rmnPoints[media_point_id]['tags'];
			if (tag_data) {
				friend_selected = tag_data[uid];
			}
			onclick_handler = "toggleMediaTag('"+media_point_id+"', '"+uid+"', '"+media_id+"')";
		}
		/*var friend_link_shell = document.createElement('div');
		friend_link_shell.innerHTML = '<a href="'+(profile?'?p=f&fid='+uid:'#" onclick="'+onclick_handler+'; return false;')+'"><div id="f'+uid+(media_tags?'tag':'')+'" class="friend_wrapper'+(friend_selected?'_selected':'')+'"><div class="friend_wrapper_thumb"><img src="'+profile_thumb+'" class="profile_pic" title="'+(first_name?first_name+" ":'')+last_name+'"/></div><div class="friend_wrapper_name">'+(first_name?first_name+'<br>':'')+'<b>'+last_name+'</b></div></div></a>';
		var friend_link = friend_link_shell.getElementsByTagName('a')[0];
		fbFriends.appendChild(friend_link);*/
		var ref_param = '';
		var ref_regex = new RegExp('&(aff|ref)=([^&]*)');
		if (location.href.match(ref_regex)) ref_param = '&'+RegExp.$1+'='+RegExp.$2;
		friendsHtml += '<a href="'+(profile?'?p=f&fid='+uid+ref_param:'#" onclick="'+onclick_handler+
			'; return false;')+'"><div id="f'+uid+(media_tags?'tag':'')+'" class="friend_wrapper'+
			(friend_selected?'_selected':'')+'"><div class="friend_wrapper_thumb"><img src="'+
			profile_thumb+'" class="profile_pic" title="'+(first_name?first_name+" ":'')+last_name+
			'"/></div><div class="friend_wrapper_name">'+//(first_name?first_name+'<br>':'')+
			//'<b>'+last_name+'</b></div></div></a>';
			(first_name?first_name+' ':'')+last_name+'</div></div></a>';
	}

	return {friends:friendsHtml,nav:navHtml,current_letter:current_letter};
}

function fixPageScroll(profile) {
	// used to fix the positioning of the page scroll
	if (profile) setTimeout("$.scrollTo({ top: '-=90px', left: '0px' }, 0)", 0);
}

function renderFriendNav(friends, profile, event_friends, media_tags) {
	var event_div = event_friends? 'Event':(media_tags?'Media':''),
		fbFriends = document.getElementById('fb'+event_div+'FriendContents'),
		fbFriendsNav = document.getElementById('fb'+event_div+'FriendsNav'),
		fbFriendsFilterWrapper = document.getElementById(event_friends?'eventFriendFilterWrapper':media_tags?'mediaFriendFilterWrapper':'friendFilterWrapper');
	fbFriends.innerHTML = '';
	if (friends && friends.length) {
		//ie needs smaller chunks.  other browsers can load a chunk the size of all the friends
		renderFriendNavChunked(friends, '', event_div, profile, event_friends, media_tags, 0, ($.browser.msie?200:friends.length), fbFriendsNav, fbFriends, fbFriendsFilterWrapper);
	} else {
		fbFriends.innerHTML = '<div id="fb'+event_div+'FriendStatus">No '+(!event_friends?'friends':'attendees')+' retrieved</div>';fbFriendsFilterWrapper.style.display = '';
	} //updateCustomScrollbar('fbFriendContents');
}

function handleAddPhotoExpandClick(section){
	var owner_photo_section = document.getElementById('addOwnerPhotosSelectorWrapper');
	var friend_photo_section = document.getElementById('addFriendPhotosSelectorWrapper');
	var flickr_photo_section = document.getElementById('addFlickrPhotosSelectorWrapper');
	var upload_photo_section = document.getElementById('addUploadPhotosSelectorWrapper');
	var owner_open = ($("#fbOwnerPhotosWrapper").css("display") == "block");
	var friend_open = ($("#fbFriendPhotosWrapper").css("display") == "block");
	var flickr_open = ($("#flickrPhotosWrapper").css("display") == "block");
	var upload_open = ($("#uploadPhotosWrapper").css("display") == "block");

	if ((section == "Friend") && (!friend_open)) {
		toggleSection('fbOwnerPhotos', 0);
		toggleSection('flickrPhotos', 0);
		toggleSection('uploadPhotos', 0);
		var swap_section = (flickr_open) ? (flickr_photo_section) : (upload_open? upload_photo_section : owner_photo_section);
		swapNodes(friend_photo_section, swap_section);
		toggleSection('fbFriendPhotos', 1);
	} else if ((section == "Owner") && (!owner_open)) {
		toggleSection('fbFriendPhotos', 0);
		toggleSection('flickrPhotos', 0);
		toggleSection('uploadPhotos', 0);
		var swap_section = (flickr_open) ? (flickr_photo_section) : (upload_open? upload_photo_section : friend_photo_section);
		swapNodes(owner_photo_section, swap_section);
		toggleSection('fbOwnerPhotos', 1);
	} else if ((section == "Flickr") && (!flickr_open)) {
		toggleSection('fbOwnerPhotos', 0);
		toggleSection('fbFriendPhotos', 0);
		toggleSection('uploadPhotos', 0);
		var swap_section = (owner_open) ? (owner_photo_section) : (upload_open? upload_photo_section : friend_photo_section);
		swapNodes(flickr_photo_section, swap_section);
		toggleSection('flickrPhotos', 1);
	} else if ((section == "Upload") && (!upload_open)) {
		toggleSection('fbOwnerPhotos', 0);
		toggleSection('fbFriendPhotos', 0);
		toggleSection('flickrPhotos', 0);
		var swap_section = (owner_open) ? (owner_photo_section) : (flickr_open? flickr_photo_section : friend_photo_section);
		swapNodes(upload_photo_section, swap_section);
		toggleSection('uploadPhotos', 1);
	}
}

function retrieveUploadedMedia() {
	if (!dataFlags.uploadedMediaRetrieved && userProfileObj.id) {
		Kaptur.modules.swfupload.initialize();
		
		// set file upload form action url
		var upload_url = '?p=upload&rmnid='+userProfileObj.id;
		
		// load uploaded file thumbs
		//jx.load(upload_url+'&method=get', processUploadedFiles);
		processUploadedFiles('[]'); // don't load uploaded files
		if (document.getElementById('photosTab')) {
			Kaptur.modules.swfupload.initialize(1);
			processUploadedFiles('[]', 0, 1);
		}dataFlags.uploadedMediaRetrieved = 1;
	}
}

function processUploadedFiles(uploaded_json, addImage, addMedia) {
	if (uploaded_json) {var addIdParam = addMedia?'Add':'';
		var wizard_page = 1;
		uploaded_json = JSON.parse(uploaded_json);
		var computerPhotoSelectorWrapper = document.getElementById('createMemoryAllPhotos'+addIdParam+'UploadPhotos');
		if (!computerPhotoSelectorWrapper) {wizard_page = 0;
			computerPhotoSelectorWrapper = document.getElementById('uploadViewPhotos');
		}if (uploaded_json.length) {
			var uploadPhotosTitle = document.getElementById(wizard_page?'createMemoryAllPhotos'+addIdParam+'UploadPhotosTitle':'uploadViewPhotosTitle');uploadPhotosTitle.style.display = '';
			if (computerPhotoSelectorWrapper.innerHTML.indexOf(wizard_page?'create_memory_photo':'photo_wrapper') == -1)
				computerPhotoSelectorWrapper.innerHTML = '';
			for (var i=0; i<uploaded_json.length; i++) {
				var uploaded_item = uploaded_json[i];
				var img_id = uploaded_item['id'];
				var img_width = uploaded_item['width'];
				var img_height = uploaded_item['height'];
				var img_taken = uploaded_item['taken'];
				var img_created = uploaded_item['created'];
				var img_src = uploaded_item['src'];
				var img_thumb = uploaded_item['thumb'];
				var img_thumb_id = wizard_page?'photos'+img_id:'m'+img_id+'thumb';
				var img_thumb_elem = document.getElementById(img_thumb_id);
				var wedding_cover = document.getElementById('memoryEditWrapper');
				if (!img_thumb_elem) {
					// store uploaded photo data in memory
					if (wizard_page) memoryCreationWizard.loaded_photos[img_id] = {'id':img_id, 'width':img_width, 'height':img_height, 'utc_time_second':img_taken, 'source':img_src, 'thumbnail':img_thumb, 'timezone_offset':(segmentData?segmentData.tzoffset:memoryCreationWizard.timezone_offset), 'contributor_kaptur_id':userProfileObj.id, 'uploaded':1};
					else fbPhotos[img_id] = {'pid':img_id, 'owner':userProfileObj.id, 'src':img_thumb, 'src_big':img_src, 'src_big_width':img_width, 'src_big_height':img_height, 'created':img_taken, 'modified':img_taken, 'uploaded':1};
					
					// insert uploaded img element
					var photo_selected, uploaded_photo_thumb = document.createElement('div');
					if (wedding_cover && !addMedia) {
						photo_selected = memoryCreationWizard.selected_photos[img_id];
						var uploaded_photo_thumb_html = '<div id="'+img_thumb_id+'" onclick="setWeddingCover(\''+img_id+'\')" class="create_memory_photo'+(photo_selected?' create_memory_photo_selected':'')+'"><img src="'+img_thumb+'"></div>';
						uploaded_photo_thumb.innerHTML = uploaded_photo_thumb_html;
						img_thumb_elem = uploaded_photo_thumb.childNodes[0];
					} else if (wizard_page || addMedia) {
						photo_selected = memoryCreationWizard.selected_photos[img_id];
						uploaded_photo_thumb.innerHTML = '<div onmouseout="memoryCreationWizard.hidePhotoControls(this, event)" onmouseover="memoryCreationWizard.showPhotoControls(this, event)" id="'+img_thumb_id+'" onclick="memoryCreationWizard.togglePhotoSelected(this, \''+img_id+'\')" class="create_memory_photo'+(photo_selected?' create_memory_photo_selected':'')+'"><img src="'+img_thumb+'"><div class="createMemorySelectPhotoOverlay">Select Photo</div><input type="checkbox" class="createMemoryViewAlbumCheckbox"'+(photo_selected?' checked':'')+'></div>';
						img_thumb_elem = uploaded_photo_thumb.childNodes[0];
					} else {
						photo_selected = fbPhotoPointIds[img_id];
						uploaded_photo_thumb.innerHTML = '<div class="photo_wrapper"><img onclick="addToCanvas(\''+img_id+'\', {\'service\':SERVICE_TYPES.kaptur})" media_id="'+img_id+'" id="m'+img_id+'thumb" class="photo_thumb'+(photo_selected?'_selected':'')+'" src="'+img_thumb+'"></div>';
						img_thumb_elem = uploaded_photo_thumb.childNodes[0];
					}computerPhotoSelectorWrapper.appendChild(img_thumb_elem);
				}
				
				if ((!uploaded_json || addImage) && (!img_thumb_elem || (img_thumb_elem && !photo_selected))) {
					if (wedding_cover && !addMedia) {if (Kaptur.modules.swfupload.numFilesSelected == 1) setWeddingCover(img_id);}
					else if (wizard_page || addMedia) memoryCreationWizard.togglePhotoSelected(img_thumb_elem, img_id);
					else addToCanvas(img_id, {'service':SERVICE_TYPES.kaptur});
				}
			}
		} else computerPhotoSelectorWrapper.innerHTML = '<div style="text-align:center;margin-top:15px">Click "upload" to upload JPEG photos from your computer.</div>';
	}
}

function toggleSection(section, expand) {
	var obj_type = 'arrow';
	var fb_owner_login_message = document.getElementById("addOwnerPhotosLoginMsg");
	if (in_array(section, ['nightFriendPics', 'retroDiaryEntries', 'nightSummary'])) obj_type = 'btn';
	if (fb_owner_login_message){
		if ((section == "fbOwnerPhotos")&&expand)
			fb_owner_login_message.style.display = "block";
		else fb_owner_login_message.style.display = "none";
	}
	var section_wrapper = document.getElementById(section+'Wrapper');
	if (section == 'nightSummary') section_wrapper = document.getElementById('nightSummaryDescText');
	if (section_wrapper) {
		var expand_btn = document.getElementById(section+'Expand');
		if (expand == null && expand_btn.className == 'expand_'+obj_type) expand = 1;
		if (expand) {
			expand_btn.className = 'collapse_'+obj_type;
			expand_btn.title = 'Less';
			if (section == 'nightFriendPics') section_wrapper.style.maxHeight = '';
			else if (section == 'retroDiaryEntries') expandDiaryEntries();
			else if (section == 'nightSummary') section_wrapper.innerHTML = segmentData.desc;
			else section_wrapper.style.display = 'block';
		} else {
			expand_btn.className = 'expand_'+obj_type;
			expand_btn.title = 'More';
			if (section == 'nightFriendPics') section_wrapper.style.maxHeight = '58px';
			else if (section == 'retroDiaryEntries') expandDiaryEntries(1);
			else if (section == 'nightSummary') section_wrapper.innerHTML = limitLen(segmentData.desc, min_desc_chars);
			else section_wrapper.style.display = 'none';
		}
	}
}

function toggleContactSheetItem(arrow) {
	var expand_div = arrow.previousSibling;
	if (arrow.className == 'expand_arrow') {
		expand_div.className = 'contactSheetMediaExpanded';
		arrow.className = 'collapse_arrow';
		arrow.title = 'Less';
	} else {
		expand_div.className = 'contactSheetMediaCollapsed';
		arrow.className = 'expand_arrow';
		arrow.title = 'More';
	}
	
}

function expandDiaryEntries(collapse) {
	var diary_entries = document.getElementById('retroDiaryEntries').childNodes;
	for (var i=0; i<diary_entries.length; i++) {
		var diary_entry = diary_entries[i];
		if (collapse && i > min_posts_shown) diary_entry.style.display = 'none';
		else diary_entry.style.display = '';
	}
}

function showAlbumDiv(album_id, uid) {
	var ownership = 'Owner';
	var album_wrapper = document.getElementById('a'+album_id+'wrapper');
	var last_shown_album = last_shown_owner_album;
	if (uid != loggedInUser) {
		last_shown_album = last_shown_friend_album;
		ownership = 'Friend';
	}document.getElementById('add'+ownership+'PhotosAlbumSelector').style.display = 'none';
	document.getElementById('add'+ownership+'PhotosPhotoSelector').style.display = 'block';
	//if (last_shown_album != album_id) {
		if (album_wrapper.childNodes.length) {
			if (last_shown_album) {
				var last_shown_album_div = document.getElementById('a'+last_shown_album);
				if (last_shown_album_div) {
					//last_shown_album_div.className = 'photo_thumb';
					document.getElementById('a'+last_shown_album+'wrapper').style.display = 'none';
				}
			}
			if (uid != loggedInUser) last_shown_friend_album = album_id;
			else last_shown_owner_album = album_id;
			album_wrapper.style.display = 'block';
			//document.getElementById('a'+album_id).className = 'photo_thumb_selected';
		} else getFBPhotos(album_id, uid);
	//}
}

function showAlbumSelector(section) {
	if (section == 'flickr') {
		document.getElementById('flickrViewAlbums').style.display = 'block';
		document.getElementById('flickrViewPhotos').style.display = '';
	} else {
		document.getElementById('add'+section+'PhotosAlbumSelector').style.display = 'block';
		document.getElementById('add'+section+'PhotosPhotoSelector').style.display = '';
	}
}

function addAlbumToCanvas(user, remove) {
	dataFlags.processingAddAll = 1;
	eval('var last_shown_album = last_shown_'+user+'_album');
	var album_pids = fbAlbums[last_shown_album];
	if (album_pids && album_pids.length) {
		if (remove || confirm("Are you sure you want to add all "+album_pids.length+" photos?")) {
			for (var i=0; i<album_pids.length; i++) {
				var album_pid = album_pids[i];
				addAlbumPhotoToCanvas(album_pid, remove);
				//setTimeout('addAlbumPhotoToCanvas("'+album_pid+(remove?'", "'+remove:'')+'")', (remove?10:500)*i);
			}
		}
	}delete dataFlags.processingAddAll;
}

function addAlbumPhotoToCanvas(album_pid, remove) {
	var photo_thumb = document.getElementById('m'+album_pid+'thumb');
	if (photo_thumb) {
		var photo_thumb_selected = photo_thumb.className.indexOf('selected') != -1;
		if ((!remove && !photo_thumb_selected) || (remove && photo_thumb_selected)) addToCanvas(album_pid);
	}
}

function loadFacebookName(fbid) {
	if (fbidsToNames[fbid] || !parseInt(fbid) || fbid.indexOf('_') != -1) return;
	//query the users name
	queryFacebook('SELECT name FROM user WHERE uid="{0}"',
		[fbid],
		function(data) {
			if (data && (data.length > 0)) {
				fbidsToNames[fbid] = data[0].name;
			} else {
				//query page name
				queryFacebook('SELECT name FROM page WHERE page_id="{0}"',
					[fbid],
					function(data) {
						if (data && (data.length > 0)) {
							fbidsToNames[fbid] = data[0].name;
						}
					}
				);
			}
		}
	);
}

function loadFacebookNameFromRmnId(rmn_id, rmn_point_id) {
	loadFacebookIdFromRmnId(rmn_id, function(fbid) {
		loadFacebookName(fbid, rmn_point_id);
	});
}

function loadFacebookIdFromRmnId (rmn_id, callback) {
	if (rmn_id) {
		if (rmnIdsToFbids[rmn_id]) {
			callback(rmnIdsToFbids[rmn_id]);return;
		}
		readFromDB("getFacebookUserIdByRmnId", [rmn_id.toString()], function(data) {
			var resp = JSON.parse(data);
			rmnIdsToFbids[rmn_id] = resp['result'];
			callback(resp['result']);
		});
	}
}

function addToCanvas(media_id, args) {
	var video_type;
	var music_type;
	var preview;
	var service;
	var photo_json;
	var media_tags;
	if (args) {
		service = args['service'];
		video_type = args['video'];
		music_type = args['music'];
		if (music_type) video_type = music_type;
		preview = args['preview'];
	}

	//remove filtering for the type added
	try {
		if (video_type) document.getElementById('filter_media_videos').checked = true;
		else document.getElementById('filter_media_photos').checked = true;
		clearMediaFilters();//filterMedia();
	} catch(err) {}

	var video_text = music_type ? 'Music' : 'Video';
	if (video_type && video_type != 'fb') {
		var extLinkError = document.getElementById('ext'+video_text+'LinkError');
		if (extLinkError) extLinkError.innerHTML = '';
	}
	
	var media_id_type = media_id + (((video_type == 'fb') || !video_type) ? '' : video_type);
	if (music_type) media_id_type += 'music';
	else if (service == SERVICE_TYPES.flickr) media_id_type += 'flickr';

	var media_item_id = 'm'+media_id_type+'_wrapper';
	var media_thumb_id = 'm'+media_id_type+'thumb';
	var media_thumb_obj = document.getElementById(media_thumb_id);
	var insert = (!media_thumb_obj) ? true : (media_thumb_obj.className.indexOf('selected') == -1);
	if (insert) {
		if (media_thumb_obj) {
			//media_thumb_obj.className = 'photo_thumb_selected';
			var photo_thumb = '.photo_thumb[id="'+media_thumb_id+'"]';
			$(photo_thumb+' ~ .createMemoryViewAlbumCheckbox').attr('checked','checked');
			$(photo_thumb).attr('class', 'photo_thumb_selected');
		}

		// check whether point has been flagged to be removed
		// if so, remove delete flag and don't add again
		removeFlaggedPoint(media_item_id);
		
		var media_time;
		var media_title;
		var media_content;
		var media_src_high_res;
		var media_thumb;
		var media_width;
		var media_height;
		var media_desc;
		var media_link;
		var media_type;
		var media_upload;
		var video_thumb;
		var point_time;
		var partner_type;
		var partner_val;

		if (service == SERVICE_TYPES.flickr) {
			var photo = flickrDataManager.getPhotoById(media_id);
			media_time = photo.created_time;
			media_title = photo.title;
			media_content = photo.url;
			media_thumb = photo.thumb_url;
			media_width = photo.width;
			media_height = photo.height;
			media_desc = photo.description;
			media_link = photo.url;
			media_type = MEDIA_TYPES.photo;
			partner_type = PARTNER_TYPES.flickr_photo;
			partner_val = d_escape(photo.ownername);
		} else if (service == SERVICE_TYPES.aviary) {
			var new_src = urldecode(args['new_src']);
			var point_id = args['point_id'];
			var point_data = rmnPoints[point_id];
			media_time = point_data.utcTimeSec.toString();
			media_title = urldecode(point_data.description);
			media_content = new_src;
			media_thumb = new_src;
			media_link = new_src;
			media_width = args['width'];
			media_height = args['height'];
			//media_width = point_data.width;
			//media_height = point_data.height;
			media_desc = urldecode(point_data.description);
			media_type = MEDIA_TYPES.photo;
			partner_type = PARTNER_TYPES.aviary_photo;
			partner_val = d_escape(urldecode(point_data.partnerIdValue));
			media_tags = point_data.tags;
		} else {
			var fbMedia;
			var partner_type;
			var partner_type_alt;
			var media_type;
			var resource_keys = {};
			if (video_type) { // adding a video
				if (video_type == 'fb') {
					var video_add = document.getElementById('m'+media_id+'add');
					if (video_add) video_add.innerHTML = 'remove';
				}
				media_type = music_type ? MEDIA_TYPES.music : MEDIA_TYPES.video;
				partner_type = PARTNER_TYPES.facebook_video;
				fbMedia = fbVideos;
				if (video_type == 'yt') {
					partner_type = music_type ? PARTNER_TYPES.youtube_music : PARTNER_TYPES.youtube_video;
					fbMedia = fbVideos.yt;
				} else if (video_type == 'vim') {
					partner_type = music_type ? PARTNER_TYPES.vimeo_music : PARTNER_TYPES.vimeo_video;
					fbMedia = fbVideos.vim;
				} else if (segmentFbPosts[media_id]) partner_type_alt = PARTNER_TYPES.facebook_post; // for fb post videos
				resource_keys = {'title':'title', 'content':'src', 'thumb':'thumbnail_link', 'created':'created_time', 'width':'width', 'height':'height'};
				if (partner_type != PARTNER_TYPES.facebook_video) clearExtVideoValues(video_text); // clear ext video input and error containers
			} else { //adding a photo
				fbMedia = fbPhotos;
				partner_type = service==SERVICE_TYPES.kaptur?PARTNER_TYPES.kaptur_photo:PARTNER_TYPES.facebook_photo;
				partner_type_alt;
				media_type = MEDIA_TYPES.photo;
				resource_keys = {'title':'caption', 'content':'src_big', 'thumb':'src', 'created':'created', 'width':'src_big_width', 'height':'src_big_height'};
			}
			
			// add facebook media to night
			var media = fbMedia[media_id];
			if (media) {
				media_time = media[resource_keys.created];
				media_title = escapeQuotes(media[resource_keys.title]);
				media_content = media[resource_keys.content];
				media_src_high_res = media['src_high_res'];
				media_thumb = media[resource_keys.thumb];
				media_width = media[resource_keys.width];
				media_height = media[resource_keys.height];
				media_desc = media['description']; // for fb videos
				media_link = media['link']; // for fb photos
				media_upload = media['uploaded']; // for uploaded photos
				if (video_type) { // for fb videos
					video_thumb = media_thumb;
					if (!video_thumb) video_thumb = TEMPLATE_VIEW_PATH+'images/placeholders/video_default.png';
					if (!media_link && video_type == 'fb') media_link = getPartnerLink(media_id);
				}
				var media_owner = media['owner'];

				var partner_val = media_owner;
				if (partner_type == PARTNER_TYPES.facebook_post || partner_type == PARTNER_TYPES.kaptur_photo)
					partner_val = media_id;
			}
		}
		
		var point_time = adjustPointTime(media_time);
		if (!point_time) point_time = randomTime();
		point_time = getUniqueTime(point_time);
		
		//adds the media to the canvas
		var insert_canvas_args = {
			'id':media_id,
			'title':media_title,
			'content':media_content,
			'type':video_type,
			'music':music_type,
			'service':service,
			'thumb':video_thumb,
			'utctime':point_time
		};
		
		insertCanvasItem(insert_canvas_args);
		
		var media_tzoffset = segmentData.tzoffset;
		var point_args = {
			'utcTimeSec':point_time,
			'description':d_escape(media_title),
			'partnerId_id':partner_type,
			'partnerIdValue':partner_val,
			'service':service,
			'timezoneOffset':media_tzoffset,
			'privacy':'public'
		};
		
		var media_args = {
			'mediaType_id':media_type,
			'title':d_escape(media_title),
			'description':d_escape(media_desc),
			'url':d_escape(media_link),
			'src':d_escape(media_content),
			'thumb':d_escape(media_thumb),
			'height':media_height,
			'width':media_width,
			'service':service,
			'utcTimeSec':point_time,
			'user_id':userProfileObj.id,
			'partnerId_id':(partner_type_alt || partner_type),
			'partnerIdValue':media_id};
		if (media_src_high_res) {
			point_args['src_high_res'] = media_src_high_res;
			media_args['alt_src'] = d_escape(media_src_high_res);
		} // set media tags and keep track of current tags in memory
		if (!media_tags) {
			media_tags = {};
			if (fbMedia && fbMedia[media_id]) media_tags = fbMedia[media_id]['tags'];
		}
		for (media_tag in media_tags) rmnPointFriendFilters[media_tag] = 1;
		updateTaggedFilterHTML();
		if (preview) previewVideo(media_content, media_id);
		if (!dataFlags.offlineView) {
			// adds the media to the database
			addMediaToNight(media_id, point_args, media_args, media_tags);
		} else { // store point id for removal
			var pointIdArray = fbPhotoPointIds;
			if (media_type == MEDIA_TYPES.video) pointIdArray = fbVideoPointIds;
			pointIdArray[media_id_type] = media_id_type;
			point_args['description'] = urldecode(urldecode(point_args['description']));
			point_args['width'] = media_width;
			point_args['height'] = media_height;
			point_args['media_type_id'] = media_id;
			point_args['media_src'] = media_content;
			point_args['src_high_res'] = media_src_high_res;
			point_args['media_thumb'] = media_thumb;
			rmnPoints[media_id_type] = point_args;
			rmnPoints[media_id_type]['tags'] = media_tags;
			rmnPoints[media_id_type]['id'] = media_id_type;
		}
	} else removeCanvasItem(media_id, {'video_type':video_type, 'music_type':music_type, 'service': service});
}

function removeFlaggedPoint(media_item_id) {
	var media_point_removed;
	var media_point_temp = rmnPoints[media_item_id];
	if (media_point_temp) {
		media_point_removed = media_point_temp['removed'];
	}
	if (media_point_removed) {
		var media_point_id = media_point_temp['point_id'];
		if (media_point_id) {
			delete rmnPoints[media_point_id]; // remove generated point data
		}
		delete media_point_temp['removed'];
		delete media_point_temp['point_id'];
	}
}

function removeCanvasItem(media_id, args) {
	var unpair, video_type, music_type, music_src, service, no_write;
	if (args) {
		unpair = args['unpair'];
		video_type = args['video_type'];
		music_type = args['music_type'];
		music_src = args['src'];
		service = args['service'];
		no_write = args['no_write'];
	}
	
	var media_id_type = media_id;
	if (service == SERVICE_TYPES.flickr) media_id_type += 'flickr';
	else if ((video_type != 'fb') && (video_type)) media_id_type += video_type;

	var canvasRow = 'nightCanvasRow';
	var pointIds;
	if (service == SERVICE_TYPES.flickr) pointIds = flickrPhotoPointIds;
	else if (video_type) pointIds = fbVideoPointIds;
	else pointIds = fbPhotoPointIds;
	
	if (music_type) {
		media_id_type += 'music';
		canvasRow = 'videoThumbRow';
	}
	
	// check to make sure user is owner before removing
	var point_id = pointIds[media_id_type];
	if (segmentData.id && !unpair && (rmnPoints[point_id] && userProfileObj.id != rmnPoints[point_id]['user_id'])) {
		if (!dataFlags.processingAddAll) alert('You can only remove what you have added.');
	} else {
		// unhighlight media icon regardless of db action
		var media_wrapper_id = 'm'+media_id_type+'_wrapper';
		var media_thumb_id = 'm'+media_id_type+'thumb';
		var media_thumb_obj = document.getElementById(media_thumb_id);
		if (media_thumb_obj) {
			//media_thumb_obj.className = 'photo_thumb';
			var photo_thumb = '.photo_thumb_selected[id="'+media_thumb_id+'"]';
			$(photo_thumb+' ~ .createMemoryViewAlbumCheckbox').removeAttr('checked');
			$(photo_thumb).attr('class', 'photo_thumb');
		}
		
		// store temp data in case media is removed before it's rendered on the canvas
		if (!rmnPoints[media_wrapper_id]) rmnPoints[media_wrapper_id] = new Object();
		if (!rmnPoints[media_wrapper_id]['removed']) rmnPoints[media_wrapper_id]['removed'] = [media_id, args];
		
		// delete point
		if (point_id || !segmentData.id) {
			if (window.weddingCoverSlideshow) weddingCoverSlideshow.removePhotoByPointId(point_id);
			if (!dataFlags.offlineView) {
				if (!no_write) {
					kapturDb.removePointFromSegment(segmentData.id, point_id);
					if (!unpair) {
						writeToDB('deletePoint', [point_id]);
					} else {
						writeToDB('unpairUsersAndPoint', [[segmentData.owner], point_id]);
					}
					
					// flag slideshow reload
					if (window.weddingCoverSlideshow) weddingCoverSlideshow.flagReload();
				}
				
				// remove segment cover if this it's the same as the deleted photo
				//if (!video_type) {
					try {
						if (media_id == memoryCreationWizard.weddingCover && !editNight && 0) {
							// pick the next cover
							if ($('#createMemoryAllPhotosKapturPhotos').children().length)
								$('#createMemoryAllPhotosKapturPhotos').children()[0].onclick();
							else setWeddingCover('');
						}
					} catch(err) {
						if (segmentData.cover) {
							var point_media_id = rmnPoints[point_id]['media_id'];
							if (point_media_id == segmentData.cover.id) refreshSegmentThumb();
						}
					}
				//}
			}
			
			try {
				var media_wrapper = document.getElementById(media_wrapper_id);
				media_wrapper.parentNode.removeChild(media_wrapper);
				//document.getElementById(canvasRow).removeChild(document.getElementById(media_wrapper_id));
				if (!rmnPoints[media_wrapper_id]['point_id']) delete rmnPoints[media_wrapper_id]; // remove temp data
			} catch (err) {
				//rmnPoints[media_wrapper_id]['test1'] = 1;
				if (rmnPoints[media_wrapper_id]['point_id'] && rmnPoints[media_wrapper_id]['removed'])
					delete rmnPoints[media_wrapper_id]; // remove temp data
			}
			
			try {
				if (!document.getElementById(canvasRow).childNodes.length) {
					if (canvasRow == 'nightCanvasRow') {
						document.getElementById('nightCanvasEmpty').style.display = '';
						document.getElementById('nightCanvasWrapper').style.display = 'none';
						document.getElementById('filterMediaBtn').style.display = 'none';
						document.getElementById('canvasViewSelectWrapper').style.display = 'none';
					} else if (canvasRow == 'videoThumbRow') document.getElementById('nightVideosAdd').style.display = '';
				}
			} catch(err) {}
			
			// update select cover from kaptur thumbs
			try {addRemoveFromKapturCoverSelect(point_id, 0, 1);} catch(err) {}
			
			if (video_type == 'fb') {
				var video_add = document.getElementById('m'+media_id+'add');
				if (video_add) video_add.innerHTML = 'add';
			}//delete rmnPointTimes[media_time]; // remove time from point times array
			delete pointIds[media_id_type]; // remove the rmn point reference from memory
			delete rmnPoints[point_id]; // remove rmn point data
			try {delete memoryCreationWizard.selected_photos[media_id_type]} catch(err) {}
			if (!unpair) removeFromArray(point_id, segmentPairingIds); // remove id from point pairing array
			
			// delete fb post id associated with item if applicable
			if (segmentFbPosts[media_id]) delete segmentFbPosts[media_id];
			
			// clear deleted video from video player - video_type 
			if (music_type) clearDeletedVideo(media_id, video_type, music_src);
			
			// remove segment cover if this it's the same as the deleted photo
			if (!dataFlags.offlineView) {
				try {
					// pick the next cover
					if (media_id == memoryCreationWizard.weddingCover && !editNight)
						chooseClearAlbumCover();
				} catch(err) {}
			}
			
			// update custom scrollbars
			updateCustomScrollbars();
		}
	}
}

var insert_queue = [];
function insertCanvasItem(media, skip_binding_lazyload) {
	var media_id = media['id'],
		media_title = escapeQuotes(media['title']),
		media_content = media['content'],
		media_thumb = media['thumb'],
		media_type = media['type'],
		media_music = media['music'],
		media_time = media['utctime'],
		media_service = media['service'],
		media_id_type = media_id,
		media_id_type_element;
	
	if (media_service == SERVICE_TYPES.flickr) media_id_type += 'flickr';
	else if (media_type && (media_type != 'fb')) media_id_type += media_type;
	if (media_music) media_id_type += 'music';
	var media_item_id = "m"+media_id_type+"_wrapper";
	
	var media_point_removed; // don't insert if item has been flagged as removed
	var media_point_temp = rmnPoints[media_item_id];
	if (media_point_temp) media_point_removed = media_point_temp['removed'];
	media_id_type_element = document.getElementById("m" + media_id_type + "thumb");
	if ((media_point_removed || (media_id_type_element && media_id_type_element.className.indexOf('selected') == -1)) && media_point_temp) {
		var media_point_id = media_point_temp['point_id'];
		if (media_point_id) {
			delete rmnPoints[media_point_id]; // remove generated point data
			delete rmnPoints[media_item_id]; // media_point_temp['removed'];
		}
	} else {
		// space out photo loading
		if (segmentFlags.loading && !media_thumb) {// && navigator.userAgent.indexOf("MSIE") != -1
			//setTimeout('insertCanvasItem('+JSON.stringify(media)+')', 250);
			insert_queue.push(JSON.stringify(media));
		} else { // extract media data
			if (!document.getElementById(media_item_id)) {
				if (!media_thumb) segmentFlags.loading = 1; // set loading flag
				var media_row;
				var media_item = document.createElement('td');
				media_item.id = media_item_id;
				media_item.style.display = (dataFlags.edit_mode ? 'inline-block' : 'none');//'inline-block';
				
				// set values based on media type
				var media_row_id = 'nightCanvasRow';
				var gridView = dataFlags.gridView;
				var media_item_classname = gridView?'night_img_wrapper_thumb':'night_img_wrapper_big';
				var media_thumb_classname = gridView?'night_img_thumb':'night_img_big';
				var media_thumb_rel = ' rel="lightbox"';
				var mediaPointIds = null;
				
				if (media_service == SERVICE_TYPES.flickr) {
					mediaPointIds = flickrPhotoPointIds;
				} else if (media_thumb) { // if this is music/video
					if (media_music) {
						media_row_id = 'videoThumbRow';
						media_item_classname = 'video_thumb_wrapper';
						media_thumb_classname = 'video_thumb';
						media_thumb_rel = ' onclick="embedVideo(\''+media_content+'\', {\'vid\':\''+media_id+'\'})"';
						//media_thumb_rel = ' onclick="embedVideo(\''+media_content+'\', {\'vid\':\''+media_id+'\'})"';
					} else {
						media_thumb_rel = ' rel="lightbox_video"';
					}
					mediaPointIds = fbVideoPointIds;
				} else {
					mediaPointIds = fbPhotoPointIds;
				}
				
				// derive permissions
				var show_delete;
				var unpair_delete = false;
				media_point_id = mediaPointIds[media_id_type];
				if (media_point_id) {
					var media_point = rmnPoints[media_point_id];
					if (media_point) {
						// for case when item is inserted after point is created
						var media_real_point_id = media_point['point_id'];
						if (media_real_point_id) {
							media_point = rmnPoints[media_real_point_id]; // swap in actual point data
							media_point_id = media_real_point_id; // swap in point id
							mediaPointIds[media_id_type] = media_real_point_id; // update media point id reference
						}delete rmnPoints[media_item_id]; // remove temp point data
						
						var media_owner = media_point['user_id'];
						show_delete = (!editNight) || (media_owner == userProfileObj.id);
						if (media_owner != userProfileObj.id) unpair_delete = true;
						
						// override media data if point data exists
						if (media_point['description']) media_title = escapeQuotes(urldecode(media_point['description']));
						media_time = media_point['utcTimeSec'];
						
						// set segment cover if it's not already set
						try {
							if (!media_thumb && !memoryCreationWizard.weddingCover && !editNight && 0)
								setWeddingCover(media_id);
						} catch(err) {
							var segment_cover = segmentData.cover;
							if (!media_thumb && (segment_cover && !segment_cover.id)) {
								var cover_id = rmnPoints[media_point_id]['media_id'];
								var cover_src = rmnPoints[media_point_id]['media_src'];
								var cover_thumb = rmnPoints[media_point_id]['media_thumb'];
								if (cover_id) {
									if (segmentData.id) writeToDB('editSegment', [{'media_id':cover_id}, segmentData.id]);
									if (segmentData.location.thumb && segmentData.location.thumb != 'null')
										cover_thumb = segmentData.location.thumb;
									segmentData.cover.id = cover_id;
									refreshSegmentThumb(cover_src, cover_thumb);
								}
							}
						}
					}
				} else {
					show_delete = true;
					media_point_id = media_item_id; // set temp point id
					if (!rmnPoints[media_point_id]) rmnPoints[media_point_id] = new Object();
					rmnPoints[media_point_id]['utcTimeSec'] = media_time; // load temp point data
				}
				
				media_row = document.getElementById(media_row_id);
				media_item.className = media_item_classname;
				if (media_point_id) media_item.setAttribute('point_id', media_point_id);
				if (media_thumb) media_item.setAttribute('media_content', media_content);
				if (media_item_id) media_item.setAttribute('media_id', media_id_type);
				var media_alt = '';
				if (media_title && (media_title != 'null') && (media_title != 'undefined'))
					media_alt = ' alt="'+media_title+'" title="'+media_title+'"';
				var item_onload_string = (!media_thumb?'segmentFlags.loading = 0; checkInsertQueue();':'')+'updateCustomScrollbars();this.removeAttribute(\'onload\')';
				var item_src = media_thumb || media_content;
				var item_html = '<img id="m'+media_id_type+'" src="'+TEMPLATE_VIEW_PATH+'images/canvas_loading.png" preload_src="'+item_src+'" grid_thumb="'+item_src+'" class="'+media_thumb_classname+'"'+media_alt+media_thumb_rel+' onload="'+item_onload_string+'" />';//<td class="inline"></td>
				//item_html += '<img src="'+TEMPLATE_VIEW_PATH+'images/btn/comments.png" class="night_img_comment" title="Add/View Comments" />';
				
				// contruct html element
				var args = '';
				if (show_delete && !segmentFlags.lockContribute) {
					if (media_thumb) {
						args += "'video_type':'"+media_type+"'";
						media_item.setAttribute('video_type', media_type);
						if (media_music) args += ", 'music_type':'"+media_music+"'";
					}if (unpair_delete) {
						if (args) args += ', ';
						args += "'unpair':1";
						media_item.setAttribute('unpair', '1');
					}if (media_service) {
						if (args) args += ', ';
						args += "'service':"+media_service;
						media_item.setAttribute('service', media_service);
					}if (args) args = ', {'+args+'}';
					if (!media_music) { // !media_type
						//item_html += '<div class="move_right_btn" title="Move right" onclick="moveCanvasItemRight(\''+media_id_type+'\''+(args?args:'')+', \'\', event)"></div>';
						//item_html = '<div class="move_left_btn" title="Move left" onclick="moveCanvasItemLeft(\''+media_id_type+'\''+(args?args:'')+', \'\', event)"></div>' + item_html;
						item_html += '<div class="delete_btn" title="Remove" args="'+args.substr(2)+'"></div>';
						item_html += '<div class="move_right_btn" title="Move right"></div>';
						item_html = '<div class="move_left_btn" title="Move left"></div>' + item_html;
					} else {
						item_html += '<div class="delete_btn" title="Remove" onclick="removeCanvasItem(\''+media_id+'\''+args+')"></div>';
						// show edit btn for videos - media_thumb
						var item_click = "editVideoDetails('"+media_id+"', '"+media_type+"', '"+media_content+"', '"+media_id+"')";
						item_html += '<div class="edit_video_btn" title="Edit" onclick="'+item_click+'"></div>';
					}
				}
				
				if (media_thumb && !media_music) {
					item_html += '<div class="play_btn"></div>'; // show 'play' icon for videos
				}
				
				// onclick="$(this).siblings(\'img\').colorbox({\'open\':true});"
				media_item.innerHTML = item_html;
				
				// update canvas
				if (!media_thumb) {
					//updateLightboxPhotos();
					var nightCanvasEmpty = document.getElementById('nightCanvasEmpty');
					if (nightCanvasEmpty) {
						nightCanvasEmpty.style.display = 'none';
						document.getElementById('nightCanvasWrapper').style.display = '';
						document.getElementById('filterMediaBtn').style.display = 'block';
						document.getElementById('canvasViewSelectWrapper').style.display = 'block';
					}
				} else { // embed first music
					if (media_music) {
						var videoPlayerWrapper = document.getElementById('videoPlayerWrapper');
						if (videoPlayerWrapper && !videoPlayerWrapper.innerHTML) {
							embedVideo(media_content, {'vid':media_id});
							// embedVideo(removeAutoplay(media_content), {'vid':media_id, 'no_autoplay':1});
							document.getElementById('nightVideosAdd').style.display = 'none';
						}
					} else {
						var nightCanvasEmpty = document.getElementById('nightCanvasEmpty');
						if (nightCanvasEmpty) {
							nightCanvasEmpty.style.display = 'none';
							document.getElementById('nightCanvasWrapper').style.display = '';
							document.getElementById('filterMediaBtn').style.display = 'block';
							document.getElementById('canvasViewSelectWrapper').style.display = 'block';
							updateLightboxVideos();
						}
					}
				}
				
				if (!media_music) {
					var point = rmnPoints[media_point_id];
					if (media_service == SERVICE_TYPES.flickr) {
						point.media_src = media_content;
						point.url = media_content;
					}
					if (window.weddingCoverSlideshow) weddingCoverSlideshow.addPhotoPoint(point);
				}
				
				addStreamItemToStream(media_item, media_row_id);
				//This stuff is super slow to do every time trigger lazyload only when all images are loaded not for each image
				//$('#m'+media_id_type).lazyload({placeholder : TEMPLATE_VIEW_PATH+"images/canvas_loading.png", event:"updatecanvas"});
				if (dataFlags.edit_mode) {
					$('#m'+media_id_type).lazyload({placeholder : TEMPLATE_VIEW_PATH+"images/canvas_loading.png"/*, event: 'updatecanvas'*/});
				}
				//$(window).trigger('updatecanvas'); // load visible photos
				// update jquery media remove event handlers
				if (show_delete && !segmentFlags.lockContribute) {
					updateAutoShowRemove(media_item_classname);
				}
				
				// update select cover from kaptur thumbs
				if (media_service != SERVICE_TYPES.flickr) { // flickr cover thumbs get added when media is created
					try {addRemoveFromKapturCoverSelect(media_point_id);} catch(err) {}
				}
			}
		}
	}
	updateTabStatus('photos', 1);
}

function processNextInsertQueueItem() {
	insertCanvasItem(JSON.parse(insert_queue.shift()));
}

function checkInsertQueue() {
	// load next item
	//if (insert_queue.length) setTimeout('insertCanvasItem('+insert_queue.shift()+')', 0);
	//if (insert_queue.length) insertCanvasItem(JSON.parse(insert_queue.shift()));
	if (insert_queue.length) {
		setTimeout(processNextInsertQueueItem, 10);
	} else {
		updateEmptyStatusesTab();
	}
}

function refreshSegmentThumb(src, thumb) {
	try {
		if (src) { // update values in memory
			segmentData.cover.src = src;
			if (thumb.indexOf('flickr.com') == -1)
				segmentData.cover.thumb = thumb.replace('_t.jpg', '_s.jpg'); // fb thumb url hack
			else segmentData.cover.thumb = thumb;
		}
		
		var nightSummaryThumbWrapper = document.getElementById('nightSummaryThumbWrapper');
		var nightSummaryThumb = document.getElementById('nightSummaryThumb');
		if (nightSummaryThumbWrapper) {
			if (src) {
				nightSummaryThumb.src = segmentData.cover.thumb;
				nightSummaryThumbWrapper.style.display = 'block';
			} else {
				//if (segmentData.id) writeToDB('editSegment', [{'media_id':''}, segmentData.id]);
				segmentData.cover = new Object();
				
				// revert state of the segment thumb
				if (segmentData.location.thumb && segmentData.location.thumb != 'null') {
					nightSummaryThumb.src = segmentData.location.thumb;
					nightSummaryThumbWrapper.style.display = 'block';
				} else nightSummaryThumbWrapper.style.display = '';
			}
		}
	} catch(err) {}
}

function refreshMoveCanvasButtons(item, mouse_x, evt){
	delegateCanvasMouseout(evt);
	/*$(item).trigger('mouseleave');
	var item_left = $(item).offset().left;
	var item_right = $(item).offset().left + $(item).width();
	if ((item_left < mouse_x) && (mouse_x < item_right)) {
		$(item).trigger('mouseenter');
	}*/
}

function autoScroll(e) {
	var scrollX = 150, scrollY = 0, scrollMargin = 150, cursorPos = e.pageX;
	var leftBound = $('#moveCanvasLeft').offset().left;
	var rightBound = $('#moveCanvasRight').offset().left;
	if (dataFlags.gridView) {
		scrollX = 0, scrollY = 100, scrollMargin = 100, cursorPos = e.pageY;
		leftBound = $('#nightTitleWrapper').offset().top;
		rightBound = $('#nightActionsWrapper').offset().top;
	}
	if (cursorPos > rightBound - scrollMargin) {
		try {$('#nightCanvas').jScrollPane().data('jsp').scrollBy(scrollX,scrollY);} catch(err) {}
		$("#nightCanvasRow").sortable("refreshPositions");
	} else if (cursorPos < leftBound + scrollMargin) {
		try {$('#nightCanvas').jScrollPane().data('jsp').scrollBy(-scrollX,-scrollY);} catch(err) {}
		$("#nightCanvasRow").sortable("refreshPositions");
	} else if (dataFlags.autoScrollInterval) {clearTimeout(dataFlags.autoScrollInterval);dataFlags.autoScrollInterval = null;}
}

function enableDragAndDrop() {//return;
	//if (!wizardMemoryData || (wizardMemoryData && segmentFlags.wizardShowContributeActive)) {
		var args = {
			start: function(event, ui) {
				dataFlags.dragActive = 1;
				$(document).bind("mousemove", function(e) {
					if (!dataFlags.autoScrollInterval) dataFlags.autoScrollInterval = setInterval('autoScroll({"pageX":'+e.pageX+', "pageY":'+e.pageY+'})', 100);
					else autoScroll(e);
					//var elem = document.elementFromPoint(e.pageX, e.pageY);
					//if (elem.className == 'timeline_bar') elem.onmouseover();
				});
				$(".move_left_btn, .move_right_btn, .delete_btn").css("visibility", "hidden");
			}, stop: function(event, ui) {
			$(document).unbind("mousemove");if (dataFlags.autoScrollInterval) {
				clearTimeout(dataFlags.autoScrollInterval);dataFlags.autoScrollInterval = null;
			}
			dataFlags.dragActive = null;$(".move_left_btn, .move_right_btn, .delete_btn").css("visibility", "");
			//document.elementFromPoint(event.pageX, event.pageY); ui.item[0].id;
			try {updateScrollbarTime();} catch(err) {}
			try {
				//retrigger mouseenter and mouseleave to get the buttons to behave properly
				refreshMoveCanvasButtons($('#'+ui.item[0].id), event.clientX, event);
			} catch(err) {}
		}, update: function(event, ui) {moveCanvasItemDragged(ui.item[0].id, event);}, tolerance: 'pointer', items: '> *:has(".delete_btn")'};
		//if (!dataFlags.gridView) args['cursorAt'] = {'bottom':-5, 'right':-5};
		if (segmentFlags.contribute) {
			$("#nightCanvasRow").sortable(args);
			$("#nightCanvasRow").sortable("enable");
		}
	//}
}

function disableDragAndDrop() {
	$("#nightCanvasRow").sortable("disable");
}

function moveCanvasItemDragged(media_wrapper_id, evt) {
	// refactor to combine with moveCanvasItemRight!!
	var canvas_row = document.getElementById('nightCanvasRow');
	var item = document.getElementById(media_wrapper_id);
	var media_point_id = item.getAttribute('point_id');
	var previous_item = item.previousSibling;
	var next_item = item.nextSibling;
	var prev_time, next_time;
	if (previous_item) {
		var prev_point_id = previous_item.getAttribute('point_id');
		prev_time = rmnPoints[prev_point_id]['utcTimeSec'];
	} else prev_time = segmentData.start;
	if (next_item) {
		var next_point_id = next_item.getAttribute('point_id');
		next_time = rmnPoints[next_point_id]['utcTimeSec'];
	} else next_time = segmentData.start;
	
	kapturDb.movePointInSegmentBefore(segmentData.id, media_point_id, next_point_id);
	
	try {
		//retrigger mouseenter and mouseleave to get the buttons to behave properly
		if (!evt) evt = window.event;
		refreshMoveCanvasButtons(item, evt.clientX, evt);
	} catch(err) {}
	
	var segment_id = segmentData.id;
	try {segment_id = memoryCreationWizard.sid;} catch(err) {}
	if (segment_id) {
		var new_time = getTimeBetweenSiblings(item);
		var time_gap = next_time - prev_time;
		if (time_gap == 1) new_time++;
		rmnPoints[media_point_id].utcTimeSec = new_time + "";
		saveTime(media_point_id);
	}
	
	// if time gap btwn items is 0 or 1 ms
	if (time_gap < 2) {
		if (next_point_id) {
			rmnPoints[next_point_id]['utcTimeSec']++;
			saveTime(next_point_id);
		}
		if (!time_gap) {
			if (prev_point_id) {
				rmnPoints[prev_point_id]['utcTimeSec']--;
				saveTime(prev_point_id);
			} else {
				segmentData.start--;
				writeToDB('editSegment', [{'utcStartSec':segmentData.start}, segmentData.id]);
			}
		}
	}
	
	// flag slideshow reload
	if (window.weddingCoverSlideshow) weddingCoverSlideshow.flagReload();
}

function moveCanvasItemLeft(media_id, args, evt) {
	// refactor to combine with moveCanvasItemRight!!
	var media_id_type = "m" + media_id + "_wrapper";
	var fbPointIds = fbPhotoPointIds;
	if (media_id.indexOf('flickr') != -1) {
		fbPointIds = flickrPhotoPointIds;
	}
	var canvas_row_id = 'nightCanvasRow';
	if (args && args['video_type']) fbPointIds = fbVideoPointIds;
	
	var segment_end = segmentData.end;
	try {segment_end = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);} catch(err) {}
	
	var canvas_row = document.getElementById(canvas_row_id);
	var item = document.getElementById(media_id_type);
	var item_point_id = item.getAttribute('point_id');
	var prev_pos = $(item).position().left;
	var previous_item = item.previousSibling;
	var prev_right_time, prev_left_time, prev_left_point_id;
	var prev_right_point_id = previous_item.getAttribute('point_id');
	if (previous_item) {
		prev_right_time = rmnPoints[prev_right_point_id]['utcTimeSec'];
		var prev_left_item = previous_item.previousSibling;
		if (prev_left_item) {
			prev_left_point_id = prev_left_item.getAttribute('point_id');
			prev_left_time = rmnPoints[prev_left_point_id]['utcTimeSec'];
		} else prev_left_time = segment_end;
		//item = canvas_row.removeChild(item);
		//item = canvas_row.insertBefore(item, previous_item);
		var item_wrapper = item.parentNode;
		item_wrapper.removeChild(item);
		item_wrapper.insertBefore(item, previous_item);
		
		kapturDb.movePointInSegmentBefore(segmentData.id, item_point_id, prev_right_point_id);
	}
	
	// move scrollbar to make multi-clicking possible
	var scrollOffset = $(item).position().left - prev_pos;
	try {$('#nightCanvas').jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40}).data('jsp').scrollBy(scrollOffset, 0);} catch(err) {}
	try {
		//retrigger mouseenter and mouseleave to get the buttons to behave properly
		if (!evt) evt = window.event;
		refreshMoveCanvasButtons(item, evt.clientX, evt);
		var next_item = item.nextSibling;
		if (next_item) refreshMoveCanvasButtons(next_item, evt.clientX, evt);
	} catch(err) {}
	
	var segment_id = segmentData.id;
	try {segment_id = memoryCreationWizard.sid;} catch(err) {}
	if (segment_id) {
		var new_time = getTimeBetweenSiblings(item);
		var time_gap = prev_right_time - prev_left_time;
		if (time_gap == 1) new_time++;
		rmnPoints[fbPointIds[media_id]].utcTimeSec = new_time + "";
		saveTime(fbPointIds[media_id]);
	}
	
	// if time gap btwn items is 0 or 1 ms
	if (time_gap < 2) {
		if (prev_right_point_id) {
			rmnPoints[prev_right_point_id]['utcTimeSec']++;
			saveTime(prev_right_point_id);
		}if (!time_gap) {
			if (prev_left_point_id) {
				rmnPoints[prev_left_point_id]['utcTimeSec']--;
				saveTime(prev_left_point_id);
			} else {
				segmentData.start--;
				var segment_start = segmentData.start;
				try {segment_start = parseInt(memoryCreationWizard.start_time.getTime()/1000, 10);} catch(err) {}
				writeToDB('editSegment', [{'utcStartSec':segment_start}, segment_id]);
			}
		}
	}
	
	// flag slideshow reload
	if (window.weddingCoverSlideshow) weddingCoverSlideshow.flagReload();
}

function moveCanvasItemRight(media_id, args, evt) {
	// refactor to combine with moveCanvasItemLeft!!
	var media_id_type = "m" + media_id + "_wrapper";
	var fbPointIds = fbPhotoPointIds;
	if (media_id.indexOf('flickr') != -1) {
		fbPointIds = flickrPhotoPointIds;
	}
	var canvas_row_id = 'nightCanvasRow';
	if (args && args['video_type']) fbPointIds = fbVideoPointIds;
	
	var segment_end = segmentData.end;
	try {segment_end = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);} catch(err) {}
	
	var canvas_row = document.getElementById(canvas_row_id);
	var item = document.getElementById(media_id_type);
	var item_point_id = item.getAttribute('point_id');
	var prev_pos = $(item).position().left;
	var next_item = item.nextSibling;
	var next_left_time, next_right_time, next_right_point_id;
	var next_left_point_id = next_item.getAttribute('point_id');
	if (next_item) {
		next_left_time = rmnPoints[next_left_point_id]['utcTimeSec'];
		var next_right_item = next_item.nextSibling;
		if (next_right_item) {
			next_right_point_id = next_right_item.getAttribute('point_id');
			next_right_time = rmnPoints[next_right_point_id]['utcTimeSec'];
		} else next_right_time = segment_end;
		//next_item = canvas_row.removeChild(next_item);
		//next_item = canvas_row.insertBefore(next_item, item);
		var item_wrapper = next_item.parentNode;
		item_wrapper.removeChild(next_item);
		item_wrapper.insertBefore(next_item, item);
	}
	
	kapturDb.movePointInSegmentBefore(segmentData.id, item_point_id, next_right_point_id);
	
	// move scrollbar to make multi-clicking possible
	var scrollOffset = $(item).position().left - prev_pos;
	try {$('#nightCanvas').jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40}).data('jsp').scrollBy(scrollOffset, 0);} catch(err) {}
	try {
		//retrigger mouseenter and mouseleave to get the buttons to behave properly
		if (!evt) evt = window.event;
		refreshMoveCanvasButtons(item, evt.clientX, evt);
		var previous_item = item.previousSibling;
		if (previous_item) refreshMoveCanvasButtons(previous_item, evt.clientX, evt);
	} catch(err) {}
	
	var segment_id = segmentData.id;
	try {segment_id = memoryCreationWizard.sid;} catch(err) {}
	if (segment_id) {
		var new_time = getTimeBetweenSiblings(item);
		rmnPoints[fbPointIds[media_id]].utcTimeSec = new_time + "";
		saveTime(fbPointIds[media_id]);
	}
	
	// if time gap btwn items is 0 or 1 ms
	var time_gap = next_right_time - next_left_time;
	if (time_gap < 2) {
		if (next_left_point_id) {
			rmnPoints[next_left_point_id]['utcTimeSec']--;
			saveTime(next_left_point_id);
		}if (!time_gap) {
			if (next_right_point_id) {
				rmnPoints[next_right_point_id]['utcTimeSec']++;
				saveTime(next_right_point_id);
			} else {
				segmentData.end++;
				var segment_end = segmentData.end;
				try {segment_end = parseInt(memoryCreationWizard.end_time.getTime()/1000, 10);} catch(err) {}
				writeToDB('editSegment', [{'utcEndSec':segment_end}, segment_id]);
			}
		}
	}
	
	// flag slideshow reload
	if (window.weddingCoverSlideshow) weddingCoverSlideshow.flagReload();
}

function saveTime(point_id) {
	writeToDB('editPoint', [{'utcTimeSec':rmnPoints[point_id].utcTimeSec}, point_id]);
}

function getTimeBetweenSiblings(media_item) {
	try {
		var previous_item = media_item.previousSibling;
		var previous_item_id = (previous_item) ? unwrapPhotoId(previous_item.id):"";
		var previous_item_time = (previous_item) ? getPointDataFromMedia(previous_item_id).utcTimeSec : segmentData.start;
		var next_item = media_item.nextSibling;
		var next_item_id = (next_item) ? unwrapPhotoId(next_item.id):"";
		var next_item_time = (next_item) ? getPointDataFromMedia(next_item_id).utcTimeSec : segmentData.end;
		var between_time = Math.floor((parseInt(previous_item_time) + parseInt(next_item_time)) / 2);
		return between_time;
	} catch (err) {}
}

function getPointDataFromMedia(id) {
	var pointIds;
	var media_type = document.getElementById('m'+id).getAttribute('rel');
	if (id.indexOf('flickr') != -1) {
		pointIds = flickrPhotoPointIds;
	} else if (media_type.indexOf('video') != -1) {
		pointIds = fbVideoPointIds;
	} else {
		pointIds = fbPhotoPointIds;
	}
	
	return rmnPoints[pointIds[id]];
}

function unwrapPhotoId(id) {
	return id.substr(1).split("_wrapper")[0];
}

function updatePointMediaData(point_id, media_id, media_src, media_thumb, fb_media_id) {
	if (rmnPoints[point_id]) {
		rmnPoints[point_id]['media_id'] = media_id;
		rmnPoints[point_id]['media_src'] = media_src;
		rmnPoints[point_id]['media_thumb'] = media_thumb;
		rmnPoints[point_id]['media_type_id'] = fb_media_id;
	}
}

function confirmAttend() {
	if (!document.getElementById('attendee'+loggedInUser)) {
		document.getElementById('attendBtn').style.display = 'none';
		addRmnUserToNight(userProfileObj.id);
		addToAttendList(loggedInUser, 0, userProfileObj.first_name, userProfileObj.last_name);
		loadFriendNewsFeed(loggedInUser); // load user fb stream
	}
}

function toggleAttend(fbid, first_name, last_name, gender, locale) {
	var friend_wrapper = document.getElementById('attendee'+fbid); // 'f'+fbid
	var remove = friend_wrapper? 1 : 0; // friend_wrapper && friend_wrapper.className.indexOf('selected') != -1
	if (fbid == loggedInUser) updateAttendBtnText(remove);
	addFbUserToNight(fbid, remove, first_name, last_name, gender, locale);
}

function toggleMediaTag(point_id, fbid, media_id) {
	var point_data = rmnPoints[point_id];
	var tag_wrapper = document.getElementById('mediaTag'+fbid);
	var friend_tag_wrapper = document.getElementById('f'+fbid+'tag');
	var fbMediaFriendsList = document.getElementById('fbMediaFriendsList');
	var remove = tag_wrapper? 1 : 0;
	if (remove) {
		var tag_id = point_data['tags'][fbid];
		writeToDB('deleteTag', [tag_id]);
		delete rmnPoints[point_id]['tags'][fbid];
		friend_tag_wrapper.className = 'friend_wrapper';
		fbMediaFriendsList.removeChild(tag_wrapper);
	} else {
		createMediaUserTag(point_data['media_id'], {'uid':fbid}, point_data, media_id);
		friend_tag_wrapper.className = 'friend_wrapper_selected';
		tag_wrapper = document.createElement('div');
		tag_wrapper.id = 'mediaTag'+fbid;
		tag_wrapper.innerHTML = '<fb:name uid="'+fbid+'" capitalize="true" linked="false"></fb:name>';
		fbMediaFriendsList.appendChild(tag_wrapper);
		loadFBML(tag_wrapper);
		rmnPointFriendFilters[fbid] = 1;
	}
}

function selectAllFriends(unselect) {
	var friends = $('#fbEventFriendContents .friend_wrapper'+(unselect?'_selected':''));
	if (unselect || (!unselect && confirm("Are you sure you want to select all friends?"))) {
		friends.each(function(index) {
			this.parentNode.onclick();
			/*var fid = $(this).attr('id').substr(1);
			toggleAttend(fid);*/
		});
	}
}

function addFbEventById() {
	var eid = document.getElementById('addFbEventId').value;
	eid = parseInt(eid, 10);
	if (eid) {
		segmentFlags.eventsLoaded = false;
		loadFbEvents(eid);
	} else alert('Invalid Facebook Id!');
}

function addFbUserToNight(fbid, remove, firstName, lastName, gender, locale) {
	var wedding_cover = document.getElementById('memoryEditWrapper');
	if (segmentData && segmentData.fbOwner && fbid == segmentData.fbOwner) return;
	readFromDB('getRmnUserInfoByFacebookId', [fbid.toString()], (function(fbid, remove) {
		return function(data) {
			var result = JSON.parse(data);
			result = result['result'];
			if (result) {
				var user_id = result['user_id'];
				var user_first_name = result['firstName'];
				var user_last_name = result['lastName'];
				var user_gender = result['gender'];
				var user_locale = result['locale'];
				if (user_first_name == 'not_set') user_first_name = '';
				if (user_last_name == 'not_set') user_last_name = '';
				if (user_gender == 'not_set') user_gender = '';
				if (user_locale == 'not_set') user_locale = '';
				if (user_id) {
					addRmnUserToNight(user_id, remove);
					if (remove) {// && !wedding_cover
						// remove user items
						removeFbUserMedia(fbPhotoPointIds, fbid, user_id);
						removeFbUserMedia(fbVideoPointIds, fbid, user_id);
						removeFbUserPosts(fbid, user_id);
					}
					
					// update name and info in db
					if ((!user_first_name && firstName) || (!user_last_name && lastName) || (!user_gender && gender) || (!user_locale && locale)) {
						writeToDB('setRmnUserInfo', [{'firstName':d_escape(firstName), 'lastName':d_escape(lastName), 'gender':d_escape(gender), 'locale':d_escape(locale)}, user_id]);
					} else if ((user_first_name && !firstName) || (user_last_name && !lastName) || (user_gender && !gender) || (user_locale && !locale)) {
						firstName = user_first_name;lastName = user_last_name;gender = user_gender;locale = user_locale;
					} else if ((!user_first_name && !user_last_name && !user_gender && !user_locale) && (!firstName && !lastName && !gender && !locale)) {
						queryFacebook('SELECT first_name, last_name, sex, locale FROM user WHERE uid="{0}"',
							[fbid], function(users) {
								var userInfo = users[0];
								var fbUserFirstName = userInfo['first_name'];
								var fbUserLastName = userInfo['last_name'];
								var fbUserGender = userInfo['sex'];
								var fbUserLocale = userInfo['locale'];
								if (fbUserFirstName || fbUserLastName || fbUserGender || fbUserLocale) writeToDB('setRmnUserInfo', [{'firstName':d_escape(fbUserFirstName), 'lastName':d_escape(fbUserLastName), 'gender':fbUserGender, 'locale':fbUserLocale}, user_id]);
								firstName = fbUserFirstName;
								lastName = fbUserLastName;
								gender = fbUserGender;
								locale = fbUserLocale;
								writeToDB('setRmnUserInfo', [{'firstName':d_escape(firstName), 'lastName':d_escape(lastName), 'gender':d_escape(gender), 'locale':d_escape(locale)}, user_id]);
								if (!remove && !wedding_cover) updateUserName(fbid, firstName, lastName);
							});
					}
				}
			} else {
				writeToDB('addRmnUserByFacebookId', [fbid.toString()], (function(remove) {
					return function(data) {
						var user_id = extractJSONid(data);
						addRmnUserToNight(user_id, remove);
						// update name in db
						if (firstName || lastName || gender || locale) {
							writeToDB('setRmnUserInfo', [{'firstName':d_escape(firstName), 'lastName':d_escape(lastName), 'gender':gender, 'locale':locale}, user_id]);
						} else {
							queryFacebook('SELECT first_name, last_name, sex, locale FROM user WHERE uid="{0}"',
								[fbid], function(users) {
									var userInfo = users[0];
									var fbUserFirstName = userInfo['first_name'];
									var fbUserLastName = userInfo['last_name'];
									var fbUserGender = userInfo['gender'];
									var fbUserLocale = userInfo['locale'];
									if (fbUserFirstName || fbUserLastName) writeToDB('setRmnUserInfo', [{'firstName':d_escape(fbUserFirstName), 'lastName':d_escape(fbUserLastName), 'gender':fbUserGender, 'locale':fbUserLocale}, user_id]);
									firstName = fbUserFirstName;
									lastName = fbUserLastName;
									gender = fbUserGender;
									locale = fbUserLocale;
									if (!remove) updateUserName(fbid, firstName, lastName);
								});
						} // set friend relationship status
						setRelationshipStatus(fbid, user_id);
					}
				}) (remove));
			}
		}
	}) (fbid, remove));
	
	if (!wedding_cover || document.getElementById('photosTab')) {
		// load user fb stream
		if (!remove) {
			toggleSection('nightFriendPics', 1);
			loadFriendNewsFeed(fbid);
		}
		
		// add or remove fb user profile icon
		addToAttendList(fbid, remove, firstName, lastName);
	}
}

function removeFbUserMedia(fbPointIds, fbid, rmnid) {
	for (var i in fbPointIds) {
		var rmnPoint = rmnPoints[fbPointIds[i]];
		if (rmnPoint) {
			var rmnPointOwner = rmnPoint['user_id'];
			var rmnPointType = rmnPoint['partnerId_id'];
			var actor_id = rmnPoint['partnerIdValue'];
			var args = new Object();
			if (fbPointIds == fbVideoPointIds) {
				var video_type = '';
				if (rmnPointType == 9) video_type = 'fb';
				else if (in_array(rmnPointType, [10, 12])) video_type = 'yt';
				else if (in_array(rmnPointType, [11, 13])) video_type = 'vim';
				if (in_array(rmnPointType, [12, 13])) {i.replace(/music$/,'');args['music_type'] = video_type;}
				args['video_type'] = video_type;
				i = i.replace(new RegExp(video_type+'$'), '');
			}
			if (rmnid == rmnPointOwner) {
				args['unpair'] = 1;
				removeCanvasItem(i, args);
			} else if (actor_id == fbid) {
				if (rmnPointOwner != userProfileObj.id) args['unpair'] = 1;
				removeCanvasItem(i, args);
			}
		}
	}
}

function removeFbUserPosts(fbid, rmnid) {
	for (var i in rmnPoints) {
		var rmnPoint = rmnPoints[i];
		var rmnPointType = rmnPoint['partnerId_id'];
		if (in_array(rmnPointType, [3,6,8])) {
			var rmnPointOwner = rmnPoint['user_id'];
			if (rmnid == rmnPointOwner && userProfileObj.id != segmentData.owner) removeDiaryEntry(i, 1);
			else {
				var actor_id = urldecode(rmnPoint['partnerIdValue']);
				try {
					var partner_val_json = JSON.parse(actor_id);
					actor_id = partner_val_json['actor_id'];
				} catch (err) {}
				if (actor_id == fbid) {
					if (rmnPointOwner == userProfileObj.id) removeDiaryEntry(i);
					else removeDiaryEntry(i, 1);
				}
			}
		}
	}
}

function addRmnUserToNight(rmnid, remove) {
	var wedding_cover = document.getElementById('memoryEditWrapper');
	var segmentFrdFn = 'addUsersToSegment';
	var pairingFn = 'pairUsersAndPoint';
	var segmentFrdArgs = [[rmnid], wedding_cover?memoryCreationWizard.sid:segmentData.id];
	if (remove) {
		segmentFrdFn = 'removeUsersFromSegment';
		pairingFn = 'unpairUsersAndPoint';
		if (!wedding_cover) removeFromArray(rmnid, segmentFriendIds);
	} else {
		segmentFrdArgs[2] = ['confirmed'];
		if (!wedding_cover) segmentFriendIds.push(rmnid);
	}
	
	writeToDB(segmentFrdFn, segmentFrdArgs);
	if (!wedding_cover) {
		// pair / unpair user to points
		for (var i=0; i<segmentPairingIds.length; i++) {
			var point_id = segmentPairingIds[i];
			var paringArgs = [[rmnid], point_id];
			if (paringArgs) paringArgs[2] = 'suggested';
			writeToDB(pairingFn, paringArgs);
		}
	}
}

function addVideoByUrl(music) {
	var video_text = music?'music':'video';
	var already_added;var canvas_args = new Object(); // flags whether video has already been added
	var video_url = document.getElementById('ext'+ucfirst(video_text)+'Link').value;
	var video_url_error = document.getElementById('ext'+ucfirst(video_text)+'LinkError');
	var already_added_msg = 'This '+video_text+' has already been added to the memory!';
	var point_owner = loggedInUser;
	if (userProfileObj.pairNewPoints && segmentData.fbOwner) point_owner = segmentData.fbOwner;
	if (video_url.indexOf('vimeo') != -1) {
		// extract vimeo clip id
		var vimid_regex = /vimeo.com.*[#\/](\d+)$/;
		var result = video_url.match(vimid_regex);
		var vimid = result[1];   
		if (!vimid){
			video_url_error.innerHTML = 'Please enter a valid Vimeo URL!';
		} else {
			canvas_args[video_text] = 'vim';
			var extThumbId = 'm'+vimid+'vim'+(music?'music':'')+'thumb';
			var extThumb = document.getElementById(extThumbId);
			if (!fbVideos['vim'][vimid]) {
				// json query to get video title and thumbnail
				var url = AJAX_WRAPPER_PATH+'?q='+encodeURIComponent('http://vimeo.com/api/v2/video/'+vimid+'.json');
				jx.load(url, function(data) {
					vim = JSON.parse(data)[0];
					if (vim) {
						// store vimeo data in memory
						fbVideos['vim'][vimid] = {'id':vimid, 'title':vim['title'], 'description':vim['description'], 'src':getPartnerLink(vimid, 'vim'), 'link':vim['url'], 'created_time':Date.parse(vim['upload_date'].replace(/-/g, '/')), 'thumbnail_link':vim['thumbnail_medium'], 'src_big_width':vim['width'], 'src_big_height':vim['height'], 'owner':point_owner};
					   
						insertExtThumb({'id':vimid, 'title':vim['title'], 'thumb':vim['thumbnail_medium'], 'type':'vim', 'music':music});
						addToCanvas(vimid, canvas_args);
					} else video_url_error.innerHTML = ucfirst(video_text)+' data not found. Please try another URL!';
					//document.getElementById("fbVideoStatus").style.display="none";
				});
			} else {
				if (!extThumb) {
					var vim = fbVideos['vim'][vimid];
					insertExtThumb({'id':vimid, 'title':vim['title'], 'thumb':vim['thumbnail_link'], 'type':'vim', 'music':music});
				}
				if (document.getElementById(extThumbId).className.indexOf('selected') == -1) addToCanvas(vimid, canvas_args);
				else video_url_error.innerHTML = already_added_msg;
			}
		}
	} else {
		var yt_link = video_url.replace('#!', '?'); // handle new yt ajax urls
		var yt_hash = '', yt_hash_regex;
		if (yt_link.indexOf('youtube.com/watch') != -1) yt_hash_regex = /youtube.com\/watch\?.*v=([^&\s]+)/;
		else if (yt_link.indexOf('youtube.com/v/') != -1) yt_hash_regex = /youtube.com\/v\/([^&\s]+)/;
		
		if (yt_link.indexOf('youtube.com/') != -1) {
			if ((yt_link.indexOf('/watch?v=') != -1) || (yt_link.indexOf('&v=') != -1)) yt_hash_regex = /[?&]v=([^&]+)/;
			else if (yt_link.indexOf('youtube.com/v/') != -1) yt_hash_regex = /youtube.com\/v\/([^&]+)/;
		}
		
		if (yt_link.match(yt_hash_regex)) yt_hash = RegExp.$1;
		if (!yt_hash) video_url_error.innerHTML = 'Please enter a valid Youtube'+(yt_link.indexOf('youtube.com') == -1? ' or Vimeo' : '')+' URL!';
		else {
			canvas_args[video_text] = 'yt';
			var extThumbId = 'm'+yt_hash+'yt'+(music?'music':'')+'thumb';
			var extThumb = document.getElementById(extThumbId);
			var yt_thumb = getPartnerLink(yt_hash, 'yt_thumb');
			if (yt_link.indexOf('youtube.com/watch') != -1) yt_link = 'http://www.youtube.com/watch?v=' + yt_hash;
			else if (yt_link.indexOf('youtube.com/v/') != -1) yt_link = 'http://www.youtube.com/v/' + yt_hash;
			if (!fbVideos['yt'][yt_hash]) {
				yt_link = getPartnerLink(yt_hash, 'yt');
				checkYouTubeSuccessCallback = function () {
				}
				//check_youtube_player_embeddable = true;
				//embedVideo(yt_link, {'vid':yt_hash});
				video_url_error.innerHTML = '<span class="adding_video_text">Adding '+video_text+'</span> ' + ajax_loader_small;
				loadYouTubeMetadata(yt_hash, function(metadata) {
					if (metadata.embeddable) {
						//only add stuff on success
						video_url_error.innerHTML = '';
						fbVideos['yt'][yt_hash] = {'id':yt_hash, 'src':yt_link, 'thumbnail_link':yt_thumb, 'owner':point_owner};
						insertExtThumb({'id':yt_hash, 'thumb':yt_thumb, 'type':'yt', 'music':music});
						addToCanvas(yt_hash, canvas_args);
					} else {
						document.getElementById('ext'+ucfirst(video_text)+'LinkError').innerHTML = "Video not embeddable";
					}
				});
				//embedVideoForCheck(yt_link, yt_hash, ucfirst(video_text));
			} else {
				if (!extThumb) insertExtThumb({'id':yt_hash, 'thumb':yt_thumb, 'type':'yt', 'music':music});
				if (document.getElementById(extThumbId).className.indexOf('selected') == -1) addToCanvas(yt_hash, canvas_args);
				else video_url_error.innerHTML = already_added_msg;
			}
		}
	}
}

function embedVideoForCheck(link, hash, music_or_video) {
	//var swf_object = new SWFObject(_1, id, w, h, _5, c, _7, _8, _9, _a);
	var so = new SWFObject(addUrlParams(link, 'autoplay=1&enablejsapi=1&playerapiid=ytplayer'+hash), "ytplayer"+hash, 1, 1, "8", "#000000");
	so.addParam("allowScriptAccess", "always");
	so.addParam("wmode", "transparent");
	so.write("hiddenVideoDiv");
	youtubeCheckingMusicorVideo = music_or_video;
	//document.getElementById("hiddenVideoDiv").innerHTML = '<object id="ytplayer'+hash+'" width="1" height="1"><param name="movie" value="'+addUrlParams(link, 'autoplay=1&enablejsapi=1&playerapiid=ytplayer'+hash)+'"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed id="ytplayer'+hash+'" src="'+addUrlParams(link, 'autoplay=1&enablejsapi=1&playerapiid=ytplayer'+hash)+'" type="application/x-shockwave-flash" wmode="transparent"'+(navigator.userAgent.indexOf("MSIE") == -1? ' allowscriptaccess="always"' : '')+' allowfullscreen="true" width="1" height="1"></embed>';
}

function onYouTubePlayerReady(ytplayerapi) {
	if (!ytplayerapi) {
		SlideShow.display_ytplayer.addEventListener("onStateChange", "onYouTubeStateChangeSlideShow");
		SlideShow.display_ytplayer.addEventListener("onError", "onYouTubeErrorSlideShow");
		SlideShow.display_ytplayer.loadVideoById(SlideShow.display_video_id);
	}
	ytplayer = document.getElementById(ytplayerapi);
	try {
		ytplayer.addEventListener("onStateChange", "onYouTubeStateChange");
		ytplayer.addEventListener("onError", "onYouTubeError");
	} catch(err) {}
	//if (ytplayerapi == 'musicPlayer') document.getElementById('musicPlayerControls').style.display = 'block';
}

function onYouTubeErrorSlideShow(error) {
	var index = SlideShow.display_index;
	if (SlideShow.slideshow_data.type == "photo") {
		index = index + 1;
	}
	SlideShow.next();
	removeIndexFromArray(SlideShow.slideshow_data, index);
	//adjust the display_index so nothing gets skipped
	SlideShow.display_index = SlideShow.display_index - 1;
}

function onYouTubeStateChangeSlideShow(newstate) {
	//SlideShow.display_ytplayer.mute();
	//SlideShow.lightbox_ytplayer.unmute();
	var data = SlideShow.slideshow_data;
	var index = SlideShow.display_index;
	if ((data[index].type === "video")) {
		clearTimeout(SlideShow.autoscroll_main_timeout);
	}

	if (newstate == 1){ //playing
		if (SlideShow.autoscroll_paused) {
			SlideShow.display_ytplayer.pauseVideo();
		}
	} else if (newstate == 0) { //ended
		if (SlideShow.autoscroll_playing) {
			SlideShow.nextMainDisplayMovieView();
			var musicPlayPause = document.getElementById('musicPlayPause');
			//if (musicPlayPause.className != 'play') togglePlayMusic();
		}
	}
}

function onYouTubeStateChange(new_state) {
	if (new_state != -1) {
		ytplayer.video_is_embeddable = true;
	}
	
	if (new_state == 3) { //if playing
		if (typeof checkYouTubeSuccessCallback == 'function') {
			checkYouTubeSuccessCallback();
			//checkYouTubeSuccessCallback = null;
			removeNode(ytplayer);
		}
	}
}

function onYouTubeError(error) {
	document.getElementById('ext'+youtubeCheckingMusicorVideo+'LinkError').innerHTML = youtubeCheckingMusicorVideo+" not embeddable";
}

function loadYouTubeMetadata(video_id,callback) {
	var metadata = null;
	if (video_id) {
		var request_url = "http://gdata.youtube.com/feeds/api/videos/"+video_id+"?v=2";
		metadata = {};
		jx.load(AJAX_WRAPPER_PATH+'?q='+encodeURIComponent(request_url), function(data) {
			var jquery_wrapper = $(data);
			metadata.id = jquery_wrapper.find("yt\\:videoid").text();
			metadata.embeddable = (jquery_wrapper.find("[action=embed]").attr("permission")=="allowed");
			metadata.duration = parseInt(jquery_wrapper.find("yt\\:duration").attr("seconds"));
			var thumbnails = jquery_wrapper.find("media\\:thumbnail");

			//try to get the default thumbnail image
			var thumb_url = "http://i.ytimg.com/vi/"+metadata.id+"/default.jpg";
			var thumb = thumbnails.find("[url="+thumb_url+"]")
			if (thumb.size() > 0) {
				var thumb_width = parseInt(thumb.attr("width"));
				var thumb_height = parseInt(thumb.attr("height"));
				metadata.thumb = {
					"url":thumb_url,
					"width":thumb_width,
					"height":thumb_height
				};

			} else {
				//this gets the first image found
				metadata.thumb = {
					"url" : thumbnails.attr("url"),
					"width" : parseInt(thumbnails.attr("width")),
					"height" : parseInt(thumbnails.attr("height"))
				}
			}

			//try to get the high quality image
			var hq_thumb_url = "http://i.ytimg.com/vi/"+metadata.id+"/hqdefault.jpg";
			var hq_thumb = thumbnails.find("[url="+hq_thumb_url+"]")
			if (hq_thumb) {
				var hq_thumb_width = parseInt(hq_thumb.attr("width"));
				var hq_thumb_height = parseInt(hq_thumb.attr("height"));
				metadata.hq_thumb = {
					"url":hq_thumb_url,
					"width":hq_thumb_width,
					"height":hq_thumb_height
				};
			}

			callback(metadata);
		});
	}

	return metadata;
}

/*function insertExtThumb(media) {
	// insert a thumb for both music and videos
	insertExtThumbType(media);
	media['music'] = 1;
	insertExtThumbType(media);
} */

function insertExtThumb(media) {
	var media_type = media['type'];
	var media_id = media['id'];
	var media_title = escapeQuotes(media['title']);
	var media_thumb = media['thumb'];
	var media_music = media['music'];
	var media_video_str = media_music?'music':'video';
	
	// set value based on type
	var thumb_type = media_type;
	var add_to_canvas_type = ", {'"+media_video_str+"':'"+(media_type?media_type:'fb')+"'}";
	var media_div = 'ext'+ucfirst(media_video_str)+'Thumbs';
	if (media_type == 'photo') {
		thumb_type = '';
		add_to_canvas_type = '';
		media_div = 'streamPhotosWrapper';
	}
	
	// create and insert thumb
	var thumb_id = 'm'+media_id+thumb_type+(media_music?'music':'')+'thumb';
	if (!document.getElementById(thumb_id)) {
		var media_wrapper = document.createElement('div');
		media_wrapper.className = 'photo_wrapper';
		var media_alt = (media_title && media_title != 'null' && media_title != 'undefined')? ' alt="'+media_title+'" title="'+media_title+'"' : '';
		media_wrapper.innerHTML = '<div class="photo_wrapper" onmouseout="memoryCreationWizard.hidePhotoControls(this, event)" onmouseover="memoryCreationWizard.showPhotoControls(this, event)" onclick="addToCanvas(\''+media_id+'\''+add_to_canvas_type+')"><img id="'+thumb_id+'" src="'+media_thumb+'" class="photo_thumb"'+media_alt+'><div class="createMemorySelectPhotoOverlay" style="display:none">Select Video</div><input type="checkbox" class="createMemoryViewAlbumCheckbox" onclick="return false"></div>';
		// '<img id="'+thumb_id+'" src="'+media_thumb+'" class="photo_thumb"'+media_alt+' onclick="addToCanvas(\''+media_id+'\''+add_to_canvas_type+')">';
		var ext_media_div = document.getElementById(media_div);
		if (ext_media_div) ext_media_div.appendChild(media_wrapper.childNodes[0]);
	}
}

function editDiaryEntry(action) {
	var add_btn = document.getElementById('retroDiaryAddBtn');
	var done_btn = document.getElementById('retroDiaryDoneBtn');
	var cancel_btn = document.getElementById('retroDiaryCancelBtn');
	var retroDiaryEdit = document.getElementById('retroDiaryEdit');
	var retroDiaryHeader = document.getElementById('retroDiaryHeader');
	var retroDiaryError = document.getElementById('retroDiaryError');
	var retroDiaryReloadFbData = document.getElementById('retroDiaryAdd');
	
	// diary entry time fields
	var diaryEntryMonth = document.getElementById('diaryEntryMonth');
	var diaryEntryDay = document.getElementById('diaryEntryDay');
	var diaryEntryYear = document.getElementById('diaryEntryYear');
	var diaryEntryHours = document.getElementById('diaryEntryHours');
	var diaryEntryMinutes = document.getElementById('diaryEntryMinutes');
	var diaryEntryAMPM = document.getElementById('diaryEntryAMPM');
	var diaryEntryTZ = document.getElementById('diaryEntryTZ');
	var diaryEntryDesc = document.getElementById('retroDiaryDesc');
	var diaryEntryPointId = document.getElementById('diaryEntryPointId');
	if (action == 'save' || action == 'cancel') {
		var error_msg = '', diaryEntryTzoffset, diaryEntryTime;
		var diaryEntryDescText = removeHtmlTags(diaryEntryDesc.value);
		
		// validate data before saving
		if (action == 'save') {
			if (!diaryEntryDescText) {
				error_msg = 'Please enter a description!';
				diaryEntryDesc.focus();
			} else {
				var dateInfo = validateDate('diaryEntry');
				diaryEntryTime = dateInfo['time'];
				diaryEntryTzoffset = dateInfo['tzoffset'];
				error_msg = dateInfo['error'];
			}
		}
		retroDiaryError.innerHTML = error_msg;
		
		if (!error_msg) {
			/*add_btn.style.display = 'block';
			done_btn.style.display = '';
			cancel_btn.style.display = '';
			retroDiaryEdit.style.display = '';
			retroDiaryHeader.style.width = '';
			retroDiaryReloadFbData.style.height = '';*/
			$.colorbox.close();
			
			if (action == 'save') {
				var point_owner = loggedInUser;
				if (userProfileObj.pairNewPoints && segmentData.fbOwner) point_owner = segmentData.fbOwner;
				
				// determine whether to edit existing point or create a new one
				if (diaryEntryPointId.value) {
					var point_id = diaryEntryPointId.value;
					writeToDB('editPoint', [{'utcTimeSec':diaryEntryTime, 'timezoneOffset':diaryEntryTzoffset, 'description':d_escape(diaryEntryDescText)}, point_id]);
					
					// remove old stream item
					document.getElementById('retroDiaryEntries').removeChild(document.getElementById(point_id));
					
					// update values in memory
					var rmnPoint = rmnPoints[point_id];
					rmnPoint['utcTimeSec'] = diaryEntryTime;
					rmnPoint['timezoneOffset'] = diaryEntryTzoffset;
					rmnPoint['description'] = diaryEntryDescText;
					
					// insert updated stream item
					var diaryEntryDescDiv = '<div class="diaryText"><b>You remember</b>: '+diaryEntryDescText+'</div><div class="diaryTimestamp">From Kaptur at '+getFormattedTime(getAdjustedTime(diaryEntryTime, segmentData.tzoffset)*1000)+'</div>';
					var streamItem = buildStreamItem(diaryEntryTime, null, diaryEntryDescDiv, null, point_owner, null, null, point_id, null, userProfileObj.id, null, null, null, rmnPoint['timezoneOffset']);
					addStreamItemToStream(streamItem, 'retroDiaryEntries');
				} else {
					// create point
					var point_desc = '<div class="diaryText"><b>You remember</b>: '+diaryEntryDescText+'</div><div class="diaryTimestamp">From Kaptur at '+getFormattedTime(getAdjustedTime(diaryEntryTime, segmentData.tzoffset)*1000)+'</div>';
					var point_args = {'utcTimeSec':diaryEntryTime, 'description':d_escape(diaryEntryDescText), 'partnerId_id':6, 'partnerIdValue':point_owner, 'timezoneOffset':diaryEntryTzoffset, 'privacy':'public'};
					var stream_args = {'createTime':diaryEntryTime, 'description':point_desc, 'actorId':point_owner, 'pointId':point_id, 'actorRmnId':userProfileObj.id, 'timezoneOffset':diaryEntryTzoffset};
					if (!dataFlags.offlineView) buildPoint(point_args, stream_args);
					else {
						// generate unique temporary point id
						var point_id = new Date().getTime();
						
						// insert point data into memory
						point_args['description'] = urldecode(urldecode(point_args['description']));
						rmnPoints[point_id] = point_args;
						rmnPoints[point_id]['id'] = point_id;
						
						// insert point into div
						insertDiaryEntry(stream_args, diaryEntryTime, point_id);
					}
				}
			}
		} else {$.colorbox.resize();$.colorbox.resize();}
	} else {
		/*add_btn.style.display = '';
		done_btn.style.display = 'block';
		cancel_btn.style.display = 'block';
		retroDiaryEdit.style.display = 'block';
		retroDiaryHeader.style.width = '553px';
		retroDiaryReloadFbData.style.height = '0px';*/
		initColorbox('', 'retroDiaryEdit');
		
		if (action == 'new') {
			// pre-populate default values
			diaryEntryMonth.value = segmentData.startMonth;
			diaryEntryDay.value = segmentData.startDay;
			diaryEntryYear.value = segmentData.startYear;
			diaryEntryHours.value = '12';
			diaryEntryMinutes.value = '00';
			diaryEntryAMPM.selectedIndex = 1;
			diaryEntryDesc.value = '';
			diaryEntryPointId.value = '';
			diaryEntryTZ.selectedIndex = segmentData.tzindex;
			
			// use starting time of segment if default time (12pm) is not within range
			var dateInfo = validateDate('diaryEntry');
			var diaryEntryTime = dateInfo['time'];
			if (diaryEntryTime < segmentData.start || diaryEntryTime > segmentData.end) {
				var startDate = new Date(getAdjustedTime(segmentData.start)*1000);
				var startDateHours = startDate.getHours();
				var startDateMinutes = startDate.getMinutes();
				if (startDateHours > 11) {
					startDateHours -= 12;
					diaryEntryAMPM.selectedIndex = 1;
				} else diaryEntryAMPM.selectedIndex = 0;
				if (!startDateHours) startDateHours = 12;
				diaryEntryHours.value = startDateHours;
				diaryEntryMinutes.value = startDateMinutes < 10? '0'+startDateMinutes : startDateMinutes;
			}
		} else {
			var point_id = action;
			var point_data = rmnPoints[point_id];
			if (point_data) {
				var point_tzoffset = point_data['timezoneOffset'];
				var point_tzindex = getTzIndex(point_tzoffset);
				var point_time = getAdjustedTime(point_data['utcTimeSec'], point_tzoffset);
				var point_date = new Date(point_time*1000);
				diaryEntryMonth.value = point_date.getMonth()+1;
				diaryEntryDay.value = point_date.getDate();
				diaryEntryYear.value = point_date.getFullYear();
				var point_hours = point_date.getHours();
				if (point_hours > 11) {
					point_hours -= 12;
					diaryEntryAMPM.selectedIndex = 1;
				} else diaryEntryAMPM.selectedIndex = 0;
				if (!point_hours) point_hours = 12;
				diaryEntryHours.value = point_hours;
				var point_minutes = point_date.getMinutes();
				diaryEntryMinutes.value = point_minutes < 10? '0'+point_minutes : point_minutes;
				diaryEntryDesc.value = unescapeQuotes(urldecode(point_data['description']));
				diaryEntryPointId.value = point_id;
				diaryEntryTZ.selectedIndex = point_tzindex;
			}
		}
		
		// highlight and jump to hours field
		/*diaryEntryDesc.focus();
		diaryEntryHours.focus();
		diaryEntryHours.select();*/
	}
}

function removeDiaryEntry(point_id, unpair) {
	kapturDb.removePointFromSegment(segmentData.id, point_id);
	if (!unpair) {
		writeToDB('deletePoint', [point_id]);
	} else {
		writeToDB('unpairUsersAndPoint', [[segmentData.owner], point_id]);
	}
	var retroDiaryEntries = document.getElementById('retroDiaryEntries');
	if (!retroDiaryEntries) retroDiaryEntries = document.getElementById('statusesTabContents');
	try {retroDiaryEntries.removeChild(document.getElementById(point_id));}
	catch(err) {}
	
	// remove fb post data if it exists
	var rmnPoint = rmnPoints[point_id];
	if (rmnPoint) {
		var partner_id = rmnPoint['partnerId_id'];
		if (partner_id == PARTNER_TYPES.facebook_post || partner_id == PARTNER_TYPES.facebook_link || !partner_id) {
			var post_id = urldecode(rmnPoint['partnerIdValue']);
			try {
				var partner_val_json = JSON.parse(post_id);
				post_id = partner_val_json['post_id'];
			} catch (err) {}
			delete segmentFbPosts[post_id];
		}
	}
	
	// remove point data from memory
	delete rmnPoints[point_id];
	if (!unpair) removeFromArray(point_id, segmentPairingIds);
	updateDiaryExpand(); // hide expand button if it's no longer needed
}

function insertDiaryEntry(stream_args, createTime, point_id, hide) {
	// insert diary entry
	var ownerPhotoUrl = stream_args['ownerPhotoUrl'];
	var description = stream_args['description'];
	var actorId = stream_args['actorId'];
	var postId = stream_args['postId'];
	var pointId = stream_args['pointId'];
	var actorRmnId = stream_args['actorRmnId'];
	var hideEdit = stream_args['hideEdit'];
	var timezoneOffset = stream_args['timezoneOffset'];
	if (!pointId) pointId = point_id;
	
	var streamItem = buildStreamItem(createTime, ownerPhotoUrl, description, null, actorId, postId, null, pointId, null, actorRmnId, null, hideEdit, null, timezoneOffset);
	if (hide) streamItem.style.display = 'none';
	addStreamItemToStream(streamItem, document.getElementById('statusesTabContents')?'statusesTabContents':'retroDiaryEntries');
}

function updateShownContactSheetFriends() {
	var friendFilter = document.getElementById('contactSheetFriendFilter').value.replace(/\s/g, '').toLowerCase();
	var friendFilterClear = document.getElementById('contactSheetFriendFilterClear');
	if (!friendFilter) friendFilterClear.style.display = '';
	else friendFilterClear.style.display = 'inline';
	$('#contactSheetWrapper .contactSheetNameLabel').each(function() {
		var contact_sheet_item = this.parentNode.parentNode;
		if (!friendFilter) contact_sheet_item.style.display = '';
		else {
			try {
				var friend_node = this.firstChild;
				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) contact_sheet_item.style.display = 'none';
				else contact_sheet_item.style.display = '';
			} catch(err) {}
		}
	});
}

function clearContactSheetFriendFilter() {
	try {
		document.getElementById('contactSheetFriendFilter').value = '';
		document.getElementById('contactSheetFriendFilterClear').style.display = '';
		updateShownContactSheetFriends();
	} catch (err) {}
}


function updateShownFriends(event_friends, media_friends) {
	var friends_wrapper = document.getElementById(event_friends?'fbEventFriends':media_friends?'fbMediaFriends':'fbFriends');
	var friend_links = friends_wrapper.getElementsByTagName('a');
	if (friend_links && friend_links.length) {
		var friendFilter = document.getElementById(event_friends?'eventFriendFilter':media_friends?'mediaFriendFilter':'friendFilter').value;
		if (friendFilter == '  Search by Name') friendFilter = '';
		friendFilter = friendFilter.replace(/\s/g, '').toLowerCase();
		var friendFilterClear = document.getElementById(event_friends?'eventFriendFilterClear':media_friends?'mediaFriendFilterClear':'friendFilterClear');
		if (!friendFilter) friendFilterClear.style.display = '';
		else friendFilterClear.style.display = 'inline';
		for (var i=0; i<friend_links.length; i++) {
			var friend_link = friend_links[i];
			if (!friendFilter) friend_link.style.display = '';
			else {
				try {
					var friend_node = friend_link.firstChild.firstChild.nextSibling;
					var friend_name = friend_node.textContent;
					if (!friend_name) friend_name = friend_node.innerText;
					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(event_friend, media_friend) {
	try {
		document.getElementById(event_friend?'eventFriendFilter':media_friend?'mediaFriendFilter':'friendFilter').value = '';
		document.getElementById(event_friend?'eventFriendFilterClear':media_friend?'mediaFriendFilterClear':'friendFilterClear').style.display = '';
		updateShownFriends(event_friend, media_friend);
	} catch(err) {}
}

function loadProfilePage() {
	loadUserSegments();
	loadProfileWidgets();
}

function loadProfileWidgets() {
	if (0 && loggedInUser && getFid != loggedInUser) {
		var fb_photos = {
			fql: 'SELECT pid, aid, owner, src, src_big, src_big_width, src_big_height, src_small, link, caption, created, modified FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject="{0}") OR aid IN (SELECT aid FROM album where owner="{0}") ORDER BY created DESC LIMIT 10',
			args: [getFid]
		};
		var fb_videos = {
			fql: 'SELECT vid, owner, title, description, embed_html, thumbnail_link, src, created_time FROM video WHERE owner="{0}" OR vid IN (SELECT vid FROM video_tag WHERE subject="{0}") ORDER BY created_time DESC LIMIT 10',
			args: [getFid]
		};
		multipleQueryFacebook([fb_photos, fb_videos], function() {
			var recent_photos = fb_photos.value;
			var recent_videos = fb_videos.value;
			var recent_photos_div = document.getElementById('profilePageRecentPhotos');
			var recent_videos_div = document.getElementById('profilePageRecentVideos');
			if (recent_photos && recent_photos.length) {
				var recent_photos_html = '';
				for (var i=0; i<recent_photos.length; i++) {
					var recent_photo = recent_photos[i];
					recent_photos_html += '<img class="photo_preview" style="margin-bottom:90px" src="'+recent_photo['src']+'" media_content="'+recent_photo['src_big']+'" rel="lightbox" alt="'+recent_photo['caption']+'" title="'+recent_photo['caption']+'">';
				}
				recent_photos_html += '<div class="clear"></div>';
				recent_photos_div.innerHTML = recent_photos_html;
			} else recent_photos_div.innerHTML = 'No photos available';
			
			if (recent_videos && recent_videos.length) {
				var recent_videos_html = '';
				for (var i=0; i<recent_videos.length; i++) {
					var recent_video = recent_videos[i];
					var video_size = extractFbVideoSize(recent_video['embed_html']); // extract video dimensions
					recent_video['width'] = video_size[0];recent_video['height'] = video_size[1];
					fbVideos[recent_video['vid']] = recent_video;
					recent_videos_html += '<img class="photo_preview" style="margin-bottom:90px" src="'+recent_video['thumbnail_link']+'" media_id="'+recent_video['vid']+'" media_content="'+recent_video['src']+'" rel="lightbox_video" alt="'+recent_video['title']+'" title="'+recent_video['title']+'">';
				}
				recent_videos_html += '<div class="clear"></div>';
				recent_videos_div.innerHTML = recent_videos_html;
			} else recent_videos_div.innerHTML = 'No videos available';
			
			// turn photos and videos into clickable jquery lightbox activators
			updateStdLightboxPhotos();updateStdLightboxVideos();
		});document.getElementById('profilePageWidgets').style.display = 'block';
	} else loadUserFriends(1);
	loadFbInfo(); // load fb info after loggedInUser is initialized
}

function loadUserSegments() {
	readFromDB("getRmnUserIdByFacebookId", [getFid.toString()], function(data) {
		var rmnId = JSON.parse(data);rmnId = rmnId['result'];
		readFromDB('getSegments', [rmnId], function(data) {
			var result = JSON.parse(data);
			var segments = result['result'];
			
			// process segment data
			if (segments && segments.length) {
				// display segment count
				// var segment_count = profileData.segments.count;
				// document.getElementById('profilePageNightCount').innerHTML = segment_count+' night'+(segment_count!=1?'s':'');
				showSegmentsHTML(segments, 'profile');
			} else {
				setEmptySegmentsHTML();
				setEmptySuggestionHandler(1);
			}
		});
	});
}

function setEmptySegmentsHTML() {
	var profilePageUserSegments = document.getElementById('profilePageUserSegments');
	var nights_empty_html = '<div id="profilePageUserSegmentsEmpty">'; // firstnameonly="true" 
	if (getFid != loggedInUser) {
		nights_empty_html += '<span><fb:name uid="'+getFid+'" useyou="false" linked="false" /></span> hasn\'t created any Kapturs yet.';
		if (!isMobileApp()) nights_empty_html += '<div style="margin-top:7px">Click to <a href="#" onclick="sendFbInvite(getFid); return false">invite</a> <span><fb:name uid="'+getFid+'" useyou="false" linked="false" /></span> to create a Kaptur.</div>';
	} else nights_empty_html += 'You haven\'t created any memories yet.<div style="margin-top:7px"><a href="?p=quickstart&generic=true">Click on New Kaptur above to create a Kaptur.</a></div>';//p=create
	// show_share(\'http://www.facebook.com/share.php?u='+DOMAIN_URL+'\', \'facebook\')
	nights_empty_html += '</div>';
	profilePageUserSegments.innerHTML = nights_empty_html;
	if (getFid != loggedInUser) loadFBML(profilePageUserSegments);
}

function setEmptySuggestionHandler(run_kml) {
	var ref_param = '';
	var ref_regex = new RegExp('&(aff|ref)=([^&]*)');
	if (location.href.match(ref_regex)) ref_param = '&'+RegExp.$1+'='+RegExp.$2;
	if (!run_kml) document.getElementById('profilePageSuggestions').innerHTML = '<div id="profilePageUserSegmentsEmpty">Kaptur will suggest new memories as they are discovered.<br>To create a new Kaptur, <a href="?p=quickstart&generic=true'+ref_param+'">click on the New Kaptur button above</a>.</div>';
	else if (loggedInUser) document.getElementById('profilePageSuggestionsBtn').onclick = function() { location.href = '?p=kaptur_my_life'+ref_param; };
}

function showSegmentsHTML(segments, type) {
	// init arrays
	profileData.segments = new Object();
	profileData.segments.data = new Array();
	profileData.segments.locations = new Object();
	profileData.segments.covers = new Object();
	profileData.segments.count = 0;
	var nightLocationIds = new Array();
	var nightMediaIds = new Array();
	for (var i=0; i<segments.length; i++) {
		var segment = segments[i];
		var segment_view_privacy = parsePrivacyIds(segment['privacy_ids'])['view'];
		if (segment_view_privacy != 'vpr' || segment_view_privacy == 'vpr' && segment['user_id'] == userProfileObj.id) {
			var segment_location_id = segment['location_id'];
			var segment_media_id = segment['media_id'];
			if (segment_location_id) nightLocationIds.push(segment_location_id);
			if (segment_media_id) nightMediaIds.push(segment_media_id);
			profileData.segments.data.push(segment);
			profileData.segments.count++;
		}
	}
	
	// query for thumb and location data, then generate html
	showSegmentsThumbHTML(nightMediaIds, nightLocationIds, type);
}

function showSegmentsThumbHTML(nightMediaIds, nightLocationIds, type) {
	if (nightMediaIds.length) {
		readFromDB('getMedia', [nightMediaIds], function(data) {
			var response = JSON.parse(data);
			if (response["status"] == "ok") {
				var segment_covers = response["result"];
				if (segment_covers && segment_covers.length) {
					for (var i=0; i<segment_covers.length; i++) {
						var segment_cover = segment_covers[i];
						var segment_cover_id = segment_cover['id'];
						profileData.segments.covers[segment_cover_id] = segment_cover;
					}
				}
			}
			showSegmentsLocationHTML(nightLocationIds, type);
		});
	} else showSegmentsLocationHTML(nightLocationIds, type);
}

function showSegmentsLocationHTML(nightLocationIds, type) {
	if (nightLocationIds.length) {
		readFromDB('getLocations', [nightLocationIds], function(data) {
			var response = JSON.parse(data);
			if (response["status"] == "ok") {
				var segment_locations = response["result"];
				if (segment_locations && segment_locations.length) {
					for (var i=0; i<segment_locations.length; i++) {
						var segment_location = segment_locations[i];
						var segment_location_id = segment_location['id'];
						profileData.segments.locations[segment_location_id] = segment_location;
					}
				}
			}
			showSegmentsCombinedHTML(type);
		});
	} else showSegmentsCombinedHTML(type);
}

function showSegmentsCombinedHTML(type) {
	var segments_html = '',
		suggestions_html = '',
		suggestions_count = 0,
		env = 'www.',
		memory_base_url = '',
		rerun_kml = 1;
	
	for (var i=0; i<profileData.segments.data.length; i++) {
		var segment = profileData.segments.data[i];
		var segment_id = segment['id'];
		var segment_app_id = segment['app_id'];
		var segment_title = urldecode(segment['title']);
		var segment_tzoffset = segment['timezoneOffset'];
		var segment_start_date = formatDateStr(new Date(getAdjustedTime(segment['utcStartSec'], segment_tzoffset)*1000), 'dotted');
		var segment_end_date = formatDateStr(new Date(getAdjustedTime(segment['utcEndSec'], segment_tzoffset)*1000), 'dotted');
		var segment_location_name = '', segment_location_desc = '', segment_location_thumb = '', segment_thumb_portrait;
		var segment_location = profileData.segments.locations[segment['location_id']];
		var segment_cover = profileData.segments.covers[segment['media_id']];
		if (segment_location) {
			segment_location_name = urldecode(segment_location['name']);
			segment_location_desc = urldecode(segment_location['description']);
			segment_location_thumb = urldecode(segment_location['thumb']);
		}
		if (segment_cover) {
			segment_location_thumb = urldecode(segment_cover['thumb']);//src
			segment_thumb_portrait = parseInt(segment_cover['height'], 10) > parseInt(segment_cover['width'], 10);
		} if (!segment_location_name || segment_location_name == 'null') segment_location_name = '';
		if (!segment_location_desc || segment_location_desc == 'null') segment_location_desc = '';
		if (!segment_location_thumb || segment_location_thumb == 'null') segment_location_thumb = TEMPLATE_VIEW_PATH+'images/placeholders/night_thumb.png';
		if (!segment_title || segment_title == 'null') {
			segment_title = segment_location_name;
			if (!segment_title || segment_title == 'null') segment_title = 'Untitled';
		} else if ((!segment_location_desc || segment_location_desc == 'null') && segment_title != segment_location_name)
			segment_location_desc = segment_location_name;
		
		
		var ref_param = '';
		var ref_regex = new RegExp('&(aff|ref)=([^&]*)');
		if (location.href.match(ref_regex)) ref_param = '&'+RegExp.$1+'='+RegExp.$2;
		var page_param = '?p=nw';// = '/kaptur.html';
		//if (segment['app_id'] == 10 && segment['utcStartSec']*1000 > new Date().getTime()) page_param = 'nw';
		/*memory_base_url = 'kapcher.com';
		if (DOMAIN_URL.indexOf('aws-dev') != -1) {
			env = 'dev.';
		} else if (DOMAIN_URL.indexOf('stg') != -1) {
			env = 'stg.';
		}
		memory_base_url = 'http://' + env + 'kapcher.com';*/
		
		var segment_html = '';
		var link_start = '<a href="' + memory_base_url + page_param + '&sid='+segment_id+ref_param+'">';
		if (type == 'choose_segment_canvas') {
			link_start = '<a href="' + memory_base_url + page_param + '&sid='+segment_id+ref_param+'" target="_blank">';
		} var table_start = '<table cellspacing="0" cellpadding="0"><tr><td align="center" valign="middle">'; var table_end = '</td></tr></table>';
		
		segment_html += '<div class="thumb_stack_wrapper'+(segment_thumb_portrait?' portrait':'')+'"><div class="thumb_stack" title="'+segment_title+'">'+link_start+'</a>'+table_start+'<div class="thumb_stack_img_wrapper">'+table_start+'<img src="'+segment_location_thumb+'" class="thumb_stack_img" alt="'+segment_title+'" />'+table_end;
		if (getFid == loggedInUser) segment_html += '<div class="delete_btn" onclick="deleteSegment(\''+segment_id+'\', this); return false"></div>';
		segment_html += '</div>'+table_end+'</div><div class="thumb_stack_title" title="'+segment_title+'">'+link_start+segment_title+'</a>';
		//<div class="recent_night_location">'+segment_location_desc+'</div>
		//<div style="margin:7px 0">'+segment_start_date+(segment_start_date!=segment_end_date?' - '+segment_end_date:'')+'</div>
		//segment_html += '<fb:like href="?night'+i+'" layout="button_count" show_faces="false" width="100" font="helvetica"></fb:like>';
		//segment_html += '<div style="margin-top:7px">Tags: <span class="orange">concerts, brooklyn</span></div>';
		segment_html += '</div>';
		segment_html += '<div class="clear"></div></div>';
		
		if (segment_app_id == 14 || segment_app_id == 28) {
			suggestions_html += segment_html;
			suggestions_count++;
		} else {
			if (in_array(parseInt(segment_app_id,10), [29,30])) rerun_kml = 0;
			segments_html += segment_html;
		}
	}
	if (type == 'profile') {
		if (segments_html) document.getElementById('profilePageUserSegments').innerHTML = segments_html+'<div class="clear"></div>';
		else setEmptySegmentsHTML();
		if (suggestions_html) {
			document.getElementById('profilePageSuggestions').innerHTML = suggestions_html+'<div class="clear"></div>';
			if (loggedInUser) updateNotificationCount('profilePageSuggestionsNotification', suggestions_count);
		} else setEmptySuggestionHandler(rerun_kml);
		if (getFid == loggedInUser) $('#editModeToggle').show();//updateAutoShowRemove('recent_night_wrapper');
	} else if ((type == 'choose_segment') || (type == 'choose_segment_canvas')) {
		document.getElementById('selectNightsList').innerHTML = segments_html;
		$.colorbox({opacity:.75, maxWidth:'85%', maxHeight:'85%', inline:true, href:"#selectNightsWrapper", onClosed:function() {try{if (segmentData && segmentData.start) createRmnSegment(userProfileObj.id, segmentData.start, segmentData.end);}catch(err){}}, onComplete:updateColorboxScrollbars});
	}
}

function updateNotificationCount(div, count) {
	var div_elem = document.getElementById(div);
	var div_elem_wrapper = div_elem.parentNode.parentNode;
	if (count.toString().length == 1) div_elem.style.left = '8px';
	else div_elem.style.left = '';
	div_elem.innerHTML = count;
	div_elem_wrapper.style.display = 'block';
}

function toggleShowEdit(type) {
	var edit_elems = $(type+' .delete_btn');
	var editModeToggle = $('#editModeToggle');
	if (editModeToggle.hasClass('selected')) {
		edit_elems.hide();
		editModeToggle.html('Edit').removeClass('selected');
	} else {
		edit_elems.show();
		editModeToggle.html('Done').addClass('selected');
	} //move_left_btn, move_right_btn
}

function loadFbEvents(eid) {
	if (!segmentFlags.eventsLoaded && loggedInUser) {
		var start_time, end_time, segment_eid = segmentData.location.eid;
		start_time = segmentData.start;
		end_time = segmentData.end;
		if (!eid) document.getElementById('nightSummaryEditEventListContents').innerHTML = '<div id="nightEventStatus">'+ajax_loader+'</div>';
		var events = {
			fql: 'SELECT name, eid, tagline, description, pic, start_time, end_time, location, venue FROM event WHERE '+(!eid?'(eid IN (SELECT eid FROM event_member WHERE uid="{0}")) AND ((start_time >= {1} AND start_time <= {2}) OR (end_time >= {1} AND end_time <= {2}) OR (start_time <= {1} AND end_time >= {2}))'+(segment_eid?' OR eid="'+segment_eid+'"':''):'eid="{3}"'),
			args: [loggedInUser, start_time, end_time, eid]
		};
		var event_members = {
			fql: 'SELECT uid, eid, rsvp_status from event_member WHERE eid '+(!eid?'IN (SELECT eid FROM {0})':'= "{2}"')+' AND rsvp_status = "attending" AND uid IN (SELECT uid2 FROM friend WHERE uid1={1})',
			args: [events, loggedInUser, eid]
		};
		var event_member_names = {
			fql: 'SELECT uid, first_name, last_name FROM user WHERE uid IN (SELECT uid FROM {0})',
			args: [event_members]
		};
		multipleQueryFacebook([events, event_members, event_member_names], function() {
			events = events.value;
			event_members = event_members.value;
			event_member_names = event_member_names.value;
			renderFbEvents(events, event_members, event_member_names, eid);
		});segmentFlags.eventsLoaded = 1;
	}
}

function renderFbEvents(events, event_members, event_member_names, eid) {
	var events_list = document.getElementById('nightSummaryEditEventListContents');
	if (events && events.length) {
		// generate fb names hash
		var event_member_names_list = new Object();
		if (event_member_names && event_member_names.length) {
			for (var i=0; i<event_member_names.length; i++) {
				var user_info = event_member_names[i];
				event_member_names_list[user_info['uid']] = [user_info['first_name'], user_info['last_name']];
			}
		}
		
		// store event members list
		var event_members_list = new Object();
		if (event_members && event_members.length) {
			for (var i=0; i<event_members.length; i++) {
				var event_member = event_members[i];
				var event_id = event_member['eid'];
				var event_member_id = event_member['uid'];
				var event_member_name = event_member_names_list[event_member_id];
				if (!event_members_list[event_id]) event_members_list[event_id] = new Object();
				//event_members_list[event_id].push(event_member['uid']);
				event_members_list[event_id][event_member_id] = [event_member_name[0], event_member_name[1]];
			}
		}
		
		var events_list_html = '';
		var curr_event_id = segmentData.location.eid;
		for (var i=0; i<events.length; i++) {
			var fb_event = events[i];
			var event_id = fb_event['eid'];
			var event_name = fb_event['name'];
			var event_desc = fb_event['desc'];
			var event_start = fb_event['start_time'];
			var event_end = fb_event['end_time'];
			var event_location = fb_event['location'];
			var event_city = fb_event['venue']['city'];
			var event_thumb = fb_event['pic'];
			if (!event_thumb) event_thumb = TEMPLATE_VIEW_PATH+'images/placeholders/fb_event.png';
			var event_radio_label = '<label for="segmentFbEvent'+event_id+'">';
			var event_click = "document.getElementById('nightSummaryLocationField').value=(unescapeQuotes('"+escapeQuotes(event_location)+"')||document.getElementById('nightSummaryLocationField').value);";
			event_click += "document.getElementById('nightSummaryTitleField').value=(unescapeQuotes('"+escapeQuotes(event_name)+"')||document.getElementById('nightSummaryTitleField').value);";
			event_click += "document.getElementById('nightSummaryCityField').value=(unescapeQuotes('"+escapeQuotes(event_city)+"')||document.getElementById('nightSummaryCityField').value);";
			events_list_html += '<div class="fb_event_row"><div class="fb_event_row_radio"><input type="radio" onclick="'+event_click+'" id="segmentFbEvent'+event_id+'" name="segmentFbEvent" value="'+event_id+'" '+(event_id==curr_event_id?' checked':'')+'></div><div class="fb_event_row_thumb">'+event_radio_label+'<img src="'+event_thumb+'" class="event_thumb" title="'+event_name+'"></label></div><div class="fb_event_row_name">'+event_radio_label+event_name+'</label></div><div class="clear"></div></div>';
			// store event data in memory
			event_suggestions_list[event_id] = {'name':event_name, 'desc':event_desc, 'start_time':event_start, 'end_time':event_end, 'location':event_location, 'thumb':event_thumb, 'members':event_members_list[event_id]};
		}
		if (!eid) events_list.innerHTML = events_list_html;
		else {
			if (!document.getElementById('segmentFbEvent'+eid)) events_list.innerHTML += events_list_html;
			else alert('This event has already been added!');
			document.getElementById('addFbEventId').value = '';
		} //updateCustomScrollbar('nightSummaryEditEventListContents');
	} else if (!eid) {
		events_list.innerHTML = 'No Facebook Events';
		if (!userProfileObj.perms['user_events'])
			events_list.innerHTML = '<a href="#" onclick="getEventsPermission(); return false;">Load Facebook Events</a>';
	}
}

function showLoginPrompt(msg, owner_only) {
	try {memoryCreationWizard;} catch(err) {
		if (getFid && !segmentFlags.segmentLoadedById) showOwnerLoginPrompt(getFid, msg, owner_only);
		else readFromDB('getFacebookUserIdByRmnId', [segmentData.owner], function(data) {
			var result = JSON.parse(data);
			var owner_fbid = result['result'];
			if (owner_fbid) showOwnerLoginPrompt(owner_fbid, msg, owner_only);
		});
	}
}

function showOwnerLoginPrompt(owner_fbid, msg, owner_only) {
	//query owner information
	queryFacebook('select uid, name, pic_square from user where uid={0}',
		[owner_fbid],
		function(users) {
			var fb_user = users[0];
			var user_name = fb_user['name'];
			var user_thumb = fb_user['pic_square'];

			// set proper messaging
			if (owner_only) msg = 'This memory is only viewable by '+user_name+'.'+(!loggedInUser?'<br>If this is your memory, sign in with Facebook.':'');
			else if (!loggedInUser) msg += 'Please sign in with Facebook to view'+(msg?' ':'<br>')+user_name+'\'s memory.';
			var promptHtml = '<table><tr><td><img src="'+user_thumb+'" class="profile_pic" /></td><td><div id="loginPromptMsg">'+msg+'</div></td></tr></table>';
			if (!loggedInUser) promptHtml += '<div id="signInFbBtn" onclick="loginToFacebook()"></div>';
			showError(promptHtml, function(){redirectOnSite(!loggedInUser?"":"?p=f")});
		}
	);
}

function redirectOnSite(destination) {
	var new_location = location.toString();
	var length_of_main_site_url = new_location.indexOf(".com") + 4;
	new_location = new_location.substr(0, length_of_main_site_url) + "/" + destination;
	location = new_location;
}

function showError(err, onCloseErrorDialog) {
	$.colorbox({opacity:.75, initialWidth:400, initialHeight:25, minWidth:650, maxWidth:'85%', maxHeight:'85%', href:'html', html:function() {return '<div id="nightErrorWrapper">'+err+'</div>';}, onComplete:updateColorboxScrollbars, onClosed:((typeof onCloseErrorDialog) == "function")?onCloseErrorDialog:function(){}});
}

function surfaceCalendar(revert) {
	var z_index = 10000;
	if (revert) z_index = '';
	document.getElementById('ui-datepicker-div').style.zIndex = z_index;
}

function showProfileTab(tab_name) {
	var last_tab = memoryCreationWizard.last_tab;
	if (tab_name != last_tab) {
		var section_items = {
			'nights_div' : document.getElementById('profilePageUserSegments'),
			'friends_div' : document.getElementById('profilePageFriends'),
			'suggestions_div' : document.getElementById('profilePageSuggestions'),
			'nights_btn' : $('#profilePageUserBtn'),
			'friends_btn' : $('#profilePageFriendsBtn'),
			'suggestions_btn' : $('#profilePageSuggestionsBtn'),
			'nights_title' : document.getElementById('profilePageMemoriesTitle')
		}; var active_div, default_div, active_btn, default_btn, active_title, default_title;
		active_div = section_items[tab_name+'_div'];
		active_btn = section_items[tab_name+'_btn'];
		active_title = section_items[tab_name+'_title'];
		default_div = section_items[last_tab+'_div'];
		default_btn = section_items[last_tab+'_btn'];
		default_title = section_items[last_tab+'_title'];
		if (!active_title) active_title = active_div;
		if (!default_title) default_title = default_div;
		if (tab_name == 'friends') $('#editModeToggle').hide();
		else $('#editModeToggle').show();
		
		// set styles
		active_div.style.display = 'block';
		default_div.style.display = 'none';
		$(active_btn).addClass('selected');
		$(default_btn).removeClass('selected');
		active_title.style.visibility = 'visible';
		default_title.style.visibility = 'hidden';
		memoryCreationWizard.last_tab = tab_name;
	}
}

function setUnsavedExitHandler() {
	for (var i in rmnPoints) {
		window.unloadTimer = setInterval("showUnsavedMessage(); clearInterval(window.unloadTimer);", 500);
		window.onunload = function() {clearInterval(window.unloadTimer);}
		return 'You are leaving the page but the memory is not saved.';
	}
}

function setStillSavingExitHandler() {
	if (segmentFlags.ajaxCalls) {
		return 'The memory is almost done saving. If you click OK, you might lose information.';
		// 'The memory is almost done saving. Please wait a few seconds before leaving this page.'
	}
}

function showUnsavedMessage() {
	var show_login = "showError('<a href=\"javascript:loginToFacebook()\">Connect with Facebook</a> to recreate and save a memory!')";
	if (navigator.userAgent.indexOf('Firefox') != -1) setTimeout(show_login, 500);
	else eval(show_login);
}

function initCustomScrollbars() {
	updateCustomScrollbars();
	$('#nightCanvas').click(function(){$(this).blur();});
	$('#videoThumbStrip').click(function(){$(this).blur();});
}

function resetScrollbarPos(elem_id) {
	try { // hack to reset scroll position to top when content is deleted
		var scrollContent = document.getElementById(elem_id).childNodes[0].childNodes[0];
		var scrollbar = scrollContent.nextSibling;
		if (!scrollbar) scrollContent.style.left = 0;
	} catch (err) {}
}

function updateScrollbarTime() {
	if (dataFlags.timelineView) { // location.href.indexOf('timeline') != -1 || 
		var scrollbar = $('.jspDrag:eq(0)');
		var scroll_width = parseInt(scrollbar.css('width'), 10);
		var scroll_offset = scrollbar.offset();
		var scroll_offset_left = Math.max(scroll_offset.left + scroll_width/2 - $(window).scrollLeft(), 0);
		var scroll_offset_top = Math.max(scroll_offset.top - $(window).scrollTop() - 20, 0);
		var canvas_elem = document.elementFromPoint(scroll_offset_left, scroll_offset_top);
		var point_id; // attempt to extract point id
		if (canvas_elem) {
			canvas_elem = canvas_elem.parentNode;
			point_id = canvas_elem.getAttribute('point_id');
			if (!point_id) {
				canvas_elem = canvas_elem.parentNode;
				point_id = canvas_elem.getAttribute('point_id');
			}
		}
		if (!point_id)  { // try a little to the left in case of a gap
			var threshold = 12;canvas_elem = document.elementFromPoint(scroll_offset_left - threshold, scroll_offset_top);
			if (canvas_elem) {
				point_id = canvas_elem.getAttribute('point_id');
				if (!point_id) {
					canvas_elem = canvas_elem.parentNode;
					point_id = canvas_elem.getAttribute('point_id');
				}
			}
			if (!point_id) { // try again, but this time look right instead
				canvas_elem = document.elementFromPoint(scroll_offset_left + threshold, scroll_offset_top);
				if (canvas_elem) {
					point_id = canvas_elem.getAttribute('point_id');
					if (!point_id) {
						canvas_elem = canvas_elem.parentNode;
						point_id = canvas_elem.getAttribute('point_id');
					}
				}
			}
		}
		if (point_id) {
			var point_time = rmnPoints[point_id]['utcTimeSec'];
			$('.jspDragLeft:eq(0)').html(formatTimeStr(getAdjustedTime(point_time)));
		} else $('.jspDragLeft:eq(0)').html('');
	}
}

function updateCustomScrollbars(noTimeout) {//return;
	if (!segmentFlags || !segmentFlags.customScroll || noTimeout) {
		$(document).ready(function() { 
			try {
				$('#nightCanvas').jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40});//,horizontalDragMaxWidth:215, animateScroll:true
				$('#nightCanvasThumbs').jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40});//,horizontalDragMaxWidth:215, animateScroll:true
				$('#videoThumbStrip').jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40});
				//if (dataFlags.timelineView) $('#nightCanvas .jspHorizontalBar').css('height', '20px');
				updateScrollbarTime();
			} catch (err) {}
			resetScrollbarPos('nightCanvas');resetScrollbarPos('nightCanvasThumbs');resetScrollbarPos('videoThumbStrip');
		});
		
		if (segmentFlags && !noTimeout) {
			var timeoutJs = 'updateCustomScrollbars(1); clearTimeout(segmentFlags.customScroll); segmentFlags.customScroll = null;';segmentFlags.customScroll = setTimeout(timeoutJs, 250);
		}
	}
}

function updateCustomScrollbar(elem_id, delayed) {
	$('#'+elem_id).parent().jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40});
	/*if (!segmentFlags.customScrollInterval) segmentFlags.customScrollInterval = new Object();
	if (!delayed && !segmentFlags.customScrollInterval[elem_id]) segmentFlags.customScrollInterval[elem_id]  = setInterval("updateCustomScrollbar('"+elem_id+"', 1)", 250);
	else if (document.getElementById(elem_id).innerHTML && $('#cboxLoadedContent').find('#'+elem_id).attr('id')) {
		setTimeout("$('#"+elem_id+"').parent().jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40});", 250);
		clearInterval(segmentFlags.customScrollInterval[elem_id]);
	}*/
}

function updateColorboxScrollbars(elem_id) {
	return; // not in use
	$('#cboxLoadedContent').jScrollPane({hideFocus:true,horizontalDragMinWidth:100,verticalDragMinHeight:40});
	/*if (elem_id == 'addVideosWrapper') updateCustomScrollbar('fbVideoContents');
	else if (elem_id == 'addPhotosWrapper') {
		updateCustomScrollbar('fbAlbumContents'); updateCustomScrollbar('fbPhotoContents');
	} else if (elem_id == 'addFriendsWrapper') updateCustomScrollbar('fbFriendContents');
	else if (elem_id == 'nightSummaryEditWrapper') updateCustomScrollbar('nightSummaryEditEventListContents');*/
}

function updateCanvasView() {
	var canvasViewSelect = document.getElementById('canvasViewSelect');
	var view_option = canvasViewSelect.selectedIndex;
	if (view_option != 2) {
		//$('#nightCanvas .jspHorizontalBar').css('height', '');
		$("#nightCanvasRow").sortable("option", "cursorAt", {});
		$('#nightCanvas').removeClass('timelineView');
		$('.jspDragLeft:eq(0)').html('');
		document.getElementById('timelineNav').style.display = 'none';
		dataFlags.timelineView = null;
	}
	if (!view_option) {
		if (dataFlags.gridView) showGridView(1);
	} else if (view_option == 1) {
		if (!dataFlags.gridView) showGridView();
	} else if (view_option == 2) {
		if (!dataFlags.timelineView) {
			if (dataFlags.gridView) showGridView(1);
			dataFlags.timelineView = 1;
			document.getElementById('timelineNav').style.display = '';
			updateDateDisplays();
			renderTimelineBars();
			updateScrollbarTime();
			//$('#nightCanvas .jspHorizontalBar').css('height', '20px');
			$('#nightCanvas').addClass('timelineView');
			$("#nightCanvasRow").sortable("option", "cursorAt", {'bottom':-5, 'right':-5});
		}
	} else if (view_option == 3) {
		viewAsSlideShow();
		if (dataFlags.gridView) canvasViewSelect.selectedIndex = 1;
		else canvasViewSelect.selectedIndex = 0;
		//if (dataFlags.gridView) showGridView(1);
		//canvasViewSelect.selectedIndex = 0;
	} else if (view_option == 4) {
		clearContactSheetFriendFilter();
		loadContactSheet();
		if (dataFlags.gridView) canvasViewSelect.selectedIndex = 1;
		else canvasViewSelect.selectedIndex = 0; // showGridView(1);
	}
	
	// track in analytics
	trackClick('album_layout/'+view_option, loggedInUser);
}

function formatGrid(revert) {
	if (!revert) {
		var nightCanvasRow = document.getElementById('nightCanvasRow');
		var nightCanvasCells = nightCanvasRow.childNodes;
		var grid_row = document.createElement('div');
		grid_row.id = 'nightCanvasRow';
		var num_cells = nightCanvasCells.length;
		for (var i=0; i<num_cells; i++) {
			grid_row.appendChild(nightCanvasCells[0]);
		}
		nightCanvasRow.appendChild(grid_row);
	} else {
		var nightCanvasRow = document.getElementById('nightCanvasRowBak');
		var grid_row = document.getElementById('nightCanvasRow');
		var grid_cells = grid_row.childNodes;
		var num_rows = grid_cells.length;
		for (var i=0; i<num_rows; i++) {
			nightCanvasRow.appendChild(grid_cells[0]);
		}
		nightCanvasRow.removeChild(grid_row);
	} /*var wrapper_div = document.createElement('div');
	var nightCanvasTable = document.getElementById('nightCanvasTable');
	var nightCanvasRow = document.getElementById('nightCanvasRow');
	wrapper_div.appendChild(nightCanvasRow);
	nightCanvasTable.appendChild(wrapper_div);*/
	/*if (!revert) { 
		var nightCanvasCells = nightCanvasRow.childNodes;
		var grid_table = document.createElement('table');
		grid_table.id = 'grid_table';
		var grid_row = document.createElement('tr');
		grid_row.id = 'nightCanvasRow';
		var num_cells = nightCanvasCells.length;
		for (var i=0; i<num_cells; i++) {
			grid_row.appendChild(nightCanvasCells[0]);
		} grid_table.appendChild(grid_row);
		nightCanvasRow.appendChild(grid_table);
	} else {
		var grid_table = document.getElementById('grid_table')
		var grid_rows = grid_table.childNodes;
		var num_rows = grid_rows.length;
		for (var i=0; i<num_rows; i++) {
			var grid_cells = grid_rows[i].childNodes;
			var num_cells = grid_cells.length;
			for (var j=0; j<num_cells; j++) {
				nightCanvasRow.appendChild(grid_cells[0]);
			}
		} nightCanvasRow.removeChild(grid_table);
	}*/
	
}

function showGridView(revert) {
	if (!revert) {
		$('#nightCanvas .night_img_wrapper_big').attr('class', 'night_img_wrapper_thumb');
		$('#nightCanvas .night_img_big').each(function() {
			var preload_src = $(this).attr('preload_src');
			$(this).attr('preload_src', $(this).attr('grid_thumb'));
			$(this).attr('grid_thumb', preload_src);
		});
		$('#nightCanvas .night_img_big').addClass('night_img_thumb');
		$('#nightCanvas .night_img_big').removeClass('night_img_big');
		$('#nightCanvas').css('height', 522);
		document.getElementById('moveCanvasLeft').style.display = '';
		document.getElementById('moveCanvasRight').style.display = '';
		document.getElementById('timelineNav').style.display = 'none';
		dataFlags.gridView = 1;
	} else {
		$('#nightCanvas .night_img_wrapper_thumb').attr('class', 'night_img_wrapper_big');
		$('#nightCanvas .night_img_thumb').each(function() {
			var preload_src = $(this).attr('preload_src');
			var img_src = $(this).attr('src');
			if (img_src.indexOf('loading') == -1 && img_src == preload_src) {
				this.loaded = false;
			}
			$(this).attr('preload_src', $(this).attr('grid_thumb'));
			$(this).attr('grid_thumb', preload_src);
		});
		$('.night_img_thumb').addClass('night_img_big');
		$('#nightCanvas .night_img_thumb').removeClass('night_img_thumb');
		$('#nightCanvas').css('height', '');
		document.getElementById('moveCanvasLeft').style.display = 'block';
		document.getElementById('moveCanvasRight').style.display = 'block';
		dataFlags.gridView = null;
	}
	formatGrid(revert);
	try {
		var scrollContent = document.getElementById('nightCanvas').childNodes[0].childNodes[0];
		scrollContent.style.left = 0;scrollContent.style.top = 0;
	} catch (err) {}
	updateCustomScrollbars();
	//$(window).trigger('updatecanvas');
	updateScrollbarTime();
	if (!revert) {
		$('#nightCanvasRow').attr('id', 'nightCanvasRowBak');
		$('#nightCanvasRow').css('white-space', 'normal');
	} else {
		$('#nightCanvasRowBak').attr('id', 'nightCanvasRow');
		$('#nightCanvasRow').css('white-space', 'nowrap');
	}
	//enableDragAndDrop();
}

function clearLoadingAnimations() {
	try {
		document.getElementById("nightCanvasLoading").style.display = "none";
		document.getElementById("nightVideosLoading").style.display = "none";
		document.getElementById("nightFriendsLoading").style.display = "none";
		document.getElementById("retroDiaryLoading").style.display = "none";
		document.getElementById("summaryLoading").style.display = "none";
		if (document.getElementById("nightCanvasRow").childNodes.length == 0) {
			document.getElementById("nightCanvasEmpty").style.display = "block";
			document.getElementById("nightCanvasWrapper").style.display = "none";
			document.getElementById('filterMediaBtn').style.display = 'none';
			document.getElementById('canvasViewSelectWrapper').style.display = 'none';
		} else {
			document.getElementById('filterMediaBtn').style.display = 'block';
			document.getElementById('canvasViewSelectWrapper').style.display = 'block';
		}
		if (document.getElementById("nightFriendPicsWrapper").childNodes.length == 0)
			document.getElementById("nightFriendsEmpty").style.display = "block";
		document.getElementById('canvasShareIcons').style.display = "block";
		if (!dataFlags.gridView) {
			document.getElementById('moveCanvasLeft').style.display = 'block';
			document.getElementById('moveCanvasRight').style.display = 'block';
		}
		updateScrollbarTime();
	} catch(err) {}
}

function updateTabStatus(section, hide) {
	var empty_msg;
	if (section == 'friends') empty_msg = 'There are no friends in this memory yet. To add friends, click the<div style="padding-bottom:4px"></div>"Add" button above and select friends in the "Friends" tab.';
	else if (section == 'photos') empty_msg = 'There are no photos in this memory yet. To add photos,<div style="padding-bottom:4px"></div>click the "Add" button in the toolbar above.';
	else if (section == 'statuses') empty_msg = 'There are no statuses in this memory.';
	//else if (section == 'statuses') empty_msg = 'There are no statuses in this memory yet. To add<div style="padding-bottom:4px"></div>statuses, select the "Add" button.';
	
	var tabSectionEmpty = document.getElementById(section+'TabEmpty');
	if (tabSectionEmpty) {
		tabSectionEmpty.style.display = (hide?'none':'');
		tabSectionEmpty.innerHTML = empty_msg;
	}
}

function scrollToBar(percent) {
	var api = $('#nightCanvas').jScrollPane().data('jsp');
	var currentPosition = api.getContentPositionX();
	api.scrollToX(1000000000,0);
	api.scrollToX(api.getContentPositionX()*percent);
	if (dataFlags.dragActive) $("#nightCanvasRow").sortable("refreshPositions");
}

function renderTimelineBars() {
	if (dataFlags.timelineView) { // location.href.indexOf('timeline') != -1 || 
		var num_bars = Math.min(document.getElementById('nightCanvasRow').childNodes.length, 20);
		if (num_bars < 3) num_bars = 0;
		var timelineBars = '';
		var canvas_width = location.href.indexOf('getmarried')!=-1?620:800;
		var time_interval = (segmentData.end - segmentData.start)/num_bars;
		for (var i=0; i<num_bars; i++) {
			var handler_function = 'scrollToBar(\''+((i+1)/(num_bars+1))+'\')';
			timelineBars += '<div class="timeline_bar" style="margin-left:'+((canvas_width-2*num_bars)/(num_bars+1))+'px" title="'+
				formatTimeStr(parseInt(segmentData.start,10)+parseInt(i*time_interval,10))+
					'" onmouseover="if (dataFlags.dragActive) '+handler_function+'" onclick="'+handler_function+'">'+
					'</div>';
		}
		document.getElementById('timelineNavBars').innerHTML = timelineBars;
	}
}

function checkFirstSave() {
	if (segmentFlags && !segmentFlags.notFirstSave) {
		if (!$.cookies.get("notFirstSave")) {
			$.colorbox({opacity:.40, initialWidth:400, initialHeight:25, width:625, maxWidth:'85%', maxHeight:'85%', href:'html', html:function() {return '<div id="nightErrorWrapper">The memory is saving as you go. To view your previously saved memories, click on the "My Memories" link at the top of this page.</div>';}, onComplete:function() {segmentFlags.closeFirstSaveHintTimer = setTimeout('$.colorbox.close()', 6000)}, onClosed:function () {if (segmentFlags.closeFirstSaveHintTimer) clearTimeout(segmentFlags.closeFirstSaveHintTimer);}});
			$.cookies.set("notFirstSave", 1, {expiresAt: new Date(new Date().getTime()+1000000000000)});
		} else segmentFlags.notFirstSave = 1;
	} // $.cookies.set("notFirstSave", null);
}

function checkFirstCreate() {
	if (segmentFlags && !segmentFlags.notFirstCreate) {
		if (!$.cookies.get("notFirstCreate")) {
			document.getElementById('newNightCreateFirstTimeWrapper').style.display = 'block';
			initNewNightCreateLightbox();//function () { document.getElementById('newNightCreateFirstTimeWrapper').style.display = '' }
			$.cookies.set("notFirstCreate", 1, {expiresAt: new Date(new Date().getTime()+1000000000000)});
		} else segmentFlags.notFirstCreate = 1;
	} // $.cookies.set("notFirstCreate", null);
}

function checkFirstWeddingCreate() {
	if (segmentFlags && !segmentFlags.notFirstWeddingCreate) {
		if (!$.cookies.get("notFirstWeddingCreate")) {
			initColorbox('', 'memoryCreateComplete');
			$.cookies.set("notFirstWeddingCreate", 1, {expiresAt: new Date(new Date().getTime()+1000000000000)});
		} else segmentFlags.notFirstWeddingCreate = 1;
	} // $.cookies.set("notFirstWeddingCreate", null);
}

function initNewNightCreateLightbox() {
	dataFlags.helpActive = 1;
	var newNightCreateStartMonth = document.getElementById('newNightCreateStartMonth');
	var newNightCreateStartDay = document.getElementById('newNightCreateStartDay');
	var newNightCreateStartYear = document.getElementById('newNightCreateStartYear');
	var newNightCreateStartHours = document.getElementById('newNightCreateStartHours');
	var newNightCreateStartMinutes = document.getElementById('newNightCreateStartMinutes');
	var newNightCreateStartAMPM = document.getElementById('newNightCreateStartAMPM');
	var newNightCreateEndMonth = document.getElementById('newNightCreateEndMonth');
	var newNightCreateEndDay = document.getElementById('newNightCreateEndDay');
	var newNightCreateEndYear = document.getElementById('newNightCreateEndYear');
	var newNightCreateEndHours = document.getElementById('newNightCreateEndHours');
	var newNightCreateEndMinutes = document.getElementById('newNightCreateEndMinutes');
	var newNightCreateEndAMPM = document.getElementById('newNightCreateEndAMPM');
	var newNightCreateViewPrivacy = document.getElementById('newNightCreateViewPrivacy');
	var newNightCreateContributePrivacy = document.getElementById('newNightCreateContributePrivacy');
	var newNightCreateDateError = document.getElementById('newNightCreateDateError');
	
	// load time values
	var start_date = new Date(getAdjustedTime(segmentData.start)*1000);
	var end_date = new Date(getAdjustedTime(segmentData.end)*1000);
	newNightCreateStartMonth.value = start_date.getMonth()+1;
	newNightCreateStartDay.value = start_date.getDate();
	newNightCreateStartYear.value = start_date.getFullYear();
	var start_hour = start_date.getHours();
	if (start_hour > 11) {
		start_hour -= 12;
		newNightCreateStartAMPM.selectedIndex = 1;
	} else newNightCreateStartAMPM.selectedIndex = 0;
	if (!start_hour) start_hour = 12;
	newNightCreateStartHours.value = start_hour;
	var start_minutes = start_date.getMinutes();
	newNightCreateStartMinutes.value = start_minutes < 10? '0'+start_minutes : start_minutes;
	// end range
	newNightCreateEndMonth.value = end_date.getMonth()+1;
	newNightCreateEndDay.value = end_date.getDate();
	newNightCreateEndYear.value = end_date.getFullYear();
	var end_hour = end_date.getHours();
	if (end_hour > 11) {
		end_hour -= 12;
		newNightCreateEndAMPM.selectedIndex = 1;
	} else newNightCreateEndAMPM.selectedIndex = 0;
	if (!end_hour) end_hour = 12;
	newNightCreateEndHours.value = end_hour;
	var end_minutes = end_date.getMinutes();
	newNightCreateEndMinutes.value = end_minutes < 10? '0'+end_minutes : end_minutes;
	setIndexByValue(newNightCreateViewPrivacy, segmentData['privacy']['view']);
	setIndexByValue(newNightCreateContributePrivacy, segmentData['privacy']['contribute']);
	newNightCreateDateError.innerHTML = '';
	
	initColorbox('', 'newNightCreateWrapper', function() {validateNewNightCreateEdit(1);dataFlags.helpActive=null});
}

function validateNewNightCreateEdit(save) {
	// validate start date
	var segment_info_modified, time_modified;
	var editParams = new Object();
	var newNightCreateDateError = document.getElementById('newNightCreateDateError');
	var date_info = validateDate('newNightCreateStart');
	var err_msg = date_info['error'];
	if (!err_msg) {
		start_time = date_info['time'];
		if (start_time != segmentData.start) {
			editParams['utcStartSec'] = start_time;
			time_modified = 1;
		}
		
		// validate end date
		date_info = validateDate('newNightCreateEnd');
		err_msg = date_info['error'];
		if (err_msg) newNightCreateDateError.innerHTML = err_msg;
		else {
			end_time = date_info['time'];
			if (end_time != segmentData.end) {
				editParams['utcEndSec'] = end_time;
				time_modified = 1;
			}
			
			// make sure end time is greater than start time
			if (end_time <= start_time) err_msg = 'The end time should come past your start time!';
		}
	}
	newNightCreateDateError.innerHTML = err_msg;
	$.colorbox.resize();
	
	if (save) {
		// write to db
		var night_view_privacy = document.getElementById('newNightCreateViewPrivacy').value;
		var night_contribute_privacy = document.getElementById('newNightCreateContributePrivacy').value;
		var night_auto_import_privacy = segmentData.privacy.autoimport;
		
		if (night_view_privacy != segmentData.privacy.view || night_contribute_privacy != segmentData.privacy.contribute) {
			editParams['privacy_ids'] = night_view_privacy+','+night_contribute_privacy+(!night_auto_import_privacy?',nai':'');
			segment_info_modified = 1;
		}
	
		if (!dataFlags.offlineView) {
			if (segmentData.id && (segment_info_modified || (time_modified && !err_msg))) {
				writeToDB('editSegment', [editParams, segmentData.id]/*, function() {if (time_modified) updateSegmentUrl();}*/);
				
				// update values in memory
				segmentData['start'] = start_time;
				segmentData['end'] = end_time;
				segmentData['privacy']['view'] = night_view_privacy;
				segmentData['privacy']['contribute'] = night_contribute_privacy;
				
				if (time_modified) {
					if ((start_time != segmentData.start) || (end_time != segmentData.end))
						reloadFacebookStream();
					
					// update calendar dates
					if (time_modified) updateDateDisplays();
				}
			}
		}
	}
}

function openLightboxReturn(lightbox_id, lightbox_id_second) {
	validateNewNightCreateEdit(1);
	if (!lightbox_id_second) {
		$('#'+lightbox_id).colorbox({'open':true, onClosed:function() {initNewNightCreateLightbox(); /*dataFlags.helpActive = null;*/$('#'+lightbox_id).colorbox({onClosed:null});}});
	}
	else {
		$('#'+lightbox_id).colorbox({'open':true, onClosed:function() {
			$('#'+lightbox_id_second).colorbox({'open':true, onClosed:function() {
				initNewNightCreateLightbox();// dataFlags.helpActive = null;
				 $('#'+lightbox_id_second).colorbox({onClosed:null});
			}});
		$('#'+lightbox_id).colorbox({onClosed:null});
		}});
	}
}

function showAddMediaBtns(hide) {
	if (!hide) {
		document.getElementById('addCanvasMediaIcons').style.display = 'block';
		if (segmentFlags.hideAddBtns) {clearTimeout(segmentFlags.hideAddBtns);segmentFlags.hideAddBtns = null;}
	} else segmentFlags.hideAddBtns = setTimeout("document.getElementById('addCanvasMediaIcons').style.display = ''", 250);
}

function viewAsSlideShow(onClosed) {
	SlideShow.onCloseFunction = onClosed;
	if (segmentData) {
		var segment_id = segmentData.id;
		if (segment_id) {
			toggleSlideshowLoading(true);
			$('nightSlideShowStatus').css('display', '');
			initializeSlideShow();
			
			SlideShow.segment_id = segmentData.id;
			SlideShow.url_base = 'http://' + location.host + '/';

			if (loggedInUser) {
				readFromDB('getSegment', [segment_id.toString()], function(data) {
					var result = JSON.parse(data);
					var rmn_segment = result['result'];
					var modified = parseInt(rmn_segment.utcLastModifiedSec);
					var use_cache = (modified == segmentData['modified']) ? "true" : "false";
					jx.load('?p=slideshowJSON&sid='+segment_id+"&cache="+use_cache, function(data){
						SlideShow.json = data;
						//slideshow_initialized = false;
						loadSlideShowData(segment_id);
					});
				});
			} else {
				jx.load('?p=slideshowJSON&sid='+segment_id+"&cache=true", function(data){
					SlideShow.json = data;
					loadSlideShowData(segment_id);
				});
			}
		}
	}
}

function initializeSlideShow(){
	if (!slideshow_initialized) {
		/*
		var width = (window.innerWidth||document.documentElement.clientWidth) - 100;
		var height = (window.innerHeight||document.documentElement.clientHeight) - 150;
		var aspect = 16/9;
		var window_aspect = width/height;
		if (window_aspect > aspect) {
			Math.floor(width = aspect * height);
		} else {
			Math.floor(height = width * 9 / 16);
		}
		*/

		var width = 540;
		var height = 360;
		SlideShow.slideshow_id = "nightSlideShowCanvas";
		SlideShow.facebook_div_id = "nightSlideShowFacebookStatuses";
		SlideShow.display_height = height;
		SlideShow.display_width = width;
		SlideShow.display_facebook_video_width = 640;
		SlideShow.display_facebook_video_height = 480;
		SlideShow.display_youtube_video_width = 640;
		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.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.fullscreen_mode = true;
		SlideShow.initialize("movie");
		slideshow_initialized = true;

		/*$("#cboxPrevious").after('<div id="cboxPause" style="display:none;"></div>');
		$("#cboxClose").before('<div id="cboxFullscreen" style="display:none;"></div>');
		$("#nightSlideShowCanvas").bind("click", function() {
			slideshowPause();
			if (SlideShow.autoscroll_playing) {
			$("#cboxPause").css("background-position", "-150px -25px");
			} else {
				$("#cboxPause").css("background-position", "-125px -25px")
			}
		});*/
	}
}

function loadSlideShowData(segment_id){
	document.getElementById('nightSlideShowStatus').style.display = 'none';
	SlideShow.loadData(SlideShow.json, true);
	SlideShow.fullscreen_mode = false;
	SlideShow.toggleFullscreen();
	if (SlideShow.slideshow_data.length > 0) {
		var width = $("#nightSlideShowCanvas").css("width");
		var height = $("#nightSlideShowCanvas").css("height");
		//redisplay the slideshow to resize to prevent arrows from causing improper
		//resizing
		if (!SlideShow.closedEarly) {
			//displaySlideShow(SlideShow.onCloseFunction);
			//loadSlideshowNavigation();
		} else {
			SlideShow.closedEarly = false;
		}
	}
	
	displaySlideShow(function() {
		SlideShow.closedEarly = true; // SlideShow.onCloseFunction();
		safeCall(SlideShow.onCloseFunction);
	});
}

function unloadSlideShowData() {
	$("#cboxFullscreen").css("display", "none");
	$("#cboxPause").css("display", "none");
	$("#cboxTitle").css("display", "none");
	$(document).unbind("keyup", setSlideshowKeys);
	$("#cboxPrevious").unbind("click", slideshowPrevious);
	$("#cboxNext").unbind("click", slideshowNext);
	SlideShow.normal_mode();
	SlideShow.unload();
}

function displaySlideShow(onClose) {
	/*var width = 540,//$("#nightSlideShowCanvas").css("width"),
		height = 360,//$("#nightSlideShowCanvas").css("height"),
		slideshowStatuses = document.getElementById('nightSlideShowFacebookStatuses'),
		slideshowStatusesToggle = $('#slideshowToggleHidden'),
		colorbox_args = {
			scrolling:false,
			inline:true,
			href:"#nightSlideShowWrapper",
			innerWidth: width,
			innerHeight: height,
			//onCleanup:unloadSlideShowData,
			onOpen : function() {
				SlideShow.loadNavigationTimeout=setTimeout("loadSlideshowNavigation()",500)
			},
			onClosed : function () {
				unloadSlideShowData();
				safeCall(onClose, []);
				if (SlideShow.loadNavigationTimeout) {
					clearTimeout(SlideShow.loadNavigationTimeout);
					SlideShow.loadNavigationTimeout = null;
				}
			}
		};
		
		if (SlideShow.fullscreen_mode) {
			colorbox_args['speed'] = 0;
		}
		
	slideshowStatuses.onclick = SlideShow.toggleHideSlideshowStatuses;
	slideshowStatusesToggle.click(SlideShow.toggleHideSlideshowStatuses);*/
	
	//$.colorbox(colorbox_args);
	
	toggleSlideshowLoading(false);
	$('#nightSlideShowWrapper').parent().removeClass('hidden');
	SlideShow.repositionSlideshowStatusToggle($('#slideshowToggleHidden').hasClass('show'), true);
	SlideShow.repositionNavigationControls();
}

function toggleSlideshowLoading(show) {
	var slideshowLoadingDiv = $("#nightSlideShowLoading");
	if (show) {
		//display the slideshow loading bar
		slideshowLoadingDiv.show();
	} else {
		//hide the slideshow loading bar
		slideshowLoadingDiv.hide();
	}
}

function closeSlideshow() {
	$('#nightSlideShowWrapper').parent().addClass('hidden');
	safeCall(SlideShow.onCloseFunction);
	SlideShow.unload(true);
}

function setSlideshowKeys(event) {
	if (event.keyCode == 39) {
		slideshowNext();
	} else if (event.keyCode == 37) {
		slideshowPrevious();
	}
}

function toggleHideSlideshowStatuses (e) {
	var slideshowStatuses = $('#nightSlideShowFacebookStatuses'),
		slideshowStatusesToggle = $('#slideshowToggleHidden'),
		slideshowStatusesText = slideshowStatusesToggle.text();
	e = getEvent(e);
	preventBubbling(e);
	slideshowStatuses.toggleClass("hidden");
	slideshowStatusesToggle.toggleClass('show');
	if (slideshowStatusesText == "hide statuses") {
		slideshowStatusesToggle.html("show statuses");
		repositionSlideshowStatusToggle(true, slideshowStatusesToggle.hasClass('fullscreen'));
	} else {
		repositionSlideshowStatusToggle(false, slideshowStatusesToggle.hasClass('fullscreen'));
		slideshowStatusesToggle.html("hide statuses");
	}
}

function slideshowFullscreen () {
	var slideshowStatuses = document.getElementById('nightSlideShowFacebookStatuses');
	if ($.browser.mozilla) {
		$("#colorbox").css("overflow", "visible");
	}
	if (slideshowStatuses) {
		slideshowStatuses.onclick = SlideShow.toggleHideSlideshowStatuses;
	}
	SlideShow.fullscreen();
}

function loadSlideshowNavigation() {
	$("#slideshowPlayButton").addClass('pause');
	//SlideShow.toggleFullscreen();
}

function slideshowPause() {
	if (SlideShow.autoscroll_playing) {
		SlideShow.pauseAutoScroll();
		$("#cboxPause").css("background-position", "-125px 0px").hover(function(){
			$(this).css("background-position", "-125px 0px");
		},
		function() {
			$(this).css("background-position", "-125px -25px");
		});
	} else {
		SlideShow.startAutoScroll();
		$("#cboxPause").css("background-position", "-150px 0px").hover(function(){
			$(this).css("background-position", "-150px 0px");
		},
		function() {
			$(this).css("background-position", "-150px -25px");
		});
	}
}

function slideshowPrevious() {
	SlideShow.previous();
}

function slideshowNext() {
	SlideShow.next();
}

function loadContactSheet() {
	initColorbox('', 'contactSheetWrapper');
	var segment_id = segmentData.id;
	jx.load("?p=contactsheet&sid="+segment_id, function(data){
		data = JSON.parse(data);
		var present_tagged = data['present_tagged'];
		var present_not_tagged = data['present_not_tagged'];
		var not_present_tagged = data['not_present_tagged'];
		var contact_sheet_html = '<div id="contactSheetFriendFilterWrapper">Find Friends: <input onkeyup="updateShownContactSheetFriends()" class="input_field_dark" id="contactSheetFriendFilter"> <a class="yellow" onclick="clearContactSheetFriendFilter(); return false;" id="contactSheetFriendFilterClear" href="#">x</a></div>'+buildContactSheetHtml(present_tagged, 1) + buildContactSheetHtml(present_not_tagged, 2) + buildContactSheetHtml(not_present_tagged, 3) + '<div class="clear"></div>';
		if (segmentData.contactSheetHTML != contact_sheet_html) {
			document.getElementById('contactSheetWrapper').innerHTML = contact_sheet_html;
			segmentData.contactSheetHTML = contact_sheet_html;
			loadFBML(document.getElementById('contactSheetWrapper'));
		}
	});
}

function buildContactSheetHtml(data, type) {
	var header_label = 'Tagged photos by friends';
	if (type == 2) header_label = 'Friends without tagged photos';
	else if (type == 3) header_label = 'Other people tagged in photos';
	var section_id = 'contactSheetSection'+type;
	var contact_sheet_html = '<div class="add_photos_section"><div class="add_photos_title" onclick="toggleSection(\''+section_id+'\')">'+header_label+'</div><div id="'+section_id+'Expand" title="Less" class="collapse_arrow" onclick="toggleSection(\''+section_id+'\')"></div><div class="clear"></div></div><div id="'+section_id+'Wrapper">';
	var contact_sheet_items = 0;
	var contact_sheet_user_item_html = '', contact_sheet_owner_item_html = '', contact_sheet_other_items_html = '';
	for (var i in data) {
		if (i != 'indexOf') {
			var tagged_media = data[i];
			var contact_sheet_item_html = '<div class="contactSheetItem"><div class="contactSheetName"><div class="float_left"><fb:profile-pic uid="'+i+'" size="square" linked="false" class="profile_pic"></fb:profile-pic></div><div class="contactSheetNameLabel"><fb:name uid="'+i+'" capitalize="true" useyou="false" linked="false"></fb:name>'+(type==3?'<br><a href="#" onclick="addFbUserToNight(\''+i+'\');this.style.display=\'none\';return false">+ add</a>':'')+'</div></div><div class="contactSheetMediaCollapsed">';
			if (type == 2) contact_sheet_item_html += '<div style="margin-top:11px;line-height:17px">No tagged photos</div>';
			else {
				var num_items = 0;
				for (var j=0; j<tagged_media.length; j++) {
					var tagged_media_item = tagged_media[j];
					if (tagged_media_item) {
						contact_sheet_item_html += '<div class="night_img_wrapper_thumb"><img src="'+tagged_media_item['thumb']+'" class="night_img_thumb" style="margin-right:5px" onclick="$(\'#m'+tagged_media_item['photoid']+(tagged_media_item['rmnPointPartnerIdId'] == 14?'flickr':'')+'\').colorbox({\'open\':true});" /></div>';
						num_items++;
					}
				}
			}
			contact_sheet_item_html += '</div>';
			if (num_items > 5) contact_sheet_item_html += '<div class="expand_arrow" title="Expand" onclick="toggleContactSheetItem(this)"></div>';
			contact_sheet_item_html += '<div class="clear"></div></div>';
			if (i == loggedInUser) contact_sheet_user_item_html += contact_sheet_item_html;
			else if (i == segmentData.fbOwner) contact_sheet_owner_item_html += contact_sheet_item_html;
			else contact_sheet_other_items_html += contact_sheet_item_html;
			contact_sheet_items++;
		}
	}
	contact_sheet_html += contact_sheet_user_item_html+contact_sheet_owner_item_html+contact_sheet_other_items_html;
	if (!contact_sheet_items) contact_sheet_html += '<div style="padding:10px 0 0 20px;font-size:18px">None</div>';
	contact_sheet_html += '</div>';
	return contact_sheet_html;
}

function error() {}

function downloadPhoto(src, pid, src_high_res) {
	if (src.indexOf('flickr.com') != -1) {
		//fix use the big photo for flickr
		src = src.replace('_z.jpg', '_b.jpg');
	}
	
	if (pid && loggedInUser && !src_high_res) {
		queryFacebook("SELECT pid, images, object_id FROM photo WHERE pid='{0}'",
			[pid], (function(src){
				return function(data) {
				if (data && data.length) {
					var images = data[0].images;
					var url = src;
					if (images && images.length > 0) {
						var height = 0;
						var new_height = 0;
						for (var i in images) {
							new_height = parseInt(images[i].height,10);
							if (new_height > height) {
								height = new_height;
								url = images[i].source;
							}
						}
					}
					var download_url = "http://" + location.hostname + "/" + TEMPLATE_VIEW_PATH + "download.php?filename=" + encodeURIComponent(url);
					if (url != src) {
						try {writeToDB('editMedia', [{'alt_src':d_escape(url)}, rmnPoints[fbPhotoPointIds[pid]]['media_id']], function() {setTimeout('location = "'+download_url+'"', 0);});} catch (err) {location = download_url;}
						// setTimeout("try { writeToDB('editMedia', [{'alt_src':'"+d_escape(url)+"'}, '"+rmnPoints[fbPhotoPointIds[pid]]['media_id']+"']); } catch (err) {}", 500);
					} else location = download_url;
				} else {
					location = "http://" + location.hostname + "/" + TEMPLATE_VIEW_PATH + "download.php?filename=" + encodeURIComponent(src);
				}
				};
			})(src)
		);
	} else {
		location = "http://" + location.hostname + "/" + TEMPLATE_VIEW_PATH + "download.php?filename=" + encodeURIComponent(src_high_res?src_high_res:src);
	}
}

function printPhoto(src) {
	var img_src = '<img src="' + src + '" />';
	var print_window = window.open('', 'print_window', 'width="100" height="100" top=0,left=0,scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no');
	if (print_window) {
		print_window.document.open();
		print_window.document.write('<html><head><style type="text/css">* {margin:0px;padding:0px;}</style></head><body onload="print();close()">' + img_src + '</body></html>');
		print_window.document.close();
	} else {
		alert("You must permit popups to use the print button");
	}
}

function displayPhotoByRmnId(rmnid) {
	var point = rmnPoints[rmnid];
	if (point) {
		var partnerId_id = point['partnerId_id'];
		var media_id = point['media_type_id'];
		var media_id_type = media_id;
		if (partnerId_id == PARTNER_TYPES.flickr_photo) {
			media_id_type += 'flickr';
		}
		var image_id = 'm' + media_id_type;
		
		$("#" + image_id).click();
	}
}

function sharePhoto(photo_rmnid, type) {
	var context = ''; // extract url context (for IE)
	//if (navigator.userAgent.indexOf("MSIE") != -1) { }
	var domain = '';
	var segment_id = segmentData.id;
	try {segment_id = memoryCreationWizard.sid;} catch(err) {}
	var link_sid = '&sid=' + segment_id;
	if (location.href.match('recreatemynight.com')) domain = 'recreatemynight';
	else domain = 'kaptur';
	
	var re = new RegExp('([^/]*)' + domain + '.com');
	var url_context = re.exec(location.href); // extract video dimensions
	if (url_context) context = '&context='+url_context[1];

	if (domain) domain = '&domain=' + domain;
	if (segmentData && segment_id) {
		if (type == "email") show_share("http://emailer.kaptur.com?share=email&p=s"+context+domain+"&sid="+segment_id+"&photo="+photo_rmnid);
		else if (type == "facebook") show_share("?share=facebook&p=s&sid="+segment_id+"&photo="+photo_rmnid, 'single_facebook');
	}
}

/**
 * Gets the link to the rss export page.  Used because when first creating a
 * night the segment id will not be available on page creation.
 */
function getRssLink(help) {
	var segment_id;
	if (segmentData && segmentData.id) {
		segment_id = segmentData.id;
	} else {
		try {segment_id = memoryCreationWizard.sid;}
		catch(err) {}
	}
	
	if (segment_id) {
		var url = "?p=export&format=rss&sid=" + segment_id;
		if (help) {
			document.getElementById('iPhotoUrl').value = DOMAIN_URL+url;
		} else {
			window.open(url, '_blank');
		}
	}
}

function addFanPage() {
	var page_url = document.getElementById("addFanPageId").value;
	var fql = "";
	var idInfo = extractFanPageIdInfoFromUrl(page_url);
	if (idInfo) {
		var id = idInfo.id;
		var type = idInfo.type;
		var fql = "";
		if (type == "username") {
			fql = 'SELECT uid, first_name, name FROM user WHERE username="{0}"';
		} else if (type == "page_id") {
			fql = 'SELECT page_id, name FROM page WHERE page_id="{0}"'
		}
		
		queryFacebook(fql,
			[id],
			function(data){
				var id = "";
				var error_message = "";
				if (data && data[0] && (data[0].page_id || data[0].uid)) {
					id = data[0].page_id || data[0].uid;
					if (document.getElementById('attendee'+id)) {
						error_message = "Page has already been added to the memory";
					}
				} else {
					error_message = "Not a Valid Fan Page";
				}

				if (!error_message) {
					var first_name = data[0].first_name? data[0].first_name : data[0].name;
					var last_name = data[0].name.replace(new RegExp(first_name+' ?'), '');
					addFbUserToNight(id, 0, first_name, last_name);
					document.getElementById('addFanPageId').value = '';
				} else {
					document.getElementById('addFanPageId').focus();
				}

				document.getElementById('addFanPageError').innerHTML = error_message;
			}
		); // end queryFacebook
	} else {
		document.getElementById('addFanPageError').innerHTML = "Invalid Fan Page URL";
	}
}

function extractFanPageIdInfoFromUrl(page_url) {
	var id = '';
	var type = '';
	var page_info = null;
	var regexp = '';

	page_url = $.trim(page_url.replace('/#!',''));

	if (page_url.indexOf('/pages/') != -1) {
		type = "page_id";
		regexp = /http:\/\/www.facebook.com\/pages\/[\w_-]+\/(\d+)/;
	} else {
		type = "username";
		regexp = /http:\/\/www.facebook.com\/([\w-_\d]+)/;
	}
	var matches = page_url.match(regexp);
	
	if (matches && matches[1]) {
		id = matches[1];
	}

	if (id && type) {
		page_info = {
			"id" : id,
			"type" : type
		};
	}

	return page_info;
}

function filterMedia(includePhotos, includeVideos) {
	/*var night_row = document.getElementById('nightCanvasRow');
	for (var i = 0; i < night_row.childNodes.length; i++) {
		var canvas_item = night_row.childNodes[i];
		var isVideo = detectVideo(canvas_item);
		if (isVideo && includeVideos) {
			canvas_item.style.display = '';
		} else if (!isVideo && includePhotos) {
			canvas_item.style.display = '';
		} else {
			canvas_item.style.display = 'none';
		}
	}*/
	var filter_friend_ids = []; // populate list of of friends to filter
	$('#filterMediaFriends input:checkbox:checked').each(function() {filter_friend_ids.push(this.value);});
	if (filter_friend_ids.length) filterMediaAndFriends(includePhotos, includeVideos, filter_friend_ids);
	else filterMediaAndFriends(includePhotos, includeVideos); //clearMediaFilters(1);
	
	updateCustomScrollbars();
	//$(window).trigger('updatecanvas');
	//setTimeout("$(window).trigger('updatecanvas')", 250);
}

function detectVideo(canvas_item) {
	var canvas_item_img = $(canvas_item).find("img")[0];
	if (canvas_item && canvas_item_img) {
		var media_id = canvas_item_img.id.substr(1);
		var isVideo = (!!fbVideoPointIds[media_id]);
		return isVideo;
	}
}

function filterMediaAndFriends(includePhotos, includeVideos, filter_friend_ids) {
	if ((typeof includePhotos) == "undefined") includePhotos = document.getElementById('filter_media_photos').checked;
	if ((typeof includeVideos) == "undefined") includeVideos = document.getElementById('filter_media_videos').checked;
	var nightCanvasRowItems = document.getElementById('nightCanvasRow').childNodes;
	var display_style = 'inline-block';
	for (var i=0; i<nightCanvasRowItems.length; i++) {
		var display_media = 0;
		var nightCanvasRowItem = nightCanvasRowItems[i];
		var isVideo = detectVideo(nightCanvasRowItem);
		if (filter_friend_ids && filter_friend_ids.length) {
			try {
				for (var j=0; j<filter_friend_ids.length; j++) {
					if (rmnPoints[nightCanvasRowItem.getAttribute('point_id')]['tags'][filter_friend_ids[j]]) {
						if (isVideo && includeVideos) {
							nightCanvasRowItem.style.display = display_style;
							display_media = 1;
							break;
						} else if (!isVideo && includePhotos) {
							nightCanvasRowItem.style.display = display_style;
							display_media = 1;
							break;
						} else nightCanvasRowItem.style.display = 'none';
					}
				}
			} catch(err) {}
			if (!display_media) nightCanvasRowItem.style.display = 'none';
		} else {
			if (isVideo && includeVideos) nightCanvasRowItem.style.display = display_style;
			else if (!isVideo && includePhotos) nightCanvasRowItem.style.display = display_style;
			else nightCanvasRowItem.style.display = 'none';
		}
	}
}

function updateTaggedFilterHTML() {
	var tagged_filter_html = '';
	for (var i in rmnPointFriendFilters) {
		if (i) tagged_filter_html += '<div class="night_friend_pic_wrapper"><input type="checkbox" id="friend'+i+'filter" class="tagged_filter_media_checkbox" value="'+i+'" onclick="filterMedia()"><img src="'+getPartnerLink(i, 'profile_pic')+'" class="profile_pic" onclick="$(\'#friend'+i+'filter\').click()"></div>';
	}
	var filterMediaFriendsInner = document.getElementById('filterMediaFriendsInner');
	if (filterMediaFriendsInner) {
		filterMediaFriendsInner.innerHTML = tagged_filter_html+'<div class="clear"></div>';
		document.getElementById('filterMediaByPerson').style.display = 'block';
	}if ($.colorbox.element().attr('id') == 'filterMediaBtn') $.colorbox.resize();
}

function clearMediaFilters(tags_only) {
	$('#filterMediaFriends input:checkbox:checked').removeAttr('checked');
	filterMedia();
	/*if (!tags_only) {
		$('#filter_media_photos, #filter_media_videos').attr('checked', true);
		var nightCanvasRowItems = document.getElementById('nightCanvasRow').childNodes;
		for (var i=0; i<nightCanvasRowItems.length; i++) nightCanvasRowItems[i].style.display = '';
	}*/
}

function reloadMediaTags(media_id, media_type, point_id) {
	if (!media_id) {
		var tagged_photos = {}, tagged_videos = {};
		var tagged_photos_list = '', tagged_videos_list = '';
		var media_items = document.getElementById('nightCanvasRow').childNodes;
		// generate list of facebook media ids
		for (var i=0; i<media_items.length; i++) {
			var point_id = media_items[i].getAttribute('point_id');
			var media_type = rmnPoints[point_id]['partnerId_id'];
			var media_type_id = rmnPoints[point_id]['media_type_id'];
			var media_id = rmnPoints[point_id]['media_id'];
			if (media_type == 4) {
				tagged_photos[media_type_id] = [point_id, media_id];
				tagged_photos_list += media_type_id + '","';
			} else if (media_type == 9) {
				tagged_videos[media_type_id] = [point_id, media_id];
				tagged_videos_list += media_type_id + '","';
			}
		} // trim facebook media id lists
		tagged_photos_list = tagged_photos_list.substr(0, tagged_photos_list.length-3);
		tagged_videos_list = tagged_videos_list.substr(0, tagged_videos_list.length-3);
		
		// add photo and video tags
		$('#filterMediaByPersonReload').fadeOut(300);
		createMediaTags(tagged_photos, tagged_photos_list);
		createMediaTags(tagged_videos, tagged_videos_list);
	} else {
		var fb_key = 'pid';
		var fb_vals=fb_key;//+', text, xcoord, ycoord, created';
		if (media_type == 9) {fb_key = 'vid';fb_vals = fb_key;}//+', created_time, updated_time'; }
		var tagged_media = {};
		tagged_media[media_id] = [point_id, rmnPoints[point_id]['media_id']];
		var btn_id = 'mediaFriendTagNamesReload';
		if (!document.getElementById('mediaTags')) btn_id = 'mediaFriendTagsReload';
		$('#'+btn_id).fadeOut(300);
		queryFacebook('SELECT '+fb_vals+', subject FROM '+(fb_key!='vid'?'photo':'video')+'_tag WHERE '+fb_key+' IN ("{0}")',
			[media_id], function(tags) {createMediaTagsLoaded(tags, tagged_media, fb_key, btn_id);});
	}
}

function createMediaTags(tagged_media, tagged_media_list, video) {
	var fb_key = 'pid';fb_vals=fb_key/*+', text, xcoord, ycoord, created'*/;var fbMedia = fbPhotos;
	if (video) {fb_key = 'vid';fb_vals=fb_key;/*+', created_time, updated_time'*/;var fbMedia = fbVideos;}
	queryFacebook('SELECT '+fb_vals+', subject FROM '+(!video?'photo':'video')+'_tag WHERE '+fb_key+' IN ("'+tagged_media_list+'")',
		[], function(tags) {createMediaTagsLoaded(tags, tagged_media, fb_key, (!video? 'filterMediaByPersonReload':''));}); // end queryFacebook
}

function createMediaTagsLoaded(tags, tagged_media, fb_key, reshow_btn) {
	if (tags) {
		for (var i=0; i<tags.length; i++) {
			var tag = tags[i];
			var tag_id = tag[fb_key];
			var tag_uid = tag['subject'];
			var point_id = tagged_media[tag_id][0];
			var media_id = tagged_media[tag_id][1];
			if (!rmnPoints[point_id]['tags']) rmnPoints[point_id]['tags'] = {};
			rmnPoints[point_id]['tags'][tag_uid] = 1;
			//if (!fbMedia[tag_id]['tags']) fbMedia[tag_id]['tags'] = {};
			//fbMedia[tag_id]['tags'][tag_uid] = 1;
			rmnPointFriendFilters[tag_uid] = 1;
			createMediaUserTag(media_id, {'uid':tag_uid}, rmnPoints[point_id]);
			if (reshow_btn == 'mediaFriendTagsReload') {
				var tag_name = document.getElementById('mediaTag'+tag_uid);
				if (!tag_name) toggleMediaTag(point_id, tag_uid);
			}
		}
		
		if (reshow_btn == 'mediaFriendTagNamesReload') {
			try {
				var tag_name_str = '';
				tag_count = 0;
				var mediaTagNames = document.getElementById('mediaTagNames');
				var point_id = tagged_media[tags[0][fb_key]][0];
				for (var i in rmnPoints[point_id]['tags']) {
					if (tag_count < 2) {
						tag_name_str += '<fb:name uid="'+i+'" capitalize="true" linked="false"></fb:name>'+(!tag_count?', ':'');
						tag_count++;
					} else tag_count;
				}
				if (tag_name_str) mediaTagNames.innerHTML = tag_name_str;loadFBML(mediaTagNames);
			} catch (err) {}
		}
	}
	
	if (reshow_btn) {
		setTimeout("$('#"+reshow_btn+"').fadeIn('slow'); updateTaggedFilterHTML();", 5000);
		updateTaggedFilterHTML();
	}
}

function toggleSaveFBTags() {
	$.cookies.set("noTagPublish", document.getElementById('saveFBTags').checked?null:1);
}

function buildCanvasFunctionArgs(data_element) {
	var service = data_element.attr('service'),
		video_type = data_element.attr('video_type'),
		fn_args = {};

	if (service == 3) fn_args.service = service;
	if (video_type) fn_args.video_type = video_type;
	if (fn_args == {}) fn_args = '';

	return fn_args;
}

function moveDelegated(event) {
	var target = getEventTarget(event),
		parent = $(getParentElement(target)),
		id = parent.attr('media_id'),
		moveFn = (target.className == 'move_left_btn') ? moveCanvasItemLeft : moveCanvasItemRight,
		fn_args = buildCanvasFunctionArgs(parent);
	
	moveFn(id, fn_args, event);
}

function deleteDelegated(event) {
	var target = getEventTarget(event),
		parent = $(getParentElement(target)),
		id = parent.attr('media_id'),
		fn_args = buildCanvasFunctionArgs(parent);
	if (fn_args.video_type == 'yt') id = id.substr(0, id.length - 2);
	else if (fn_args.video_type == 'vim') id = id.substr(0, id.length - 3);
	if (fn_args.service == 3) id = id.replace('flickr', '');
	
	var target_args = target.getAttribute('args');
	if (target_args) fn_args = JSON.parse(target_args.replace(/'/g, '"'));
	removeCanvasItem(id, fn_args);
}

function delegateCanvasClick(event) {
	var target, class_name, no_btn_clicked;
	
	try {
		event = getEvent(event);
		target = getEventTarget(event);
		class_name = target.className;
	} catch(err) {}

	switch (class_name) {
		case "move_left_btn":
		case "move_right_btn":
			moveDelegated(event);
			break;
		case "delete_btn":
			deleteDelegated(event);
			break;
		case "play_btn":
			try {
				if (memoryCreationWizard.organizeActive) no_btn_clicked = 1;
			} catch(err) {}
			if (!no_btn_clicked) $(target).siblings('img').colorbox({'open':true});
			break;
		default:no_btn_clicked = 1;
	}
	
	try {
		// organize handling
		if (memoryCreationWizard.organizeActive) {
			if (no_btn_clicked) {
				var target_wrapper = target.parentNode;
				if (!target_wrapper.style.borderColor) {
					target_wrapper.style.borderColor = '#a9a9a9';
					memoryCreationWizard.organize_ids[target_wrapper.id] = 1;
				} else {
					target_wrapper.style.borderColor = '';
					delete memoryCreationWizard.organize_ids[target_wrapper.id];
				}
			}
			preventBubbling(event);
		}
	} catch(err) {}
}

function delegateCanvasMouseover(event) {
	return; //deprecated
	//if (!wizardMemoryData || (wizardMemoryData && segmentFlags.wizardShowContributeActive)) {
		var target = getEventTarget(event),
			tag = target.nodeName.toLowerCase(),
			buttons_to_show = '.delete_btn';
		preventBubbling(event);
	
		while (tag != 'td') {
			target = getParentElement(target);
			if (target != null) tag = target.nodeName.toLowerCase();
			else return;
		}
	
		if (!isLastChild(target)) buttons_to_show += ',.move_right_btn';
		if (!isFirstChild(target)) buttons_to_show += ',.move_left_btn';
	
		target = $(target);
		target.find(buttons_to_show).show();
	//}
}

function delegateCanvasMouseout(event) {
	return; //deprecated
	var target = getEventTarget(event),
		tag = target.nodeName.toLowerCase(),
		buttons_to_show = '.delete_btn,.move_right_btn,.move_left_btn';
	preventBubbling(event);

	while (tag != 'td') {
		target = getParentElement(target);
		if (target != null) tag = target.nodeName.toLowerCase();
		else return;
	}

	target = $(target);
	target.find(buttons_to_show).hide();
}

