
var currentTopics; //latest topics in the main list
var windowcount = 100;  //to track the stacking of windows
var mytopics = new Array(); //topic windows i have open (refresh comments)
var last_update="";
var refreshing=false;
var intervalId;
var interval = 10000;
var topTopic;
var topChat;
var friendsfoes;
var activeusers;
var loggedin = false;
var useroptstimeout;
var access;
var countTopics=40;
var idleness=120000;//two minutes
var myStatus='IDLE';
var myLastAction= (new Date()).getTime();
var markingStatus = false;
var currentUser;
var myChats= new Object();
var refreshingUsers = false;

function updateMyStatus(status){
	if(loggedin && !markingStatus){
		marking = true;
		var url = '/uu.jsp?a=UPDATESTATUS&status='+status;
		new Ajax.Request(url, { method:'post',
		  onSuccess: function(transport){
		        response = transport.responseText;
				response = trim(response);
				//alert(response);		
				if(response=='200'){
					myStatus=status;
					if(myStatus=="ACTIVE"){
						loadTopics();
						loadActiveUsers();
					}
				}else{
					log(response);
				}
				element("mystatus").innerHTML = myStatus;
				markingStatus = false;
		    }
		  });
	}
	if(!loggedin){
		myStatus=status;
		element("mystatus").innerHTML = myStatus;
	}
	return false;
}
function checkMeActive(){
	//element("mystatus").innerHTML += ".";
	var now = new Date();
	if(now.getTime()>(myLastAction+idleness)){
		if(myStatus!=="IDLE"){
			updateMyStatus("IDLE");
		}//if not already idle
	}//if it's been a while
	element("mystatus").innerHTML=myStatus;
}

