function addDropDown(wrapper, list) {
    if (wrapper !== null && list !== null) {
	wrapper.addEvents({
	    'click':function() {
	    if (list.isVisible()) {
		list.hide();
	    } else {
		list.show();
	    }
	},
	'mouseenter' : function() {
		if (list.isVisible()) {
			list.hide();
		} else {
			list.show();
		}
	}
	});
	list.addEvents({
	    'mouseleave' : function(){
	    list.hide();
	}
	});
	wrapper.addEvents({
	    'mouseleave' : function(){
	    list.hide();
	}
	});
    }
}

//FIXME: duplication, move to library
function render_emote_names(emote) {
    var i;
    if(emote.emoters && emote.emoters.length > 0) {
	var length = emote.emoters.length;
	if(length === 1) {
	    return emote.emoters[0].name;
	} else if(length === 2) {
	    return emote.emoters[0].name + ' and ' +  emote.emoters[1].name;
	} else {
	    var emote_names = "";
	    for(i = 0; i < emote.emoters.length; i++) {
		emote_names = emote_names + emote.emoters[i].name;
		emote_names = emote_names + ", ";
		if(i === length-2) {
		    emote_names = emote_names + 'and ';
		}
	    }
	    return emote_names.substr(0, emote_names.length-2);
	}
    }
}

//gets an emote that is the right emote, and also has you removed from emoters list if you are in there
function get_filtered_emote(notification) {
    var the_emote, i, j;
    for (j=0; j<notification.emotes.length; j++) {
	if (notification.emotes[j].emote_id.toString() === notification.notification_type) {
	    the_emote = notification.emotes[j];
	}
    }
    var filtered_emoters = [];
    var my_id = DynamicValues.Notifications.member_id;
    if (the_emote.emoters) {
	for (i=0; i<the_emote.emoters.length; i++) {
	    if (the_emote.emoters[i].id !== my_id) {
		filtered_emoters.push(the_emote.emoters[i]);
	    }
	}
    }
    the_emote.emoters = filtered_emoters;
    return the_emote;
}

function get_emote_names_from_notification(notification) {
    var the_emote = get_filtered_emote(notification);
    var friend_text = render_emote_names(the_emote);
    return friend_text;
}

//given an array of names, format them like bob, mary, and susan or bob or bob and mary
function format_name_text(names) {
    var i;
    if (names && names.length > 0) {
	if(names.length === 1) {
	    return names[0];
	} else if(names.length === 2) {
	    return names[0] + ' and ' + names[1];
	} else {
	    var retnames = "";
	    for(i = 0; i < names.length; i++) {
		retnames = retnames + names[i] + ", ";
		if(i === names.length-2) {
		    retnames = retnames + 'and ';
		}
	    }
	    return retnames.substr(0, retnames.length-2);
	}
    } else {
	return "";
    }
}

//self explanatory - need to remove self and also remove dupes (if someone comments more than once)
function get_comment_names_from_notification(notification) {
    var filtered_commenters_names = [];
    var j;
    var my_id = DynamicValues.Notifications.member_id;
    for (j=0; j<notification.latest_comments.length; j++) {
	if (notification.latest_comments[j].body.user_data.id !== my_id && !filtered_commenters_names.contains(notification.latest_comments[j].body.user_data.name)) {
	    filtered_commenters_names.push(notification.latest_comments[j].body.user_data.name);
	}
    }
    return format_name_text(filtered_commenters_names);
}

//get profile pic, profile link, and profile name for rendering purposes
//assumes that comments doesn't contain current user id
function get_profile_picture_from_comments(comments) {
    var picture = {};
    if (comments && comments.length > 0) {
	//should always be true
	//get last commenter
	picture.profile_id = comments[comments.length-1].body.user_data.id;
	picture.profile_picture = comments[comments.length-1].body.user_data.avatar_small;
	picture.user_name = comments[comments.length-1].body.user_data.name;
	return picture;
    }
    return null;
}

//get profile pic, profile link, and profile name for rendering purposes
function get_profile_picture_from_emote_notification(notification) {
    var picture = {};
    var the_emote = get_filtered_emote(notification);
    var emoters = the_emote.emoters;
    //get last emoter
    picture.profile_id = emoters[emoters.length-1].id;
    picture.profile_picture = emoters[emoters.length-1].avatar_small;
    picture.user_name = emoters[emoters.length-1].name;
    return picture;
}

