//HISTORY TABLE OBJECT TYPE
/** object types */
var USER_OBJECT       = 0;
var VIDEO_OBJECT      = 1;
var TOPIC_OBJECT      = 2;
var SUBTOPIC_OBJECT   = 3;
var GENRE_OBJECT      = 4;
var SHOWTYPE_OBJECT   = 5;
var ACTOR_OBJECT      = 6;
var ACTRESS_OBJECT    = 7;
var FRIENDCAST_OBJECT = 8;
var EXTERN_OBJECT     = 9;

/** message types */
var MESSAGE_VIEWED      = 0;
var MESSAGE_THUMBS_UP   = 1;
var MESSAGE_THUMBS_DOWN = 2;
var MESSAGE_FOLLOWED    = 3;
var MESSAGE_UNFOLLOWED  = 4;
var MESSAGE_FRIENDED    = 5;
var MESSAGE_UNFRIENDED  = 6;
var MESSAGE_COMMENT     = 7;
var MESSAGE_FAVORITE    = 8;
var MESSAGE_UNFAVORITE  = 9;
var MESSAGE_REVIEW      = 10;
var MESSAGE_WALLPOST    = 11;
var MESSAGE_PERSONAL    = 12;
var MESSAGE_RECOMMEND   = 14;
var MESSAGE_FRIENDCAST  = 15;
var MESSAGE_CHAT        = 16;
var MESSAGE_FACEBOOK    = 17;
var MESSAGE_TWITTER     = 18;

var THUMBS_HOST = '';

var TITLE_BASE = "Rippol";

var JSCROLLPANE_OPTIONS = {
	wheelSpeed: 50, 
	showArrows: false,
	dragMinHeight: 66,
	dragMaxHeight: 66,
	scrollbarWidth: 17
};

var showtypes = {
	episode: 'TV Shows',
	movie: 'Movies',
	sports: 'Sports',
	news: 'News',
	lecture: 'Lectures',
	clip: 'Clips',
	live: 'Live',
	political: 'Political',
	tutorials: 'Tutorials',
	trailers: 'Trailers',
	music: 'Music Videos',
	buzzy: 'Buzzy'
};

function urlencode(str) {
	return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
}

function urldecode(str) {
	return unescape(str.replace('+', ' '));
}

function logMsg(msg) {
	$('#log_window').html('<br />' + msg + $('#log_window').html());
}
function time_format(runtime) {
	ret = "";
	if (parseInt(runtime) > 3600) {
		hours = Math.floor(parseInt(runtime) / 3600);
		ret = hours + " hour";
		if (hours > 1) {
			ret += "s";
		}
		ret += " ";
	}
	if (parseInt(runtime) > 60) {
		minutes = Math.floor(parseInt(runtime) % 3600 / 60);
		ret += minutes + " minute";
		if (minutes > 1) {
			ret += "s";
		}
		ret += " ";
	}
	seconds = (parseInt(runtime) % 60);
	ret += seconds + " second";
	if (seconds > 1) {
		ret += "s";
	}
	return ret;
}

watch_uris = {};

var _current_watch_id = 0;
var _current_watch_video_id = 0;
var _last_watch_video_params = {};

function rpcStartWatch(params) {
	_last_watch_video_params = params;
	if (params.video_id) {
		statsGotoLink(params.video_id,0, 0, params.topic, params.subtopic, "passbackinfo"); //aaron edit
	}
				  
	_current_watch_id = 0;
	var param_type = '';
	var param_value = 0;
	if (params.video_id) {
		_current_watch_video_id = params.video_id;
		param_type = 'video_id';
		param_value = params.video_id;
	} else if (params.extern_id) {
		_current_watch_video_id = params.extern_id;
		param_type = 'extern_id';
		param_value = params.extern_id;
	}
	var watch_delay = 60*1000;
	$.doTimeout('watch_video', watch_delay, function() {
		$.getJSON(main_site_uri() + "rpcs/watch_start.php?" + param_type + "=" + param_value + "&watch_delay=" + watch_delay, function(data) {
			_current_watch_id = data['watch_id'];
		});
	});
}

function rpcEndWatch() {
	var params = _last_watch_video_params;
	if (params.video_id) {
		statsBackFromLink(_current_watch_video_id); //aaron edit
	}

	// cancels pending timeout, if any
	$.doTimeout('watch_video');

	if (_current_watch_id != 0) {
		if (params.video_id) {
			$.get(main_site_uri() + "rpcs/watch_end.php?video_id=" + params.video_id + "&watch_id=" + _current_watch_id, 
				function(data) {}
			);
		} else if (params.extern_id) {
			$.get(main_site_uri() + "rpcs/watch_end.php?extern_id=" + params.extern_id + "&watch_id=" + _current_watch_id, 
				function(data) {}
			);
		}
		_current_watch_id = 0;
		_current_watch_video_id = 0;
	}
}

function favorite_current_video() {
	favorites.add({ video_id: _current_video.id });
	_current_video.favorite = true;
}
function unfavorite_current_video() {
	favorites.remove({ video_id: _current_video.id });
	_current_video.favorite = false;
}
function init_letterbar() {
	// bottom letter-bar animations
	$('div.scrollbutton').mouseover(function() { 
		$(this).animate({ fontSize: '50px', marginTop: '-20px' }, 50);
	}).mouseout(function() { 
		$(this).animate({ fontSize: '20px', marginTop: '12px' }, 50);
	});
}

function activateListItem(parent) {
	$(parent).siblings().removeClass('active_list_item');
	$(parent).addClass('active_list_item');
	return parent;
};

function navListElement(title) {
	elem = $('<div></div>').addClass('list_item').html(title);
	elem.click(function() { activateListItem(this); });
	return elem;
};

function render_input() {
	var container = $('#ui_templates .my_streamy_content_box').clone(true).removeClass('auto_resizable').css({ 
		height: 30, 
		width: '100%'
	});	
	var elem = $('#ui_templates .tpl_generic_input').clone(false);
	container.find('.content_box_inner').empty();
	elem.appendTo(container.find('.content_box_inner'));
	
	return { container: container, elem: elem };
};