function markMeActive(){
	log("marking ACTIVE [old:"+myStatus+"]");
	var now = new Date();
	myLastAction = now.getTime();
	if(myStatus!=='ACTIVE'){
		log("changed from IDLE to ACTIVE");
		updateMyStatus("ACTIVE");
	}
}
function openPMOLDLDLDLDLL(){//just open in a new window for now
	alert("still working!  use at own risk!");
	if(exists('pms')){
		raisePM();
		return;
	}

	var newdiv = document.createElement('div');
	newdiv.id = 'pms';
	newdiv.className = 'pmwindow';
	newdiv.style.position = "absolute";
	newdiv.style.left = rand(400);
	newdiv.style.top = rand(20);
	newdiv.style.zIndex = windowcount;
	newdiv.onclick=function() { raisePM();};

	var html = "";
	html += "<div id='pmhead'>";
	html += "<div class='closew'><a href='' onclick='closePM();return false;'>close</a></div>";
	html += "<div id='pmtitle'>Private Messages</div>";
	html += "</div>";
	html += "<iframe src='upm.jsp' width=600 height=800></iframe>";	
	newdiv.innerHTML = html;

	windowcount++;
	document.body.appendChild(newdiv);

	Drag.init(element("pmtitle"), element("pms"));
}
function checkPM(){
	//alert("coming soon. "+topicid+":"+pollid+":"+optionid);
	//alert("submitting vote");
	var url = '/uu.jsp?a=CHECKPM';
	new Ajax.Request(url, { method:'post',
	  onSuccess: function(transport){
	        response = transport.responseText;
			response = trim(response);
			var json = eval('('+response+')');
			var a = json[0];
			var msg = ""; 
			if(a.score=="0"){
				msg = "<a href='accountpm.jsp' target='_new' onclick='checkPM();'>personal messages</a>";
				element("accountpm").innerHTML = msg;
				element("accountpm").style.backgroundColor = "#AAAAFF";
			}else{
				msg = "<a href='accountpm.jsp' target='_new' onclick='setTimeout(\"checkPM()\",5000);'>"+a.score+" new messages</a><img src='http://www.pendletonunderground.com/images/jumping_star.gif'>";
				element("accountpm").innerHTML = msg;
				element("accountpm").style.backgroundColor = "pink";
			}
			
	    }
	  });
	return false;
}
function vote(topicid, pollid, optionid){
	markMeActive();
	//alert("coming soon. "+topicid+":"+pollid+":"+optionid);
	//alert("submitting vote");
	var url = '/uu.jsp?a=VOTE&topicId='+topicid+'&pollId='+pollid+'&optionId='+optionid;
	new Ajax.Request(url, { method:'post',
	  onSuccess: function(transport){
	        response = transport.responseText;
			response = trim(response);
			alert(response);
			loadTopicHeader(topicid);
	    }
	  });
	  
	return false;
}
function newTopicLinks(){
	var s = "<a href='#' onclick='openNewTopic(\"CHAT\");return false;'>Start a Discussion</a>";
	s += "...<a href='#' onclick='openNewTopic(\"POLL\");return false;'>Create a Poll</a>";
	return s;
}
function loadNewLinks(){
	element("newlinks").innerHTML = newTopicLinks();
}
function closeNewTopic(){
	var e = element("newtopic");
	if(e) {
		document.body.removeChild(e);
	}
}
function closePM(){
	var e = element("pms");
	if(e) {
		document.body.removeChild(e);
	}
}
function startTopic(form){
	markMeActive();
	//alert("submitting topic");
	new Ajax.Request('/uu.jsp?a=NEWTOPIC', { method:'post',
	  parameters: Form.serialize(form),
	  onSuccess: function(transport){
	        response = transport.responseText;
			response = trim(response);
			//log('comment posted:'+response);
			//alert(response);
			if(response==200){
				//update text
				loadTopics();
				closeNewTopic();
			}else{
				alert(response);
			}
	    }
	  });
	return false;
}
function openNewTopic(topictype){
	markMeActive();
	var div = element("newtopic");
	if(!div){
		var newdiv = document.createElement('div');
		newdiv.id = 'newtopic';
		newdiv.className = 'newtopic';
		newdiv.style.position = "absolute";
		newdiv.style.left = rand(400);
		newdiv.style.top = rand(20);
		newdiv.style.zIndex = windowcount;
		newdiv.onclick=function() { raiseNewTopic();};
		document.body.appendChild(newdiv);
	}	
	var existingform = findForm("newtopicform");
	if(existingform){
		var ititle = findFormElement(existingform,"title");
		var itext = findFormElement(existingform,"postText");
	}
	var title = "";if(ititle) title = ititle.value;
	var text = "";if(itext) text = itext.value;
	
	var s = "<div id='newtopichead' class='newtopichead'>";
	s += "<div class='closew'><a href='#' onclick='closeNewTopic();return false;'>close window</a></div>";
	s += "<div id='newtopictitle' class='newtopictitle'>Create a New Topic</div>";
	s += "<div style='clear:both'></div>";
	s += "</div>";
	s += "<div id='newtopiclinks'>"+newTopicLinks()+"</div>";
	s += "<div id='newtopicbody'><form action='' name='newtopicform' onsubmit='startTopic(this);return false'>";
	s += "<input type='hidden' name='t' value='"+topictype+"'>";
	s += "<input type='hidden' name='customNumber' value='0'>";
	s += "<input type='hidden' name='eventDate' value=''>";
	s += "Title:<br><input type='text' name='title' value='"+title+"' size=60><br>";
	s += "Comments:<br><textarea name='postText' rows=6 cols=55>"+text+"</textarea><br>";
	if(topictype=="POLL"){
		s += "Enter poll choices (one per line)<br>";
		s += "<textarea name='options' rows=6 cols=55></textarea><br>";
	}
	s += "<input type='submit' value='Start the Discussion!'>";
	s += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='#' onclick='closeNewTopic();return false;'>Cancel</a>";
	s += "</form>";
	s += "</div>";

	log("new topic form loaded");
	
	element("newtopic").innerHTML = s;

	Drag.init(element("newtopichead"), element("newtopic"));
}
function unpad(s){
	if(s.indexOf("0")==0) return s.substring(1);
	return s;
}
function dateDiff(older,newer){
	var diff = older.getTime()-newer.getTime();
	diff = Math.abs(diff);
	diff = diff/1000;//s
	if(diff < 60) return Math.floor(diff)+" sec";
	diff = diff/60;//minutes
	if(diff < 60) return Math.floor(diff)+" min";
	diff = diff/60;//hours
	if(diff < 24) return Math.floor(diff)+" hours";
	diff = diff/24;//days
	return Math.floor(diff)+" days";
	
}
function dateDiffMinutes(older,newer){
	var diff = older.getTime()-newer.getTime();
	diff = Math.abs(diff);
	diff = diff/1000;//s
	diff = diff/60;//minutes
	return Math.floor(diff);
}
function dateDiffDays(older,newer){
	var diff = older.getTime()-newer.getTime();
	diff = Math.abs(diff);
	diff = diff/1000;//s
	diff = diff/60;//minutes
	diff = diff/60;//hours
	diff = diff/24;//days
	return Math.floor(diff);
}
function parseDate(sdate){
	var year = sdate.substring(0,4);
	var month = sdate.substring(5,7);
	var day = sdate.substring(8,10);
	var hour = sdate.substring(11,13);
	var min = sdate.substring(14,16);
	var sec = sdate.substring(17,19);
	var s = year+", "+ unpad(month)+", "+ unpad(day)+", "+ unpad(hour)+", "+ unpad(min)+", "+ unpad(sec);
	//alert(s);
	//alert(Date.UTC(s));

	var d = new Date();
	d.setYear(unpad(year));
	d.setMonth(unpad(month)-1);
	d.setDate(unpad(day));
	d.setHours(unpad(hour));
	d.setMinutes(unpad(min));
	d.setSeconds(unpad(sec));
	
	//TODO: be smarter than this:
	var offsethours = 2;
	d.setTime(d.getTime() + offsethours*60*60*1000);
	
	return d;
	
}
function canEdit(comment){
	if(!access) {
		log("no access object found");
		return false;
	
	}
	if(access.can_comments_edit=="true"){
		log("moderator: can edit comments");
		return true;
	}
	if(comment.account_id==access.account_id){
		//log("!account_id:"+comment.account_id+":"+access.account_id);
		log("!i can edit, because i created it.");
		//log("date_created:"+comment.date_posted);
		//log("date posted:"+parseDate(comment.date_posted));
		//log("now:"+new Date());
		//log("diff (min):"+dateDiffMinutes(parseDate(comment.date_posted),new Date()));
		if(dateDiffMinutes(parseDate(comment.date_posted),new Date())<60){
			log("and it's been less than one hour");
			return true;
		}
		log("!done checking date diff");
	}
	return false;
}
function canDelete(comment){
	if(!access)  {
		log("no access object found");
		return false;
	}
	if(access.can_comments_delete=="true"){
		return true;
	}
	return false;
}
function editComment(id){
	markMeActive();

	var url = '/uu.jsp?a=FETCHCOMMENT&id='+id;
	//alert(url);
	new Ajax.Request(url , { method:'post',
	  onSuccess: function(transport){
		//alert(transport.responseText);
	        response = transport.responseText;
		response = trim(response);
		var jsoncomment = eval('('+response+')');
		var comment = jsoncomment[0];
		if(canEdit(comment)){
			openEditComment(comment);//alert(comment.comment_text);	
		}else{
			alert("Not allowed to edit");
		}
	    }
	  });
}
function openEditComment(comment){
	markMeActive();

	var f = "<form action='' name='editcomment"+comment.comment_id+"' onsubmit='saveComment(this);return false;'>";
	f += "<input type='hidden' name='id' value='"+comment.comment_id+"'>";
	f += "<textarea name='comment_text' rows=6 cols=50>"+comment.comment_text+"</textarea>";
	f += "<br><input type='submit' value='save'>";
	f += "</form>";

	element("commenttext"+comment.comment_id).innerHTML =f;
}
function saveComment(form){
	markMeActive();
	var id = form.id.value;
	var text = form.comment_text.value;
	//alert(id+":"+text);

	new Ajax.Request('/uu.jsp?a=SAVECOMMENT', { method:'post',
	  parameters: Form.serialize(form),
	  //parameters: "topic="+topic+"&comment="+comment,
	  onSuccess: function(transport){
	        response = transport.responseText;
		response = trim(response);
		//log('comment posted:'+response);
		//alert(response);
		if(response==200){
			//update text
			element("commenttext"+id).innerHTML = text;
		}else{
			alert(response);
		}

	    }
	  });
	return false;


}
function deleteComment(id){
	markMeActive();
	alert("coming soon");
}
function appendToCommentForm(id,text){
  
  //var form = eval("document.commentform"+id+"");
  var form = findForm("commentform"+id);
  var comment = findFormElement(form,"comment");
  comment.value=comment.value+text;
}
function addImage(id){
	markMeActive();
  var url = prompt("Enter the URL of the picture to add","");
  if(url) appendToCommentForm(id, "[img]"+url+"[/img]");
  return false;
}
function addLink(id){
	markMeActive();
  var url = prompt("Enter the URL of the link","");
  if(url){
	var title = prompt("Enter the title you wish to display","");
	if(url && title){
		appendToCommentForm(id, "[url="+url+"]"+title+"[/url]");
	}
  }
  return false;
}
function quote(id){
	markMeActive();
  var t = getSelText();
  if(!t || t.length == 0) {
	alert("please select some text to quote first");
  }else {
	appendToCommentForm(id, "[i]"+t+"[/i]");
  }
  return false;
}
function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return;
    return txt;
}

function scroll(){
	//scroll the div
	var tt = element('topicbody'+topTopic);
	var pos = tt.scrollTop+200;
	tt.scrollTop = pos;
	log(pos+" scrollTop");
}
function scrollBottom(id){
	//scroll the div
	var tt = element('topicbody'+id);
	tt.scrollTop = tt.scrollHeight;
	log("scrolled to "+tt.scrollTop);
}
function scrollChatBottom(id){
	//scroll the div
	//log("scrolling the chat");
	var tt = element('chatbody'+id);
	//log(tt);
	//alert(tt.scrollTop+":"+tt.scrollHeight);
	tt.scrollTop = tt.scrollHeight;
	//alert("scrolled to "+tt.scrollTop);
}
function loadPage(){
	//myStatus="ACTIVE";
	//markMeActive();
	log("current status 1:"+myStatus);
	
	//one time
	loadNewLinks();
	loadTodo();
	loadHowto();
	log("current status 2:"+myStatus);
	checkLoggedIn();
	//loadAccess();
	//loadActiveUsers();
	loadTopics();
	log("current status 3:"+myStatus);
	
	popSounds();
	//checkLoggedIn();
	setInterval("checkLoggedIn()",120000);
	setInterval("checkMeActive()",10000);
	//loadTopics();
	setInterval("loadTopics()",60000);
	//loadActiveUsers()
	//setInterval("loadActiveUsers()",20000);
	//loadNewComments();
	setInterval("loadNewComments()",4000);
	setInterval("loadNewChats()",3000);
	setInterval("checkPM()",60000);
	log("page loaded");
	//intervalId = setTimeout("refresh()",interval);
}