//return time that day (i.e. 9:30 PM)
function get_notification_time(notification) {
    var theDate = new Date(notification.notification_updated*1000);
    return theDate.format("%l:%M %p");
}


//FIXME: duplication, move to library
function convert_time(then) {
    var ONE_MINUTE, ONE_HOUR, ONE_DAY, ONE_WEEK, ONE_MONTH, ONE_YEAR, seconds_ago;
    ONE_MINUTE = 60;
    ONE_HOUR = 60 * ONE_MINUTE;
    ONE_DAY = 24 * ONE_HOUR;
    ONE_WEEK = 7 * ONE_DAY;
    ONE_MONTH = ONE_DAY * 3652425 / 120000;
    ONE_YEAR = ONE_DAY * 3652425 / 10000;
    seconds_ago = Math.round(new Date().getTime()/1000) - then;
    if (seconds_ago <= 0) {
	return "now";
    }
    if(seconds_ago === 1) {
	return "1 second ago";
    }
    if(seconds_ago < ONE_MINUTE) {
	return Math.round(seconds_ago) + " seconds ago";
    }
    if(seconds_ago < 2 * ONE_MINUTE) {
	return "1 minute ago";
    }
    if(seconds_ago < ONE_HOUR) {
	return Math.round(seconds_ago/ONE_MINUTE) + " minutes ago";
    }
    if(seconds_ago < 2 * ONE_HOUR) {
	return "1 hour ago";
    }
    if(seconds_ago < ONE_DAY) {
	return Math.round(seconds_ago/ONE_HOUR) + " hours ago";
    }
    if(seconds_ago < 2 * ONE_DAY) {
	return "1 day ago";
    }
    if(seconds_ago < ONE_WEEK) {
	return Math.round(seconds_ago/ONE_DAY) + " days ago";
    }
    if(seconds_ago < 2 * ONE_MONTH) {
	return "1 month ago";
    }
    if(seconds_ago < ONE_YEAR) {
	return Math.round(seconds_ago/ONE_MONTH) + " months ago";
    }
    if(seconds_ago < 2 * ONE_YEAR) {
	return "1 year ago";
    }
    return Math.round(seconds_ago/ONE_YEAR) + " years ago";
}

//filter out comment notifications that are empty, comment notifications where the only comment is the viewing user,
//and emote notifications where the count is 0 (own emote is not counted in the count)
function remove_invalid_notifications(notifications) {
    var ret, i, k, j;
    ret = [];
    for(i=0; i<notifications.length; i++) {
	var my_id = DynamicValues.Notifications.member_id;
	if (notifications[i].notification_type === 'FC') {
	    var comments = notifications[i].latest_comments;
	    if(notifications[i].latest_comments !== null) {
		var friend_comment_exists = false;
		for (j=0; j<comments.length; j++) {
		    if (comments[j].user_id !== my_id) {
			friend_comment_exists = true;
			break;
		    }
		}
		if (friend_comment_exists) {
		    ret.push(notifications[i]);
		}
	    }
	} else if (notifications[i].notification_type === 'PC') {
	    ret.push(notifications[i]);
	} else {
	    //emote
	    var emotes = notifications[i].emotes;
	    var emote_type = notifications[i].notification_type;
	    if(emotes !== null) {
		for (k=0;k<emotes.length;k++) {
		    if (emotes[k].emote_id.toString() === emote_type && emotes[k].count > 0) {
			ret.push(notifications[i]);
			break;
		    }
		}
	    }
	}
    }
    return ret;
}


