var start_time, mid_point, dur1;

var first_chunk_loaded, current_chunk;
var chunk_delay = 100; // chunk display buffer delay in milliseconds
var chunk_size = 75; // size of initial chunk; size of display buffer
var large_chunk = 750; // secondary chunk size

var friendsRequested = 0;
function renderFriendPicker(retry, linked, friendListFQL) {
	if (!friendsRequested || retry) {
		var friend_list_div = document.getElementById('friend_selector');
		//if (friend_list_div) friend_list_div.style.display = 'block';
		
		// load user friend data
		start_time = new Date();
		/*api.friends_get(null, function(friends) {
			mid_point = new Date();
			dur1 = mid_point - start_time;
			writeToDebug('Time to load friend id array: '+dur1/1000+' s');
			var getUserInfoFQL = 'SELECT first_name, last_name, pic_square, email FROM user WHERE uid IN ('+friends.join(',')+')';
			//api.fql_query(getUserInfoFQL, loadFriendData);
			renderFriendData(friends);
			//api.users_getInfo(friends, ['first_name', 'last_name', 'pic_square', 'email'], loadFriendData);
		});*/
		
		current_letter = null;
		var friend_data = document.getElementById('friends');
		var alphabet_nav = document.getElementById('alphabet_nav');
		if (friendListFQL) {
			friend_list_filter = 1;
			friend_data = document.getElementById('friend_list');
			alphabet_nav = document.getElementById('friend_list_alpha_nav');
			friend_data.innerHTML = ''; alphabet_nav.innerHTML = ''; // flush friend list data divs
		} // only reload if friend widget doesn't contain friend data
		var loader_id = 'selector'; if (linked) loader_id = 'page'; // sets proper container width
		if (friend_data && !friend_data.getElementsByTagName('div').length) {
			//friend_data.innerHTML = '<br>Loading...';
			//friend_data.innerHTML = '<img src="'+TEMPLATE_VIEW_PATH+'images/loadingAnimation.gif" id="friend_'+loader_id+'_loader">';
			alphabet_nav.innerHTML = '';
			alphabet_nav.style.display = 'none';
			friend_data.style.marginRight = '21px';
			first_chunk_loaded = 0; current_chunk = chunk_size;
		}
		
		var friends_html, alpha_nav_html;
		if (session_vars.user == loggedInUser && !friendListFQL) {
			if (linked) {
				friends_html = session_vars.friends_linked_html;
				alpha_nav_html = session_vars.alpha_nav_linked_html;
			} else {
				friends_html = session_vars.friends_html;
				alpha_nav_html = session_vars.alpha_nav_html;
			}
		} else {
			// clear session vars on expired session
			session_vars.friends_linked_html = null;
			session_vars.alpha_nav_linked_html = null;
			session_vars.friends_html = null;
			session_vars.alpha_nav_html = null;
			commitSessionVars();
		}
		
		if (!friends_html) {
			var friends_query = friendListFQL;
			if (!friends_query) friends_query = 'SELECT uid2 FROM friend WHERE uid1 = \''+loggedInUser+'\'';
			var getFriendsFQL = 'SELECT uid, first_name, last_name, pic_square FROM user WHERE uid IN ('+friends_query+') ORDER BY lower(last_name) ASC LIMIT 0, '+chunk_size;
			api.fql_query(getFriendsFQL, (function (linked, friendListFQL) {return function(data, err) { loadFriendDataChunks(data, err, linked, friendListFQL) }}) (linked, friendListFQL));
		} else {
			friend_data.innerHTML = friends_html;
			if (!linked) toggleSelectedFriends();
			document.getElementById('friend_'+loader_id+'_loader').style.display = 'none';
			friend_data.style.marginRight = '0';
			alphabet_nav.innerHTML = alpha_nav_html;
			alphabet_nav.style.display = 'block';
			updateShownFriends();
		} friendsRequested = 1;
	}
}

function loadFriendDataChunks(user_friends, err, linked, friendListFQL) {
	if (user_friends) {
		var friend_chunks = new Array();
		
		// build chunks array
		for (var i=0; i<user_friends.length; i+=chunk_size) {
			friend_chunks.push(user_friends.slice(i, i+chunk_size));
		}
		
		// load chunks incrementally
		for (var i=0; i<friend_chunks.length; i++) {
			setTimeout(function(friend_data, linked, friendListFQL) { return function() { loadFriendData(friend_data, linked, friendListFQL); } } (friend_chunks[i], linked, friendListFQL), chunk_delay*i);
		}
		
		// loop until returned friend list chunk is empty
		if (user_friends.length) {
			var friends_query = friendListFQL;
			if (!friends_query) friends_query = 'SELECT uid2 FROM friend WHERE uid1 = \''+loggedInUser+'\'';
			var getFriendsFQL = 'SELECT uid, first_name, last_name, pic_square FROM user WHERE uid IN ('+friends_query+') ORDER BY lower(last_name) ASC LIMIT '+current_chunk+', '+large_chunk;
			api.fql_query(getFriendsFQL, (function(linked, friendListFQL) {return function(friends, err) {
				first_chunk_loaded = 1;
				current_chunk += large_chunk;
				
				if (friendListFQL) {
					document.getElementById('friends').style.display = 'none';
					document.getElementById('alphabet_nav').style.display = 'none';
					document.getElementById('friend_list_holder').style.display = 'block';
				} loadFriendDataChunks(friends, err, linked, friendListFQL);
			}}) (linked, friendListFQL));
		} else lastChunkLoaded(linked, friendListFQL);
	} else lastChunkLoaded(linked, friendListFQL);
}

function lastChunkLoaded(linked, friendListFQL) {
	// after the last chunk is loaded
	var friends_div = document.getElementById('friends');
	var alphabet_nav = document.getElementById('alphabet_nav');
	if (friendListFQL) {
		friends_div.style.display = 'none';
		alphabet_nav.style.display = 'none';
		document.getElementById('friend_list_holder').style.display = 'block';
		friends_div = document.getElementById('friend_list');
		alphabet_nav = document.getElementById('friend_list_alpha_nav');
	} var loader_id = 'selector'; if (linked) loader_id = 'page'; // sets proper container width
	document.getElementById('friend_'+loader_id+'_loader').style.display = 'none';
	if (!first_chunk_loaded) friends_div.innerHTML = 'No friends retrieved.';
	else { alphabet_nav.style.display = 'block'; friends_div.style.marginRight = '0'; }
	if (!linked) renderPhotoAlbums(); // determine whether to load the next section
	
	// store data in session var (only cache if there are friends)
	if (friends_div.getElementsByTagName('a').length > 0 && !friendListFQL) {
		if (linked) {
			session_vars.friends_linked_html = friends_div.innerHTML;
			session_vars.alpha_nav_linked_html = alphabet_nav.innerHTML;
		} else {
			session_vars.friends_html = friends_div.innerHTML.replace(/friend_row_selected/g, 'friend_row');
			session_vars.alpha_nav_html = alphabet_nav.innerHTML;
		} session_vars.user = loggedInUser;
		commitSessionVars();
	}
}

function hideFriendList() {
	document.getElementById('friends').style.display = '';
	document.getElementById('alphabet_nav').style.display = '';
	document.getElementById('friend_list_holder').style.display = 'none';
	friend_list_filter = null; updateShownFriends();
}

function loadUserGroups() {
	var getGroupsFQL = "SELECT gid, name, pic_small FROM group WHERE gid IN (SELECT gid FROM group_member WHERE uid = '"+loggedInUser+"')";
	api.fql_query(getGroupsFQL, function(data) {
		var user_groups_div = document.getElementById('you_were_with_user_groups');
		user_groups_div.innerHTML = '';
		if (data && data.length) {
			for (var i=0; i<data.length; i++) {
				var gid = data[i]['gid'];
				var name = data[i]['name'];
				var pic = data[i]['pic_small'];
				user_groups_div.innerHTML += '<a href="#" onClick="loadGroupMembers(\''+gid+'\'); return false;"><img src="'+pic+'" class="eventThumb" title="'+name+'" alt="'+name+'" style="margin:0 3px 3px 0"/></a>';
			}
		}
	});
}

function loadGroupMembers(gid) {
	var owner_id = getFid;
	if (!owner_id) owner_id = loggedInUser;
	var friendListFQL = "SELECT uid FROM group_member WHERE gid='"+gid+"' AND uid <> '"+owner_id+"'";
	renderFriendPicker(1, 0, friendListFQL);
}

function loadEventMembers(eid) {
	var owner_id = getFid;
	if (!owner_id) owner_id = loggedInUser;
	var friendListFQL = "SELECT uid FROM event_member WHERE eid='"+eid+"' AND rsvp_status='attending AND uid <> '"+owner_id+"'";
	renderFriendPicker(1, 0, friendListFQL);
}

function commitSessionVars() {
	var session_vars_str = JSON.stringify(session_vars);
	window.name = session_vars_str.substr(1,session_vars_str.length-2);
}

function clearSessionVars() {
	window.name = null;
}