function refresh(){  //THIS IS OLDDDD
	if(refreshing)
		return;
	refreshing = true;
	log("last comment id: "+last_update);
	loadTopics();
	log("topics refreshed");
	loadNewComments();
	log("new comments loaded");
	loadActiveUsers();
	log("active users loaded");
	refreshing = false;
	clearTimeout(intervalId);
	//intervalId = setTimeout("refresh()",interval);
	markRefresh();
}
function markRefresh(){
	var tt = element('refresh');
	var s = tt.innerHTML;
	if(s.length>=30) s = "";
	s += ".";
	tt.innerHTML = s;
}
function loadAccess(){
	log("######### starting access load ###########");
	new Ajax.Request('/uu.jsp?a=FETCHACCESS', { method:'post',
	  onSuccess: function(transport){
	    response = transport.responseText;
log("######### access response ###########"+response);
		response = trim(response);
		var jsonaccess = eval('('+response+')');
		access = jsonaccess[0];
		log("accesses loaded: can edit comments:"+access.can_comments_edit);
log("######### COMPLETED access load ###########");
	
	    }
	  });
}
function checkLoggedIn(){
	new Ajax.Request('/uu.jsp?a=CHECKLOGGEDIN', { method:'post',
	  onSuccess: function(transport){
		    response = transport.responseText;
			response = trim(response);
			if(response=='200'){
				loadFriendsFoes();
				log("friends foes loaded");
				writeLogout();
				loggedin = true;
				loadAccess();
				checkPM();
				
			}else{
				writeLoginForm();
				
				
				loggedin = false;
			}
			loadActiveUsers();
	    }
	  });
}
function writeLoginForm(){
	element("account").innerHTML = "adsfasfads";
	var html = "";
	html += "<form action='' onsubmit='return login(this)'>";
	html += "<table>";
	html += "<tr><td>email:</td><td><input type='text' name='email' size='17' onkeydown='clearLoginStatus()'></td></tr>";
	html += "<tr><td>password:</td><td><input type='password' name='password' size='17' onkeydown='clearLoginStatus()'></td></tr>";
	html += "<tr><td></td><td><input type='submit' value='login!'></td></tr>";
	html += "</table><div class='chatstatus' id='loginstatus'></div></form>";
	element("account").innerHTML = html;
}
function clearLoginStatus(){
	element("loginstatus").innerHTML = "";
}