//tab for list of unread mail
function render_mail_notifications() {
    function openUrl(e) {
	location.href="/mail/MailView.jsp?PersonalMessageId=" + this.get('id');
    }
    var i;
    //clear out old stuff
    $('loading-throbber').show();
    if($('view-more-mail')) {
	$('view-more-mail').hide();
    }
    var notificationList = $('mail-feed').getChildren();
    for (i=0; i<notificationList.length-2;i++) {
	notificationList[i].dispose();
    }
    var options = {};
    options.url = '/c/mail/ajax_get_mail_summary';
    options.method = 'POST';
    options.onComplete=function(response) {
	var mail_list;
	if(response !== undefined && response.mail !== undefined){
	    $('loading-throbber').hide();
	    mail_list = response.mail;
	    var html;
	    html = Mustache.to_html($('mail-notification-tmpl').get('html'),
		    {'mail': mail_list});
	    $('mail-feed').set('html', html);
	}
	if (mail_list.length > 0) {
	    var mail_list_items = $('mail-feed').getChildren();
	    for (i=0; i<mail_list_items.length-2;i++) {
		mail_list_items[i].addEvent('click', openUrl);
	    }
	    $('no-mail-items').hide();
	} else {
	    $('no-mail-items').show();
	}
	$('view-more-mail').addEvent('click', function(e) {location.href="/mail/Mail.jsp";});
	$('view-more-mail').show();
    };
    var data = {};
    var req = new Request.JSON(options);
    req.post(data);
}

//render tab with stuff that used to be in the home page - moderate comments, etc
function render_other_notifications() {
    function openUrl(e) {
	location.href = this.get('url');
    }
    var i;
    //clear out old stuff
    $('loading-throbber').show();
    var notificationList = $('other-notifications-list').getChildren();
    for (i=0; i<notificationList.length-2;i++) {
	notificationList[i].dispose();
    }
    var options = {};
    options.url = '/c/home/ajax_get_notifications';
    options.onComplete=function(response) {
	if(response !== undefined && response.notifications !== undefined){
	    $('loading-throbber').hide();
	}
	var notifications_list = response.notifications;
	var html;
	html = Mustache.to_html($('other-notification-tmpl').get('html'),
		{'items': notifications_list});
	$('other-notifications-list').set('html', html);
	var new_count = 0;
	for(i=0; i<notifications_list.length; i++) {
	    if(notifications_list[i].new_item) {
		new_count = new_count + 1;
	    }
	}
	if (notifications_list.length > 0) {
	    var items = $('other-notifications-list').getChildren();
	    for (i=0; i<items.length-2;i++) {
		items[i].addEvent('click', openUrl);
	    }
	    $('no-other-items').hide();
	} else {
	    $('no-other-items').show();
	}
	//set up red indicator
	if (new_count > 0) {
	    $('new-other-notification-count').set('html', new_count);
	    $('new-other-notification-count').show();
	} else {
	    $('new-other-notification-count').hide();
	}
    };

    var data = {};
    var req = new Request.JSON(options);
    req.post(data);
}

//helper to generate start text for emote notifications
function get_emote_count_text(notification) {
    //handle emote
    //FIXME: this should be handled on the backend probably
    var emote_count = 0;
    var emotes = notification.emotes;
    var k;
    for(k=0; k<emotes.length; k++) {
	if (emotes[k].emote_id.toString() === notification.notification_type) {
	    emote_count = emotes[k].count;
	    break;
	}
    }
    var friend_text = (emote_count>1) ? " friends" : " friend";
    return emote_count + friend_text;
}

//helper to get an array of only friend comments in comment notifications (removes own comments)
function get_friend_comments(notification) {
    var friends_comments, j;
    friends_comments = [];
    for (j=0;j<notification.latest_comments.length;j++) {
	if (notification.latest_comments[j].body.user_data.id !== DynamicValues.Notifications.member_id) {
	    friends_comments.push(notification.latest_comments[j]);
	}
    }
    return friends_comments;
}

function get_comment_hash_for_rendering(notification) {
    var friends_comments = get_friend_comments(notification);
    if (friends_comments !== null && friends_comments.length !== 0) {
	var time_ago = convert_time(notification.notification_updated);
	var feed_desc = notification.notification_desc;
	var cnhash = {
		'time' : get_notification_time(notification),
		'friend_count' : friends_comments.length,
		'time_ago' : time_ago,
		'feed_type' : feed_desc
	};
	if (DynamicValues.Notifications.member_id !== notification.user_data.id) {
	    //not your feed item
	    cnhash.friend_member_id = notification.user_data.id;
	    cnhash.friend_display_name = notification.user_data.name;
	}
	var comment_picture = get_profile_picture_from_comments(friends_comments);
	cnhash.picture = comment_picture;			    
	//set up names
	cnhash.names = get_comment_names_from_notification(notification);
	return cnhash;
    } else {
	return null;
    }
}