var current_letter;
function loadFriendData(user_friends, linked, friendListFQL) {
	var friend_data = document.getElementById('friends');
	var alphabet_nav = document.getElementById('alphabet_nav');
	if (friendListFQL) {
		friend_data = document.getElementById('friend_list');
		alphabet_nav = document.getElementById('friend_list_alpha_nav');
	} var loader_id = 'selector'; if (linked) loader_id = 'page'; // sets proper container width
	document.getElementById('friend_'+loader_id+'_loader').style.display = 'none';
	if (first_chunk_loaded) {
		alphabet_nav.style.display = 'block';
		friend_data.style.marginRight = '0';
	} if (user_friends) {
		/*user_friends = shuffle(user_friends);
		user_friends = user_friends.slice(0,75);*/
		user_friends = user_friends.sort(sortByLastName);
		if (friend_data && !friend_data.getElementsByTagName('div').length) friend_data.innerHTML = '';
		for (var i=0; i<user_friends.length; i++) {
			/*if (i == 75) {
				setTimeout(loadFriendData, 100, user_friends.slice(75));
				break;
			}*/
			var friend = user_friends[i];
			var uid = friend['uid'];
			var first_name = friend['first_name'];
			var last_name = friend['last_name'];
			var email = friend['email'];
			var new_letter = last_name.charAt(0).toUpperCase();
			var profile_thumb = friend['pic_square'];
			// if (!profile_thumb) continue;
			
			if (current_letter != new_letter && new_letter.match(/[A-Z]/) && (!current_letter || current_letter < new_letter)) {
				current_letter = new_letter;
				if (alphabet_nav) {
					var alphabet_nav_link = document.createElement('div');
					alphabet_nav_link.innerHTML = '<a href="#'+new_letter+(friendListFQL?'2':'')+'" onClick="clearFriendFilter()">'+new_letter+'</a>';
					alphabet_nav.appendChild(alphabet_nav_link);
					//alphabet_nav += '<a href="#' +new_letter+ '">' +new_letter+ '</a><br>';
					var alphabet_nav_div = document.createElement('div');
					alphabet_nav_div.className = 'float_left';
					alphabet_nav_div.innerHTML = '<a name="'+new_letter+(friendListFQL?'2':'')+'"></a>';
					friend_data.appendChild(alphabet_nav_div);
					//friend_data += '<a name="' +new_letter+ '" style="float:left"><div></div></a>';
				}
			}
			
			var friend_link_div = document.createElement('a');
			if (!linked) {
				var friend_link_holder = document.createElement('div');
				friend_link_holder.innerHTML = '<a href="#" onclick="return toggleFromInviteList(\''+uid+'\')"></a>';
				friend_link_div = friend_link_holder.getElementsByTagName('a')[0];
				//friend_link_div.href = '#';
				//eval('friend_link_div.onclick = function() {return toggleFromInviteList("'+uid+'")}');
			} else {
				friend_link_div.href = '?p=f&fid='+uid; // link to user's page
				//eval('friend_link_div.onclick = function() {location.href = "?p=f&fid='+uid+'"}');
			} //friend_link_div.innerHTML = '<div id="friend_'+uid+'" class="friend_row"><div class="friend_row_img"><img src="'+profile_thumb+'" class="friend_thumb" title="'+first_name+" "+last_name+'"/></div><div class="friend_row_name"><a style="color:inherit">'+first_name+'<br/><b>'+last_name+'</b></a></div></div>';
			
			var friend_link_div_inner = document.createElement('div');
			friend_link_div_inner.id = 'friend_'+uid;
			friend_link_div_inner.className = 'friend_row';
			
			var friend_link_div_inner_img = document.createElement('div');
			friend_link_div_inner_img.className = 'friend_row_img';
			var img_click_handler = '';
			if (navigator.userAgent.indexOf("MSIE") != -1 && linked)
				img_click_handler = ' onclick="location.href=\''+friend_link_div.href+'\'"';
			
			var img_tag = '<img src="'+profile_thumb+'" class="friend_thumb" title="'+first_name+" "+last_name+'"'+img_click_handler+'/>';
			//if (linked) img_tag = '<a href="'+friend_link_div.href+'">'+img_tag+'</a>';
			friend_link_div_inner_img.innerHTML = img_tag;
			
			var friend_link_div_inner_name = document.createElement('div');
			friend_link_div_inner_name.className = 'friend_row_name';
			friend_link_div_inner_name.innerHTML = first_name+'<br/><b>'+last_name+'</b>';
			//friend_link_div_inner_name.innerHTML = '<a'+(linked?' href="'+friend_link_div.href+'"':'')+' style="color:inherit">'+first_name+'<br/><b>'+last_name+'</b></a>';
			
			friend_link_div_inner.appendChild(friend_link_div_inner_img);
			friend_link_div_inner.appendChild(friend_link_div_inner_name);
			friend_link_div.appendChild(friend_link_div_inner);
			
			//friend_link_div.innerHTML = '<div id="friend_'+uid+'" class="friend_row"><div class="friend_row_img"><fb:profile-pic uid="'+uid+'" linked="false" size="square" class="friend_thumb" title="'+first_name+" "+last_name+'" /></div><div class="friend_row_name"><a style="color:inherit">'+first_name+'<br/><b>'+last_name+'</b></a></div></div>';
			if (friend_data) friend_data.appendChild(friend_link_div);
			//friend_data += '<a href="#" onClick="return toggleFromInviteList(\''+uid+'\')"><div id="friend_'+uid+'" class="friend_row"><div class="friend_row_img"><img src="'+profile_thumb+'" class="friend_thumb" title="'+first_name+" "+last_name+'"/></div><div class="friend_row_name">'+first_name+"<br/><b>"+last_name+"</b></div></div></a>";
		}
		//document.getElementById('alphabet_nav').innerHTML = alphabet_nav;
		//document.getElementById('friends').innerHTML = friend_data;
	} else if (!first_chunk_loaded) {
		friend_data.innerHTML = 'Error retrieving data from Facebook. <a href="javascript:renderFriendPicker(1)">Retry</a>';
		alphabet_nav.innerHTML = '';
		//document.getElementById('friends').innerHTML = "Error retrieving data from Facebook.";
		//document.getElementById('alphabet_nav').innerHTML = "";
	}
	
	// highlight friend list based on current data
	if (!linked) toggleSelectedFriends();
	updateShownFriends(); // maintain updated friend search filter
	
	mid_point = new Date();
	dur1 = mid_point - start_time;
	writeToDebug('Time to load friend data: '+dur1/1000+' s');
}

/*function renderFriendData(friends) {
	var end_time = new Date();
	dur2 = end_time - mid_point;
	writeToDebug('Time to load friend data: '+dur2/1000+' s');
	if (friends) {
		var friend_data = '';
		for (var i=0; i<friends.length; i++) {
			var fid = friends[i]['uid'];
			var thumbnail = '';//'<fb:profile-pic size="square" uid="'+fid+'" class="friend_thumb"></fb:profile-pic>';
			var first_name = '<fb:name uid="'+fid+'" capitalize="true" firstnameonly="true" linked="false" />';
			var last_name = '<fb:name uid="'+fid+'" capitalize="true" lastnameonly="true" linked="false" />';
			var link_start = '<a href="#" onClick="return toggleFromInviteList(\''+fid+'\')">';
			friend_data += link_start+'<div id="friend_'+fid+'" class="friend_row"><div class="friend_row_img">'+thumbnail+'</div><div class="friend_row_name"><div>'+first_name+'</div><div><b>'+last_name+"</b></div></div></div></a>";
		}
		document.getElementById('friends').innerHTML = friend_data;
	} else {
		document.getElementById('friends').innerHTML = "Error retrieving data from Facebook.";
	} FB.XFBML.Host.parseDomElement(document.getElementById('friends'));
}*/

function loadRecommendations(data) {
	var events = data['event_invites'];
	/*data['friend_requests'];
	data['messages']['most_recent'];
	data['shares']['most_recent'];*/
}

function loadEventRecommendations(request_reload) {
	var location_list_div = document.getElementById('location_list');
	//if (location_list_div) location_list_div.style.display = 'block';
	var date_numeric;
	var event_date_field = document.getElementById('event_date');
	if (event_date_field) date_numeric = new Date(event_date_field.value).getTime() / 1000;
	else date_numeric = getSts;
	var start_time =  date_numeric + new Date().getTimezoneOffset()*60;
	var end_time = start_time + 24*60*60;
	
	// load event recommendations
	var readEventsFQL = 'SELECT eid, name, tagline, description, pic, start_time, end_time, location, venue FROM event WHERE (eid IN (SELECT eid FROM event_member WHERE uid=\'' +loggedInUser+ '\')) AND ((start_time >= ' +start_time+ ' AND start_time <= ' +end_time+ ') OR (end_time >= ' +start_time+ ' AND end_time <= ' +end_time+ ') OR (start_time <= ' +start_time+ ' AND end_time >= ' +end_time+ '))';
	api.fql_query(readEventsFQL, (function (request_reload) { return function (data, err) {eventRecommendationsLoaded(data, err, request_reload)} }) (request_reload));
	//if (event_date_field) event_date_field.disabled = true;
	toggleDateSelector();
	document.getElementById('event_suggestions').innerHTML = 'Loading event suggestions...<br><br>';
}