function writeLogout(){
	var html = "<div id='accountpm'></div><div class='accountactions'><a href='#' onclick='logout();return false;'>logout</a></div>";
	element("account").innerHTML = html;
}
function logout(){
	markMeActive();
	new Ajax.Request('/uu.jsp?a=LOGOUT', { method:'post',
	  onSuccess: function(transport){
			checkLoggedIn();
			friendsfoes=null; loadActiveUsers();
			myStatus='';
	    }
	  });
	return false;
}
function loginme(form){
	alert("coming soon...");
	return false;
}
function bookmarkUser(id,type,msgdest){
	markMeActive();
	var url = '/uu.jsp?a=BOOKMARKUSER&id='+id+'&type='+type;
	//alert(url);
	new Ajax.Request(url , { method:'post',
	  onSuccess: function(transport){
		//alert(transport.responseText);
	        response = transport.responseText;
		response = trim(response);
		if(response=="200"){
			var msg="";
			if(type=="FOE") msg = "<div class='msgfailure'>user blocked</div>";
			if(type=="FRIEND") msg = "<div class='msgsuccess'>user added as friend</div>";
			if(msgdest=="CHAT"){
				element("chat"+id).style.backgroundColor="#CCCCCC";
				element("chatstatus"+id).innerHTML = msg;
			}
			if(msgdest=="USER"){
				element("useroptsmsg").innerHTML = msg;
			}
			loadFriendsFoes();
			writeActiveUsers();

		}else{
			alert(response);
		}
	
	    }
	  });
}
function unBookmarkUser(id,msgdest){
	markMeActive();
	var url = '/uu.jsp?a=UNBOOKMARKUSER&id='+id;
	//alert(url);
	new Ajax.Request(url , { method:'post',
	  onSuccess: function(transport){
		//alert(transport.responseText);
	        response = transport.responseText;
		response = trim(response);
		if(response=="200"){
			var msg="";
			msg = "<div class='msgsuccess'>removed</div>";
			if(msgdest=="CHAT"){
				element("chat"+id).style.backgroundColor="#CCCCCC";
				element("chatstatus"+id).innerHTML = msg;
			}
			if(msgdest=="USER"){
				element("useroptsmsg").innerHTML = msg;
			}
			loadFriendsFoes();
			writeActiveUsers();

		}else{
			alert(response);
		}
	
	    }
	  });
}
function findForm(formname){
	var forms = document.forms;
	//alert(forms.length+" forms");
	for(var i=0;i<forms.length;i++){
		var f = forms[i];
		//alert("form name:"+f.name);
		if(f){
			//alert("form name:"+f.name);
			if(f.name == formname) return f;
		}
	
	}
	return null;
}
function findFormElement(theForm, theElementName){
	var fe = theForm.elements[theElementName];
	if(!fe){
		var ee = theForm.elements;
		for(var ii=0;ii<ee.length;ii++){
			var e = ee[ii];
			if(e){
				if(e.name == theElementName) return e;
			}
			//alert("element name:"+e.name);
			//alert("element value:"+e.value);
		}
	}
	return fe;
}
function postComment(id, form){
	markMeActive();
	var ff = findForm("commentform"+id);
	var itopic = findFormElement(ff,"topic");
	var icomment = findFormElement(ff,"comment");
	var topic = itopic.value;
	var comment = icomment.value;

	var status = element('commentstatus'+topic);
	status.innerHTML = "posting....";
	var response;
	new Ajax.Request('/uu.jsp?a=POSTCOMMENT', { method:'post',
	  parameters: Form.serialize(ff),
	  //parameters: "topic="+topic+"&comment="+comment,
	  onSuccess: function(transport){
	        response = transport.responseText;
		response = trim(response);
		//log('comment posted:'+response);

		//update status
		status.innerHTML = response;

		//refresh();//pull new comments in
		loadNewComments();
		setTimeout("scroll()",500);
	
		icomment.value="";//clear the comment form
		icomment.focus();
	
	    }
	  });
	return false;
}
function login(form){
	var email = form.email.value;
	var password = form.password.value;
	new Ajax.Request('/uu.jsp?a=LOGIN', { method:'post',
	  parameters: Form.serialize(form),
	  onSuccess: function(transport){
	        var response = transport.responseText;
			response = trim(response);
			if(response.indexOf("200")==0){
				loggedin = true;
				checkLoggedIn();
				markMeActive();
				loadActiveUsers();
			}else{
				var msg ="<div class='msgfailure'>"+response+"</div>";
				loggedin = false;
				element('loginstatus').innerHTML = msg;
			}
	    }
	  });

	return false;
}
function sendChat(form){
	markMeActive();
	var to = form.to.value;
	var comment = form.text.value;
	//alert(to);
	//alert(comment);
	var status = element('chatstatus'+to);
	status.innerHTML = "<div class='msginfo'>posting....</div>";
	var response;
	new Ajax.Request('/uu.jsp?a=SENDCHAT', { method:'post',
	  parameters: Form.serialize(form),
	  onSuccess: function(transport){
	    response = transport.responseText;
		response = trim(response);
		//alert(response.indexOf("200:"));
		//log('comment posted:'+response);
		var msg ="";
		if(response.indexOf("200")>=0){
			//alert("good!"+response.indexOf("200:"));
			msg = "<div class='msgsuccess'>chat sent successfully!</div>";
		}else{
			//alert("bad!"+response.indexOf("200:"));
			msg = "<div class='msgfailure'>"+response+"</div>";
		}
			
		//update status
		status.innerHTML = msg;
		
		var curtext = element('chatbody'+to);
		curtext.innerHTML += "<div class='chatme'>"+comment+"</div>";
		
		form.text.value="";//clear the comment form
		form.text.focus();
		var tt = element("chat"+to);
		tt.style.backgroundColor = "white";
		
		scrollChatBottom(to);
		
		}
	  });
	return false;
}
function loadTopics(){
	if(myStatus=='ACTIVE'){
		log("loading topics");
		new Ajax.Request('/uu.jsp?a=FETCHTOPICS', { method:'post',
		  onSuccess: function(transport){
		      var response = transport.responseText;
			//alert(response);
			//alert("cp1");
			var jsontopics = eval('('+response+')');
			//alert("cp2");
			//alert(document.getElementById('topics').innerHTML);
			//alert($('topics'));// = "hi adam";
			//alert(jsontopics[0].title);
			//alert("done with topics");
			printTopicList(jsontopics);
			currentTopics = jsontopics;
		    }
		  });
		  log("topics loaded");
	}else{
		log("idle.  not loading new topics");
	}
}
function loadNewChats(){
	var url = '/uu.jsp?a=FETCHNEWCHATS';
	log(url);
	
	new Ajax.Request(url, { method:'post',
	  onSuccess: function(transport){
	    var response = transport.responseText;
		log(response);
		var jsonchats = eval(response);
		processNewChats(jsonchats);
		}
	  });
	 log("newchats loaded");
	 
}
function loadNewComments(){
	var url = '/uu.jsp?a=FETCHNEWCOMMENTS&last='+last_update+'&'+getMyTopicList();
	log(url);
	
	new Ajax.Request(url, { method:'post',
	  onSuccess: function(transport){
	    var response = transport.responseText;
		log(response);
		var jsoncomments = eval(response);
		processNewComments(jsoncomments);
		}
	  });
	 log("newcomments loaded");
	 
}
function processNewComments(comments){
	for(var i=0;i<comments.length;i++){
		var comment = comments[i];
		if(!element("comment"+comment.comment_id)){ //if comment doesn't already exist
			var html = getCommentBlock(comment);
			var dest = element("topiccommentsholder"+comment.topic_id);
			dest.innerHTML += html;
			var tt = element("topic"+comment.topic_id);
			tt.style.backgroundColor = "yellow";
			updateLast(comment.comment_id);
		}
	}
	//alert("printing "+comments.length+" new comments");
}
function processNewChats(chats){
	for(var i=0;i<chats.length;i++){
		var chat = chats[i];
		
		
		//user may have been inactive.  reload.
		var chatuser = findUser(chat.from_id);
		if(!chatuser) {
			loadActiveUsers(true);//force a reload
			setTimeout('processNewChats([{"to_id" : "'+chat.to_id+'", "to_name" : "??????", "from_id" : "'+chat.from_id+'", "from_name" : "'+chat.from_name+'", "text" : "'+chat.text+'", "date" : "???"}])',4000);
			return;
		}else if(chatuser.online_status=='IDLE') {
			loadActiveUsers();
		}
		
		
		openChat(chat.from_id, chat.text);
		
		var html = "<div class='chatthem'>"+chat.text+"</div>";
		var dest = element("chatbody"+chat.from_id);
		dest.innerHTML += html;
		
		var tt = element("chat"+chat.from_id);
		tt.style.backgroundColor = "yellow";
		//updateLast(comment.comment_id);
		scrollChatBottom(chat.from_id);
	}
	if(chats.length>0){
		playSound();
	}
	//alert("printing "+comments.length+" new comments");
}
function minTopic(id){
	markMeActive();
	element("topicshell"+id).style.display = "none";
	element("topic"+id).style.width = "550px";
	element("topic"+id).style.height = "";
	element("topicshow"+id).innerHTML = "<a href='#' onclick='normalTopic("+id+");return false;'>normal</a>";
	element("topicshow2"+id).innerHTML = "<a href='#' onclick='maxTopic("+id+");return false;'>max</a>";
}
function normalTopic(id){
	markMeActive();
	element("topicshell"+id).style.display = "block";
	element("topic"+id).style.width = "550px";
	element("topic"+id).style.height = "600px";
	element("topicshow"+id).innerHTML = "<a href='#' onclick='minTopic("+id+");return false;'>shrink</a>";
	element("topicshow2"+id).innerHTML = "<a href='#' onclick='maxTopic("+id+");return false;'>max</a>";
	scrollBottom(id);
}
function maxTopic(id){
	markMeActive();
	element("topicshell"+id).style.display = "block";
	element("topic"+id).style.left = "5px";
	element("topic"+id).style.top = "5px";
	element("topic"+id).style.width = "95%";
	element("topic"+id).style.height = "95%";
	element("topicshow"+id).innerHTML = "<a href='#' onclick='minTopic("+id+");return false;'>shrink</a>";
	element("topicshow2"+id).innerHTML = "<a href='#' onclick='normalTopic("+id+");return false;'>normal</a>";
}
function fetchTopic(id){
	var url = '/uu.jsp?a=FETCHTOPIC&id='+id;
	log(url);
	
	new Ajax.Request(url, { method:'post',
	  onSuccess: function(transport){
	    	var response = transport.responseText;
			//log(response);
			var jsontopic = eval(response);
			var topic = jsontopic[0];
			if(topic && topic.topic_id && topic.topic_id>0){
				currentTopics[currentTopics.length]=topic;
				openTopic(id);
			}else{
				alert(response);
			}
		}
	  });
}
function openTopic(id){
	markMeActive();
	//alert("opening topic "+id);
	//TODO: check to see if already open
	if(exists('topic'+id)){
		raiseTopic(id);
		return;
	}

	var tt = findTopic(id,currentTopics);
	if(!tt || tt==null){
		fetchTopic(id);
		return;
	}

	var newdiv = document.createElement('div');
	newdiv.id = 'topic'+id;
	newdiv.className = 'topicwindow';
	//newdiv.innerHTML = "asdfasdfsdafsdaf";
	newdiv.style.position = "absolute";
	newdiv.style.left = rand(400);
	newdiv.style.top = rand(20);
	newdiv.style.zIndex = windowcount;
	newdiv.onclick=function() { raiseTopic(id);};
	
	var actions = "";
	actions += "<div class='scroll'><a href='#' onclick='scrollBottom("+id+");return false;'>scroll to bottom</a></div>";
	actions += "<div style='clear:both;'></div>";
	
	var titlehtml = "";
	titlehtml += "<div class='closew'><a href='#' onclick='closeTopic("+id+");return false;'>close window</a></div>";
	titlehtml += "<div id='topicshow2"+id+"' class='closew'><a href='#' onclick='maxTopic("+id+");return false;'>max</a></div>";
	titlehtml += "<div id='topicshow"+id+"' class='closew'><a href='#' onclick='minTopic("+id+");return false;'>shrink</a></div>";
	titlehtml += "<div class='topictitletext'>"+tt.title+"</div>";
	var titlediv = makeDiv("topictitle"+id, "topictitle", titlehtml);

	var shelldiv = makeDiv("topicshell"+id);//to allow min/max
	var actionstopdiv = makeDiv("topicsub"+id, "topicsub", actions);//top actions
	var headerdiv = makeDiv("topicheader"+id, "topicheader", "");//block for the poll, etc
	var actionsbottomdiv = makeDiv("topicsub"+id, "topicsub", actions);//bottom actions
	
	var bodyhtml = "<div id='topicheader"+id+"' class='topicheader'></div><div id='topiccommentsholder"+id+"'><img src='images/loading.gif'></div>";
	var bodydiv = makeDiv("topicbody"+id, "topicbody", bodyhtml);//middle section for comments and header
	
	var commentformdiv = makeDiv("topiccomment"+id, "topiccomment");
	var commenthtml = "<form action='' onsubmit='return postComment(this);' name='commentform"+id+"'>";
	commenthtml += "<input type='hidden' name='topic' value='"+id+"'><textarea name='comment' rows=3 cols=60></textarea><input type='submit' value='post comment'></form><div id='commentstatus"+id+"'>";

	//commentformdiv.innerHTML = commenthtml;
	var cform = commentForm(id);
	commentformdiv.appendChild(cform);

	newdiv.appendChild(titlediv);
	 shelldiv.appendChild(actionstopdiv);
	 shelldiv.appendChild(bodydiv);
	 shelldiv.appendChild(actionsbottomdiv );
	 //shelldiv.appendChild(commentformdiv);
	 shelldiv.appendChild(commentForm(id));
	 //shelldiv.appendChild(commentForm(id));
	newdiv.appendChild(shelldiv);
	

	windowcount++;
	document.body.appendChild(newdiv);

	loadComments(id);
	loadTopicHeader(id);
	Drag.init(element("topictitle"+id), element("topic"+id));
	
	mytopics[id]=tt;
	log(mytopics.length+" in mytopics");
	topTopic = id;

}
function makeDiv(id,className,contents){
	var newdiv = document.createElement('div');
	if(id) newdiv.id = id;
	if(className) newdiv.className = className;
	if(contents) newdiv.innerHTML = contents;
	return newdiv;
}
function commentForm(id){
	var d=makeDiv();

	var f = document.createElement('form');
	f.action = "";
	//f.method = "POST"
	f.name = "commentform"+id;
	f.id = "commentform"+id;
	f.onsubmit = function(){ postComment(id, this);return false;}
 	
	var links = "<a href='' onclick='return addImage("+id+");'>insert picture</a> ... <a href='' onclick='return addLink("+id+");'>insert link</a>";
	var l = makeDiv("commentlinks"+id, "commentlinks",links);

	var h = document.createElement('input');
	h.type="hidden";
	h.name="topic";
	h.value=id;

	var t = document.createElement('textarea');
	t.rows="3";
	t.cols="55";
	t.name="comment";

	var ss = document.createElement('input');
	ss.type="submit";
	ss.value="Post Comment";

	f.appendChild(h);//hidden topic id
	f.appendChild(t);//textarea
	f.appendChild(document.createElement("br"));
	f.appendChild(ss);//submit button
	
	d.appendChild(l);//links
	d.appendChild(f);//form
	d.appendChild(makeDiv("commentstatus"+id, "commentstatus"));

	
	return d;
}
function hideUserOptions(userid){
	log('hiding');
	element("useropts").innerHTML = "";
	element("useropts").style.display="none";
	//document.removeElement(element("useropts"));
	element("user"+userid).style.backgroundColor="#FFFFFF";
}
function unhighlightUser(id){
	log("unhighlighting");
	element("user"+id).style.backgroundColor="#FFFFFF";
}
function highlightUser(id){
	element("user"+id).style.backgroundColor="#CCCCFF";
	showUserOptions(id);
}
function showUserOptions(userid){
	markMeActive();
	clearTimeout(useroptstimeout);
	useroptstimeout = setTimeout("hideUserOptions("+userid+")",3000);
	var opts = element("useropts");
	if(!opts){
		opts = document.createElement('div');
		opts.style.position = "absolute";
		opts.id = 'useropts';
		opts.className = 'useropts';
		document.body.appendChild(opts);
	
	}
	opts.style.display="block";
	var loc = Element.cumulativeOffset(element("user"+userid));
	opts.style.left = loc[0]+160;
	opts.style.top = loc[1];

	var user = findUser(userid);
	var ff = findFriendFoe(userid);
	//alert(user.avatar_thumb);
	var html = "";
	if(user.avatar){
		html += "<img src='images/avatar/"+user.avatar_thumb+"' class='avatarImg'>";
	}
	html += "<div><a href='#' onclick='openProfile("+userid+");return false;'>show profile</a></div>";
	if(!ff || ff.type=="FRIEND"){
		html += "<div><a href='#' onclick='bookmarkUser("+userid+",\"FOE\",\"USER\");return false;'>block user</a></div>";
	}
	if(ff && ff.type=="FOE"){
		html += "<div><a href='#' onclick='unBookmarkUser("+userid+");return false;'>unblock user</a></div>";
	}
	if(ff && ff.type=="FRIEND"){
		html += "<div><a href='#' onclick='unBookmarkUser("+userid+");return false;'>remove as friend</a></div>";
	}
	if(!ff || !ff.type=="FRIEND"){
		html += "<div><a href='#' onclick='bookmarkUser("+userid+",\"FRIEND\",\"USER\");return false;'>make friend</a></div>";
	}

	html += "<div id='useroptsmsg'></div>";
	opts.innerHTML = html;
	//alert("showing options");
}
//displays the user profile
function showProfile(id){
	alert("coming soon");
}
function openChat(id, text){
	markMeActive();
	log("opening chat "+id);
	if(exists('chat'+id)){
		raiseChat(id);
		return;
	}

	var uu = findUser(id);
	if(!uu){
		alert("user not currently online");
		return;
	}

	var newdiv = document.createElement('div');
	newdiv.id = 'chat'+id;
	newdiv.className = 'chatwindow';
	newdiv.style.position = "absolute";
	newdiv.style.left = rand(400);
	newdiv.style.top = rand(200);
	newdiv.style.zIndex = windowcount;
	newdiv.onclick=function() { raiseChat(id);};
	
	var actions = "<div id='topicsub"+id+"' class='topicsub'>";
	actions += "<div class='scroll'><a href='#' onclick='scrollBottom("+id+");return false;'>scroll to bottom</a></div>";
	actions += "<div style='clear:both;'></div>";
	actions += "</div>";

	var html = "<div id='chattitle"+id+"' class='chattitle'>";
	html += "<div class='closew'><a href='#' onclick='closeChat("+id+");return false;'>close</a></div>";
	html += "<div class='chattitletext'>"+uu.title+"</div>";
	html += "</div>";
	html += "<div class='chatopts'>";
	html += "<a href='#' onclick='openProfile("+id+");return false;'>show profile</a> ... ";
	html += "<a href='#' onclick='bookmarkUser("+id+",\"FOE\");return false;'>block user</a>";
	html += "</div>";
	
	
	html += "<div id='chatbody"+id+"' class='chatbody'>";
	if(text){
		//html += "<div class='chatthem'>"+text+"</div>";
	}
	html += "";
	html += "</div>";
	
	html += "<div id='chatuserstatus"+id+"' class='chatstatus' style='display:none;'></div>";
	html += "<div id='chatcomment"+id+"' class='chatcomment'>";
	html += "<form name='chatform"+id+"' action='' onsubmit='return sendChat(this)'><input type='hidden' name='to' value='"+id+"'><input type='text' name='text' size='30'></form>";
	html += "</div>";
	
	html += "<div id='chatstatus"+id+"' class='chatstatus'><div class='msginfo'>type your message and hit enter!</div></div>";
	
	//html += actions;
	
	
	newdiv.innerHTML = html;

	windowcount++;
	document.body.appendChild(newdiv);
	myChats[id]="YES";
	Drag.init(element("chattitle"+id), element("chat"+id));

	log("chat "+id+" loaded");
	topChat = id;
	
	//focus on the text input
	var fff = findFormElement(findForm("chatform"+id),"text");
	fff.focus();
	scrollChatBottom(id);
	
}
function openProfile(id){
	markMeActive();
	log("opening profile "+id);
	if(exists('profile'+id)){
		raiseProfile(id);
		return;
	}
	new Ajax.Request('/uu.jsp?a=FETCHPROFILE&id='+id, { method:'post',
	  onSuccess: function(transport){
	      var response = transport.responseText;
		var jsonusers = eval('('+response+')');
		//alert("about to load profile");
		displayProfile(jsonusers[0]);
	    }
	  });
	
	
}
function displayProfile(profile){

	var newdiv = document.createElement('div');
	newdiv.id = 'profile'+profile.account_id;
	newdiv.className = 'profilewindow';
	newdiv.style.position = "absolute";
	newdiv.style.left = rand(400);
	newdiv.style.top = rand(200);
	newdiv.style.zIndex = windowcount;
	newdiv.onclick=function() { raiseProfile(profile.account_id);};
	
	//alert("#1");
	var html = "<div id='profilehead"+profile.account_id+"' class='profilehead'>";
	html += "<div class='closew'><a href='#' onclick='closeProfile("+profile.account_id+");return false;'>close</a></div>";
	html += "<div class='profiletitle'>"+profile.title+"</div>";
	html += "</div>";
	
	html += "<div class='profilelinks'>";
	html += "<a href='#' onclick='openChat("+profile.account_id+");return false;'>chat with me!</a>";
	html += " ... <a href='#' onclick='loadLatestComments("+profile.account_id+");return false;'>show latest comments</a>";
	html += "</div>";
	html += "<div id='profilecomments"+profile.account_id+"'></div>";
	html += "<div class='profilebody'>";
	if(profile.avatar){
		html += "<div>";
		html += "<img src='images/avatar/"+profile.avatar+"'>";
		html += "</div>";
	}
	html += "<div>";
	html += ""+profile.account_profile;
	html += "</div>";

	html += "</div>";
	
	newdiv.innerHTML = html;

	windowcount++;
	document.body.appendChild(newdiv);
	Drag.init(element("profilehead"+profile.account_id), element("profile"+profile.account_id));
	//alert("#3");

	log("profile "+profile.account_id+" loaded");

}