var Server = {
	MyFeed: {
		currentData: [],
		last_seen: 0,
		first_load: true,
		hasListen: true,
		loadData: function() {
			var request = main_site_uri() + 'rpcs/getFeed.php?limit=50';
			if (Server.MyFeed.last_seen > 0) {
				request += '&start=' + Server.MyFeed.last_seen;
			}
			$.getJSON(request, function(data) {
				if (data.items.length) {
					// we walk backwards (oldest to newest) in existing events and in new events
					if (Server.MyFeed.first_load == false) {
//						console.log("New event and this isn't the first load");
						var new_array = [];
						var new_events = data.items;
//						console.log(new_events.length + ' new events received from getFeed.php');
						var j = new_events.length - 1;
						var next_new = new_events[j];
//						console.log('next_new = evid ' + next_new.id);
						var i = Server.MyFeed.currentData.length - 1; 
//						console.log('Currently we have ' + Server.MyFeed.currentData.length + ' events, i = ' + i);
						while (i >= 0) {
//							console.log('i=' + i + ' j=' + j);

							var item = Server.MyFeed.currentData[i];
								
							var found_new_id = 0;
							$.each(new_events, function(ii, jj) {
								if (jj.orig_id && jj.orig_id == item.id || (item.orig_id && jj.orig_id == item.orig_id)) {
									found_new_id = jj.id;
									return true;
								}
							});
							if (found_new_id > 0) {
//								console.log('This event got replaced by ' + found_new_id + ', removing from our cache.');
								$(item).trigger('replaced', found_new_id);
								--i;
								continue;
							}

							if (j >= 0 && item.timestamp > next_new.timestamp) { // existing event is newer than a new event
								// new event
//								console.log('This is a newer event - ' + next_new.id + ' (timestamp=' + next_new.timestamp + ')');
								new_array.push(next_new);
								$(item).trigger('insert_after', next_new);
								--j;
								if (j >= 0) {
									next_new = new_events[j];
								}
							}
//							console.log('event ' + item.id + ' (timestamp=' + item.timestamp + ') < event ' + next_new.id + ' (timestamp=' + next_new.timestamp + '); this is a previously-known event');
							new_array.push(item);
							--i;
						}

						while (j >= 0) {
							new_array.push(new_events[j]);
//							console.log('Triggering "new_message" event');
							$(Server.MyFeed).trigger('new_message', new_events[j]);

							if (new_events[j].messagetype == 11) {
								notify = new_events[j].target && new_events[j].target.id != profile.userProfile.user_id;
							} else {
								if (item.comments.length && item.comments[item.comments.length - 1].author_id != profile.userProfile.user_id) {
									notify = true;
								} else {
									notify = new_events[j].who && new_events[j].who.id != profile.userProfile.user_id;
								}
							}
							if (notify) {
//								console.log('notifying id=' + item.id + ' orig_id=' + item.orig_id);
								$(Server.MyFeed).trigger('notify', new_events[j]);
							} else {
//								console.log('not notifying' + item.id + ' orig_id=' + item.orig_id);
							}

							--j;
						}

						new_array.reverse();
						Server.MyFeed.currentData = new_array;
					} else {
						Server.MyFeed.currentData = data.items;
					}
					Server.MyFeed.last_seen = data.items[0].id;
//					console.log('Feed updated, posting event.');
					$(Server.MyFeed).trigger('updated');

/*
					$.each(data.items, function(i, item) {
						var notify = false;
						if (!Server.MyFeed.first_load) {
							if (item.orig_id && item.orig_id != 0) {
								// means the item is replacing another item (ID change)
								// we need to iterate through our array and find all previous copies
								// (expected only one, but just in case...) and remove them; since JS array
								// doesn't have remove nor lookups, this is tedious (iterate and copy)
								var new_array = [];
								$.each(Server.MyFeed.currentData, function(i, ii) {
									if (ii.id == item.orig_id || (ii.orig_id && ii.orig_id != 0 && ii.orig_id == item.orig_id)) {
										$(ii).trigger('replaced', item.id); // replaced with newer item
									} else {
										new_array.push(ii);
									}
								});
								Server.MyFeed.currentData = new_array;
							}

							// insert to beginning
							Server.MyFeed.currentData = [ item ].concat(Server.MyFeed.currentData);
							if (item.id > Server.MyFeed.last_seen) {
								$(Server.MyFeed).trigger('new_message', item);
							}
							if (item.messagetype == 11) {
								notify = item.target && item.target.id != profile.userProfile.user_id;
							} else {
								notify = item.who && item.who.id != profile.userProfile.user_id;
							}
							if (notify) {
//								console.log('notifying id=' + item.id + ' orig_id=' + item.orig_id);
								$(Server.MyFeed).trigger('notify', item);
							} else {
//								console.log('not notifying' + item.id + ' orig_id=' + item.orig_id);
							}
						} else {
							Server.MyFeed.currentData.push(item);
						}
					});
*/
				}
				Server.MyFeed.first_load = false;
				
				if (Server.MyFeed.hasListen) {
					setTimeout(function() {
						var start_listen = function() {
							$.ajax({
								url: '/listen?channel=0_' + $.cookie('cookuser') + '&evid=' + Server.MyFeed.last_seen,
								dataType: 'json',
								success: function(data) {
									Server.MyFeed.loadData();
								},
								error: function(request) { 
									if (request.status == 404) {
										setTimeout(function() { Server.MyFeed.loadData(); }, 3000); // fallback to polling
										Server.MyFeed.hasListen = false;
									} else {								
										setTimeout(function() { start_listen(); }, 1000); 
									}
								}
							});
						}
						start_listen();
					}, 1000);
				} else {
					setTimeout(function() { Server.MyFeed.loadData(); }, 3000);
				}
			});
		}
	},

	getData: function(params, callback) {},
	getGenres: function(callback) {},
	getVideoDetails: function(video_id, callback) {},
	getTopicDetails: function(topic_id, callback) {},
	getInbox: function(limit, callback) {
		$.getJSON(main_site_uri() + 'rpcs/getFeed.php?show=' + MESSAGE_PERSONAL + '&limit=' + limit, callback);
	},
	getUserFeed: function(user_id, limit, callback) {
		$.getJSON(main_site_uri() + 'rpcs/getFeed.php?other_id=' + user_id + '&other_type=' + USER_OBJECT + '&limit=' + limit, callback);
	},
	getRealtimeFeed: function(callback) {},
	followUser: function(user_id, callback) {
		$.get(main_site_uri() + 'rpcs/stats.php?qtype=11&follow=1&other_id=' + user_id + '&other_type=' + USER_OBJECT, callback);
	},
	followTopic: function(topic_id, callback) {},
	followVideo: function(video_id, callback) {},
	unFollowUser: function(user_id, callback) {
		$.get(main_site_uri() + 'rpcs/stats.php?qtype=11&follow=0&other_id=' + user_id + '&other_type=' + USER_OBJECT, callback);
	},
	unFollowTopic: function(topic_id, callback) {},
	unFollowVideo: function(video_id, callback) {},
	
	addFriend: function(user_id, callback) {
		$.get(main_site_uri() + 'rpcs/add_friend.php?user_id=' + user_id, callback);
	},
	removeFriend: function(user_id, callback) {
		$.get(main_site_uri() + 'rpcs/remove_friend.php?user_id=' + user_id, callback);
	},
	confirmFriend: function(user_id, callback) {
		$.get(main_site_uri() + 'rpcs/confirm_friend.php?user_id=' + user_id, callback);
	},
	ignoreFriendRequest: function(user_id, callback) {
		$.get(main_site_uri() + 'rpcs/ignore_friend.php?user_id=' + user_id, callback);
	}
};