var event_suggestions_list = new Object();
function eventRecommendationsLoaded(data, err, request_reload) {
	if (friendsRequested) toggleSelectedFriends(); // if friends are loaded, highlight the ones in who you were with array
	else renderFriendPicker(); // start rendering friends right after event recommendations are loaded
	
	var event_date_field = document.getElementById('event_date');
	var event_suggestions_div = document.getElementById("event_suggestions");
	if (event_suggestions_div) event_suggestions_div.innerHTML = '';
	event_suggestions_list = new Object();
	var event_invites = document.getElementById('you_were_with_event_invites');
	event_invites.innerHTML = ''; // used to store list of event links for extracting participant list
	if (data && data.length) {
		for (var i=0; i<data.length; i++) {
			var eid = data[i]['eid'];
			
			var event_yes_filled = '';
			if (!request_reload) {
				// skip all events other than the saved one if night has already been saved (unless user requests reload)
				if (activeLocationId && fbEventId != eid) continue;
				
				// fill in radio button if event is the same as saved event
				if (fbEventId == eid) event_yes_filled = ' checked';
			}
			
			var name = escapeQuotes(data[i]['name']);
			var desc = escapeQuotes(data[i]['description']);
			desc = desc.replace(/\n/g, "\\n");
			if (!desc) desc = escapeQuotes(data[i]['tagline']);
			var pic = data[i]['pic'];
			var start_time = data[i]['start_time'];
			var end_time = data[i]['end_time'];
			var location = escapeQuotes(data[i]['location']);
			var venue = data[i]['venue'];
			if (venue) {
				var street = escapeQuotes(venue['street']);
				var city = escapeQuotes(venue['city']);
				var state = escapeQuotes(venue['state']);
				var country = escapeQuotes(venue['country']);
				var latitude = venue['latitude'];
				var longitude = venue['longitude'];
			}
			
			// store data for later use
			event_suggestions_list[eid] = {'name':name,'desc':desc,'start_time':start_time,'end_time':end_time,'location':location,'thumb':pic};
			
			// append event members link
			event_invites.innerHTML += '<a href="#" onClick="loadEventMembers(\''+eid+'\'); return false;"><img src="'+pic+'" class="eventThumb" title="'+name+'" alt="'+name+'" style="margin:0 3px 3px 0"/></a>';
			
			/*var link_start = '<a href="#" onClick="return loadEventDetails(\''+eid+'\', \''+name+'\', \''+desc+'\', \''+pic+'\', \''+location+'\')">';
			event_suggestions += link_start+'<img src="'+pic+'" class="friend_thumb"></a> '+link_start+name+'</a><br>';*/
			//var clickHandler = ' onClick="createLocation(\''+location+'\', 1); toggleEventRadioBtns('+eid+')"';
			var clickHandler = ' onClick="toggleEventRadioBtns(\''+eid+'\')"';
			var clickUnsetHandler = ' onClick="unsetEvent(\''+eid+'\')"';
			
			var event_item = document.createElement('div');
			var event_item_photo = document.createElement('div');
			var event_item_description = document.createElement('div');
			var event_item_selector = document.createElement('div');
			
			event_item.className = "event";
			event_item_photo.className = "eventPhoto";
			event_item_description.className = "eventDescription";
			event_item_selector.className = "eventSelector";
			
			event_item.appendChild(event_item_photo);
			event_item.appendChild(event_item_description);
			event_item.appendChild(event_item_selector);
			event_suggestions_div.appendChild(event_item);
			
			event_item_photo.innerHTML = '<img src="'+pic+'" class="eventThumb"/>';
			event_item_description.innerHTML = name;
			event_item_selector.innerHTML = '<input type="radio" name="event_'+eid+'" id="event_'+eid+'_yes"'+clickHandler+event_yes_filled+'><label for="event_'+eid+'_yes"'+clickHandler+'>Yes</label> <input type="radio" name="event_'+eid+'" id="event_'+eid+'_no"'+clickUnsetHandler+'><label for="event_'+eid+'_no"'+clickUnsetHandler+'>No</label>';
		}
	} else if (event_suggestions_div) event_suggestions_div.innerHTML = 'No event suggestions for this date.';
	/*var userAddedLocation = document.createElement('div');
	userAddedLocation.setAttribute("class","userAddedLocation");
	userAddedLocation.innerHTML = '<form id="submit_segment" onsubmit="return createLocation()">Enter Location: <input id="event_location" onKeyUp="checkLocationChanged();mirrorLocationValue();"'+(activeLocation? ' value="'+activeLocation+'"':'')+'><br><span style="font-size: 12px;">e.g. Brooklyn, Ronnie\'s Apartment, 1501 Broadway, etc.</span></form>';
	if (event_suggestions_div) event_suggestions_div.appendChild(userAddedLocation);*/
	var event_location_field = document.getElementById('event_location');
	if (event_location_field && activeLocation) event_location_field.value = activeLocation;
	//if (event_date_field) event_date_field.disabled = false;
	updateSavedNightInfo('location');
	toggleDateSelector(1);
}

var fbEventId = '';
function toggleEventRadioBtns(activeEid) {
	if (fbEventId != activeEid) {
		fbEventId = activeEid;
		for (var i in event_suggestions_list) {
			var eid = i;
			if (eid != activeEid) {
				document.getElementById('event_'+eid+'_yes').checked = false;
				document.getElementById('event_'+eid+'_no').checked = true;
			}
		} activeLocationChanged = true;
		var event_location_field = document.getElementById('event_location');
		var fb_event_name = event_suggestions_list[fbEventId]['name'];
		if (event_location_field && fb_event_name) {
			event_location_field.value = unescapeQuotes(fb_event_name);
			mirrorLocationValue();
		} updateSavedNightInfo('location');
		var stream_items_exist = document.getElementById('user_news_feed').childNodes.length;
		if (stream_items_exist) toggleSaveNightBtn();
	}
}

function unsetEvent(unsetEid) {
	if (fbEventId == unsetEid) {
		fbEventId = '';
		activeLocationChanged = true;
		updateSavedNightInfo('location');
		var stream_items_exist = document.getElementById('user_news_feed').childNodes.length;
		if (stream_items_exist) toggleSaveNightBtn();
	}
}

function loadEventDetails(eid, name, desc, pic, location) {
	document.getElementById('event_name').value = name;
	document.getElementById('event_desc').value = desc;
	document.getElementById('event_location').value = location;
	document.getElementById('new_custom_log_location').value = location;
	
	var readEventMembersFQL = 'SELECT uid from event_member where eid = ' + eid;
	api.fql_query(readEventMembersFQL, loadEventMemberRecommendations);
	return false;
}


function loadEventMemberRecommendations(data) {
	data[0]['uid'];
}

var activeLocation = ''; var activeLocationChanged = false;
function checkLocationChanged() {
	if (activeLocationChanged) return true;
	var currentLocation = document.getElementById('event_location');
	if (currentLocation) currentLocation = currentLocation.value;
	if (activeLocation != currentLocation) {
		activeLocationChanged = true;
		var stream_items_exist = document.getElementById('user_news_feed').childNodes.length;
		if (stream_items_exist) toggleSaveNightBtn();
	} else activeLocationChanged = false;
}

function mirrorLocationValue() {
	document.getElementById('new_custom_log_location').value = document.getElementById('event_location').value;
	updateSavedNightInfo('location');
}

function loadAlbumRecommendations(albums, album_covers, album_div) {
	var album_thumbs_html = '<div id="'+album_div+'_album0_title_div" class="album_title_div section_header normal_case" title="Tagged Photos"><div class="closedFolder" id="'+album_div+'_album0_state" onClick="toggle_show_album(\'0\', \''+album_div+'\')"></div><div class="album_title" onClick="toggle_show_album(\'0\', \''+album_div+'\')">&nbsp;Tagged Photos</div></div><div id="'+album_div+'_album_0" class="album_photos_div"></div>';
	
	// load tagged photo albums after div gets created
	// has room for code optimization
	/*if (album_div == 'period')
		api.fql_query(getPeriodPhotosFQL, function(photos) {loadTaggedPhotoRecommendations(photos, 'period')});
	else */ if (album_div == 'all')
		api.fql_query(getAllPhotosFQL, function(photos) {loadTaggedPhotoRecommendations(photos, 'all')});
	
	var orderedAlbumPhotos = new Array();
	if (albums) {
		for (var i=0; i<albums.length; i++) {
			var album_id = albums[i]['aid'];
			var album_name = escapeQuotes(albums[i]['name']);
			// for some reason fb is returning the name for this album as a blank object
			if (!album_name) album_name = "Profile Pictures";
			var album_created = albums[i]['created'];
			if (album_covers[i]) var album_cover = album_covers[i]['src_small'];
			var album_modified = albums[i]['modified'];
			var album_location = albums[i]['location'];
			var album_link = albums[i]['link'];
			var cover_pid = albums[i]['cover_pid'];
			
			var clickHandler = ' onClick="toggle_show_album(\''+(i+1)+'\', \''+album_div+'\')"';
			album_thumbs_html += '<div id="'+album_div+'_album'+(i+1)+'_title_div" class="album_title_div section_header normal_case" title="'+album_name+'"><div class="closedFolder" id="'+album_div+'_album'+(i+1)+'_state"'+clickHandler+'></div><div class="album_title"'+clickHandler+'>&nbsp;'+album_name+'</div>';
			if (album_name != "Profile Pictures" && album_name != "Wall Photos" && album_name != "Mobile Uploads" && album_name != "Webcam Photos") album_thumbs_html += '<div class="float_right"><a href="#" onClick="return addToValidationList(this, \'album\')" media_id="'+album_id+'" album_name="'+album_name+'" src="'+album_cover+'" album_url="'+album_link+'" cover_pid="'+cover_pid+'" created="'+album_created+'">+ add album</a></div>';
			album_thumbs_html += '</div><div id="'+album_div+'_album_'+(i+1)+'" class="album_photos_div"></div>';
			
			// display album pictures in order by album
			var getPhotosFQL = 'SELECT pid, aid, owner, src, src_big, src_small, link, caption, created, modified FROM photo WHERE aid = \''+album_id+'\'';
			if (album_div != 'all') getPhotosFQL += ' AND created > '+night_search_start+' AND created < '+night_search_end;
			getPhotosFQL += ' ORDER BY created DESC';
			orderedAlbumPhotos[i] = api.fql_query(getPhotosFQL, (function(album_div, album_div_id) {
				return function(data) { loadPhotoRecommendations(data, album_div, album_div_id); }
			}) (album_div, (i+1)));
		}
	} document.getElementById('user_'+album_div+'_albums').innerHTML = album_thumbs_html;
	toggle_show_album('0', 'all');
	
	// load album covers
	//api.photos_get(null, null, album_cover_ids, function (photos) { loadPhotoAlbumCovers(photos, album_div)} );
}

var current_period_album_id, current_month_album_id, current_all_album_id;
function loadPhotoRecommendations(photos, album_div, album_div_id) {
	/*var current_album_id;
	if (album_div == "period") current_album_id = current_period_album_id;
	else if (album_div == "month") current_album_id = current_month_album_id;
	else current_album_id = current_all_album_id;*/
	if (photos && photos.length) {
		for (var i=0; i<photos.length; i++) {
			var photo_id = photos[i]['pid'];
			var photo_owner = photos[i]['owner'];
			var photo_thumb = photos[i]['src'];
			var photo_date = photos[i]['created']*1000;
			var photo_caption = photos[i]['caption'];
			var photo_thumb_big = photos[i]['src_big'];
			var album_photo_holder = document.createElement('div');
			album_photo_holder.className = 'photo_thumb_holder';
			var album_photo = document.createElement('img');
			album_photo.className = 'photo_thumb';
			album_photo.id = 'm'+photo_id;
			album_photo.src = photo_thumb;
			album_photo.setAttribute('src_big', photo_thumb_big);
			album_photo.setAttribute('created', photo_date);
			album_photo.setAttribute('media_id', photo_id);
			album_photo.setAttribute('media_type', 1);
			
			album_photo.alt = photo_caption;
			album_photo.title = photo_caption;
			album_photo.setAttribute('caption', photo_caption);
			album_photo.setAttribute('owner', photo_owner);
			album_photo.onclick = function() { addToValidationList(this, "image") }
			album_photo_holder.appendChild(album_photo);
			document.getElementById(album_div+'_album_'+album_div_id).appendChild(album_photo_holder);
		}
		
		// highlight saved media
		for (var i in photosSelectedArray) {
			processMediaId(photosSelectedArray[i][0], photosSelectedArray, i, photosSelectedArray[i][1]);
		}
		
		/*if (album_div == "period") current_period_album_id++;
		else if (album_div == "month") current_month_album_id++;
		else current_all_album_id++;*/
	} else if (document.getElementById(album_div+'_album'+album_div_id+'_title_div'))
		document.getElementById(album_div+'_album'+album_div_id+'_title_div').style.display = 'none';
}