function findUser(id){
	for(var i=0;i<activeusers.length;i++){
		var uu = activeusers[i];
		if(id==uu.account_id){
			return uu;
		}
	}
	return false;
}
function findFriendFoe(id){
	if(!friendsfoes) return null;
	for(var i=0;i<friendsfoes.length;i++){
		var uu = friendsfoes[i];
		if(id==uu.account_id){
			return uu;
		}
	}
	return null;
}
function findTopic(id){
	for(var i=0;i<currentTopics.length;i++){
		var topic = currentTopics[i];
		if(id==topic.topic_id){
			return topic;
		}
	}
	return null;
}
function findMyTopic(id){
	var tt = mytopics[id];
	return tt;
}
function getMyTopicList(){
	var s="";
	for(var i in mytopics){
		var topic = mytopics[i];
		if(topic && topic.topic_id){
			if(i>0)	{
				s += "&topic="+topic.topic_id;
			}else{
				s += "topic="+topic.topic_id;
			}	
		}
	}
	return s;
}
function loadLatestComments(id,n,start){
	markMeActive();
	if(!n || n==null) n = 5;
	if(!start || start==null) start=0;
	//alert('loading latest comments');
	element("profilecomments"+id).innerHTML = "loading latest comments.......";
	new Ajax.Request('/uu.jsp?a=FETCHLATESTCOMMENTS&id='+id+'&n='+n+'&start='+start, { method:'post',
	  onSuccess: function(transport){
	      	var response = transport.responseText;
	      	var jsoncomments = eval('('+response+')');
	      	//alert("got response:"+response);
			log(response);
			printLatestCommentList(id, n,start,jsoncomments);
	    }
	  });
	  log("topic header loaded");
}
function loadTopicHeader(id){
	//alert('loading topic header');
	new Ajax.Request('/uu.jsp?a=FETCHTOPICHEADER&id='+id, { method:'post',
	  onSuccess: function(transport){
	      var response = transport.responseText;
		//alert(response);
		element("topicheader"+id).innerHTML = response;
	    }
	  });
	  log("topic header loaded");
}
function loadComments(id){
	//alert('loading comments');
	new Ajax.Request('/uu.jsp?a=FETCHCOMMENTS&topic='+id, { method:'post',
	  onSuccess: function(transport){
	      var response = transport.responseText;
		//alert(response);
		var jsoncomments = eval('('+response+')');
		log(response);
		printCommentList(id, jsoncomments);
		//alert('cp3');
	    }
	  });
	  log("comments loaded");
}