function add_secnav_button(title, link, to) {
	var btn = $("<div><table cellpadding='0' cellspacing='0' class='st_outer'><tr><td class='full_showtype_left'>&nbsp;</td><td class='full_showtype_center unselectable sec_nav_btn_text'></td><td class='full_showtype_right'>&nbsp;</td></tr></table></div>");
	btn.find('.full_showtype_center').html(title);
	btn.css({ display: 'inline', float: 'left' });

	if (link) {
		btn.click(function() { 
			$('#secondary_navigation_bar .st_outer_active').removeClass('st_outer_active');
			$(this).addClass('st_outer_active');
			$.address.value(link); 
		});
	}

	if (to) {
		btn.appendTo(to);
		$('#secondary_navigation_bar .st_outer_active').removeClass('st_outer_active');
	} else {
		btn.appendTo($('#sec_nav_inner_left'));
		$('#secondary_navigation_bar .st_outer_active').removeClass('st_outer_active');
	}

	btn.addClass('st_outer_active');
	return btn;
}

function wrap_user_thumb_large(thumb_img) {
	var outer = $('<div></div>').addClass('user_thumb_wrapper user_thumb_wrapper_large');
	$('<div></div>').addClass('user_thumb_wrapper_overlay').appendTo(outer);
	var inner = $('<div></div>').addClass('user_thumb_wrapper_inner');
	$('<img />').attr({ src: thumb_img }).appendTo(inner);
	inner.appendTo(outer);
	return outer;
}

function wrap_user_thumb(thumb_img) {
	var outer = $('<div></div>').addClass('user_thumb_wrapper');
	$('<div></div>').addClass('user_thumb_wrapper_overlay').appendTo(outer);
	var inner = $('<div></div>').addClass('user_thumb_wrapper_inner');
	$('<img />').attr({ src: thumb_img }).appendTo(inner);
	inner.appendTo(outer);
	return outer;
}
function wrap_user_thumb_small(thumb_img) {
	var outer = $('<div></div>').addClass('user_thumb_wrapper user_thumb_wrapper_small');
	$('<div></div>').addClass('user_thumb_wrapper_overlay').appendTo(outer);
	var inner = $('<div></div>').addClass('user_thumb_wrapper_inner');
	$('<img />').attr({ src: thumb_img }).appendTo(inner);
	inner.appendTo(outer);
	return outer;
}
function wrap_user_thumb_micro(thumb_img) {
	var outer = $('<div></div>').addClass('user_thumb_wrapper user_thumb_wrapper_micro');
	$('<div></div>').addClass('user_thumb_wrapper_overlay').appendTo(outer);
	var inner = $('<div></div>').addClass('user_thumb_wrapper_inner');
	$('<img />').attr({ src: thumb_img }).appendTo(inner);
	inner.appendTo(outer);
	return outer;
}

function wrap_video_thumb(thumb_img) {
	var outer = $('<div></div>').addClass('video_thumb_wrapper');
	$('<div></div>').addClass('video_thumb_wrapper_overlay').appendTo(outer);
	var inner = $('<div></div>').addClass('video_thumb_wrapper_inner');
	$('<img />').attr({ src: thumb_img }).appendTo(inner);
	inner.appendTo(outer);
	return outer;
}

function wrap_video_thumb_small(thumb_img) {
	var outer = $('<div></div>').addClass('video_thumb_wrapper_small');
	$('<div></div>').addClass('video_thumb_wrapper_small_overlay').appendTo(outer);
	var inner = $('<div></div>').addClass('video_thumb_wrapper_small_inner');
	$('<img />').attr({ src: thumb_img }).appendTo(inner);
	inner.appendTo(outer);
	return outer;
}

function notification_message(title, message) {
	var c = $('#ui_templates .tpl_notif_message').clone(true);
	c.addClass('quicknote');
	c.find('.notif_message_title').html(title);
	c.find('.notif_message_text').html(message);
	return c;
}