function loadTaggedPhotoRecommendations(photos, album_div) {
	if (photos && photos.length) {
		//document.getElementById(album_div+'_album0_cover').src = photos[0]['src'];
		for (var i=0; i<photos.length; i++) {
			var photo_id = photos[i]['pid'];
			var photo_owner = photos[i]['owner'];
			var photo_thumb = photos[i]['src'];
			var photo_date = photos[i]['created']*1000;
			var photo_caption = photos[i]['caption'];
			var photo_thumb_big = photos[i]['src_big'];
			var album_photo_holder = document.createElement('div');
			album_photo_holder.className = 'photo_thumb_holder';
			var album_photo = document.createElement('img');
			album_photo.className = 'photo_thumb';
			album_photo.id = 'm'+photo_id;
			album_photo.src = photo_thumb;
			album_photo.setAttribute('src_big', photo_thumb_big);
			album_photo.setAttribute('media_id', photo_id);
			album_photo.setAttribute('created', photo_date);
			
			album_photo.alt = photo_caption;
			album_photo.title = photo_caption;
			album_photo.setAttribute('caption', photo_caption);
			album_photo.setAttribute('owner', photo_owner);
			album_photo.onclick = function() { addToValidationList(this, "image") }
			album_photo_holder.appendChild(album_photo);
			document.getElementById(album_div+'_album_0').appendChild(album_photo_holder);
		}
		
		// highlight saved media
		for (var i in photosSelectedArray) {
			processMediaId(photosSelectedArray[i][0], photosSelectedArray, i, photosSelectedArray[i][1]);
		}
	} else if (document.getElementById(album_div+'_album0_title_div'))
		document.getElementById(album_div+'_album0_title_div').style.display = 'none';
}

var list_unique_id = '';
function addToValidationList(obj, type) {
	if (type == "image") {
		var photo_date = parseInt(obj.getAttribute('created'),10)+new Date().getTimezoneOffset()*60;
		var photo_id = obj.getAttribute('media_id');
		
		if (!obj.style.borderColor) {
			var photo_owner = obj.getAttribute('owner');
			var photo_caption = obj.getAttribute('caption');
			var photo_thumb = obj.src;
			var photo = obj.getAttribute('src_big');
			var time_input = document.getElementById('list_time_input');
			var photo_input = document.getElementById('list_photo');
			var desc_input = document.getElementById('list_desc_input');
			time_input.value = getFormattedTime(photo_date, 1);
			desc_input.value = photo_caption;
			photo_input.src = photo_thumb;
			photo_input.setAttribute('src_big', photo);
			photo_input.setAttribute('media_id', photo_id);
			photo_input.setAttribute('owner', photo_owner);
			addCustomLogEntry(1); // automatically add to log
		}
	} else if (type == "video") {
		var video_date = getFormattedTime(parseInt(obj.getAttribute('created'),10)+new Date().getTimezoneOffset()*60, 1);
		var video_id = obj.getAttribute('media_id');
		
		if (!obj.style.borderColor) {
			var video_owner = obj.getAttribute('owner');
			var video_caption = obj.getAttribute('caption');
			var video_thumb = obj.src;
			var video_url = obj.getAttribute('video_url');
			var video_width = obj.getAttribute('video_width');
			var video_height = obj.getAttribute('video_height');
			document.getElementById('video_time_input').value = video_date;
			document.getElementById('video_desc_input').value = video_caption;
			var video_thumb_obj = document.getElementById('list_video');
			video_thumb_obj.src = video_thumb;
			video_thumb_obj.setAttribute('video_url', video_url);
			video_thumb_obj.setAttribute('video_width', video_width);
			video_thumb_obj.setAttribute('video_height', video_height);
			video_thumb_obj.setAttribute('media_id', video_id);
			video_thumb_obj.setAttribute('owner', video_owner);
			addCustomLogEntry(2); // automatically add to log
		}
	} else if (type == "album") {
		var cover_pid = obj.getAttribute('cover_pid');
		var album_thumb = document.getElementById('m'+obj.getAttribute('cover_pid'));
		if (album_thumb) var album_point_id = album_thumb.getAttribute('pointId');
		if (!album_point_id) {
			var album_date = getFormattedTime(parseInt(obj.getAttribute('created'), 10)+new Date().getTimezoneOffset()*60, 1);
			var album_id = obj.getAttribute('media_id');
			var album_caption = obj.getAttribute('album_name');
			var album_thumb = obj.getAttribute('src');
			var album_url = obj.getAttribute('album_url');
			document.getElementById('list_time_input').value = album_date;
			document.getElementById('list_desc_input').value = album_caption;
			var album_thumb_obj = document.getElementById('list_photo');
			album_thumb_obj.src = album_thumb;
			album_thumb_obj.setAttribute('album_url', album_url);
			album_thumb_obj.setAttribute('media_id', album_id);
			album_thumb_obj.setAttribute('cover_pid', cover_pid);
			addCustomLogEntry(6); // add to log
		}
	}
	
	if (night_search_start) {
		var is_video; if (type == 'video') is_video = 1;
		var thumbnail_obj = obj;
		if (type == "album") thumbnail_obj = document.getElementById('m'+cover_pid);
		if (thumbnail_obj) {
			if (!thumbnail_obj.style.borderColor) highlightMedia(thumbnail_obj, null, is_video);
			else highlightMedia(thumbnail_obj, 1, is_video);
		}
	}
	
	return false;
}

function highlightMedia(obj, unhighlight, video) {
	var mediaType = 'photo'; if (video) mediaType = 'video'; // retrieve the proper strip
	var film_strip_row = document.getElementById(mediaType+'_film_strip').getElementsByTagName('table')[0].getElementsByTagName('tr')[0];
	if (unhighlight) {
		obj.style.borderColor = '';
		
		// remove thumbnail from film strip
		var film_strip_thumb = document.getElementById(obj.id+'_strip_thumb');
		if (film_strip_thumb) film_strip_row.removeChild(film_strip_thumb);
		
		var pointId = obj.getAttribute('pointId');
		if (pointId) {
			var pointDiv = document.getElementById(pointId);
			if (pointDiv) {
				var activatorElement = pointDiv.getElementsByTagName('a');
				activatorElement = activatorElement[activatorElement.length - 3];
				if (activatorElement.parentNode.className == 'pointDelete') {
					if (activatorElement.getAttribute('onclick').toString().indexOf('(this)') == -1)
						removeStreamItemFromStream(activatorElement, 1);
					else removeStreamItemFromStream(activatorElement);
				}
			} obj.removeAttribute('pointId');
		}
	} else if (!obj.style.borderColor) {
		obj.style.borderColor = '#CBEAED';
		
		// add to film strip
		var film_strip_photo = document.createElement('td');
		film_strip_photo.id = obj.id+"_strip_thumb";
		film_strip_photo.innerHTML = '<img src="'+obj.src+'" class="film_strip_photo" onClick="'+(video? 'embedVideo(\''+obj.getAttribute('video_url')+'\')':'photoCanvas.surfaceImage(\''+obj.id.substr(1)+'\')')+'" alt="'+obj.alt+'" title="'+obj.title+'">'+'<img src="'+TEMPLATE_VIEW_PATH+'images/remove.png" class="film_strip_rm" onClick="highlightMedia(document.getElementById(\''+obj.id+'\'), 1'+(video?', 1':'')+')">';
		film_strip_row.appendChild(film_strip_photo);
		
		// add to highlighted media array
		var selectedItem = [obj.id.substr(1), null];
		if (!video) photosSelectedArray.push(selectedItem);
		else videosSelectedArray.push(selectedItem);
	}
}

function highlightYoutubeThumb(media_id, yt_video_thumb, yt_link, point_id, not_owned) {
	var media_thumb = document.getElementById('m'+media_id);
	if (!media_thumb && !not_owned) { // only create img obj if point was added by owner of night
		var thumbnail_obj = document.createElement('img');
		thumbnail_obj.id = 'm'+media_id;
		thumbnail_obj.src = yt_video_thumb;
		thumbnail_obj.setAttribute('video_url', yt_link);
		var media_type = 10;
		if (yt_link.indexOf('vimeo') != -1) media_type = 11;
		thumbnail_obj.setAttribute('media_type', media_type);
		document.getElementById('ghost_div').appendChild(thumbnail_obj);
		media_thumb = thumbnail_obj;
	} if (media_thumb && point_id) media_thumb.setAttribute('pointId', point_id);
	// don't add the same thumbnail again if it's already added
	if (!document.getElementById('m'+media_id+'_night_strip_thumb')) {
		addToSavedNightStrip(media_id, yt_video_thumb, yt_link);
		// only add to owner strip if creator is logged in user
		if (media_thumb && !not_owned) highlightMedia(media_thumb, null, 1);
	} else return false;
	return true;
}

function removeAutoplay(url) {
	if (url) return url.replace('&autoplay=1','');
	else return '';
}

function removeSuggestion(sid) {
	if (!sid) sid = '';
	document.getElementById('suggestions_list').removeChild(document.getElementById('suggestion'+sid));
	return false;
}

function loadPhotoAlbumCovers(photos, album_div) {
	if (photos && photos.length) {
		for (var i=0; i<photos.length; i++)
			document.getElementById(album_div+'_album'+(i+1)+'_cover').src = photos[i]['src'];
	} renderUserVideos();
}