function raiseTopic(id){
	markMeActive();
	var dd= element('topic'+id);
	dd.style.zIndex = windowcount;
	dd.style.backgroundColor = "white";
	windowcount++;
	topTopic = id;
}
function raiseNewTopic(){
	markMeActive();
	var dd= element('newtopic');
	dd.style.zIndex = windowcount;
	windowcount++;
}
function raisePM(){
	markMeActive();
	var dd= element('pms');
	dd.style.zIndex = windowcount;
	windowcount++;
}
function raiseChat(id){
	markMeActive();
	var dd= element('chat'+id);
	dd.style.zIndex = windowcount;
	var uu = findUser(id);
	if(uu !== null && uu.online_status=='ACTIVE'){
		dd.style.backgroundColor = "white";
	}//otherwise it will make gray white
	windowcount++;
	topChat = id;
}
function raiseProfile(id){
	markMeActive();
	var dd= element('profile'+id);
	dd.style.zIndex = windowcount;
	windowcount++;
}
function closeTopic(id){
	markMeActive();
	var dd= element('topic'+id);
	document.body.removeChild(dd);
	mytopics[id] = null;
}

function closeChat(id){
	markMeActive();
	var dd= element('chat'+id);
	document.body.removeChild(dd);
	myChats[id]="NO";
}
function closeProfile(id){
	markMeActive();
	var dd= element('profile'+id);
	document.body.removeChild(dd);
}


//UTILITIES ******************************
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
function element(id){
	return document.getElementById(id);
}
function cut(s,len){
	if(s==null) return ""; 
	if(s.length > len) return s.substring(0,len)+"...";
	return s;
}
function log(msg){
	var logger = document.getElementById('log');
	var curlog = logger.innerHTML;
	if(curlog.length > 10000) curlog = curlog.substring(0,10000);
	logger.innerHTML = msg + "<br>\n" + curlog;
}

function rand(max){
	return Math.ceil(max*Math.random());
}
function exists(id){
	if(element(id)){
		return true;
	}else{
		return false;
	}
}
function updateLast(id){
	if(id > last_update) last_update = id;
}
//RENDERERS ******************************