function showRecommendDialog(other_id, other_type, data) {
	$('.watch_frame').hide();
	var tpl = createWindow({
		style: { width: 820, height: 390 },
		center: true,
		fixed_size: true
	});
//	tpl.find('.window_contents_wrapper').css({ top: 6 });
	tpl.find('.left_title').html('Recommend to a friend');
	$('#ui_templates .tpl_recommend').clone(true).appendTo(tpl.find('.window_contents'));
	tpl.find('.target_buttons').remove().appendTo(tpl.find('.right_title'));
	tpl.addClass('tpl_recommend');
	tpl.find('.recommend_left').css({ top: 0 });
	tpl.find('.recommend_right').css({ top: 0 });

	var cancel_btn = createCloudButton('med', 'Cancel');
	cancel_btn.addClass('cancel_button')
		.click(function() {
			tpl.remove();
			$('.watch_frame').show();
		})
		.appendTo(tpl.find('.window_bottom'));

	var recipient = '';
	var active_tab = 'rippol';
	var send_btn = createCloudButton('med', 'Send').css({ float: 'right' });

	var close_dialog = function() {
		tpl.remove();
		$('.watch_frame').show();
	}

	send_btn.addClass('send_button')
		.click(function() { 
			var subject = tpl.find('.message_title').find('input').attr('value');
			var message = tpl.find('.message_text').find('textarea').attr('value');
			if (subject == tpl.find('.message_title').find('input').attr('name')) {
				subject = '';
			}
			if (message == tpl.find('.message_text').find('textarea').attr('name')) {
				message = '';
			}
			if (active_tab == 'rippol' && recipient != '') {
				$.post(main_site_uri() + 'rpcs/send_message.php', 'other_type=0&other_id=' + recipient + '&message=' + message + '&subject=' + subject + '&attachment_id=' + other_id + '&attachment_type=' + other_type, function(data) {
					close_dialog();
				});
			} else if (active_tab == 'email' && recipient != '') {
				$.post(
					main_site_uri() + 'rpcs/recommend.php', {
						subject: subject,
						message: message,
						target: recipient,
						video_title: tpl.find('.video_title').html(),
						video_desc: tpl.find('.video_desc').html(),
						video_uri: share_link
					},
					function(data) {
						if (data.error) {
							alert(data.error);
						} else {
							close_dialog();
						}
					},
					'json'
				);
			} else if (active_tab == 'facebook' && recipient != '') {
				message += ' ' + tpl.find('.video_title').html() + ' ' + share_link;
				message = message.replace('#', '%23');
				message = message.replace('&', '%26');
				if (subject == '') {
					subject = 'check this out';
				}
				subject = subject.replace('#', '%23');
				subject = subject.replace('&', '%26');
				var uri = "http://www.facebook.com/inbox/?compose=1&id=" + recipient + "&subject=" + subject + '&message=' + message;
				window.open(uri);
				close_dialog();
			} else if (active_tab == 'twitter' && recipient != '') {
				var max_msg_len = 140 - 29 - recipient.length - 2;
				if (message == '') {
					message = tpl.find('.video_title').html();
				}
				message = '@' + recipient + ' ' + message.substr(0, max_msg_len);
//				message = message.replace('#', '%23');
//				message = message.replace('&', '%26');
				var tw_share = Base64.encode('http://twitter.com/home?status=' + urlencode(message) + ' TEMPLATE %23Rippol');
				window.open(main_site_uri() + 'shorten.php?shorten=' + Base64.encode(data.share_link) + '&target=' + tw_share, '', "width=800,height=400,scrollbars=yes");
			} else {
				alert('Recipient not selected.');
			}
		})
		.appendTo(tpl.find('.window_bottom'));
	wrap_user_thumb_small(profile.userProfile.thumb)
		.appendTo(tpl.find('.my_thumb_container'));

	var scrollify_desc = function() {
		tpl.find('.video_details_inner').jScrollPane({
			wheelSpeed: 50,
			showArrows: false,
			dragMinHeight: 46,
			dragMaxHeight: 46,
			scrollbarWidth: 8
		});
	}

	var share_link = '';
	var process_data = function() {
		share_link = main_site_uri() + '?';
		if (other_type == VIDEO_OBJECT) {
			wrap_video_thumb(data.thumb).appendTo(tpl.find('.video_thumbnail'));
			tpl.find('.video_title').html(data.title);
			tpl.find('.video_desc').html(data.desc ? data.desc : data.description);
			share_link += 'v=' + other_id
		} else if (other_type == TOPIC_OBJECT) {
			wrap_video_thumb(data.thumb).appendTo(tpl.find('.video_thumbnail'));
			tpl.find('.video_title').html(data.title);
			tpl.find('.video_desc').html(data.desc ? data.desc : data.description);
			share_link += 't=' + other_id;
		} else if (other_type == FRIENDCAST_OBJECT) {
			wrap_video_thumb(data.thumb).appendTo(tpl.find('.video_thumbnail'));
			tpl.find('.video_title').html(data.title);
			tpl.find('.video_desc').html(data.desc ? data.desc : data.description);
			share_link += 'f=' + other_id;
		} else if (other_type == EXTERN_OBJECT) {
			wrap_video_thumb(data.thumb).appendTo(tpl.find('.video_thumbnail'));
			tpl.find('.video_desc').html(data.desc ? data.desc : data.description);
			share_link += 'e=' + other_id;
		}
		scrollify_desc();
	}

	if (!data) {
		if (other_type == VIDEO_OBJECT) {
			$.getJSON(main_site_uri() + 'rpcs/getVideo.php?video_id=' + other_id, function(_data) { 
				data = _data; 
				process_data();
			});
		} else if (other_type == TOPIC_OBJECT) {
			$.getJSON(main_site_uri() + 'rpcs/getVideo.php?topic_id=' + other_id, function(_data) {
				data = _data;
				process_data();
			});
		} else if (other_type == FRIENDCAST_OBJECT) {
			$.getJSON(main_site_uri() + 'rpcs/getVideo.php?fcast_id=' + other_id, function(_data) {
				data = _data;
				process_data();
			});
		} else if (other_type == EXTERN_OBJECT) {
			$.getJSON(main_site_uri() + 'rpcs/getVideo.php?extern_id=' + other_id, function(_data) {
				data = _data;
				process_data();
			});
		}
	} else {
		process_data();
	}

	var toggle_button = function(self) {
		tpl.find('.target_buttons').find('.cloud_btn_subnav_alternate').removeClass('cloud_btn_subnav_alternate');
		$(self).addClass('cloud_btn_subnav_alternate');
	};

	var scrollify = function() {
		tpl.find('.friends_area_inner').jScrollPane(JSCROLLPANE_OPTIONS);
	}


	var render_friends = function(data) {
		var results = tpl.find('.friends_area_inner');
		$.each(data, function(i, item) {
			var thumb = wrap_user_thumb_small(item.thumb).css({ float: 'left', marginRight: -10 });
			var name = $('<div></div>').css({ paddingTop: 20 }).html(item.firstName + ' ' + item.lastName);
			var elem = $('<div></div>').addClass('recommend_friends_elem');
			elem.click(function() {
				results.find('.recommend_friends_elem_selected').removeClass('recommend_friends_elem_selected');
				$(this).addClass('recommend_friends_elem_selected');
				recipient = item.id;
			});

			thumb.appendTo(elem);
			name.appendTo(elem);
			elem.appendTo(results);
		});
		tpl.find('.friends_area_inner').jScrollPane(JSCROLLPANE_OPTIONS);
	};

	var rippol = createCloudButton('subnav', 'Rippol').click(function() {
		if (!$(this).hasClass('cloud_btn_subnav_alternate')) {
			active_tab = 'rippol';
			toggle_button(this);
			tpl.find('.message_title').show();
			var text = 'Type friend name to search';
			tpl.find('.search_area input').remove();
			$('#ui_templates .tpl_generic_input').clone(true).attr({ name: text, value: text }).appendTo(tpl.find('.search_area'));
			var load_friends = function() {
				var i = tpl.find('.search_area input');
				var filter = '';
				if (i.attr('value') != i.attr('name')) {
					filter = 's=' + i.attr('value');
				}
				$.getJSON(main_site_uri() + 'rpcs/get_friends.php?limit=50&' + filter, function(data) {
					tpl.find('.friends_area_inner').empty();
					render_friends(data.friends);
				});
				scrollify();
			}
			load_friends();
			tpl.find('.search_area input').keyup(function() {
				$.doTimeout('search_rippol_friends', 400, function() {
					load_friends();
				});
			});
		}
	});
	rippol.appendTo(tpl.find('.target_buttons'));

	var email = createCloudButton('subnav', 'Email').click(function() {
		if (!$(this).hasClass('cloud_btn_subnav_alternate')) {
			active_tab = 'email';
			toggle_button(this);
			tpl.find('.message_title').show();
			tpl.find('.friends_area_inner').empty();
			scrollify();
			var text = 'Type email address to send to';
			tpl.find('.search_area input').remove();
			$('#ui_templates .tpl_generic_input').clone(true).attr({ name: text, value: text }).appendTo(tpl.find('.search_area'));
			tpl.find('.search_area input').keyup(function() {
				recipient = $(this).attr('value');
			});
		}
	});
	email.appendTo(tpl.find('.target_buttons'));

	var loadingIcon = { show: function() { }, hide: function() {} };

	var facebook = createCloudButton('subnav', 'Facebook')
		.addClass('facebook_button')
		.click(function() {
			if (!$(this).hasClass('cloud_btn_subnav_alternate')) {
				active_tab = 'facebook';
				toggle_button(this);
				var text = 'Type friend name to search';
				tpl.find('.message_title').show();
				tpl.find('.search_area input').remove();
				$('#ui_templates .tpl_generic_input').clone(true).attr({ name: text, value: text }).appendTo(tpl.find('.search_area'));

				var start = 0;
				var limit = 10;
				var last = 0;
				var request_in_progress = false;

				var load_facebook_friends = function() {
					request_in_progress = true;
					loadingIcon.show();
					var results = tpl.find('.friends_area_inner');
					facebook_login(function() {
						enable_facebook_features(); // turns on chat and stuff
						var uid = FB.Connect.get_loggedInUser();
						var str_filter = tpl.find('.search_area input').attr('value');
						var query = "SELECT first_name, last_name, sex, uid, pic, is_app_user, status, about_me FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + uid + ")";
						if (str_filter != '' && str_filter != tpl.find('.search_area input').attr('name')) {
							query += " AND (strpos(lower(first_name), lower('" + str_filter + "')) == 0 OR strpos(lower(last_name), lower('" + str_filter + "')) == 0)";
						}
						query += " ORDER BY first_name LIMIT " + start + ',' + limit;
						request_in_progress = true;
						last = 0;
						FB.Facebook.apiClient.fql_query(query, function(data) {
							if (start == 0) {
								tpl.find('.friends_area_inner').empty();
							}
							$.each(data, function(i, item) {
								item.firstName = item.first_name;
								item.lastName = item.last_name;
								item.thumb = item.pic;
								item.id = 'fb' + item.uid;
								item.fb_uid = item.uid;

								var thumb = wrap_user_thumb_small(item.thumb).css({ float: 'left' });
								var name = $('<div></div>').css({ paddingTop: 20 }).html(item.firstName + ' ' + item.lastName);
								var elem = $('<div></div>').addClass('recommend_friends_elem');
								elem.click(function() {
									results.find('.recommend_friends_elem_selected').removeClass('recommend_friends_elem_selected');
									$(this).addClass('recommend_friends_elem_selected');
									recipient = item.fb_uid;
								});

								thumb.appendTo(elem);
								name.appendTo(elem);
								elem.appendTo(results);
								last = elem;

								++start;
							});
							if (!data || data.length < limit) {
								last = 0;
							}
							request_in_progress = false;
							loadingIcon.hide();
							scrollify();
						});
					});
				};

				tpl.find('.friends_area_inner').scroll(function() {
					if (active_tab == 'facebook') {
						if (last && !request_in_progress) {
							if (tpl.find('.friends_area_inner').position().top + last.position().top <= tpl.find('.friends_area_inner').parent().height()) {
								load_facebook_friends();
							}
						}
					}
				});

				tpl.find('.search_area input').keyup(function() {
					$.doTimeout('search_facebook_friends', 400, function() {
						start = 0;	
						load_facebook_friends();
					});
				});

				load_facebook_friends();
			}
		});

	facebook.appendTo(tpl.find('.target_buttons'));
	
	var twitter = createCloudButton('subnav', 'Twitter')
		.addClass('twitter_button')
		.click(function() {
			if (!$(this).hasClass('cloud_btn_subnav_alternate')) {
				active_tab = 'twitter';
				toggle_button(this);
				var results = tpl.find('.friends_area_inner');
				results.empty();
//				var text = 'Type friend name to search';
				tpl.find('.search_area input').remove();
				tpl.find('.message_title').hide();
//				$('#ui_templates .tpl_generic_input').clone(true).attr({ name: text, value: text }).appendTo(tpl.find('.search_area'));
				var load_friends = function() {
					$.getJSON('http://twitter.com/statuses/friends.json?callback=?', function(data) {
						$.each(data, function(i, item) {
							item.firstName = item.screen_name;
							item.lastName = '';
							item.thumb = item.profile_image_url;
							item.tw_uid = item.uid;
							item.id = 'tw' + item.tw_uid;

							var thumb = wrap_user_thumb_small(item.thumb).css({ float: 'left', marginRight: -10 });
							var name = $('<div></div>').css({ paddingTop: 20, paddingLeft: 10 }).html(item.firstName + ' ' + item.lastName);
							var elem = $('<div></div>').addClass('recommend_friends_elem');
							elem.click(function() {
								results.find('.recommend_friends_elem_selected').removeClass('recommend_friends_elem_selected');
								$(this).addClass('recommend_friends_elem_selected');
								recipient = item.screen_name;
							});

							thumb.appendTo(elem);
							name.appendTo(elem);
							elem.appendTo(results);
							last = elem;
						});
						scrollify();
					});
				}
				load_friends();
//				tpl.find('.search_area input').keyup(function() {
//					$.doTimeout('search_rippol_friends', 400, function() {
//						load_friends();
//					});
//				});
			}
	});
	twitter.appendTo(tpl.find('.target_buttons'));

	rippol.trigger('click');
}