var search_period_end, search_month_end;
var getPeriodPhotosFQL, getAllPhotosFQL;
var photoAlbumsRequested = 0, allAlbumsRequested = 0;
function renderPhotoAlbums() {
	if (!photoAlbumsRequested) {
		//current_period_album_id = 1;
		//current_month_album_id = 1;
		current_all_album_id = 1;
		search_period_end = night_search_start + 10*24*60*60;
		search_month_end = search_period_end + 20*24*60*60;
		
		var getAlbumsFQL = 'SELECT aid, cover_pid, owner, name, created, modified, description, location, link, size, visible FROM album WHERE owner=\''+loggedInUser+'\'';
		var getPhotosFQL = 'SELECT pid, aid, owner, src, src_big, src_small, link, caption, created, modified FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject="'+loggedInUser+'") AND owner != \''+loggedInUser+'\'';
		var getAlbumsFQLTail = ' AND modified > '+night_search_start;
		var getPhotosFQLTail = ' AND created > '+night_search_start+' AND created < ';
		var FQLTail = ' ORDER BY created DESC';
		var FQLTailDesc = ' ORDER BY modified DESC';
		//var getPeriodAlbumsFQL = getMonthAlbumsFQL = getAlbumsFQL+getAlbumsFQLTail+FQLTail;
		var getAllAlbumsFQL = getAlbumsFQL+FQLTailDesc;
		//getPeriodPhotosFQL = getPhotosFQL+getPhotosFQLTail+search_period_end+FQLTail;
		//var getMonthPhotosFQL = getPhotosFQL+getPhotosFQLTail+search_month_end+FQLTail;
		getAllPhotosFQL = getPhotosFQL+FQLTail;
		
		/*api.fql_query(getPeriodAlbumsFQL, function(albums) {loadAlbumRecommendations(albums, 'period')});
		api.fql_query(getMonthAlbumsFQL, function(albums) {loadAlbumRecommendations(albums, 'month')});
		api.fql_query(getMonthPhotosFQL, function(photos) {loadTaggedPhotoRecommendations(photos, 'month')});*/
		//if (!allAlbumsRequested) api.fql_query(getAllAlbumsFQL, function(albums) {loadAlbumRecommendations(albums, 'all')});
		if (!allAlbumsRequested) {
			var getAllAlbumsFQL = {
				'albums':getAllAlbumsFQL,
				'album_covers':'SELECT src_small FROM photo WHERE pid IN (SELECT cover_pid FROM #albums)'
			}
			
			api.callMethod('fql_multiquery', {queries:getAllAlbumsFQL}, function(albums) {
				if (albums) loadAlbumRecommendations(albums[0]['fql_result_set'], albums[1]['fql_result_set'], 'all')
			});
		} allAlbumsRequested = 1;
		
		for (var i in friend_invite_list) {
			var friend_album_toggler = document.createElement('img');
			friend_album_toggler.className = 'pointPhoto';
			friend_album_toggler.src = friend_invite_list[i];
			friend_album_toggler.alt = friend_invite_list[i];
			friend_album_toggler.title = friend_invite_list[i];
			friend_album_toggler.onclick = toggleUserPhotos(friend_invite_list[i]);
		}
		
		for (var i in friend_invite_list) {
			var friend_album_div = document.createElement('div');
			friend_album_div.id = 'f'+friend_invite_list[i]+'_albums';
			friend_album_div.innerHTML = friend_album_div.id;
			friend_album_div.style.display = 'none';
			friend_album_div.style.clear = 'both';
		}
		
		photoAlbumsRequested = 1;
	}
}

var userVideosRequested = 0;
function renderUserVideos() {
	if (!userVideosRequested) {
		var getAllVideosFQL = 'SELECT vid, owner, title, description, thumbnail_link, embed_html, created_time FROM video WHERE owner=\''+loggedInUser+'\' OR vid IN (SELECT vid FROM video_tag WHERE subject=\''+loggedInUser+'\') ORDER BY created_time DESC';
		api.fql_query(getAllVideosFQL, loadVideoRecommendations);
		userVideosRequested = 1;
	}
}

function extractFbVideoUrl(video_url) {
	var re = /<embed src="([^"]+)"[^>]+>/g;
	video_url = re.exec(video_url);
	video_url = video_url[1] // extract video url
	re.lastIndex = 0; // reset lastIndex for next iteration
	return video_url;
}

function extractFbVideoSize(embed_html) {
	//var re = /<[^>]+width="?([^"]+)"?\s+height="?([^"]+)"?[^>]*>/g;
	var re = new RegExp('<[^>]+width="?([^"]+)"?\\s+height="?([^"]+)"?[^>]*>', 'g');
	var video_size = re.exec(embed_html); // extract video dimensions
	if (video_size) {
		var embed_width = video_size[1];
		var embed_height = video_size[2];
		return [embed_width, embed_height];
	} re.lastIndex = 0; // reset lastIndex for next iteration
	return null;
}

function loadVideoRecommendations(videos) {
	var video_selector = document.getElementById('video_thumbs_selector');
	if (videos && videos.length) {
		video_selector.innerHTML = '';
		for (var i=0; i<videos.length; i++) {
			var video_url = extractFbVideoUrl(videos[i]['embed_html']);
			var video_size = extractFbVideoSize(videos[i]['embed_html']);
			var video_id = videos[i]['vid'];
			var video_owner = videos[i]['owner'];
			var video_thumb = videos[i]['thumbnail_link'];
			var video_date = videos[i]['created_time']*1000;
			var video_caption = videos[i]['title'];
			var video_thumb_holder = document.createElement('div');
			video_thumb_holder.className = 'photo_thumb_holder';
			var video_thumb_obj = document.createElement('img');
			
			video_thumb_obj.id = 'm'+video_id;
			video_thumb_obj.className = 'photo_thumb';
			video_thumb_obj.src = video_thumb;
			video_thumb_obj.setAttribute('created', video_date);
			video_thumb_obj.setAttribute('video_url', video_url);
			if (video_size) {
				video_thumb_obj.setAttribute('video_width', video_size[0]);
				video_thumb_obj.setAttribute('video_height', video_size[1]);
			} video_thumb_obj.setAttribute('media_id', video_id);
			video_thumb_obj.setAttribute('media_type', 2);
			
			video_thumb_obj.alt = video_caption;
			video_thumb_obj.title = video_caption;
			video_thumb_obj.setAttribute('caption', video_caption);
			video_thumb_obj.setAttribute('owner', video_owner);
			video_thumb_obj.onclick = function() { addToValidationList(this, "video") }
			
			video_thumb_holder.appendChild(video_thumb_obj);
			video_selector.appendChild(video_thumb_holder);
		}
		
		// highlight saved media
		for (var i in videosSelectedArray) {
			processMediaId(videosSelectedArray[i][0], videosSelectedArray, i, videosSelectedArray[i][1]);
		}
	} else video_selector.innerHTML = "No videos available.";
}

var updateTimezone;
function timezoneModified() {
	updateTimezone = 1;
	setLocalTimezone();
	confirmTimezone('local_timezone');
	confirmTimezone('new_custom_log_timezone');
	updateSavedNightInfo();
	toggleSaveNightBtn();
}

function changeTimezone(dropdownId) {
	document.getElementById(dropdownId).style.display = 'inline';
	document.getElementById(dropdownId+'_display').style.display = 'none';
	return false;
}

function confirmTimezone(dropdownId) {
	var dropdownElem = document.getElementById(dropdownId);
	var dropdownDisplay = document.getElementById(dropdownId+'_display');
	if (dropdownId == 'new_custom_log_timezone') updateTimezoneDisplay(dropdownId);
	dropdownElem.style.display = '';
	dropdownDisplay.style.display = '';
}

function updateTimezoneDisplay(dropdownId) {
	document.getElementById(dropdownId+'_display').innerHTML = offsetToGMTStr(document.getElementById(dropdownId).value).substr(1);
}

var default_fb_thumb = TEMPLATE_VIEW_PATH+'images/fb_default.gif';
function loadUserFriendSample() {
	var getFriendsFQL = 'SELECT uid2 FROM friend WHERE uid1 = \''+loggedInUser+'\'';
	api.fql_query(getFriendsFQL, function(data) {
		if (data && data.length) {
			data = shuffle(data);
			data = data.slice(0,6);
			for (var i=0; i<data.length; i++) {
				data[i] = data[i]['uid2'];
			} var frd_str = "'"+data.join("','")+"'";
			var getFriendsFQL = 'SELECT uid, first_name, last_name, pic_square FROM user WHERE uid IN ('+frd_str+')';
			api.fql_query(getFriendsFQL, function(data) {
				if (data) {
					var friends_html = '';
					for(var i=0; i<data.length; i++) {
						var friend_thumb = data[i]['pic_square'];
						if (!friend_thumb) friend_thumb = default_fb_thumb;
						var friend_name = data[i]['first_name']+" "+data[i]['last_name'];
						
						friends_html += '<div class="fbFriendHolder"><a href="?p=f&fid='+data[i]['uid']+'"><img src="'+friend_thumb+'" class="fbFriend" alt="'+friend_name+'" title="'+friend_name+'"></a></div>';
						if ((i+1)%3 == 0) friends_html += '<div class="clear"></div>';
					}
					document.getElementById('rotate_friends').innerHTML = friends_html;
				}
			});
		}
	});
}