function get_emote_hash_for_rendering(notification) {
    var emote_names = get_emote_names_from_notification(notification);
    var emote_type = notification.notification_emote;
    var time_ago = convert_time(notification.notification_updated);
    var feed_desc = notification.notification_desc;
    var ehash = {'names' : emote_names,
	    'time' : get_notification_time(notification),
	    'time_ago' : time_ago,
	    'feed_type' : feed_desc,
	    'emote_type' : emote_type,
	    'notification_text' : notification.notification_text
    };
    if (DynamicValues.Notifications.member_id !== notification.user_data.id) {
	//not your feed item
	ehash.friend_member_id = notification.user_data.id;
	ehash.friend_display_name = notification.user_data.name;
    }
    //set up picture
    var emote_picture = get_profile_picture_from_emote_notification(notification);
    ehash.picture = emote_picture;
    return ehash;
}

function get_photo_comment_hash_for_rendering(notification) {
    var picture = {};
    var names = "";
    if (notification.source_user_data) {
	picture.profile_id = notification.source_user_data.id;
	picture.profile_picture = notification.source_user_data.avatar_small;
	picture.user_name = notification.source_user_data.name;
	names = notification.source_user_data.name;
    } else {
	//FIXME empty source user data?
	picture = null;
	names = "A Bebo User";
    }
    var time_ago = convert_time(notification.notification_updated);
    var hash = {'names' : names,
	    'picture' : picture,
	    'member_id' : notification.user_data.id,
	    'photo_id' : notification.body.photo_id,
	    'photo_album_id': notification.body.photo_album_id,
	    'time_ago' : time_ago,
	    'time' : get_notification_time(notification)};
    return hash;
}

//for notification list elements
function openUrl(e) {
    var notification_type = this.get('notification_type');
    if (notification_type && notification_type === 'PC') {
	location.href = '/c/photos/view?MemberId=' + this.get('member_id') + '&PhotoAlbumId=' + this.get('photo_album_id') + '&PhotoId=' + this.get('photo_id');
    } else {
	location.href="/c/home/display_feed_item?feed_id=" + this.get('id');
    }
}

