// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// STAGE EVENTS

	// ----------------------------------------------------------------------------------------
	// private variables

		_stage_v_is_initial = true;
		_stage_v_stagename = '';
		_stage_v_stagetiedto = '';
		_stage_v_stagemode = 'default';
		_stage_v_stagetheme = 'default';
		_stage_v_timeout = false;
		_stage_v_ajax = false;
		_stage_v_testmodedisplayid = false;
		_stage_v_isloggedin = false;
		_stage_v_username = false;
		_stage_v_lastalert = '';
		_general_using_stage = false;	/* false if there is no stage on this page - true if there is */
		_stage_v_lastpageshown = 0;
		_stage_v_getapage = false;


	// ----------------------------------------------------------------------------------------
	// private functions

		function _stage_reply_return_check(e, formid) {
			if((e.keyCode || e.which) == 13) $('#'+formid).submit();
		}


		function _stage_update(page) {
			// is this a call for a numbered page of results, or an update?
			var pg = '';
			if(_stage_v_getapage) { _stage_v_lastpageshown++; pg = '&pg='+_stage_v_lastpageshown; }
			var newthreadcounter = 0;

			// turn on the ping led
			$('#noticeping').attr('src', '/images/led_on.gif');
			// run the ajax to get any updates
			//dom_ajax('/ajax/stage-updater.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+pg, null, '_stage_update_response');
			//dom_ajax('/ajax/event-server.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&sm='+_stage_v_stagemode+pg, null, '_stage_update_response');
			$.get('/ajax/event-server.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&sm='+_stage_v_stagemode+pg, function(data) {
		//}

		//function _stage_update_response(data) {
			// turn the ping led off
			$('#noticeping').attr('src', '/images/led_out.gif');
			// if we've got data, deal with it
			if(data != '' && data != null) {
				// split the incoming data up
				events = data.split('|');
				//if(_stage_v_testmodedisplayid != false) $('#'+_stage_v_testmodedisplayid).val('Debug: '+events[0]+' '+events[1]);
				// what is our response code?
				if(events[0] == 'Error') {
					// show an error
					alert('Oops, there was an error:\n'+events[1]);
					// stop everything
					stage_stop();
					return;
				} else if(events[0] == 'Timeout') {
					// do nothing
					tmp = 1;
				} else if(events[0] == 'None') {
					// do nothing
					tmp = 1;
				} else if(events[0] == 'P-Ok' || events[0] == 'U-Ok' || events[0] == 'X-Ok') {
					// what sort of set of events was this?
					if(events[0] == 'P-Ok') waspage = true; else waspage = false;
					// iterate through the events
					for(var i = 2; i < events.length; i++) {
						if(events[i] != '') {
							// split this event up
							e = events[i].split('^');
							// deal with each event type
							switch(e[0]) {
								case 'ALERT': // an incoming server alert that will come up in a popup
									if(e.length == 3) {
										if(_stage_v_lastalert != e[1]) dom_bubble_alert('System Alert', e[2]);
									}
									break;
								case 'RADIO': // radio now-playing update
									if(e.length == 4) {
										var html = '<a href="'+stage_helper_get_member_url(e[3], 'B')+'" target="_blank" class="mini">'+e[3]+'</a> - ';
										html += '<a href="#" class="mini" onclick="dom_bubble_open(\Voting\', \'/ajax/iframe-voting.php?tid='+e[1]+'\', \'small\', TYPE_AJAX, \'\', \'ok\');return false;">'+e[2]+'</a>';
										$('#nowplayingdiv').html(html);
									}
									break;
								case 'FRNDS': // number of friends online
									if(e.length == 2) {
										$('#noticesfriendsnum').text(e[1]);
									}
									break;
								case 'MAILS': // number of unread mails
									if(e.length == 2) {
										if(e[1] == 0) $('#noticesmailtxt').text('NO NEW MAIL'); else $('#noticesmailtxt').text('NEW MAIL ('+e[1]+')');
									}
									break;
								case 'NOTIC': // number of unread notices
									if(e.length == 2) {
										$('#noticesnum').text(e[1]);
										if(e[1] > 0) {
											var t = $(document).attr('title');
											if(t.substr(0, 1) == '(')
												$(document).attr('title', t.replace(/\(\d+\)/g, '('+e[1]+')'));
											else
												$(document).attr('title', '('+e[1]+') ' + t);
										} else {
											var t = $(document).attr('title');
											if(t.substr(0, 1) == '(')
												$(document).attr('title', t.replace(/\(\d+\)/g, ''));
										}
									}
									break;
								case 'GROUP': // number of new groups posts
									if(e.length == 2) {
										$('#noticesgroupsnum').text(e[1]);
									}
									break;
								case 'BSKET': // number of items in user's basket
									if(e.length == 2) {
										if(e[1] == 0) $('#basketitems').text(''); else $('#basketitems').text('('+e[1]+')');
									}
									break;
								case 'N_THD': // new thread
									if(e.length == 18) {
										if(!($('#'+e[2]).length > 0)) { // simple check to make sure we're not creating a duplicate
											newthreadcounter++;
											_stage_threads_new(waspage, e);
											stage_timers_add(e[1], e[3]);
										}
									}
									break;
								case 'U_THD': // update thread
									if(e.length == 18) {
										stage_timers_remove(e[1]);
										_stage_thread_update(e);
										stage_timers_add(e[1], e[3]);
									}
									break;
								case 'R_THD': // remove thread
									if(e.length == 3) {
										if($('#'+e[2]).length > 0) { // simple check to make sure this thread exists
											stage_timers_remove(e[1]);
											$('#'+e[2]).hide('fast', function() { $('#'+e[2]).html(''); }); // nicely close then remove
											// the replies stage timers will be automatically removed when they next update - brutal but effective
										}
									}
									break;
								case 'N_RPY': // new reply
									if(e.length == 13) {
										if(!($('#reply'+e[1]).length > 0)) { // simple check to make sure we're not creating a duplicate
											_stage_reply_add(e);
											stage_timers_add(e[1], e[3]);
										}
									}
									break;
								case 'U_RPY': // update reply
									if(e.length == 13) {
										stage_timers_remove(e[1]);
										_stage_reply_update(e);
										stage_timers_add(e[1], e[3]);
									}
									break;
								case 'R_RPY': // remove reply
									if(e.length == 3) {
										if($('#reply'+e[1]).length > 0) { // simple check to make sure this reply exists
											stage_timers_remove(e[1]);
											$('#reply'+e[1]).hide('fast', function() { $('#reply'+e[1]).html(''); }); // nicely close then remove
										}
									}
									break;
							}
						}
					}
				}
			}
			// if this was a page reset the more button
			if(_stage_v_getapage) { 
				$('#gettingpageimg').hide(0);
				if(newthreadcounter > 9) $('#gettingpagelink').show(0); else $('#gettingpagelink').hide(0);
				_stage_v_getapage = false;
			}

			// do this again in 7 seconds - we only do this once the ajax response has been got
			_stage_v_timeout = setTimeout('_stage_update()', 7000);
					
			// now run the stage timers
			if(_stage_v_stagename != 'none') _stage_timers_update();

			// make sure all of the textareas in the stage autogrow
			$('textarea').autogrow();

		});
		}

	// ----------------------------------------------------------------------------------------
	// public functions

		function stage_begin(sn, tt, username, theme, stagemode) {
			// are we logged in?
			if(username != '') {
				_stage_v_isloggedin = true;
				_stage_v_username = username;
				_stage_v_stagemode = stagemode;
				if(_stage_v_stagemode != 'latest') _stage_v_stagemode = 'default';
			}
			// set the stage and tied_to we're using
			_stage_v_stagename = sn;
			_stage_v_stagetiedto = tt;
			_stage_v_stagetheme = theme;
			_stage_v_lastpageshown = 0;
			// build the initial staging area (only for loggedin users)
			if(_stage_v_stagename != 'none') _stage_threads_share_area();
			// get the initial page
			_stage_v_getapage = true;
			setTimeout('_stage_update(1)', 1000);
			// reset the iframe posting area
			var iframeheight = 80;
			if(!_stage_v_isloggedin) iframeheight = 0;
			if(_stage_v_stagename != 'none') stage_helper_resetiframe(iframeheight);
			// make sure we run the stopping process before leaving the page
			$(window).unload(function() { stage_stop(); });
		}


		function stage_stop() {
			// stop any ajax calls currently in progress
			clearTimeout(_stage_v_timeout);
			//_stage_v_ajax.abort();
		}


		$(window).unload( function() { stage_stop(); } );


// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// STAGE TIMERS

		_stage_v_timer = function (a, b) { this.pid = a; this.timestamp = b; }
		_stage_v_timers = new Array();


	// ----------------------------------------------------------------------------------------
	// private functions

		// this function is called every 3 seconds - it calls itself so on failure will not call itself again
		function _stage_timers_update() {
			var ts = Math.round((new Date()).getTime() / 1000);
			$('#stageduration').val(ts);
			for(var n = 0; n < _stage_v_timers.length; n++) {
				if(_stage_v_timers[n] != null) {
					if($('#stagetimer'+_stage_v_timers[n].pid).length > 0) { // make sure this time exists
						_stage_timers_set(_stage_v_timers[n].pid, _stage_v_timers[n].timestamp, ts); // update the timer
					} else {
						_stage_v_timers[n] = null; // timer does not exist, so delete it
					}
				}
			}
		}


		function _stage_timers_set(id, t1, t2) {
			td = t2 - t1;
			if(td < 2) {
				$('#stagetimer'+id).text('New');
			} else if(td < 60) {
				$('#stagetimer'+id).text(td + ' seconds ago');
			} else if(td < 120) {
				$('#stagetimer'+id).text('1 minute ago');
			} else if(td < 3600) {
				$('#stagetimer'+id).text(Math.floor(td / 60) + ' minutes ago');
			} else if(td < 7200) {
				$('#stagetimer'+id).text('1 hour ago');
			} else if(td < 86400) {
				$('#stagetimer'+id).text(Math.floor(td / 3600) + ' hours ago');
			} else if(td < 172800) {
				$('#stagetimer'+id).text('Yesterday');
			} else if(td < 604800) {
				$('#stagetimer'+id).text(Math.floor(td / 86400) + ' days ago');
			} else if(td < 1209600) {
				$('#stagetimer'+id).text('Last week');
			} else if(td < 2592000) {
				$('#stagetimer'+id).text(Math.floor(td / 604800) + ' weeks ago');
			} else if(td < 5184000) {
				$('#stagetimer'+id).text('Last month');
			} else if(td < 31536000) {
				$('#stagetimer'+id).text(Math.floor(td / 2592000) + ' months ago');
			} else if(td < 63072000) {
				$('#stagetimer'+id).text('Last year');
			} else {
				$('#stagetimer'+id).text(Math.floor(td / 31536000) + ' years ago');
			}
		}


	// ----------------------------------------------------------------------------------------
	// public functions

		// add a timer to the stage
		function stage_timers_add(id, timestamp) {
			_stage_v_timers[_stage_v_timers.length] = new _stage_v_timer(id, timestamp);
			_stage_timers_set(id, timestamp, Math.round((new Date()).getTime() / 1000));
		}


		// remove a timer from the stage
		function stage_timers_remove(id) { 
			if((a = jQuery.inArray(id, _stage_v_timers)) !== false) {
				_stage_v_timers[a] = null;
			}
		}


		// clear all timers from the stage
		function stage_timers_clear() { _stage_v_timers = new Array(); }






// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// STAGE THREADS

	// ----------------------------------------------------------------------------------------
	// private functions

	//function _stage_threads_post_new() {
	//	v = $('#stagenewpost').val();
	//	if(v.length < 5) alert("Post needs to be longer than 5 characters");
	//	if(v.length > 1000) alert("Post needs to be shorter than 1000 characters");
	//	$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&msg='+escape(v)+'&job=addt', function(data) { 
	//		resp = data.split('|');
	//		if(resp[0] != 'Ok') {
	//			alert(resp[0]+"\n"+resp[1]);
	//			$('#stagenewpostsubmit').attr('disabled', '');
	//		} else {
	//			$('#stagenewpost').val('');
	//			$('#stagenewpostsubmit').attr('disabled', '');
	//		}
	//	});
	//}


	function _stage_threads_share_area() {
		var html = '';
		if(_stage_v_isloggedin) {
			html += '<div id="stagenewpostarea" class="stagenewpostarea" align="left">';
			if(_stage_v_stagename == 'profiles' && _stage_v_username.replace(' ', '_') == _stage_v_stagetiedto) {
				html += '<div align="right" style="padding-right:11px; padding-bottom:3px;">';
				html += '<a href="#" onclick="stage_stop();stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, \'default\');return false;" class="v2-button">My Profile</a> &nbsp;';
				html += '<a href="#" onclick="stage_stop();stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, \'latest\');return false;" class="v2-button">Friends Posts</a>';
				html += '</div>';
			}
			html += '<iframe id="stagenewpostiframe" scrolling="no" frameborder="0" framespacing="0" border="0" spacing="0" style="width:100%;height:80px;border:0px;padding:0px;margin:0px;" src="" allowtransparency="true"></iframe>';
			html += '</div>';
		}
		html += '<div id="stagingareastickies"></div>';
		html += '<div id="stagingarea"></div>';
		html += '<div id="stagemorebutton" align="center"><img src="/images/icon-loading2.gif" id="gettingpageimg"/><a href="#" style="display:none;" id="gettingpagelink" onclick="$(\'#gettingpageimg\').show(0);$(\'#gettingpagelink\').hide(0);_stage_v_getapage = true; return false;">---- MORE ----</a></div>';
		$('#thestage').attr('className', 'thestage');
		$('#thestage').html(html);
		$('#stagenewpostiframe').attr('src','/ajax/stage-poster.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&sm='+_stage_v_stagemode+'&thm='+_stage_v_stagetheme);
	}


	// 0=[N_THD] ^ 1=[POST_ID] ^ 2=[TOPIC_ID] ^ 3=[TIME_CREATED] ^ 4=[IS_LOCKED] ^ 5=[IS_STICKY] ^ 6=[MESSAGE] ^ 7=[POSTER_NAME] ^ 8=[POSTER_USERTYPE] ^
	// 9=[POSTER_ONLINE] ^ 10=[I_LIKE] ^ 11=[NUM_REPLIES] ^ 12=[NUM_LIKES] ^ 13=[LAST_5_LIKES] ^ 14=[OPTIONS_OWNER] ^ 15=[OPTIONS_MODERATOR] ^
	// 16=[MESSAGE_SOURCE] ^ 17=[OWNER OF TIED TOPIC]

	function _stage_threads_new(waspage, event) {

		// build the content for this thread
		var html = '';
		html += '<div id="'+event[2]+'" class="stagethread'+(event[5]=='y' ? 'sticky' : '')+'" style="display:'+(waspage ? 'block' : 'none')+';">';
		html += _stage_threads_make_interior(event);
		html += '</div>';

		// if we're adding this new thread from a given page of results, we append to the staging area as they are older than current
		if(waspage && event[5] == 'n') { $('#stagingarea').append(html); }
		if(waspage && event[5] == 'y') { $('#stagingareastickies').append(html); }
		
		// if we're adding this new thread from an update, we prepend to the staging area, as this thread has to be newer
		// once it's inserted, get it's final height and move the scrollbar by that amount
		if(!waspage) {
			if(event[5] == 'n') $('#stagingarea').prepend(html);
			if(event[5] == 'y') $('#stagingareastickies').prepend(html);
			$('#'+event[2]).show('slide', {direction:'up'}, 'slow');
		}
	}


	function _stage_thread_update(event) {
		// updating a thread, we can only do a few things - so no need to rebuild the whole lot
		// 1) show the basic likes div and hide the all-likes div with the new info
		if(event[13] == '' && event[10] == 'n') {
			$('#threadlikesholder'+event[2]).hide('slow');
			$('#stagealllikes'+event[1]).text('Show All Likes');
			if($('#threadalllikesholder'+event[2]).is(":visible")) 
				$('#threadalllikesholder'+event[2]).hide('slow', function() { $('#threadalllikesholder'+event[2]).html(''); } );
		} else {
			html = ' Liked by ';
			if(event[10] == 'y') { 
				html += 'You';
				event[12] -= 1;
				if(event[12] > 0) html += ', ';
			}
			likers = event[13].split(',');
			for(var i = 0; i < likers.length; i++) {
				utype = likers[i].substr(0,1);
				uname = stage_helper_ucwords(likers[i].substr(1));
				url = stage_helper_get_member_url(uname, utype);
				html += ' <a href="'+url+'" class="staginginfo" target="_blank">'+uname+'</a>';
				if(i < likers.length - 1) html += ',';
				event[12] -= 1;
			}
			if(event[12] > 0) html += ', and '+event[12]+' others';
			$('#threadliketext'+event[2]).html(html);
		
			if($('#stagealllikes'+event[1]).text() == 'Show All Likes') {
				if(!$('#threadlikesholder'+event[2]).is(":visible")) 
					$('#threadlikesholder'+event[2]).show('slide', {direction:'up'}, 'slow');
			} else {
				$('#stagealllikes'+event[1]).text('Show All Likes');
				$('#threadalllikesholder'+event[2]).hide('slow', function() { $('#threadalllikesholder'+event[2]).html(''); } );
				$('#threadlikesholder'+event[2]).show('slide', {direction:'up'}, 'slow');
			}
		}

		// 2) - updating the message text
		$('#threadholder'+event[2]).html(stage_helper_parse_message(event[6]));
		$('#threadeditholder'+event[2]).hide();
		$('#threadholder'+event[2]).show();

		// 3) making a thread sticky
		if(event[5] == 'y') {
			$('#'+event[2]).attr('class', 'stagethreadsticky');
		} else {
			$('#'+event[2]).attr('class', 'stagethread');
		}

		// 4) locking a thread [ removing reply options, edit buttons, like buttons ]
		if(event[4] == 'y') {
			$('#threadreplybutton'+event[2]).hide();
			$('#threadlock'+event[2]).hide();
			$('#threadunlock'+event[2]).show();
			$('#stagelikeunlike'+event[1]).hide();
			$('#stagelockedtext'+event[1]).show();
		} else { 
			$('#threadreplybutton'+event[2]).show();
			$('#threadunlock'+event[2]).hide();
			$('#threadlock'+event[2]).show();
			$('#stagelikeunlike'+event[1]).show();
			$('#stagelockedtext'+event[1]).hide();
		}
	}


	function _stage_threads_make_interior(event) {
		var html = '';
		//var is_editable = (event[6].substr(0,3) == 'TXT' &&  (event[14] == 'y' || event[15] == 'y')) ? true : false;

		html += '<table width="100%" cellspacing="6" cellpadding="0" border="0" onmouseover="$(\'#threadopts'+event[2]+'\').show();" onmouseout="$(\'#threadopts'+event[2]+'\').hide();">';
		html += '<tr>';
		if(event[7] == 'System')
			html += '<td valign="top" rowspan="2" style="width:50px;" align="center"><img src="/images/icon-50-alert.png"/></td>';
		else
			html += '<td valign="top" rowspan="2"><a href="'+stage_helper_get_member_url(event[7], event[8])+'"><img src="/avatars/'+event[7]+'.gif" width="50" border="0"/></a></td>';
		html += '<td valign="top" width="90%" align="left" class="stagethreadbackground">';

		if(event[4] == 'y') lockhtml = '<div id="stagelockedtext'+event[1]+'" style="float:right;">&nbsp; LOCKED</div>'; else lockhtml = '<div id="stagelockedtext'+event[1]+'" style="float:right;display:none;">&nbsp; LOCKED</div>';

		if(_stage_v_stagemode == 'default')
			html += '<div>'+lockhtml+stage_helper_make_member_button(event[7], event[8], event[9])+'</div>';
		else
			html += '<div>'+lockhtml+stage_helper_make_member_button(event[7], event[8], event[9])+' Posted to '+event[17]+'\'s profile</div>';

		html += '<div id="threadholder'+event[2]+'" style="display:block;padding:4px;font-size:9pt;">'+stage_helper_parse_message(event[6])+'</div>';
		//if(is_editable)
			//html += '<div id="threadeditholder'+event[2]+'" style="display:none;padding:4px;"><textarea id="threadedit'+event[2]+'" style="width:478px;height:60px;font-size:9pt;">'+event[6].substr(4)+'</textarea><div id="threadeditbuttonholder'+event[2]+'" align="right" style="padding:3px;"><a href="#" onclick="stage_helper_post_edit(\''+event[2]+'\',\''+event[1]+'\', $(\'#threadedit'+event[2]+'\').val());return false;" class="v2-button">Save edit</a></div></div>';

		// start the info holder [  | TIMER | LIKE/UNLIKE | COMMENT | SHOW ALL LIKES | SHOW ALL COMMENTS ]
			html += '<div id="threadinfoholder'+event[2]+'" class="stagethreadsub" style="padding:4px; margin-bottom:2px;">';
			html += '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
			html += '<tr>';
		// ORIGIN_ICON
			if(event[16] == 'P') 
				html += '<td><img src="/images/icon-stage-phone.png" title="Via Mobile/Cell Phone"></td>';
			else
				html += '<td><img src="/images/icon-stage-net.png" title="Via Web"></td>';
		
		// TIMER
			html += '<td style="padding-left:6px;" width="98%">';
			html += '<span id="stagetimer'+event[1]+'"></span>';

		// LIKE/UNLIKE LINK
			if(_stage_v_isloggedin) {
				if(event[4] == 'n') {
					html += '<span id="stagelikeunlike'+event[1]+'">';
				} else {
					html += '<span id="stagelikeunlike'+event[1]+'" style="display:none;">';
				}
				if(event[10] == 'n') {
					html += '<a href="#" id="stagelike'+event[1]+'" class="staginginfopadded" onclick="stage_helper_like_toggle(\''+event[2]+'\',\''+event[1]+'\');return false;">Like</a>';
				} else {
					html += '<a href="#" id="stagelike'+event[1]+'" class="staginginfopadded" onclick="stage_helper_like_toggle(\''+event[2]+'\',\''+event[1]+'\');return false;">Unlike</a>';
				}
				html += '</span>';
			}


		// REPLY LINK
			if(_stage_v_isloggedin && event[4] == 'n') {
				html += '<a href="#" class="staginginfopadded" id="threadreplybutton'+event[2]+'" onclick="if(!$(\'#threadreply'+event[2]+'\').is(\':visible\')) { $(\'#threadreply'+event[2]+'\').show(\'slide\', {direction:\'up\'}, \'slow\'); } return false;">Reply</a>';
			}
			if(_stage_v_isloggedin && event[4] == 'y') {
				html += '<a href="#" class="staginginfopadded" id="threadreplybutton'+event[2]+'" style="display:none;" onclick="if(!$(\'#threadreply'+event[2]+'\').is(\':visible\')) { $(\'#threadreply'+event[2]+'\').show(\'slide\', {direction:\'up\'}, \'slow\'); } return false;">Reply</a>';
			}

		// SHOW ALL LIKES
			html += '<a href="#" id="stagealllikes'+event[1]+'" class="staginginfopadded" onclick="stage_helper_all_likes_toggle(\''+event[2]+'\',\''+event[1]+'\');return false;">Show All Likes</a> ';

		// SHOW ALL REPLIES
			var showallrepliestext = 'Show All Replies';
			if(event[11] > 0) showallrepliestext += ' ('+event[11]+')';
			html += '<a href="#" id="stageallreplies'+event[2]+'" class="staginginfopadded" onclick="stage_helper_all_replies(\''+event[2]+'\',\''+event[1]+'\');return false;">'+showallrepliestext+'</a>';

		// close the info holder
			html += '</td></tr></table>';
			html += '</div>';

		// do the likes holder
		html += '<div id="threadlikesholder'+event[2]+'" class="stagethreadsub" style="padding:4px; margin-bottom:2px; display:'+(event[12]>0 ? 'block' : 'none')+';">';
		html += '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
		html += '<tr>';
		html += '<td><img src="/images/icon-stage-like.png"></td>';
		html += '<td style="padding-left:6px;" width="98%" id="threadliketext'+event[2]+'"> Liked by ';
		if(event[10] == 'y') { 
			html += 'You';
			event[12] -= 1;
			if(event[12] > 0) html += ', ';
		}
		likers = event[13].split(',');
		if(likers[0] != '') {
			for(var i = 0; i < likers.length; i++) {
				utype = likers[i].substr(0,1);
				uname = stage_helper_ucwords(likers[i].substr(1));
				url = stage_helper_get_member_url(uname, utype);
				html += ' <a href="'+url+'" class="staginginfo" target="_blank">'+uname+'</a>';
				if(i < likers.length - 1) html += ',';
				event[12] -= 1;
			}
			if(event[12] > 0) html += ', and '+event[12]+' others';
		}
		html += '</td></tr></table>';
		html += '</div>';

		// make a hidden "all likes" holder
		html += '<div id="threadalllikesholder'+event[2]+'" class="stagethreadsub" style="display:none; padding:4px; margin-bottom:2px;"><table border="0" cellspacing="0" cellpadding="0"><tr><td id="threadalllikesholderinterior'+event[2]+'"></td></tr></table></div>';

		// make the replies holder
		html += '<div id="threadrepliesholder'+event[2]+'" style="margin:0px;padding:0px;"></div>';

		// make the replies poster
		if(_stage_v_isloggedin) {
			html += '<div id="threadreply'+event[2]+'" class="stagethreadsub" style="display:none; padding:4px; margin-bottom:2px;">';
			html += '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
			html += '<tr>';
			html += '<td><img src="/avatars/'+_stage_v_username+'.gif" width="30"/></td>';
			html += '<td style="padding-left:6px;" width="99%">';
			html += '<form id="replyform'+event[2]+'" name="replyform'+event[2]+'" action="." method="get" onsubmit="_stage_replies_post_new(\''+event[2]+'\');return false;">';
			if(_stage_v_username == 'Following Dark')
				html += '<textarea id="threadreplypost'+event[2]+'" class="stageframepostbox" value="Write a reply..." style="width:410px; height:16px; line-height:1;" onkeyup="_stage_reply_return_check(event, \'replyform'+event[2]+'\');" onkeydown="if($(\'#threadreplypost'+event[2]+'\').val() == \'Write a reply...\') $(\'#threadreplypost'+event[2]+'\').val(\'\');" onclick="if($(\'#threadreplypost'+event[2]+'\').val() == \'Write a reply...\') $(\'#threadreplypost'+event[2]+'\').val(\'\');"/></textarea>';
			else
				html += '<input type="text" id="threadreplypost'+event[2]+'" class="stageframepostbox" value="Write a reply..." style="width:99%;" onkeydown="if($(\'#threadreplypost'+event[2]+'\').val() == \'Write a reply...\') $(\'#threadreplypost'+event[2]+'\').val(\'\');" onclick="if($(\'#threadreplypost'+event[2]+'\').val() == \'Write a reply...\') $(\'#threadreplypost'+event[2]+'\').val(\'\');"/>';
			html += '<input type="submit" style="display:none;">';
			html += '</form>';
			html += '</td>';
			html += '</tr>';
			html += '</table>';
			html += '</div>';
		}

		html += '</td>';

		// now the modification icons
		html += '<td width="20" valign="top" rowspan="2">';
		html += '<div id="threadopts'+event[2]+'" style="display:none;">';
		if(_stage_v_isloggedin) {
			// editing topics
			//if(is_editable && event[14] == 'y' && event[4] == 'n') {
				// edit own post if not locked
				//html += '<a href="#" onclick="$(\'#threadholder'+event[2]+'\').toggle();$(\'#threadeditholder'+event[2]+'\').toggle();return false;" title="Edit own post"><img src="/images/icon-stage-edit.png" border="0"/></a>';
			//} else if(is_editable && event[15] == 'y' && event[14] != 'y') {
				// moderators edit post
				//html += '<a href="#" onclick="$(\'#threadholder'+event[2]+'\').toggle();$(\'#threadeditholder'+event[2]+'\').toggle();return false;" title="Moderator edit post"><img src="/images/icon-stage-edit.png" border="0"/></a>';
			//}

			// locking topics
			if(event[15] == 'y') { // moderators only
				if(event[4] == 'n') { // currently unlocked
					html += '<a href="#" id="threadlock'+event[2]+'" onclick="stage_helper_thread_lock(\''+event[2]+'\');return false;" title="Moderator lock post"><img src="/images/icon-stage-lock.png" border="0"/></a>';
					html += '<a href="#" id="threadunlock'+event[2]+'" style="display:none;" onclick="stage_helper_thread_unlock(\''+event[2]+'\');return false;" title="Moderator unlock post"><img src="/images/icon-stage-lock.png" border="0"/></a>';
				} else { // currently locked
					html += '<a href="#" id="threadlock'+event[2]+'" style="display:none;" onclick="stage_helper_thread_lock(\''+event[2]+'\');return false;" title="Moderator lock post"><img src="/images/icon-stage-lock.png" border="0"/></a>';
					html += '<a href="#" id="threadunlock'+event[2]+'" onclick="stage_helper_thread_unlock(\''+event[2]+'\');return false;" title="Moderator unlock post"><img src="/images/icon-stage-lock.png" border="0"/></a>';
				}
			}

			// stickying topics
			if(event[5] == 'y') stickytext = 'unsticky'; else stickytext = 'sticky';
			if(event[15] == 'y' && event[5] == 'n') { // moderator sticky
				html += '<a href="#" onclick="stage_helper_thread_sticky(\''+event[2]+'\');return false;" title="Moderator '+stickytext+' post"><img src="/images/icon-stage-sticky.png" border="0"/></a>';
			} else if(event[15] == 'y' && event[5] == 'y') { // moderator unsticky
				html += '<a href="#" onclick="stage_helper_thread_unsticky(\''+event[2]+'\');return false;" title="Moderator '+stickytext+' post"><img src="/images/icon-stage-sticky.png" border="0"/></a>';
			}

			// deleting topics
			if(event[14] == 'y' && event[4] == 'n') { // owner delete
				html += '<a href="#" onclick="stage_helper_thread_delete(\''+event[2]+'\');return false;" title="Owner delete post"><img src="/images/icon-stage-delete.png" border="0"/></a>';
			} else if(event[15] == 'y' && event[4] == 'n') { // moderator delete
				html += '<a href="#" onclick="stage_helper_thread_delete(\''+event[2]+'\');return false;" title="Moderator delete post"><img src="/images/icon-stage-delete.png" border="0"/></a>';
			}
		}
		html +='</div>';
		html += '<img src="/images/blank.gif" width="20" height="2">';
		html += '</td>';
		html += '</tr>'; 
		html += '</table>';
		return html;
	}






// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// STAGE REPLIES

	// ----------------------------------------------------------------------------------------
	// private functions

	// 0=[N_THD] ^ 1=[POST_ID] ^ 2=[TOPIC_ID] ^ 3=[TIME_CREATED] ^ 4=[MESSAGE] ^ 5=[POSTER_NAME] ^ 6=[POSTER_USERTYPE] ^
	// 7=[POSTER_ONLINE] ^ 8=[I_LIKE] ^ 9=[NUM_LIKES]  ^ 10=[OPTIONS_OWNER] ^ 11=[OPTIONS_MODERATOR] ^ 12=[MESSAGE_SOURCE]

	function _stage_replies_post_new(tid) {
		v = $('#threadreplypost'+tid).val();
		if(v.length < 5) alert("Post needs to be longer than 5 characters");
		if(v.length > 500) alert("Post needs to be shorter than 500 characters");
		$('#threadreplypost'+tid).val('');
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+tid+'&msg='+escape(v)+'&job=addr', function(data) { 
			resp = data.split('|');
			if(resp[0] != 'Ok') {
				alert(resp[0]+"\n"+resp[1]);
			} else {
				$('#threadreplypost'+tid).val('Write a reply...');
			}
		});
	}


	function _stage_reply_add(event) {
		// set the replies holder visible
		if(!$('#threadrepliesholder'+event[2]).is(":visible")) $('#threadrepliesholder'+event[2]).show('slide', {direction:'up'}, 'slow');
		// now create the html for this reply
		var html = '';
		html += '<div id="reply'+event[1]+'" class="stagethreadsub" style="padding:4px; margin-bottom:2px;">';
		html += '<table border="0" cellspacing="0" cellpadding="0" width="100%" onmouseover="$(\'#replyopts'+event[1]+'\').show();" onmouseout="$(\'#replyopts'+event[1]+'\').hide();">';
		 html += '<tr>';
		  html += '<td valign="top"><a href="'+stage_helper_get_member_url(event[5], event[6])+'"><img src="/avatars/'+event[5]+'.gif" width="30" border="0"/></a></td>';
		  html += '<td style="padding-left:6px;" width="95%">';
		   html += '<div style="padding-bottom:2px;">';
		   html += '<table border="0" cellspacing="0" cellpadding="0">';
		   html += '<tr>';
		   html += '<td nowrap="nowrap">'+stage_helper_make_member_button(event[5], event[6], event[7])+'</td>';
		   html += '<td width="90%" align="right">';
		   html += '<table border="0" cellspacing="0" cellpadding="0">';
		   html += '<tr>';
		   html += '<td style="padding-left:6px;" nowrap="nowrap"><span id="stagetimer'+event[1]+'"></span></td>';
		   if(_stage_v_isloggedin) {
			html += '<td style="padding-left:6px;" nowrap="nowrap"><a href="#" id="replylikelink'+event[1]+'" class="staginginfo" onclick="stage_helper_reply_like_toggle(\''+event[2]+'\', \''+event[1]+'\'); return false;">'+(event[8]=='y'?'Unlike':'Like')+'</a></td>';
		   }
		   html += '<td style="padding-left:6px;" nowrap="nowrap"><img src="/images/icon-stage-like.png"></td>';
		   html += '<td style="padding-left:6px;" nowrap="nowrap" id="replylikes'+event[1]+'">'+(event[9]<1 ? '' : event[9]+' '+(event[9]==1 ? 'person' : 'people'))+'</td>';
		   html += '</tr>';
		   html += '</table>';
		   html += '</td>';
		   html += '</tr>';
		   html += '</table>';
		   html += '<div id="replymsg'+event[1]+'" style="font-size:8pt;padding:3px;">'+stage_helper_parse_message(event[4])+'</div>';
		  html += '</td>';
		  html += '<td valign="top">';
		  html += '<div id="replyopts'+event[1]+'" style="display:none;">';
		  if(_stage_v_isloggedin) {
			if(event[10] == 'y') { // owner delete
				html += '<a href="#" onclick="stage_helper_reply_delete(\''+event[2]+'\',\''+event[1]+'\');return false;" title="Owner delete reply"><img src="/images/icon-stage-delete.png" border="0"/></a>';
			} else if(event[11] == 'y') { // moderator delete
				html += '<a href="#" onclick="stage_helper_reply_delete(\''+event[2]+'\',\''+event[1]+'\');return false;" title="Moderator delete reply"><img src="/images/icon-stage-delete.png" border="0"/></a>';
			}
		  }
		  html += '</div>';
		  html += '<img src="/images/blank.gif" width="20" height="2">';
		  html += '</td>';
		 html += '</tr>';
		html += '</table>';
		html += '</div>';
		$('#threadrepliesholder'+event[2]).append(html);
	}


	function _stage_reply_update(event) {
		// updating a reply, we can only do a few things - so no need to rebuild the whole lot
		// 1) update the like info
		var html = event[9] < 1 ? '' : event[9]+' '+(event[9] == 1 ? 'person' : 'people');
		$('#replylikes'+event[1]).text(html);
		// 2) update the message text
		$('#replymsg'+event[1]).text(stage_helper_parse_message(event[4]));
	}





// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------
// STAGE HELPER FUNCTIONS

	// ----------------------------------------------------------------------------------------
	// public functions

	function stage_helper_thread_lock(threadid) {
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&job=tlock', function(data) {
		//	stage_stop();
		//	stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, _stage_v_stagemode);
		});
	}

	function stage_helper_thread_unlock(threadid) {
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&job=tunlock', function(data) {
		//	stage_stop();
		//	stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, _stage_v_stagemode);
		});
	}

	function stage_helper_thread_sticky(threadid) {
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&job=tsticky', function(data) {
			stage_stop();
			stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, _stage_v_stagemode);
		});
	}

	function stage_helper_thread_unsticky(threadid) {
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&job=tunsticky', function(data) {
			stage_stop();
			stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, _stage_v_stagemode);
		});
	}

	function stage_helper_thread_delete(threadid) {
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&job=tdelete', function(data) {
			stage_stop();
			stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, _stage_v_stagemode);
		});
	}

	function stage_helper_reply_delete(threadid,postid) {
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+postid+'&job=rdelete', function(data) {
			stage_stop();
			stage_begin(_stage_v_stagename, _stage_v_stagetiedto, _stage_v_username, _stage_v_stagetheme, _stage_v_stagemode);
		});
	}

	function stage_helper_post_edit(topicid, postid, newmsg) {
		$('#threadeditbuttonholder'+topicid).html('<img src="/images/icon-loading2.gif" />');
		$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+topicid+'&pid='+postid+'&job=pedit&msg='+newmsg);
	}

	function stage_helper_ucwords(str) {
		str = str.toLowerCase();
		return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) { return $1.toUpperCase(); });
	}


	function stage_helper_get_member_url(username, usertype) {
		if(usertype == 'X') return('#" onclick="return false;'); // this stops closed accounts from having a link
		if(usertype == 'U') return('http://www.soundawesome.com/listeners/'+username);
		if(usertype == 'V') return('http://www.soundawesome.com/services/'+username);
		return('http://'+username.toLowerCase().replace(/ /g,'-')+'.soundawesome.com');
	}


	function stage_helper_make_member_button(username, usertype, lastonline) {
		// create all the vars needed
		if(username == 'System') return '';
		var url = stage_helper_get_member_url(username, usertype);
		var d = new Date();
		var unixt = Math.round(d.getTime() / 1000);
		var today = new Date(d.getFullYear, d.getMonth, d.getDay, 0, 0, 0, 0);
		var unixtoday = Math.round(today.getTime() / 1000);
		var un = stage_helper_ucwords(username);
		if(un == 'Soundawesome') un = 'SoundAwesome';

		// create the last online text
		var lastonline_text = "Last online over a month ago";
		if(lastonline > unixt - (86400 * 31)) lastonline_text = "Last online this month";
		if(lastonline > unixt - (86400 * 7)) lastonline_text = "Last online upto a week ago";
		if(lastonline > unixt - (86400 * 3)) lastonline_text = "Last online 2 days ago";
		if(lastonline > unixt - (86400 * 2)) lastonline_text = "Last online yesterday";
		if(lastonline > unixt - 86400) lastonline_text = "Last online today";

		var ret = '<span class="av2u" style="padding-top:0px;padding-left:3px;padding-bottom:1px;padding-right:5px;">';
		if(lastonline > unixt - 300)
			ret += '<img src="/images/icon-ledon.png" alt="Online now!" title="Online now!"> ';
		else
			ret += '<img src="/images/icon-ledoff.png" alt="'+lastonline_text+'" title="'+lastonline_text+'"> ';
		ret += '<a href="'+url+'" target="_blank" class="user">'+un+'</a>';
		ret += '</span>';
		return ret;
	}


	function stage_helper_like_toggle(threadid, pid) {
		if($('#stagelike'+pid).text() == 'Like') {
			$('#stagelike'+pid).text('Unlike');
			$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+pid+'&lik=y', function(data) { } );
		} else {
			$('#stagelike'+pid).text('Like');
			$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+pid+'&lik=n', function(data) {  } );
		}
	}


	function stage_helper_reply_like_toggle(threadid, pid) {
		if($('#replylikelink'+pid).text() == 'Like') {
			$('#replylikelink'+pid).text('Unlike');
			$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+pid+'&lik=y', function(data) { } );
		} else {
			$('#replylikelink'+pid).text('Like');
			$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+pid+'&lik=n', function(data) {  } );
		}
	}


	function stage_helper_all_likes_toggle(threadid, pid) {
		if($('#stagealllikes'+pid).text() == 'Show All Likes') {
			$('#stagealllikes'+pid).text('Hide All Likes');
			$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+pid+'&job=reqlik', function(data) { 
				var html = '';
				html += '<table border="0" cellspacing="0" cellpadding="0">';
				html += '<tr>';
				html += '<td valign="top"><img src="/images/icon-stage-like.png"></td>';
				html += '<td style="padding-left:6px;"> Full Likes List:-<br />';
				likers = data.split(',');
				if(likers[0] == '') {
					html += 'No-one has selected \'like\' for this post yet';
				} else {
					for(var i = 0; i < likers.length; i++) {
						utype = likers[i].substr(0,1);
						uname = stage_helper_ucwords(likers[i].substr(1));
						url = stage_helper_get_member_url(uname, utype);
						html += ' <a href="'+url+'" class="staginginfo" target="_blank">'+uname+'</a>';
						if(i < likers.length - 1) html += ',';
					}
				}
				html += '</td></tr></table>';
				$('#threadlikesholder'+threadid).hide('slow');
				$('#threadalllikesholderinterior'+threadid).html(html);
				$('#threadalllikesholder'+threadid).show('slide', {direction:'up'}, 'slow');
				} );
		} else {
			$('#stagealllikes'+pid).text('Show All Likes');
			$('#threadalllikesholder'+threadid).hide('slow', function() { $('#threadalllikesholderinterior'+threadid).html(''); } );
			$('#threadlikesholder'+threadid).show('slide', {direction:'up'}, 'slow');
		}
	}


	function stage_helper_all_replies(threadid, pid) {
		if($('#stageallreplies'+threadid).text().substr(0,16) == 'Show All Replies') {
			$('#stageallreplies'+threadid).text('Hide All Replies');
			$('#threadrepliesholder'+threadid).hide('slow');
			$('#threadrepliesholder'+threadid).html('');
			$.get('/ajax/stage-putter.php?sn='+_stage_v_stagename+'&tt='+_stage_v_stagetiedto+'&tid='+threadid+'&pid='+pid+'&job=reqrpy', function(data) { 
				if(data != '') {
					// split the response into parts
					reps = data.split('|');
					if(reps[0] == 'Error') {
						alert("Error:\n"+reps[1]);
					} else {
						// iterate through each one
						for(var n = 0; n < reps.length; n++) {
							// split this up
							rep = reps[n].split('^');
							if(rep.length == 13) {
								_stage_reply_add(rep);
								stage_timers_add(rep[1], rep[3]);
							}
						}
					}
				} 
			} );
			// kill timers that used in the replies that already exist (the next iteration of the timers will do this automatically)
			$('#threadrepliesholder'+threadid).show('slide', {direction:'up'}, 'slow');
		} else {
			$('#stageallreplies'+threadid).text('Show All Replies');
			// kill timers that used in the replies that already exist (the next iteration of the timers will do this automatically)
			$('#threadrepliesholder'+threadid).hide('slow', function() { $('#threadrepliesholder'+threadid).html(''); } );
		}
	}


	function stage_helper_add_another_photo() {
		var d = $('#stagenewpostiframe')[0].contentWindow.document;
		if(!$('#stagenewphoto1', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewphoto1', d).show('slide', {direction:'up'}, 'slow'); return; }
		if($('#stagenewphoto1', d).is(":visible") && !$('#stagenewphoto2', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewphoto2', d).show('slide', {direction:'up'}, 'slow'); return; }
		if($('#stagenewphoto2', d).is(":visible") && !$('#stagenewphoto3', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewphoto3', d).show('slide', {direction:'up'}, 'slow'); return; }
		if($('#stagenewphoto3', d).is(":visible") && !$('#stagenewphoto4', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewphoto4', d).show('slide', {direction:'up'}, 'slow'); return; }
		if($('#stagenewphoto4', d).is(":visible") && !$('#stagenewphoto5', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewphoto5', d).show('slide', {direction:'up'}, 'slow'); return; }
		if($('#stagenewphoto5', d).is(":visible") && !$('#stagenewphoto6', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewphoto6', d).show('slide', {direction:'up'}, 'slow'); return; }
	}


	function stage_helper_add_youtube() {
		var d = $('#stagenewpostiframe')[0].contentWindow.document;
		if(!$('#stagenewyoutube', d).is(":visible")) { $('#stagenewpostiframe').height($('#stagenewpostiframe').height()+26); $('#stagenewyoutube', d).show('slide', {direction:'up'}, 'slow'); return; }
	}


	function stage_helper_resetiframe(dowhat) {
		if(dowhat != 0)
			$('#stagenewpostiframe').height(dowhat);
		else
			$('#stagenewpostiframe').remove();
	}


	function stage_helper_parse_message(message) {
		var response = '';
		//messages = message.split('#sep#');
		//for(var m = 0; m < messages.length; m++) {
			messageparts = message.split('`');
			for(var q = 0; q < messageparts.length-1; q+=2) {
				switch(messageparts[q]) {
					case 'YTB':
						var iparts = messageparts[q+1].split('~');
						var iid = iparts[0];
						var icap = iparts[1];
						response += '<a href="#" onclick="stage_helper_lightbox(\'youtube\',\''+iid+'\'); return false;" style="margin:12px;margin-left:64px;" title="Click to play video"><img src="http://i2.ytimg.com/vi/'+iid+'/default.jpg" style="border:solid 1px #333333;"></a>';
						break;
					case 'IMG':
						var iparts = messageparts[q+1].split('~');
						var iid = iparts[0];
						var icap = iparts[1];
						response += '<a href="#" onclick="stage_helper_lightbox(\'image\',\''+iid+'\'); return false;" style="margin:12px;" title="Click to view image"><img src="/user_photos/'+iid+'-thumb.jpg" style="border:solid 1px #333333;"></a> ';
						break;
					case 'PNG':
						var iparts = messageparts[q+1].split('~');
						var iid = iparts[0];
						var icap = iparts[1];
						response += '<a href="#" onclick="stage_helper_lightbox(\'imagepng\',\''+iid+'\'); return false;" style="margin:12px;" title="Click to view image"><img src="/user_photos/'+iid+'-thumb.jpg" style="border:solid 1px #333333;"></a> ';
						break;
					case 'GIF':
						var iparts = messageparts[q+1].split('~');
						var iid = iparts[0];
						var icap = iparts[1];
						response += '<a href="#" onclick="stage_helper_lightbox(\'imagegif\',\''+iid+'\'); return false;" style="margin:12px;" title="Click to view image"><img src="/user_photos/'+iid+'-thumb.jpg" style="border:solid 1px #333333;"></a> ';
						break;
					case 'FLV':
						var iparts = messageparts[q+1].split('~');
						var iid = iparts[0];
						var icap = iparts[1];
						response += '<a href="#" onclick="stage_helper_lightbox(\'video\',\''+iid+'\'); return false;" style="margin:12px;" title="Click to view video"><img src="/user_photos/'+iid+'-thumb.jpg" style="border:solid 1px #333333;"></a> ';
						break;
					case 'TXT':
						// we can do a smilie filter here, or a bad words filter
						response += messageparts[q+1].replace(/\\n/g, '<br>').wordSplit().url2anchor();
						break;
					case 'USR':
						var ut = messageparts[q+1].substr(0, 1);
						var un = messageparts[q+1].substr(1);
						response += 'Has joined SoundAwesome';
						break;
					case 'TRK':
						response += '<a href="#" onclick="" style="float:left; margin-right:12px;"><img src="/user_track_images/'+messageparts[q+1]+'.jpg" width="50" border="0" style="border:solid 1px #333333;" /></a>Added a new track:-<br>';
						break;
					case 'RVW':
						break;
					case 'FRM':
						break;
					case 'BLG':
						break;
					case 'FND':
						break;
					case 'MRC':
						break;
					case 'TRK':
						break;
					case 'MOO':
						break;
					case 'PUP':
						break;
					default:
						// copes with older texts
						//response += messageparts[q];
				}
			//}
		}
		return response;//+'<br style="clear:both;">';
	}


	function stage_helper_lightbox(type, id, optionaltext) {

		// create an overlay div
		var div = '<div id="stageoverlay" style="position:fixed; top:0px; width:100%; height:100%; left:0px; z-index:200; background:url(/images/theme-dialogue-mask.png);"></div>';
		$('body').append(div);

		// create the div and table lightbox
		var box = '<div id="stagelightbox" style="position:fixed; z-index:201; filter:alpha(opacity=1); opacity:0.01; left:50%; top:50%; background:#333333; padding:8px; padding-top:2px; -khtml-border-radius:8px; -webkit-border-radius:8px; -moz-border-radius:8px;">';
		box += '<div align="right"><a href="#" onclick="stage_helper_lightbox_close();return false;"><img src="/images/icon-24-cross.png" border="0"></a></div>';
		box += '<div style="background:#ffffff; padding:8px; -khtml-border-radius:8px; -webkit-border-radius:8px; -moz-border-radius:8px;">';
		box += '<table border="0" cellspacing="0" cellpadding="0">';
		box += '<tr>';
		
		if(type == 'image') {
			box += '<td><img id="lightboximage" src="/user_photos/'+id+'.jpg"></td>';
		}
		if(type == 'imagepng') {
			box += '<td><img id="lightboximage" src="/user_photos/'+id+'.png"></td>';
		}
		if(type == 'imagegif') {
			box += '<td><img id="lightboximage" src="/user_photos/'+id+'.gif"></td>';
		}
		if(type == 'video') {
			box += '<td><iframe width="425" height="280" src="http://www.soundawesome.com/embed/video/v'+id+'-w425-h280" frameborder="0" allowfullscreen></iframe></td>';
		}
		if(type == 'youtube') {
			box += '<td><iframe width="425" height="349" src="http://www.youtube.com/embed/'+id+'" frameborder="0" allowfullscreen></iframe></td>';
		}

		box += '</tr>';
		box += '</table>';
		box += '</div>';
		box += '</div>';
		$('body').append(box);



		if(type == 'image' || type == 'imagegif' || type == 'imagepng') {
			$("#lightboximage").load(function() { stage_helper_lightbox_image_resize_to_fit_screen(); stage_helper_lightbox_centralize(); });
		}
		if(type == 'youtube' || type == 'video') {
			stage_helper_lightbox_centralize();
		}
	}


	function stage_helper_lightbox_close() {
		$('#stagelightbox').remove();
		$('#stageoverlay').remove();
	}


	function stage_helper_lightbox_centralize() {
		var w = $('#stagelightbox').width();
		var h = $('#stagelightbox').height();
		var winW = $(window).width();
		var winH = $(window).height();
		$('#stagelightbox').css('left',Math.round((winW - w) / 2)+'px');
		$('#stagelightbox').css('top', Math.round((winH - h) / 2)+'px');
		// show the lightbox
		$('#stagelightbox').fadeTo("fast", 100);
	}


	function stage_helper_lightbox_image_resize_to_fit_screen() {
		var borderVt=100; //value based on css style. bottom bar + padding of photoContain
		var borderHz=100; //value based on css style photoContain padding

		var origSizeW = $("#lightboximage").width();
		var origSizeH = $("#lightboximage").height();
		var ratioVt=(origSizeW/origSizeH);
		var ratioHz=(origSizeH/origSizeW);
		var winW = $(window).width();
		var winH = $(window).height();
		var screenSizeW=Math.round(winW-borderHz);
		var screenSizeH=Math.round(winH-borderVt);

		if(origSizeH > screenSizeH) {
			$("#lightboximage").css("width", "auto").css("height", "auto"); // Remove existing CSS
			$("#lightboximage").removeAttr("width").removeAttr("height"); // Remove HTML attributes   

			if(origSizeW>=origSizeH) {
				var newHeight = Math.round(screenSizeW*ratioHz);
				if(newHeight <= screenSizeH) {
					$("#lightboximage").css("width", screenSizeW); // Set new width
					$("#lightboximage").css("height", newHeight);
				} else {
					$("#lightboximage").css("height", screenSizeH);
				}
			} else {
				$("#lightboximage").css("height", screenSizeH); // Set new height
			}
		} else {
			//$("#lightboximage").css("width", screenSizeH); // Set new height
			//$("#lightboximage").css("height", screenSizeH); // Set new height
		}
	}

		



// -----------------------------------------------------------------------------------------------------------------------------------