function loadLatestUploads() {
	var getLatestPhotosFQL = {
		'tagged':'SELECT pid, aid, owner, src, src_big, src_small, link, caption, created, modified FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject=\''+loggedInUser+'\') ORDER BY created DESC LIMIT 3',
		'album_pics':'SELECT pid, aid, owner, src, src_big, src_small, link, caption, created, modified FROM photo where aid IN (SELECT aid FROM album where owner=\''+loggedInUser+'\') ORDER BY created DESC LIMIT 3'
	};
	
	api.callMethod('fql_multiquery', {queries:getLatestPhotosFQL}, function(photos) {
		if (photos) {
			var tagged_photos = photos[0]['fql_result_set'];
			var album_photos = photos[1]['fql_result_set'];
			var uploads_html = ''; var total_added = 0;
			
			for (var i=0; i<tagged_photos.length; i++) {
				var img_created = tagged_photos[i]['created']*1000;
				var img_desc = tagged_photos[i]['caption'];
				img_desc = getFormattedDate(img_created) + (img_desc? ' - ' + img_desc : '');
				uploads_html += '<img src="'+tagged_photos[i]['src_small']+'" class="fbMedia" alt="'+img_desc+'" title="'+img_desc+'" onClick="populateDate('+img_created+')">';
				total_added++;
				if (total_added%3 == 0) uploads_html += '<br>';
			}
			
			for (var i=0; i<album_photos.length; i++) {
				var img_created = album_photos[i]['created']*1000;
				var img_desc = album_photos[i]['caption'];
				img_desc = getFormattedDate(img_created) + (img_desc? ' - ' + img_desc : '');
				uploads_html += '<img src="'+album_photos[i]['src_small']+'" class="fbMedia" alt="'+img_desc+'" title="'+img_desc+'" onClick="populateDate('+img_created+')">';
				total_added++;
				if (total_added%3 == 0) uploads_html += '<br>';
			}
		} if (uploads_html) document.getElementById('latest_uploads').innerHTML = uploads_html;
	});
}

var recent_events, current_event;
function loadLatestEvents() {
	// load recent events
	var readEventsFQL = 'SELECT eid, name, tagline, description, pic, start_time, end_time, location, venue, creator, hide_guest_list FROM event WHERE (eid IN (SELECT eid FROM event_member WHERE uid=\'' +loggedInUser+ '\')) AND start_time < '+parseInt(new Date().getTime()/1000, 10)+' ORDER BY start_time DESC LIMIT 30';
	readEventsFQL = {
		'events':readEventsFQL
		//'creators':'SELECT name FROM user WHERE uid IN (SELECT creator FROM #events)'
	};
	
	api.callMethod('fql_multiquery', {queries:readEventsFQL}, function(events) {
		var num_events;
		if (events && events.length) {
			num_events = events[0]['fql_result_set'].length;
			if (num_events > 0) {
				recent_events = new Array();
				for (var i=num_events-1; i>=0; i--) {
					var event_name = events[0]['fql_result_set'][i]['name'];
					var start_time = events[0]['fql_result_set'][i]['start_time'];
					var event_thumb = events[0]['fql_result_set'][i]['pic'];
					var creator = events[0]['fql_result_set'][i]['creator'];
					recent_events.push({'event_name':event_name,'start_time':start_time,'event_thumb':event_thumb,'creator':creator});
				} current_event = num_events-1; // set the current event to the last (most recent) event
				displayEvent(current_event);
			} if (!num_events) {
				num_events = 0;
				var recent_events_status = document.getElementById('recent_events_status');
				if (recent_events_status) {
					recent_events_status.style.backgroundImage = 'none';
					recent_events_status.innerHTML = 'No recent events.';
				}
			} var recent_events_count = document.getElementById('recent_events_count');
			if (recent_events_count) recent_events_count.innerHTML = num_events;
		}
	});
}

function loadUserEvents() {
	var query_utc_start = new Date(query_year, 0, 1, 0, 0, 0, 0);
	query_utc_start = parseInt(query_utc_start.getTime()/1000, 10);
	var query_utc_end = query_utc_start+356*24*60*60;
	
	// load user events
	var readEventsFQL = 'SELECT eid, name, tagline, description, pic, start_time, end_time, location, venue, creator, hide_guest_list FROM event WHERE (eid IN (SELECT eid FROM event_member WHERE uid=\'' +loggedInUser+ '\')) AND start_time >= '+query_utc_start+' AND end_time <= '+query_utc_end+' ORDER BY start_time DESC';
	
	readEventsFQL = {
		'events':readEventsFQL
		//'creators':'SELECT name FROM user WHERE uid IN (SELECT creator FROM #events)'
	}
	
	api.callMethod('fql_multiquery', {queries:readEventsFQL}, function(events) {
		var events_empty = document.getElementById('events_empty');
		var events_main = document.getElementById('events_main');
		if (events && events.length) {
			var num_events = events[0]['fql_result_set'].length;
			if (num_events > 0) {
				for (var i=0; i<num_events; i++) {
					var event_name = events[0]['fql_result_set'][i]['name'];
					var start_time = events[0]['fql_result_set'][i]['start_time'];
					start_time = start_time - new Date(start_time*1000).getTimezoneOffset()*60; // adjust by current timezone
					var event_thumb = events[0]['fql_result_set'][i]['pic'];
					var creator = //events[1]['fql_result_set'][i]? events[1]['fql_result_set'][i]['name'] :
						'<fb:name uid="'+events[0]['fql_result_set'][i]['creator']+'" linked="false" useyou="false" />';
					var event_year = new Date(start_time*1000).getFullYear();
					
					var event_div = document.createElement('div');
					event_div.className = 'event_page_div darkyellow_bg';
					event_div.innerHTML = '<div class="event_page_thumb"><a href="?p=h&sts='+start_time+'"><img class="eventThumbNorm" src="'+event_thumb+'"></a></div><div class="event_page_desc" onClick="location.href=\'?p=h&sts='+start_time+'\'"><b>'+event_name+'</b><br>'+getFormattedTime(start_time*1000)+', '+getFormattedDay(start_time*1000)+'/'+event_year+'<br>created by <b>'+creator+'</b></div>';
					events_main.appendChild(event_div);
				} loadFBML(events_main);
				events_empty.style.display = 'none';
				events_main.style.display = 'block';
			} else {
				events_empty.innerHTML = 'No Events Retrieved.';
				events_main.style.display = 'none';
			}
		} else {
			events_empty.innerHTML = 'No Events Retrieved.';
			events_main.style.display = 'none';
		}
	});
}

function displayEvent(index) {
	if (recent_events && recent_events.length) {
		var recent_events_status = document.getElementById('recent_events_status');
		if (recent_events_status) recent_events_status.style.display = 'none';
		var event_data = recent_events[index];
		if (event_data) {
			var start_time = event_data['start_time']*1000;
			var recent_event_img = document.getElementById('recent_event_img');
			var recent_event_desc = document.getElementById('recent_event_desc');
			recent_event_img.src = '';
			recent_event_img.src = event_data['event_thumb'];
			recent_event_img.setAttribute('created', start_time);
			recent_event_img.style.display = 'block';
			recent_event_desc.style.display = 'block';
			recent_event_desc.innerHTML = '<div id="recent_event_desc_title">'+event_data['event_name']+'</div>'+getFormattedTime(start_time)+', '+getFormattedDay(start_time)+'<br>created by <b><fb:name uid="'+event_data['creator']+'" linked="false"/></b>';
			document.getElementById('recent_events_prev').setAttribute('val', parseInt(index,10)-1);
			document.getElementById('recent_events_next').setAttribute('val', parseInt(index,10)+1);
			loadFBML(recent_event_desc);
		}
	}
}

function selectDate(dateText) {
	var date_parts = dateText.split('/');
	document.getElementById('night_month').value = date_parts[0];
	document.getElementById('night_day').value = date_parts[1];
	document.getElementById('night_year').value = date_parts[2];
	validateDate();
}

function validateDate() {
	var monthVal = document.getElementById('night_month').value;
	var dayVal = document.getElementById('night_day').value;
	var yearVal = document.getElementById('night_year').value;
	var dateStr = monthVal+"/"+dayVal+"/"+yearVal;
	var newDate = new Date(dateStr)
	if (newDate.toString() == "Invalid Date" || newDate == "NaN")
		alert("Please enter a valid date.");
	else {
		document.getElementById('event_date').value = dateStr;
		loadLogEntries();
	} return false;
}

function displayNight(index) {
	if (saved_nights && saved_nights.length) {
		var saved_nights_status = document.getElementById('saved_nights_status');
		if (saved_nights_status) saved_nights_status.style.display = 'none';
		var night_data = saved_nights[index];
		if (night_data) {
			var start_time = night_data['nightDate']*1000;
			var night_friends = night_data['nightFriends'];
			var night_offset = night_data['nightTzOffset'];
			var adjusted_start_time = start_time-night_offset*60*60*1000+new Date().getTimezoneOffset()*60*1000;
			var save_night_date = document.getElementById('saved_night_widget_info');
			var saved_night_desc = document.getElementById('saved_night_desc');
			generateCalendarDate(adjusted_start_time, 'saved_night_widget');
			var saved_night_date = new Date(adjusted_start_time);
			start_time = Date.parse((saved_night_date.getMonth()+1)+'/'+saved_night_date.getDate()+'/'+saved_night_date.getFullYear()+' 00:00:00 UTC')/1000-night_offset*60*60;
			save_night_date.setAttribute('created', start_time);
			save_night_date.style.display = 'block';
			saved_night_desc.style.display = 'block';
			saved_night_desc.innerHTML = '<b>'+getFormattedDay(adjusted_start_time)+'</b><br>'+night_friends+' Friend'+(night_friends==1?'':'s');
			document.getElementById('saved_nights_prev').setAttribute('val', parseInt(index,10)-1);
			document.getElementById('saved_nights_next').setAttribute('val', parseInt(index,10)+1);
		}
	}
}

function removeDuplicateNights(ignoreLocation) {
	// do a preliminary pass to remove less relevant duplicates (hack to handle constellations duplicate nights)
	var lastNightInfo = new Object();
	for (var i=saved_nights.length-1; i>=0; i--) {
		var night_data = saved_nights[i];
		var start_time = night_data['nightDate']*1000;
		var night_friends = night_data['nightFriends'];
		var night_location_id = night_data['nightLocation'];
		var night_location_info = saved_night_locations[night_location_id];
		var night_location_thumb = '';
		if (night_location_info) night_location_thumb = night_location_info['thumb'];
		
		// remove the item with less information when an item with the same time has been detected
		if (lastNightInfo['time'] == start_time) {
			if (!ignoreLocation) {
				if ((lastNightInfo['thumb'] && !night_location_thumb) || (!(lastNightInfo['thumb'] ^ night_location_thumb) && (lastNightInfo['friends'] > night_friends))) saved_nights.splice(i, 1);
				else {
					saved_nights.splice(i+1, 1);
					lastNightInfo['time'] = start_time;
					lastNightInfo['friends'] = night_friends;
					lastNightInfo['thumb'] = night_location_thumb;
				}
			} else {
				if (lastNightInfo['friends'] > night_friends)
					saved_nights.splice(i, 1);
				else saved_nights.splice(i+1, 1);
			}
		} else {
			lastNightInfo['time'] = start_time;
			lastNightInfo['friends'] = night_friends;
			lastNightInfo['thumb'] = night_location_thumb;
		}
	}
}