//activity feed
function render_feed_notifications(show_all) {    
    $('loading-throbber').show();
    $('no-feed-items').hide();
    $('view-more').hide();
    //clear out old stuff
    var i;
    var notificationList = $('activity-feed').getChildren();
    for (i=0; i<notificationList.length-2;i++) {
	notificationList[i].dispose();
    }
    var comment_notification_item = $('comment-notification-tmpl').get('html');
    var photo_comment_notification_item = $('photo-comment-notification-tmpl').get('html');
    var emote_notification_item = $('emote-notification-tmpl').get('html');

    var options = {};
    options.url = '/c/feed/get_notifications';
    options.method = 'POST';
    options.onRequest=function(){
	// making request
    };
    options.onComplete=function(response){
	var jres = response;
	if( jres !== undefined && jres.message!=="error"){
	    $('loading-throbber').hide();
	    var max_time;
	    if (jres.notifications && jres.notifications.length > 0) {
		max_time = jres.notifications[0].notification_updated;
	    }	    
	    var notifications = remove_invalid_notifications(jres.notifications);
	    if (notifications && notifications.length > 0) {
		$('no-feed-items').hide();
		//console.log("notifications length: " + notifications.length);
		var limit = 5;
		if (show_all) {
		    limit = notifications.length;
		}
		if (limit >= notifications.length) {
		    limit = notifications.length;
		    //$('view-more').hide();
		    $('view-more').show();
		} else {
		    $('view-more').show();
		}
		var new_notification_count = 0;
		for(i = 0; i < limit; i++) {
		    //console.log(notifications[i]);
		    var feed_item_id = notifications[i].id;
		    var html;
		    if (notifications[i].notification_type === 'FC') {
			var cnhash = get_comment_hash_for_rendering(notifications[i]);
			if (cnhash) {
			    html = Mustache.to_html(comment_notification_item, cnhash);
			}
		    } else if (notifications[i].notification_type === 'PC') {
			var pchash = get_photo_comment_hash_for_rendering(notifications[i]);
			if (pchash) {
			    html = Mustache.to_html(photo_comment_notification_item, pchash);
			}
		    } else {
			var ehash = get_emote_hash_for_rendering(notifications[i]);
			if (ehash) {
			    html = Mustache.to_html(emote_notification_item, ehash);
			}
		    }
		    //console.log(html);
		    var newNotificationRow = new Element('li');
		    if (notifications[i].status === 'U') {
			newNotificationRow.addClass('new');
			new_notification_count = new_notification_count + 1;
		    }
		    newNotificationRow.set('id', feed_item_id);
		    if (notifications[i].notification_type === 'PC') {
			newNotificationRow.set('notification_type', notifications[i].notification_type);
			newNotificationRow.set('photo_id', notifications[i].body.photo_id);
			newNotificationRow.set('photo_album_id', notifications[i].body.photo_album_id);
			newNotificationRow.set('member_id', notifications[i].user_data.id);
		    }
		    newNotificationRow.set('html', html);
		    newNotificationRow.inject($('no-feed-items'), 'before');
		}

		//set up red indicator
		if (new_notification_count > 0) {
		    $('new-feed-notification-count').set('html', new_notification_count);
		    $('new-feed-notification-count').show();
		    //read notifications after opening dropdown		    
		} else {
		    $('new-feed-notification-count').hide();
		}
		new Request.JSON({url : '/c/feed/read_notifications?max_time=' + max_time}).send();

		notificationList = $('activity-feed').getChildren();
		for (i=0; i<notificationList.length-2;i++) {	    
		    notificationList[i].addEvent('click', openUrl);
		}
	    } else {
		//no notifications
		$('no-feed-items').show();
		$('view-more').hide();
	    }
	}
    };
    var data = {'num_items':'5'}; //only get 5 items
    var req = new Request.JSON(options);
    req.post(data);
}

function blink_title(message, count) {
    var title;
    if ($('notifications-count').hasClass('new') && count < 6) {
	if ((count%2) === 0) {
	    title = message;
	} else {
	    title = message.replace(/\([0-9]+\)/, "");
	}
	count = count + 1;
	document.title = title;
	window.setTimeout("blink_title(\"" + message + "\", " + count + ");", 1000);
    } else {
	document.title = message;
    }
}