function send_message_dialog(data) {
	var tpl = $('#ui_templates .send_msg_wnd').clone(true);
	tpl.find('input[name=other_id]').attr({ value: data.user_id });
	tpl.find('form').ajaxForm(function() {
		tpl.remove();
	});
	var default_subject_text = 'Type message subject here';
	tpl.find('input[name=subject]').attr({ value: default_subject_text }).focus(function() {
		if ($(this).attr('value') == default_subject_text) {
			$(this).attr({ value: '' });
		}
	}).blur(function() {
		if ($(this).attr('value') == '' || $(this).attr('value') == $(this).attr('name')) {
			$(this).attr({ value: default_subject_text });
		}
	});
	var default_message_text = 'Type message text here';
	tpl.find('textarea[name=message]').attr({ value: default_message_text }).focus(function() {
		if ($(this).attr('value') == default_message_text) {
			$(this).attr({ value: '' });
		}
	}).blur(function() {
		if ($(this).attr('value') == '' || $(this).attr('value') == $(this).attr('name')) {
			$(this).attr({ value: default_message_text });
		}
	});

	tpl.find('.header').html('Sending message to ' + data.firstName);
	createCloudButton('notif', 'Cancel').css({ float: 'right', marginRight: 4 }).mouseup(function() {
		tpl.remove();
	}).appendTo(tpl.find('.submit_container'));
	createCloudButton('notif', 'Send').css({ float: 'right', marginRight: 4 }).mouseup(function() {
		tpl.find('form').submit();
	}).appendTo(tpl.find('.submit_container'));
	tpl.appendTo('body');
}