function renderSavedNights(div) {
	var recent_nights_div = document.getElementById('profile_recent_saved_nights');
	if (saved_nights && saved_nights.length) {
		var saved_nights_html = '';
		var date_today = new Date(); // use today's date to determine when to move onto upcoming events div
		var month_today = date_today.getMonth()+1;
		var day_today = date_today.getDate();
		var year_today = date_today.getFullYear();
		var calendar_date_today = month_today+'/'+day_today+'/'+year_today;
		
		for (var i=saved_nights.length-1; i>=0; i--) {
			var night_data = saved_nights[i];
			var night_id = night_data['nightId'];
			var start_time = night_data['nightDate']*1000;
			var night_friends = night_data['nightFriends'];
			var night_offset = night_data['nightTzOffset'];
			var night_location_id = night_data['nightLocation'];
			var night_location_info = saved_night_locations[night_location_id];
			var night_location_name = '', night_location_thumb = '';
			if (night_location_info) {
				night_location_name = night_location_info['name'];
				night_location_thumb = night_location_info['thumb'];
			} var adjusted_start_time = start_time-night_offset*60*60*1000+new Date().getTimezoneOffset()*60*1000;
			var saved_night_date = new Date(adjusted_start_time);
			var night_month = saved_night_date.getMonth();
			var night_day = saved_night_date.getDate();
			var night_year = saved_night_date.getFullYear();
			var saved_night_month_text = months[night_month]+" "+night_year;
			var saved_night_day_text = night_day;
			var saved_night_calendar_date = (night_month+1)+'/'+night_day+'/'+night_year;
			var saved_night_date_text = getFormattedDay(adjusted_start_time);
			
			// shift items to upcoming events div for future events
			if (div.id.indexOf('upcoming') != -1 && Date.parse(saved_night_calendar_date) <= Date.parse(calendar_date_today)) {
				if (saved_nights_html) {
					div.innerHTML = saved_nights_html + '<div class="clear"></div>';
					saved_nights_html = '';
				} div = recent_nights_div;
			}
			
			// handle the case for no recent nights
			if (i == 0 && div.id.indexOf('recent') == -1) {
				recent_nights_div.innerHTML = 'No recent nights.';
				toggleNightSet('upcoming');
			}
			
			var delete_link = '';
			if (getFid == loggedInUser && !featured_user) delete_link = '<a href="#" onClick="return deleteNight(\''+night_id+'\', this)" class="nightDelete"><img src="'+TEMPLATE_VIEW_PATH+'images/delete.png" border="0" alt="Delete Night" title="Delete Night"></a>';
			
			// insert event name and thumbnail if available
			var saved_night_info = '';
			if (night_location_thumb && night_location_thumb != 'null') {
				if (!location.href.match(/theconstellations.([^\.]+\.)?recreatemynight.com/)) saved_night_info += '<div class="float_left"><img src="'+night_location_thumb+'" class="eventThumbProfile"></div>';
				saved_night_info += '<div class="saved_night_info_right">';
			} else saved_night_info += '<div>';
			if (night_location_name && night_location_name != 'null') saved_night_info += '<div class="saved_night_info_location">'+night_location_name+'</div>'+saved_night_date_text;
			else saved_night_info += '<b>'+saved_night_date_text+'</b>';
			
			saved_night_date = new Date(start_time);
			start_time = Date.parse((saved_night_date.getMonth()+1)+'/'+saved_night_date.getDate()+'/'+saved_night_date.getFullYear()+' 00:00:00 UTC')/1000-night_offset*60*60;
			var clickHandler = ' onClick="if (!deleteNightClicked) location.href=\'?p=h&fid='+getFid+'&sts='+start_time+'\'; deleteNightClicked = null;"';
			
			var night_div = '<div class="saved_night_date_holder"'+clickHandler+'>';
			if (!location.href.match(/theconstellations.([^\.]+\.)?recreatemynight.com/)) night_div += '<div class="saved_night_date_profile"><div class="saved_night_month_profile">'+saved_night_month_text+'</div><div class="saved_night_day_profile">'+saved_night_day_text+'</div>';
			else {
				var night_thumb = night_location_thumb;
				if (!night_thumb || night_thumb == 'null') night_thumb = TEMPLATE_VIEW_PATH+'images/aff/theconstellations/fb_thumb.jpg';
				night_div += '<div class="saved_night_date_thumb"><img src="'+night_thumb+'" style="width:81px;height:81px">';
			}
			
			night_div += '</div></div><div class="saved_night_info_holder darkyellow_bg"'+clickHandler+'>'+saved_night_info+'<br>'+night_friends+' Friend'+(night_friends==1?'':'s')+delete_link+'</div></div>';
			if (div.id.indexOf('upcoming') != -1) saved_nights_html = night_div + saved_nights_html;
			else saved_nights_html += night_div; // reverse ordering for upcoming nights
		} saved_nights_html += '<div class="clear"></div>';
		div.innerHTML = saved_nights_html;
	} else recent_nights_div.innerHTML = 'No recent nights.';
}

function loadUserProfileData() {
	if (getFid) {
		var getFBUserDataFQL = {
			'photos':'SELECT pid, aid, owner, src, src_big, src_small, link, caption, created, modified FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject=\''+getFid+'\') OR aid IN (SELECT aid FROM album where owner=\''+getFid+'\') ORDER BY created DESC LIMIT 10',
			'videos':'SELECT vid, owner, title, description, thumbnail_link, embed_html, created_time FROM video WHERE owner=\''+getFid+'\' OR vid IN (SELECT vid FROM video_tag WHERE subject=\''+getFid+'\') ORDER BY created_time DESC LIMIT 10'
		}
		
		if (featured_user) authenticate_session(1);
		api.callMethod('fql_multiquery', {queries:getFBUserDataFQL}, renderFBData);
	}
}