window.addEvent('domready', function(){
    addDropDown($('drop-menu-wrapper'), $('drop-menu'));
    addDropDown($('drop-user-menu-wrapper'), $('drop-user-menu'));
    function showActivityTab() {
	$('mail-content').hide();
	$('activity-content').show();
	$('other-content').hide();
	render_feed_notifications(false);
    }
    function showMailTab() {
	$('mail-content').show();
	$('activity-content').hide();
	$('other-content').hide();
	render_mail_notifications();
    }
    function showOtherTab() {
	$('other-content').show();
	$('mail-content').hide();
	$('activity-content').hide();
	render_other_notifications();
    }
    function handleFeedNotificationClick(e) {
	if (!$('activity-content').isVisible()) {
	    showActivityTab();
	}
    }
    function handleMailNotificationClick(e) {
	if (!$('mail-content').isVisible()) {
	    showMailTab();
	}
    }
    function handleOtherNotificationClick(e) {
	if (!$('other-content').isVisible()) {
	    showOtherTab();
	}
    }
    //set up tabs
    var myTabs;
    if ($('header-notify-menu')) {
	myTabs = new YAHOO.widget.TabView('header-notify-menu');
	var tabArray = myTabs.get('tabs');
	tabArray[0].addListener('click', handleFeedNotificationClick);
	tabArray[1].addListener('click', handleMailNotificationClick);
	tabArray[2].addListener('click', handleOtherNotificationClick);
    }

    function closeNotificationsDropDown() {
	$('header-notify-menu').hide();
	$('notifications-count').removeClass('new'); //un-highlight icon in nav bar
    }
    
    if ($('header-notify')) {
	$('view-more').addEvent('click', function() {
	    //render_feed_notifications(true);
	    location.href="/c/home/feed_notifications";
	});

	//get notification count
	new Request.JSON({url : '/c/feed/get_notification_count',
	    onComplete : function(response){
	    var notif_count = 0;
	    if(response !== undefined && response.message !== "error"){
		notif_count = response.unread;
	    }
	    var new_other_notif_count = 0;
	    if (DynamicValues.Notifications.other_count) {
		new_other_notif_count = parseInt(DynamicValues.Notifications.other_count, 10);
	    }

	    var added_count = notif_count + new_other_notif_count;
	    $('notifications-count').set('html', added_count);
	    if (added_count > 0) {
		if (new_other_notif_count > 0) {
		    $('new-other-notification-count').set('html', new_other_notif_count);
		    $('new-other-notification-count').show();
		    myTabs.selectTab(2); //let's show the other notifications first if there are any new ones
		} else {
		    $('new-other-notification-count').hide();
		}
		
		//set up red indicator for feed notifications
		if (notif_count > 0) {
		    $('new-feed-notification-count').set('html', notif_count);
		    $('new-feed-notification-count').show();	    
		} else {
		    $('new-feed-notification-count').hide();
		}
		
		document.title = document.title + " (" + added_count + ")";
		$('notifications-count').addClass('new'); //flash icon if we have activity notifications or other notifications
		blink_title(document.title, 0);//also blink title a few times
	    }
	    
	}}).send();

	$('header-notify').addEvents({
	    'click' : function() {
	    	show_notification_dropdown(myTabs, closeNotificationsDropDown, showActivityTab, showOtherTab, showMailTab);		
	    },
	    'mouseenter' :  function() {
	    	show_notification_dropdown(myTabs, closeNotificationsDropDown, showActivityTab, showOtherTab, showMailTab);		
	    }
	
	});
    }
    
    $(document.body).addEvent('click', function(e) {
	if ($('header-notify-menu') && $('header-notify-menu').isVisible() &&
		(!e.target || ($(e.target) !== $('header-notify') &&
			!$(e.target).getParents().contains($('header-notify')) &&
			!$(e.target).getParents().contains($('header-notify-menu'))))) {
	    closeNotificationsDropDown();
	}
    });
    
   
         
    new Autocompleter.Request.JSON($('friend-search'), '/c/friends/get_friends_json', {
		'minLength': 1,
		'autoSubmit': true,
		'delay' : 0,
		'selectMode': 'pick',
		'injectChoice': function(token){
			var choice = new Element('li');
			//var elem = new Element('span', {'class' : 'search-auto', 'id' : token.member_id, 'html': "<a href=/Profile.jsp?MemberId=" + token.member_id + ">" + this.markQueryValue(token.name)+"</a>"}).inject(choice);
			
			var searchTerm = token.name;
			var searchTerm = token.name.replace(/\"/g,"");
			searchTerm = searchTerm.replace("Search Bebo for ", '');
			
			choice.inputValue = searchTerm;
			var elem = new Element('span', {'class' : 'search-auto', 'id' : token.member_id, 'html': this.markQueryValue(token.name)}).inject(choice);
			
			this.addChoiceEvents(choice).inject(this.choices);

		elem.addEvent('click', function(e){
			    	e.stop(); 
		 	    	process_search(e);
		  });
			 
			 	 			
		},
		'onSelect' : function(input, sel, val) { $('search-profile-id').value = sel.getElement('span').get('id');}
		//'onSelection' : function(input, sel, val, sugg) { $('search-profile-id').value = sel.getElement('span').get('id');}

	});
    
});


function show_notification_dropdown(myTabs, closeNotificationsDropDown, showActivityTab, showOtherTab, showMailTab){
	    if ($('header-notify-menu').isVisible()) {
		closeNotificationsDropDown();
	    } else {
		$('header-notify-menu').show();
		if (myTabs) {
		    if(myTabs.get('activeIndex') === 0) {
			showActivityTab();
		    } else if(myTabs.get('activeIndex') === 1) {
			showMailTab();
		    } else {
			showOtherTab();
		    }
		}
	    }
	
}

function process_search(e) {
	var member_id = $('search-profile-id').value;
	if(member_id.length > 0 && member_id != "0") {
		document.location = "/Profile.jsp?MemberId=" + member_id; 
	}
	else {
		$('header-search-form').submit();
	}
}