function process_embed_code(data) {
	if (data.provider_id != 1 && data.embed_code && data.embed_code != '' && data.embed_code != 'undefined') {
		if (data.embed_code.search('http://academicearth.org/') != -1) {
			data.embed_object = $(data.embed_code).find('embed');
		} else if (data.embed_code.search('ustream.tv') != -1) {
			data.embed_code = data.embed_code.replace(/autoplay=false/g, 'autoplay=true');
			data.embed_object = $(data.embed_code);
		} else {
			data.embed_object = $(data.embed_code);
		}
		var e = data.embed_object.find('embed');
		if (e.attr('src')) {
			if (e.attr('src').search('youtube.com') != -1) {
				e.attr({ src: e.attr('src') + '&fs=1&autoplay=1' });
			} else if (e.attr('src').search('joost.com') != -1) {
				e.attr({ src: e.attr('src') + '?autoplay=true' });
			} else if (e.attr('src').search('5min.com') != -1) {
				e.attr({ src: e.attr('src') + '?isAutoStart=True' });
			}
		}
		data.embed_object.attr({ wmode: 'transparent' });
		if (data.provider_id != 23 || data.embed_code.search('last.fm') == -1) {
			data.embed_object.attr({ width: '100%', height: '100%' })
				.css({ width: '100%', height: '100%' });
		}
		if (data.embed_object.find('embed')) {
			data.embed_object.find('embed').attr({wmode : 'transparent' });
			if (data.provider_id != 23 || data.embed_code.search('last.fm') == -1) {
				data.embed_object.find('embed').attr({ width: '100%', height: '100%' })
					.css({ width: '100%', height: '100%' });
			}
		}
	} else {
		if (data.provider_id && data.video_id) {
			data.embed_object = $('<iframe />').attr({ frameBorder: 0, border: 0, width: '100%', height: '100%', src: main_site_uri() + 'pre_paid.php?v=' + data.video_id });
		} else {
			data.embed_object = $('<iframe />').attr({ frameBorder: 0, border: 0, width: '100%', height: '100%', src: data.watch_uri });
		}
	}
}

function process_chat_embed(data) {
	if (data.embed_chat) {
/*
		var wrapper = $('<div></div>').css({ 
			zIndex: 35, 
			position: 'absolute', 
			bottom: 30, 
			left: 0, 
			width: 350, 
			height: 400,
			backgroundColor: 'white'
		});
		wrapper.attr({ id: 'live_chat' });
*/
		var attrs = { wmode: 'transparent', width: '100%', height: '100%' };
		var style = { width: '100%', height: '100%', backgroundColor: 'white' };
		data.chat_object = $(data.embed_chat);
		data.chat_object.attr(attrs);
		data.chat_object.find('object').attr(attrs);
		data.chat_object.find('object').css(style);
		data.chat_object.css(style);
/*
		$('#live_chat').remove();
		$('#live_chat_button').remove();
		data.chat_object.appendTo(wrapper);
		var btn = createCloudButton('notif', 'Hide Live Chat').attr({ id: 'live_chat_button' });
		btn.click(function() {
			if (wrapper.css('display') == 'block') {
				$(this).find('.btn_text').html('Live Chat');
				wrapper.hide();
			} else {
				$(this).find('.btn_text').html('Hide Live Chat');
				wrapper.show();
			}
		});
		btn.appendTo('.bottom_left_buttons');
		wrapper.prependTo('body');
*/
	}
}

function main_site_uri() {
	if ($('#site_uri').length > 0) {
		return $('#site_uri').attr('href');
	} else {
		return $('#light_logo').parent('a').attr('href');
	}
}

var createWindow = function(options) {
	var w = $('#ui_templates .window').clone(true);

	if (options && options.style) { w.css(options.style); }

	var min_top = 0;

	if (!options || !options.no_move) {
		w.find('.window_title').css({ cursor: 'move' }).bind('drag', function(event) {
			if (event.offsetY < min_top) { event.offsetY = min_top; }
			$(this).parents('.window').css({ left: event.offsetX - 20, top: event.offsetY - 5 });
		});
	}

	if (!options || !options.fixed_size) {
		w.find('.top_left').css({ cursor: 'nw-resize' }).bind('drag', function(event) {
			if (event.offsetY < min_top) { event.offsetY = min_top; }
			var w = $(this).parents('.window');
			var aw = w.offset().left - event.offsetX;
			var ah = w.offset().top - event.offsetY;
			w.css({ 
				width: w.width() + aw, left: event.offsetX,
				height: w.height() + ah, top: event.offsetY
			});
			w.trigger('resize');
		});
		w.find('.top_center').css({ cursor: 'n-resize' }).bind('drag', function(event) {
			if (event.offsetY < min_top) { event.offsetY = min_top; }
			var w = $(this).parents('.window');
			var ah = w.offset().top - event.offsetY;
			w.css({ height: w.height() + ah, top: event.offsetY });
			w.trigger('resize');
		});
		w.find('.top_right').css({ cursor: 'ne-resize' }).bind('drag', function(event) {
			if (event.offsetY < min_top) { event.offsetY = min_top; }
			var w = $(this).parents('.window');
			var ah = w.offset().top - event.offsetY;
			w.css({ 
				width: event.offsetX - w.offset().left + 9,
				height: w.height() + ah, top: event.offsetY
			});
			w.trigger('resize');
		});
		w.find('.center_right').css({ cursor: 'e-resize' }).bind('drag', function(event) {
			var w = $(this).parents('.window');
			w.css({ width: event.offsetX - w.offset().left + 9 });
			w.trigger('resize');
		});
		w.find('.bottom_right').css({ cursor: 'se-resize' }).bind('drag', function(event) {
			var w = $(this).parents('.window');
			w.css({ 
				width: event.offsetX - w.offset().left + 9,
				height: event.offsetY - w.offset().top + 14
			});
			w.trigger('resize');
		});
		w.find('.bottom_center').css({ cursor: 's-resize' }).bind('drag', function(event) {
			var w = $(this).parents('.window');
			w.css({ height: event.offsetY - w.offset().top + 14});
			w.trigger('resize');
		});
		w.find('.bottom_left').css({ cursor: 'sw-resize' }).bind('drag', function(event) {
			var w = $(this).parents('.window');
			var aw = w.offset().left - event.offsetX;
			w.css({ 
				height: event.offsetY - w.offset().top + 14,
				width: w.width() + aw, left: event.offsetX
			});
			w.trigger('resize');
		});
		w.find('.center_left').css({ cursor: 'w-resize' }).bind('drag', function(event) {
			var w = $(this).parents('.window');
			var aw = w.offset().left - event.offsetX;
			w.css({ width: w.width() + aw, left: event.offsetX });
			w.trigger('resize');
		});
	}
	w.appendTo('body');
	var re_size = function() {
		if ($(window).height() < w.height()) {
			w.css({ height: $(window).height() });
		} else {
			w.css({ height: options.style.height });
		}
		if ($(window).width() < w.width()) {
			w.css({ width: $(window).width() });
		} else {
			w.css({ width: options.style.width });
		}
		w.trigger('resize');
	}
	var re_center = function() {
		if (options && options.center) {
			var top = ($(window).height() - w.height() - min_top) / 2;
			if (top < min_top) {
				top = min_top;
			}
			w.css({ 
				top: top,
				left: ($(window).width() - w.width()) / 2
			});
		}
	};
	var re_scroll = function() {
		if (!options || !options.no_scroll) {
			setTimeout(function() {
				w.find('.window_contents').jScrollPane({ 
					wheelSpeed: 50, 
					showArrows: false,
					dragMinHeight: 66,
					dragMaxHeight: 66,
					scrollbarWidth: 17
				});
				w.find('.jScrollPaneContainer').css({ width: '100%', height: '100%' });
			});
		}
	}
	$(window).resize(function() { 
		re_size(); 
		if (options && options.no_move) {
			re_center(); 
		}
		re_scroll();
	});
	re_size();
	re_center();
	w.resize(function() { re_scroll(); });

	if (options && options.modal) {
		$('#fade_black').show();
		$('iframe').hide();
		w.css({ zIndex: $('#fade_black').css('zIndex') + 1 });
		w.fadeIn(300, re_scroll);
		if ($.browser.msie) {
			w.find('.window_outer_table .center_center').css({ 
				backgroundColor: 'rgb(235, 235, 235)'
			});
		}
	} else {
		w.fadeIn(300, re_scroll);
	}
	return w;
}