function renderFBData(data) {
	var recent_photos_div = document.getElementById('profile_recent_photos');
	var recent_videos_div = document.getElementById('profile_recent_videos');
	
	if (data && data.length) {
		var recent_photos = data[0]['fql_result_set'];
		var recent_videos = data[1]['fql_result_set'];
		
		if (recent_photos && recent_photos.length) {
			var recent_photos_html = '';
			for (var i=0; i<recent_photos.length; i++) {
				//?p=h&fid='+getFid+'&sts='+recent_photos[i]['created']
				//recent_photos_html += '<a href="'+recent_photos[i]['src_big']+'" target="_blank"><img class="photo_preview" style="margin-bottom:90px" src="'+recent_photos[i]['src']+'" alt="'+recent_photos[i]['caption']+'" title="'+recent_photos[i]['caption']+'"></a>';
				recent_photos_html += '<img class="photo_preview" style="margin-bottom:90px" src="'+recent_photos[i]['src']+'" media_content="'+recent_photos[i]['src_big']+'" rel="lightbox" alt="'+recent_photos[i]['caption']+'" title="'+recent_photos[i]['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++) {
				//?p=h&fid='+getFid+'&sts='+recent_videos[i]['created_time']
				var video_url = extractFbVideoUrl(recent_videos[i]['embed_html']); // extract video url
				var video_size = extractFbVideoSize(recent_videos[i]['embed_html']); // extract video dimensions
				//recent_videos_html += '<a href="'+video_url+'" target="_blank"><img class="photo_preview" src="'+recent_videos[i]['thumbnail_link']+'" alt="'+recent_videos[i]['title']+'" title="'+recent_videos[i]['title']+'"></a>';
				recent_videos_html += '<img class="photo_preview" style="margin-bottom:90px" src="'+recent_videos[i]['thumbnail_link']+'" media_content="'+video_url+'" video_width="'+video_size[0]+'" video_height="'+video_size[1]+'" rel="lightbox_video" alt="'+recent_videos[i]['title']+'" title="'+recent_videos[i]['title']+'">';//</a>';
			} 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
		updateLightboxPhotos(); updateLightboxVideos();
	} else {
		recent_photos_div.innerHTML = 'No photos available.';
		recent_videos_div.innerHTML = 'No videos available.';
	}
}

function moveMediaCanvases(revert) {
	// if (highlighted_media && highlighted_media.length) { // only take action if there are highlighted media
	if (night_search_start) { // only take action if a date has been selected
		var saved_night_holder = document.getElementById('saved_night_holder');
		var saved_night_right = document.getElementById('saved_night_right');
		var saved_night_photos_widget = document.getElementById('saved_night_photos_widget');
		var photo_selector_right = document.getElementById('photo_selector_right');
		var photo_canvas = document.getElementById('photoCanvasDivHolder');
		var saved_night_videos_widget = document.getElementById('saved_night_videos_widget');
		var video_selector_right = document.getElementById('video_selector_right');
		var video_canvas = document.getElementById('videoPlayerHolder');
		if (revert) {
			if (saved_night_holder.style.width) {
				saved_night_holder.style.width = '';
				saved_night_right.style.display = '';
				saved_night_photos_widget.removeChild(photo_canvas);
				photo_selector_right.appendChild(photo_canvas);
				saved_night_videos_widget.removeChild(video_canvas);
				video_selector_right.appendChild(video_canvas);
			}
		} else {
			if (!saved_night_holder.style.width) {
				saved_night_holder.style.width = '980px';
				saved_night_right.style.display = 'block';
				photo_selector_right.removeChild(photo_canvas);
				saved_night_photos_widget.appendChild(photo_canvas);
				video_selector_right.removeChild(video_canvas);
				saved_night_videos_widget.appendChild(video_canvas);
			}
		}
		
		// make sure to reload player for IE
		if (navigator.userAgent.indexOf("MSIE") != -1 && music_playing) initialize();
		else {
			removeYtAutoplay(); // remove youtube video autoplay flag on move
			if (music_playing) initialize();
		}
	}
}

function addVideoByUrl() {
	var video_url = document.getElementById('yt_video_link').value;
	if (video_url.indexOf('vimeo') != -1) {
		// extract vimeo clip id
		var vimeo_id = '';
		var vimeo_id_regex = /vimeo.com\/([\d]+)/;
		if (video_url.match(vimeo_id_regex)) vimeo_id = RegExp.$1;
		var validator = document.getElementById('videoLogValidator');
		if (!vimeo_id) {
			validator.innerHTML = '<i>Please enter a valid Vimeo URL!</i>';
			return false;
		} // video_url.lastIndex = 0;
		
		// json query to get video title and thumbnail
		jx.load(JSON_RESOURCE_PATH+'?q='+escape('http://vimeo.com/api/v2/video/'+vimeo_id+'.json'), function(data) {
			var vimeo_data = JSON.parse(data);
			vimeo_data = vimeo_data[0];
			
			if (vimeo_data) {
				var video_thumb_obj = document.getElementById('list_video');
				video_thumb_obj.src = vimeo_data['thumbnail_medium'];
				video_thumb_obj.title = vimeo_data['title'];
				video_thumb_obj.setAttribute('vid', vimeo_id);
			} else {
				validator.innerHTML = '<i>Video data not found. Please try another URL!</i>';
				return false;
			} addCustomLogEntry(11); // add vimeo video
		});
	} else addCustomLogEntry(10);
	return false;
}

function removeYtAutoplay() {
	var video_canvas = document.getElementById('videoPlayerHolder');
	var embed_obj = video_canvas.firstChild;
	if (embed_obj) embed_obj.src = removeAutoplay(embed_obj.src);
	if (!music_playing) video_canvas.innerHTML = video_canvas.innerHTML; // used to reload the video player in IE
}

function removeJwAutoplay() {
	var video_canvas = document.getElementById('videoPlayerHolder');
	var music_thumb = document.getElementById('mtheconstellations_southerngothic_night_strip_thumb');
	var embed_obj = video_canvas.firstChild;
	if (music_thumb && embed_obj) {
		autostart = false; initialize();
		play(playlistUrl);
		music_playing = 1; autostart = true; // ie handling
		
		/*var flashvars = embed_obj.getAttribute('flashvars');
		if (flashvars) embed_obj.setAttribute('flashvars', flashvars.replace('autostart=true',''));
		else {
			autostart = false; initialize();
			play(playlistUrl);
			music_playing = 1; autostart = true; // ie handling
			/*flashvars = embed_obj.childNodes;
			for (var i=0; i<flashvars.length; i++) {
				if (flashvars[i].getAttribute('name') == 'flashvars') {
					flashvars[i].setAttribute('value', flashvars[i].getAttribute('value').replace('autostart=true',''));
					break;
				}
			}*/
		//}
	}
}

function moveWhoYouWereWith(revert) {
	var friend_list_section_holder = document.getElementById('you_were_with_friends');
	var friend_list_view_holder = document.getElementById('you_were_with');
	var friend_list_contents = document.getElementById('you_were_with_contents');
	if (revert) {
		friend_list_view_holder.removeChild(friend_list_contents);
		//friend_list_section_holder.appendChild(friend_list_contents);
		friend_list_section_holder.insertBefore(friend_list_contents, friend_list_section_holder.firstChild);
	} else {
		if (friend_list_contents.parentNode == friend_list_section_holder)
			friend_list_section_holder.removeChild(friend_list_contents);
		friend_list_view_holder.appendChild(friend_list_contents);
	}
}

function embedVideo(video_url) {
	if (video_url) {
		var player_width = '350';
		if (video_url.indexOf('facebook.com') == -1) player_width = '100%';
		document.getElementById('videoPlayerHolder').innerHTML = '<embed src="'+video_url+'" type="application/x-shockwave-flash" wmode="transparent"'+(navigator.userAgent.indexOf("MSIE") == -1? ' allowscriptaccess="always"' : '')+' allowfullscreen="true" width="'+player_width+'" height="265"></embed>'; // allowscriptaccess="always" breaks youtube videos on ie
		music_playing = null; // turn off music flag
	}
}

var music_playing;
function addToSavedNightStrip(objId, src, videoUrl, playlistUrl) {
	var new_media_thumb = document.createElement('img');
	new_media_thumb.id = 'm'+objId+'_night_strip_thumb';
	new_media_thumb.className = 'saved_night_strip_photo';
	new_media_thumb.src = src;
	// new_media_thumb.src = document.getElementById('m'+objId+'_stream').src; // use thumbnail source
	
	if (!document.getElementById(new_media_thumb.id)) { // avoid duplicates
		if (!videoUrl) {
			if (playlistUrl) {
				eval("new_media_thumb.onclick = function() { initialize(); play('"+playlistUrl+"'); music_playing = 1}");
				document.getElementById('saved_night_videos_strip').appendChild(new_media_thumb);
			} else {
				eval("new_media_thumb.onclick = function() {photoCanvas.surfaceImage('"+objId+"')}");
				document.getElementById('saved_night_photos_strip').appendChild(new_media_thumb);
				photosSelectedArray.push([objId,null]); // add to processed photos array
			}
		} else {
			new_media_thumb.setAttribute('video_url', videoUrl);
			eval("new_media_thumb.onclick = function() {embedVideo('"+videoUrl+"')}");
			document.getElementById('saved_night_videos_strip').appendChild(new_media_thumb);
			
			var videoPlayerHolder = document.getElementById('videoPlayerHolder');
			if (!videoPlayerHolder.innerHTML) embedVideo(removeAutoplay(videoUrl));
			videosSelectedArray.push([objId,null]); // add to processed videos array
		}
	}
}

function removeFromSavedNightStrip(objId, mediaType) {
	var saved_night_strip_thumb = document.getElementById('m'+objId+'_night_strip_thumb');
	if (saved_night_strip_thumb) {
		document.getElementById('saved_night_'+mediaType+'s_strip').removeChild(saved_night_strip_thumb);
		// flush video player if element removed is the same as the current video
		if (mediaType == 'video') {
			var videoPlayer = document.getElementById('videoPlayerHolder').firstChild;
			if (videoPlayer && removeAutoplay(saved_night_strip_thumb.getAttribute('video_url')) == removeAutoplay(videoPlayer.src))
				document.getElementById('videoPlayerHolder').innerHTML = '';
		}
	}
}

var friend_list_filter;
function updateShownFriends() {
	var friends_div = document.getElementById('friends');
	if (friend_list_filter) friends_div = document.getElementById('friend_list');
	var friend_links = friends_div.getElementsByTagName('a');
	if (friend_links && friend_links.length) {
		var friends_shown = 0;
		var friend_filter_text = document.getElementById('friend_filter_text').value.replace(/\s/g, '').toLowerCase();
		var friend_filter_clear = document.getElementById('friend_filter_clear');
		if (!friend_filter_text) friend_filter_clear.style.display = '';
		else friend_filter_clear.style.display = 'block';
		for (var i=0; i<friend_links.length; i++) {
			var friend_link = friend_links[i];
			if (!friend_filter_text) {
				friend_link.style.display = '';
				friends_shown++;
			} 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(friend_filter_text) == -1) friend_link.style.display = 'none';
					else { friend_link.style.display = ''; friends_shown++; }
				} catch(err) {}
			}
		}
		
		// hack for ie to fix scrollbar overlap problem
		if (document.all) {
			if (friends_shown > 4) {
				if (friends_div.parentNode.id == 'friend_links_holder') friends_div.style.width = '783px';
				else friends_div.style.width = '470px';
			} else friends_div.style.width = '';
			friends_div.style.paddingRight = '15px';
		}
	} else if (document.all) { friends_div.style.width = ''; friends_div.style.paddingRight = '15px'; }
}

function clearFriendFilter() {
	document.getElementById('friend_filter_text').value = '';
	document.getElementById('friend_filter_clear').style.display = '';
	updateShownFriends();
}

function toggleNightSet(div) {
	var recent_nights_div = document.getElementById('profile_recent_saved_nights');
	var upcoming_nights_div = document.getElementById('profile_upcoming_saved_nights');
	var recent_nights_link = document.getElementById('recent_nights_section_link');
	var upcoming_nights_link = document.getElementById('upcoming_nights_section_link');
	if (!div) {
		div = recent_nights_div;
		upcoming_nights_div.style.display = 'none';
		recent_nights_link.style.fontWeight = 'bold';
		upcoming_nights_link.style.fontWeight = 'normal';
	} else if (div == 'upcoming') {
		div = upcoming_nights_div;
		recent_nights_div.style.display = 'none';
		recent_nights_link.style.fontWeight = 'normal';
		upcoming_nights_link.style.fontWeight = 'bold';
	} div.style.display = 'block';
	return false;
}

function updateLightboxPhotos() {
	$("img[rel='lightbox']").colorbox({opacity:.75, maxWidth:'95%', maxHeight:'95%', rel:'lightbox', href:function(){
		var media_content = $(this).attr('media_content');
		if (media_content) return media_content;
		return $(this).attr('src_big'); }, title:function(){ return '&nbsp;'; }
	});
}

function updateLightboxVideos() {
	$("img[rel='lightbox_video']").colorbox({opacity:.75, maxWidth:'90%', maxHeight:'90%', rel:'lightbox_video', current:"video {current} of {total}", title:function(){ return '&nbsp;'; }, html:function() {
			var media_content = $(this).attr('media_content');
			if (!media_content) media_content = $(this).attr('video_url');
			var player_size = 'width="640" height="385"'; // default youtube dimensions
			if (media_content.indexOf('http://www.facebook.com/v/') === 0 && navigator.userAgent.indexOf("MSIE") != -1) {
				var player_width = $(this).attr('video_width');
				var player_height = $(this).attr('video_height');
				if (!player_width || !player_height) { player_width = 480; player_height = 360; }
				player_size = 'width="'+player_width+'" height="'+player_height+'"';
			} return '<embed '+player_size+' src="'+media_content+'" type="application/x-shockwave-flash" wmode="transparent"'+(navigator.userAgent.indexOf("MSIE") == -1? ' allowscriptaccess="always"' : '')+' allowfullscreen="true"></embed>';
		}, href:function() {return '';}
	});
}