function printCommentList(id,comments){
	//alert('printing list');
	log(comments.length+" total comments");
	//alert('logged 1');
	var html = "";
	html = "";//"<div class='topictitle' id='topictitle"+id+"'>topic title</div>";
	html += "<div class='topiccomments' id='topiccomments"+id+"'>";
	for(i=0;i<comments.length;i++){
		var comment = comments[i];
		html += getCommentBlock(comment);
		updateLast(comment.comment_id);
		log(comment.comment_id+":"+comment.account_name);
	}
	html += "</div>";
	log("done rendering comments");
	//log(comments.length+"\n\n"+html);
	var dd= element('topiccommentsholder'+id);
	dd.innerHTML = html;
	log("comments added to topic");
}
function printLatestCommentList(id,n,start,comments){
	//alert('printing list');
	//if(!comments) alert("no comments!");
	//alert(comments.length+" total comments");
	var html = "";
	html += "<div class='???' id='??"+id+"'><b>Latest Comments</b>";
	for(i=0;i<comments.length;i++){
		var comment = comments[i];
		html += "<div class='latestcommentstitle'>";
		html += "<a href='' onclick='openTopic("+comment.topic_id+");return false;'>"+comment.title+"</a>";
		html += "&nbsp; <span style='color:#888888;font-size:90%'>posted "+dateDiff(parseDate(comment.date_posted),new Date())+ " ago</span>";
		html += "</div>";
		html += "<div class='latestcommentstext'>"+cut(comment.comment_text,500)+"</div>";
	}
	html += "<div style='text-align:right;padding:5px;'><a href='' onclick='loadLatestComments("+id+","+n+","+(start+n)+");return false;'><b>Older &raquo;&raquo;</b></a></div>";
	html += "</div>";
	log("done rendering comments");
	//log(comments.length+"\n\n"+html);
	var dd= element('profilecomments'+id);
	dd.innerHTML = html;
	log("comments added to profile");
}
function printTopicList(topics){
	var html = "<table>";
	var n = topics.length;
	if(n==0){
		html += "No topics."
	}
	if(n>countTopics) n=countTopics;
	for(var i=0;i<n;i++){
		var topic = topics[i];
		html += getTopicListBlock2(topic);
	}
	html += "</table>";
	var dd= element('topics');
	dd.innerHTML = html;
}

function getTopicListBlock(topic){
	var html = "<div class='topiclistitem' id='topiclist"+topic.topic_id+"'>";
	html += "<a href='#"+topic.topic_id+"' onclick='openTopic("+topic.topic_id+");return false;'>"+topic.title+"</a>";
	html += "";
	html += "";
	html += "";
	html += "</div>";
	return html;
}

function getTopicListBlock2(topic){
	html = "";
	html += '<tr valign="middle" onmouseover="markMeActive();">';
	html += ' <td class="topicRow">';
	html += "  <a href='#"+topic.topic_id+"' onclick='openTopic("+topic.topic_id+");return false;'>";
	html += '   <img src="http://www.bookoo.com/img/site/go.jpg" border=0>';
	html += '  </a>';
	html += ' </td>';
	html += ' <td class="topicRow">';
	//log("cp1");
	html += "  <a href='#"+topic.topic_id+"' onclick='openTopic("+topic.topic_id+");return false;'>";
	html += cut(topic.title,300)+'</a>';
	html += ' </td>';
	html += ' <td class="topicRow">'+topic.total_comments+'</td>';
	html += ' <td class="topicRow">'+topic.total_views+'</td>';
	html += ' <td class="topicRow" width="80">';
	//log("cp2");
	html += '  <a href="#" onclick="openProfile('+topic.last_poster_id+');return false;" styleClass="link3">'+cut(topic.last_poster_name,15)+'</a>';
	//log("cp3");
	html += '  <br>';
	html += '  <span class="textSmall">';
	html += '   '+dateDiff(parseDate(topic.date_last_post),new Date())+' ago';
	html += '  </span>';
	html += ' </td>';
	html += ' <td class="topicRow" width="80">';
	html += '  <a href="#" onclick="openProfile('+topic.account_id+');return false;" styleClass="link3">'+cut(topic.creator_name,15)+'</a>';
	html += '  <br>';
	html += '  <span class="textSmall">';
	html += '   '+dateDiff(parseDate(topic.date_created),new Date())+' ago';
	html += '  </span>';
	html += ' </td>';
	html += '</tr>';
	html += '';
	//log("cpEnd");
	
	return html;
}