function loadExternalSite(url, title) {
	var w = createWindow({ style: { width: 1060, height: 800 }, modal: true, fixed_size: true, no_move: true, center: true });
	w.find('.left_title').html(title);
	var f = $('<iframe></iframe>').attr({ border: 0, id: 'top_frame', frameBorder: 0, src: url, scrolling: 'auto' });
	f.appendTo(w.find('.window_contents'));

	var return_address = last_address;
	createCloudButton('med', 'Close').css({ float: 'right' }).click(function() { 
		w.remove();
		$('#fade_black').hide();
		if (return_address && return_address.value != $.address.value()) {
			$.address.value(return_address.value);
		} else {
			$.address.value('/');
		}
	}).appendTo(w.find('.window_bottom'));
}

function get_var(name) {
	var input = $('#_GET input[name=' + name + ']');
	if (input) {
		return input.attr('value');
	} else {
		return undefined;
	}
}

function showTypeToName(showType) {
	var showTypeMap = {
		episode: 'TV Shows',
		movie: 'Movies',
		sports: 'Sports',
		news: 'News',
		lecture: 'Academic',
		clip: 'Clip',
		live: 'Live',
		political: 'Political',
		tutorials: 'Tutorials',
		trailers: 'Trailers',
		music: 'Music'
	};
	return eval('showTypeMap.' + showType);
}

function previewFriendcast(data) {
	var wnd = createWindow({
		center: true,
		fixed_size: true,
		style: { width: 640, height: 440 }
	});
	var tpl = $('#ui_templates .preview_friendcast').clone(true);
	tpl.appendTo(wnd.find('.window_contents'));

	wnd.find('.left_title').html('Friendcast - ' + data.title);
	if (data.showType) {
		wnd.find('.video_showtype').attr({ value: data.showType });
	}
	if (data.genre) {
		wnd.find('.video_genre').attr({ value: data.genre }).css({ color: 'black' });
	}
	if (data.topic) {
		wnd.find('.video_topic').attr({ value: data.topic }).css({ color: 'black' });
	}
	if (data.subtopic) {
		wnd.find('.video_subtopic').attr({ value: data.subtopic }).css({ color: 'black' });
	}
	createCloudButton('med', 'Cancel')
		.css({ float: 'left' })
		.click(function() { wnd.remove(); })
		.appendTo(wnd.find('.window_bottom'));
	createCloudButton('med', 'Friendcast')
		.css({ float: 'right' })
		.click(function() {
			var me = tpl.find('.manual_embed');
			if (me && me.attr('name') != me.attr('value')) {
				data.embed_code = me.attr('value');
			} else {
				if (!data.embed_code) {
					data.embed_code = '';
				}
			}
			var showtype = tpl.find('.video_showtype').attr('value');
			var genre = tpl.find('.video_genre').attr('value');
			if (genre == tpl.find('.video_genre').attr('name')) { genre = ''; };
			var topic = tpl.find('.video_topic').attr('value');
			if (topic == tpl.find('.video_topic').attr('name')) { topic = ''; };
			var subtopic = tpl.find('.video_subtopic').attr('value');
			if (subtopic == tpl.find('.video_subtopic').attr('name')) { subtopic = ''; }
			var title = tpl.find('.video_title').attr('value');
			if (title == tpl.find('.video_title').attr('name')) { title = ''; }
			var desc = tpl.find('.video_desc').attr('value');
			if (desc == tpl.find('.video_desc').attr('name')) { desc = ''; }
			var post_data = {
				url: data.watch_uri,
				showType: showtype,
				genre: genre,
				topic: topic,
				subtopic: subtopic,
				embed_code: data.embed_code,
				title: title,
				description: desc,
				thumb: data.thumb
			};
			if (data.embed_chat) {
				post_data.embed_chat = data.embed_chat;
			}
			$.post(main_site_uri() + 'rpcs/friendcast.php', post_data, function(data) {
				wnd.remove();
			}, 'json');			
		}).appendTo(wnd.find('.window_bottom'));
	
	wrap_user_thumb_small(profile.userProfile.thumb)
		.css({ float: 'left' })
		.prependTo(tpl.find('.notice_cell'));

	if (data.embed_code) {
		process_embed_code(data);
		if (data.embed_object) {
			data.embed_object.appendTo(tpl.find('.embed_container'));
		}
	} else {
		var ef = $('#ui_templates .friendcast_embed_failed').clone(true);
		rounded_corner(ef, 4);
		ef.appendTo(tpl.find('.embed_container'));
		
	}
	if (data.title) {
		tpl.find('.video_title').attr({ value: data.title }).css({ color: 'black' });
	}
	if (data.desc) {
		tpl.find('.video_desc').html(data.desc).css({ color: 'black' });
	}
}

function rounded_corner(element, size) {
	element.css("-moz-border-radius", size + "px");
	element.css("-webkit-border-radius", size + "px");
	element.css("-khtml-border-radius", size + "px");
}

function chat_wnd(data, item) {
	var event_id = 0;
	if (item) {
		event_id = item.id;
		if (item.orig_id && item.orig_id != 0) {
			event_id = item.orig_id;
		}
		if ($('.chat_wnd_evid_' + event_id).length > 0) {
			return; // we already have a chat window for this event
		}
	}

	var wnd = createWindow({
		center: true,
		style: { width: 400, height: 300 }
	});
	wnd.find('.window_inner_wrapper').css({ bottom: 62 });
	wnd.find('.inner_center_background').css({ bottom: 63 });
	wnd.find('.window_contents_wrapper').css({ bottom: 64 });

	if (!data.firstName) {
		data.firstName = data.title;
	}

	wnd.find('.left_title').html('Chat with ' + data.firstName);
	createCloudButton('notif', 'Close')
		.click(function() { 
			$(Server.MyFeed).unbind('new_message', on_message); 
			wnd.remove(); 
		})
		.css({ float: 'right' })
		.appendTo(wnd.find('.right_title'));

	var tpl = $('#ui_templates .chat_lower').clone(false);
	var send_btn = createCloudButton('med', 'Send').css({ float: 'right' });
	send_btn.appendTo(tpl.find('.chat_send_button_cell'));
	tpl.appendTo(wnd.find('.window_bottom'));
	var first_message = true;
	var text_area = tpl.find('textarea');
	text_area.css({ color: 'black' });
	text_area.bind('keyup', 'return', function() { 
//		console.log('(myid=' + event_id + '): textarea enter pressed');
		if ($(this).attr('value') != "\n" && $(this).attr('value') != '') {
			send_btn.trigger('click'); 
		} else {
			$(this).attr('value') = '';
		}
	});
	text_area.focus();

	var append_message = function(who, message) {
//		console.log('(myid=' + event_id + '): appending message:' + message);
		var wrapper = $('<div></div>').css({ width: '100%' });
		$('<div></div>').html('<b>' + who + '</b>&gt; ' + message).appendTo(wrapper);
		wrapper.appendTo(wnd.find('.window_contents'));
		wnd.trigger('resize');
		wnd.find('.window_contents')[0].scrollTo(wrapper.offset().top);
	}

	// incoming chat
	if (item) { // event_id is updated in the beginning of this func
		$('<div></div>').addClass('chat_wnd_evid_' + event_id).css({ display: 'none' }).appendTo(wnd.find('.window_contents'));
		first_message = false;
		append_message(item.who.title, item.main_msg);
	}

	var last_comment = -1;
	var on_message = function(event, item) {
//		console.log('(myid=' + event_id + '): an event happened');
//		console.log('(myid=' + event_id + '): our event_id=' + event_id + ' item.id=' + item.id + ' item.orig_id=' + item.orig_id);
		if (item.id == event_id || (item.orig_id && item.orig_id == event_id)) {
//			console.log('(myid=' + event_id + '): rendering comments');
			if (item.comments && item.comments.length) {
				$.each(item.comments, function(i, comment) {
					if (i > last_comment) {
						last_comment = i;
						if (comment.author_id != $.cookie('cookuser')) {
							append_message(comment.title, comment.comment);
						}
					}
				});
			} else { // first message only
				if (item.who.id != $.cookie('cookuser')) {
					append_message(item.who.title, item.main_msg);
				}
			}
		} else {
//			console.log('(myid=' + event_id + '): This is not our event');
		}
	}
	$(Server.MyFeed).bind('new_message', on_message);

	send_btn.click(function() {
		var message = text_area.attr('value');
		if (message == "\n" || message == "") {
			return;
		}
//		$('(myid=' + event_id + '): send button clicked');
		text_area.attr({ value: '' });
		append_message('Me', message);
		if (first_message == true) {
//			console.log('sending first message');
			$.post(
				main_site_uri() + 'rpcs/send_message.php', 
				'other_id=' + String(data.user_id) + 
				'&other_type=' + String(USER_OBJECT) + 
				'&message=' + message + 
				'&chat=1', function(data) {
					first_message = false;
					event_id = data.id;
					$('<div></div>').addClass('chat_wnd_evid_' + event_id).css({ display: 'none' }).appendTo(wnd.find('.window_contents'));
					wnd.trigger('resize');
//					console.log(' our chat event id is ' + event_id);
				}, 'json'
			);
		} else {
			$.post(
				main_site_uri() + 'rpcs/eventComment.php',
				'event_id=' + event_id + '&comment=' + message + '&action=add',
				function(data) {
				}, 'json'
			);
		}
	});
}

function StopWatch() {
	var timer = {
		start: new Date(),
		elapsed: function() {
			var end = new Date();
			return end.getTime() + end.getMilliseconds() - (timer.start.getTime() + timer.start.getMilliseconds());
		},
		reset: function() {
			timer.start = new Date();
		}
	};
	return timer;
}

function timestamp_to_since(timestamp) {
	if (isNaN(parseInt(timestamp)) || parseInt(timestamp) < 100) {
		return timestamp;
	}
	var cur = new Date();
	var cur_ms = Math.floor(cur.getTime() / 1000);
	var evt_ms = Math.floor(parseInt(timestamp));
	var timediff = cur_ms - evt_ms;

	if (timediff < 0) {
		return 'just now';
	} else if (timediff < 60) {
		return timediff + ' seconds ago';
	} else if (timediff < 60*60) {
		return Math.floor(timediff / 60) + ' minutes ago';
	} else if (timediff < 60*60*24) {
		return Math.floor(timediff / 60 / 60) + ' hours ago';
	} else if (timediff < 60*60*24*2) {
		return 'yesterday';
	} else if (timediff < 60*60*24*3) {
		return 'two days ago';
	} else {
		var evt_d = new Date();
		evt_d.setTime(evt_ms * 1000);
		return evt_d.toLocaleDateString();
	}
}

// creates a new cloud button of specified size 
// ('small', 'med', 'large') and title and returns it
function createCloudButton(size, text, clone, showType) {
	var btn = $('#tpl_cloud_btn_' + size).clone(clone);
	if (showType) {
		btn.addClass('cloud_btn_' + showType);
	}
	btn.find('.btn_text').addClass('unselectable').text(text);
	var icon = $('<div class="btn_icon"></div>');
	icon.prependTo(btn.find('.btn_text'));

	btn.mouseover(function() {
		if (showType) {
			$(this).addClass('cloud_btn_' + size + '_' + showType + '_overlay');
		} else {
			$(this).addClass('cloud_btn_' + size + '_overlay');
		}
	}).mouseout(function() {
		if (showType) {
			$(this).removeClass('cloud_btn_' + size + '_' + showType + '_overlay');
		} else {
			$(this).removeClass('cloud_btn_' + size + '_overlay');
		}
	});

	btn.addClass(btn.attr('id'));
	btn.attr({ 'id' : ''});

	// button click (pressed) animation
	btn.mousedown(function() {
		$(this).css({ paddingTop: 2, paddingBottom: 0, paddingLeft: 2, paddingRight: 0 })
	}).mouseup(function() {
		$(this).css({ padding: 1 });
	});

	return btn;
}