function getCommentBlock(comment){
	var html = "<div class='commentblock' id='comment"+comment.comment_id+"'>";
	html += "<b><a href='#' onclick='openProfile("+comment.account_id+");return false;'>"+comment.account_name+"</a></b> ";
	html += " - posted "+dateDiff(parseDate(comment.date_posted),new Date())+" ago ";
	html += " - <a href='#' onmousedown='quote("+comment.topic_id+")'>quote</a>";
	
	if(canEdit(comment)){
			html += " - <a href='#' onmousedown='editComment("+comment.comment_id+")'>edit</a>";
	}
	if(canDelete(comment)){
		html += " - <a href='#' onmousedown='deleteComment("+comment.comment_id+")'>delete</a>";
	}
	//OLDhtml += "<b><a href='#' onclick='openProfile("+comment.account_id+");return false;'>"+comment.account_name+"</a></b> - posted "+comment.date_posted+ "  - <a href=\"javascript:paste_string(selektion,'"+comment.topic_id+"',1)\" onmousedown='quote("+comment.topid_id+")'>quote</a>";
	
	html += "<div class='comment' id='commenttext"+comment.comment_id+"'>"+comment.comment_text_clean+"</div>";
	html += "";
	html += "";
	html += "</div>";
	return html;
}
function loadTodo(){
	var html = '<div class="textSmall"><b>working on...</b><br><ol>';
	html += '<li>allow flagging of comments and users';
	html += '<li>hide comments posted by your hosers';
	html += '<li>show topic header (polls, signups, etc)';
	html += '<li>view pms';
	html += '<li>....';
	html += '</ol></div>';
	element('todo').innerHTML = html;

}
function loadHowto(){
	var html = "<b>Welcome</b> to Live!  Here's how it works:";
	html += ' 	<ol>';
	html += ' 	<li>the users listed are online. click on their name to chat. ';
	html += ' 	<li>mouse over their names to see other options';
	html += ' 	<li>the topic list refreshed automatically, and new comments are pulled live into your topics.';
	html += ' 	<li>topics, chats, and profiles open in windows. you can drag them around by dragging around the title bar.';
	html += ' 	<li>you can also shrink and expand topic windows';
	html += ' 	</ol>';
	element("howitworks").innerHTML = html;
}
function loadActiveUsers(force){
	if(myStatus=='ACTIVE' || force){
		log("loading active users");
		refreshingUsers = true;
		new Ajax.Request('/uu.jsp?a=FETCHACTIVEUSERS', { method:'post',
		  onSuccess: function(transport){
				//log("users:");
		        response = transport.responseText;
				log(response);
		        var jsonusers = eval('('+response+')');
				activeusers = jsonusers;
				writeActiveUsers();
				log("active users loaded");
				refreshingUsers = false;
		    }
		  });
	}else{
		log("idle.  not loading active users");
	}
}
function loadFriendsFoes(){
	log("loading friends foes");
	        
	new Ajax.Request('/uu.jsp?a=FETCHFRIENDSFOES', { method:'post',
	  onSuccess: function(transport){
		//log("users:");
	        response = transport.responseText;
		//log(response);
	        var jsonusers = eval('('+response+')');
		friendsfoes = jsonusers;
		writeActiveUsers();
	    }
	  });

}
function writeFriendsFoesOLDDLDL(users){
	var html = '';
	for(var i=0;i<users.length;i++){
		html += getUserBlock(users[i]);
	}
	element("friendsfoes").innerHTML = html;
	log("friends foes loaded");

}
function isFriend(uid){
	//alert(uid);
	if(!friendsfoes) return false;
	for(var i=0;i<friendsfoes.length;i++){
		var u = friendsfoes[i];
		if(u.account_id==uid && u.type=='FRIEND') {
			//alert('friend'+u.title);
			return true;
		}//if friend
	}//for each ff
	return false;
}
function writeActiveUsers(){
	if(!activeusers) return;
	var friends = '';var fc = 0;
	var others = '';var oc = 0;
	log(users.length+" active users");
	var html = '';
	for(var i=0;i<activeusers.length;i++){
		var uu = activeusers[i];
		if(isFriend(uu.account_id)) {
			friends += getUserBlock(uu); 
			fc++;
			//log("friend:"+uu.title);
		}else{
			others += getUserBlock(uu); 
			oc++;
			//log("other:"+uu.title);
		}

	}
	if(access && access.account_id==uu.account_id){
		myStatus = uu.online_status;
		log("changed my status to "+myStatus);
	}
	element("friends").innerHTML = ""+friends;
	element("friendsfoes").innerHTML = ""+others;
	log("active users loaded");
	
	updateChatUserStatus();

}
function tester(){
	alert("testing");
	var m=Object();
	m["adam"]="YES";
	m["austin"]="NO";
	alert("done");
	alert(m["austin"]);
	alert("done assigning."+m.length);
	for(var i in m){
		alert(m[i]);
	}	
}
function updateChatUserStatus(){
	//alert("updating chat window status");
	var s="";
	for(var ii in myChats){
		s+= ii+":";
	}
	//alert("chats|"+s);
	for(var i in myChats){
		var isChat = myChats[i];
		if(isChat=="YES"){
			var uu = findUser(i);
			var status='OFFLINE';
	
			if(uu) status = uu.online_status;
			if(status !== 'IDLE' && status !== 'ACTIVE') status='OFFLINE';
			log("STATUS");
			log("STATUS:"+i+":"+uu.title+":"+status);
			if(status=='OFFLINE'){
				//OFFLINE
				//alert("cannot find user: "+i);
				//element("chatuserstatus"+i).style.display="block";
				//element("chatuserstatus"+i).innerHTML="<div style='font-size:80%;color:white;background-color:black'>User is not online</div>";
				element("chatstatus"+i).style.display="block";
				element("chatstatus"+i).innerHTML="<div style='font-size:80%;color:white;background-color:black'>User is not online</div>";
				element("chat"+i).style.backgroundColor="#BBBBBB";
				document.forms["chatform"+i].elements["text"].disabled=true;
			}
			if(status=='IDLE'){
				//IDLE
				//alert("user is idle: "+i);
				//element("chatuserstatus"+uu.account_id).style.display="block";
				//element("chatuserstatus"+uu.account_id).innerHTML="<div style='font-size:80%;'><img src='images/zzz.gif' align=bottom> "+uu.title+" is zZzZzZzZing...</div>";
				element("chatstatus"+uu.account_id).style.display="block";
				element("chatstatus"+uu.account_id).innerHTML="<div style='font-size:80%;'><img src='images/zzz.gif' align=bottom> "+uu.title+" is zZzZzZzZing...</div>";
				element("chat"+uu.account_id).style.backgroundColor="#DDDDDD";
				document.forms["chatform"+i].elements["text"].disabled=false;
			}
			if(status=='ACTIVE'){
				//ACTIVE
				//alert("user is active: "+i);
				//element("chatuserstatus"+uu.account_id).style.display="";
				//element("chatuserstatus"+uu.account_id).innerHTML="type your message and hit enter!";
				//element("chatstatus"+uu.account_id).style.display="";
				element("chatstatus"+uu.account_id).innerHTML="<div class='msginfo'>type your message and hit enter!</div>";
				element("chat"+uu.account_id).style.backgroundColor="#FFFFFF";
				document.forms["chatform"+i].elements["text"].disabled=false;
			}
		}//if chat window open
		else{
			//alert("chatwindow is not open:"+i+":"+isChat);
		}
	}//for each chat object
	
}
	
function getUserBlock(user){

	var html = "<div class='user' id='user"+user.account_id+"' onmouseover='highlightUser("+user.account_id+");' ";
	html += " onmouseout='unhighlightUser("+user.account_id+");'>";
	var doodad="";
	var ff = findFriendFoe(user.account_id);
	if(ff && ff.type=='FOE'){
		doodad = "<img src='http://www.lumpypro.com/images/black_dot.jpg'>";
	}else if(ff && ff.type=='FRIEND'){
		doodad = "<img src='http://www.cyberbee.com/images/smiley.small.gif'>";
	}else {
		doodad = "<img src='http://web.live.weatherbug.com/Broadcaster/talent/greenBall.gif'>";
	}
	if(user.online_status=='IDLE') doodad = " zZz...";
	
	html += doodad+"<a href='#' onclick=\"loadChat("+user.account_id+");return false;\" >"+cut(user.title,20)+"</a>";
	//html += "<a href='#' onclick=\"tester();return false;\">T</a>";
	html += "</div>";
	return html;
}

function loadChat(userid){
	if(!loggedin){
		alert("you must be logged in to chat");
	}else{	
		//alert("coming soon...  :-)");
		openChat(userid);
	}
}

var sound = 4;//default to the first
var sounds1 = new Array("[off]","yahoo!","notify","bloop","boing","chime","gasp","fanfare","yes","kiss","voices","wahoobie!");
var sounds2 = new Array("","yahoo.wav","notify.wav","bloop.wav","boing.wav","chime_up.wav","gasp.wav","fanfare.wav","yes.wav","kiss.wav","voices.wav","wahoobie.mp3");

function popSounds(){
	var s = "Change sound: ";
	for(var i=0;i<sounds1.length;i++){
		s += " &raquo; <a href='javascript:changeSound("+i+");'>"+sounds1[i]+"</a>"
	}
	element("soundopts").innerHTML=s;
}
function changeSoundOLD(n){
	sound = n;
	playSound();
}
function playSoundOLD(){
	if(sound > 0){
	//if(sound > 0 && !hasFocus){
		element("sound").innerHTML=   "<embed src='scripts/"+sounds2[sound]+"' hidden=true autostart=true loop=false>";
	}
}
function changeSound(n){
	sound = n;
	//element("soundwav").src="scripts/"+sounds2[sound];
	element("sound").innerHTML=   "<embed src='scripts/"+sounds2[sound]+"' autostart=true width=0 height=0 id='soundwav' enablejavascript='true'>";
	//element("sound").innerHTML=   "<embed type='"+getMimeType()+"' src='scripts/"+sounds2[sound]+"' autostart=true width=0 height=0 id='soundwav' enablejavascript='true'>";
	log(element("soundwav").src+" = new sound path");
	playSound(); 
	
}
function playSound(){
	if(sound > 0){
	//if(sound > 0 && !hasFocus){
		element("soundwav").Play();
	}
}
function getMimeType(){
	var mimeType = "application/x-mplayer2"; //default
	var agt=navigator.userAgent.toLowerCase();
	if (navigator.mimeTypes && agt.indexOf("windows")==-1) {
	//non-IE, no-Windows
	  var plugin=navigator.mimeTypes["audio/mpeg"].enabledPlugin;
	  if (plugin) mimeType="audio/mpeg" //Mac/Safari & Linux/FFox
	}//end no-Windows
	return mimeType;
}//end function getMimeType

