// Forum Javascript Class
// Change this.function's to be local. get rid of eval (instance_name + '.function_name()');


function Topic(topic,container,instance,goto,limit)
{
	/* 
		pass the data about this topic to this.data as an object in the following format:
		data.info								= (object with the following properties):
															rel_image, rel_type, rel_name, rel_link, name, posted_by, time_passed, moderator, online
		data.posts							= (array of posts)
		data.posts.id 					= (object for each top-level post with the following properties):
															id, date_posted, posted_by, user_image, comment, parent, time_passed
	*/
	var indent = 20;		// size of indent
	var textarea_class = 'forum_post_focus fillwindow';
	var textarea_class_blur = 'forum_post_blur fillwindow';	
	var post_container_class = 'post_container';
	var small_text_class = 'forum_small_grey';
	var rel_container_class = 'forum_header_container';
	var topic_name_class = 'forum_topic_name';
	var posts;
	var info;
	var last_parent_container = container;
	var new_post_container = Builder.node('DIV'); // for textarea post input
	
	var loading_img = Builder.node('IMG',{src:jsconfig.loading_image});
	var loading			= Builder.node('DIV',{className:'center bold'},['Loading Topic',Builder.node('P',{},[loading_img])]);
	var limit = limit ? limit : 0;
	
	container.appendChild(loading);
	
	this.load_topic = function()
	{	
		var poststr = 'action=loadtopic&topic=' + topic + '&limit=' + limit;
		xmlhttp.open("GET", jsconfig.site.root+"library/forum_actions.php?"+poststr,true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) 
			{
				var response = JSON.parse(xmlhttp.responseText);
				if (response == false) return false; // alert(xmlhttp.responseText);
				else if (response.permission == false) {
						container.removeChild(loading);
						no_permission();
				}				
				else 
				{ 
					container.removeChild(loading);
					posts = response.posts;					
					info 	= response.info;
					//eval(instance+'.display_header()'); 
					//eval(instance+'.display_posts()');
					display_header()
					if (info.rel_type == 'User') container.appendChild(new_post_container);					
					display_posts();
					if (info.rel_type != 'User') container.appendChild(new_post_container);
					new_post_container.style.marginTop = '20px';
					
					if (response.end_link) {
						var end_link = Builder.node('P',{className:'center'});
						end_link.innerHTML = response.end_link;
						container.appendChild(end_link);
					}
					
					if (goto && $('post'+goto))
					{
						var postgoto = $('post'+goto);
						postgoto.style.backgroundColor = '#FFFF66';
						new Effect.ScrollTo('post'+goto);
						//setTimeout(highlightGoto,1000);

					}					
				}
			}
		}
		xmlhttp.send(null);
	}
	
	var no_permission = function() 
	{
		var permission_text = 'You do not have permission to view this topic';
		var permission = Builder.node('DIV',{className:'padding red center'},[permission_text]);
		container.appendChild(permission);
	}
	
	var highlightGoto = function()
	{
		$('post'+goto).style.backgroundColor = '#FFFF66';
		new Effect.Shake('post'+goto,{duration: 2});
	}
	
	this.display_header = function()
	{
		var skip_header = false;
	  // skip header on User forum
		if (info.rel_type == 'User') skip_header = true;
    // change group to course
		if (info.rel_type == 'Group') info.rel_type = 'Course';

		var post					= document.createElement('BUTTON');
		var clear					= document.createElement('BUTTON');		
		var textarea			= document.createElement('TEXTAREA');

		// append topic name to the element if found on page 
		if ($('forum_topic_name')) $('forum_topic_name').appendChild(document.createTextNode(info.name));		

		if (!skip_header) {		
			var rel_image			= document.createElement('IMG');
			var rel_info			= document.createElement('DIV');
			var the_table 		= document.createElement('TABLE');
			var the_tbody			= document.createElement('TBODY');
			var the_row				= document.createElement('TR');
			var left_cell 		= document.createElement('TD');
			var right_cell		= document.createElement('TD');		
			var rel_link			= document.createElement('A');
			var online_image	= document.createElement('IMG');
			var posted_by			= document.createElement('a');
			var date_posted		= document.createElement('SPAN');
			var topic_name		= document.createElement('SPAN');
			var textarea_title = Builder.node('P',{className:'bold'});
			
			online_image.className = 'user_online_image indent5px';
			if (info.online == true) 	online_image.src = jsconfig.user_online_image;
			else											online_image.src = jsconfig.user_offline_image;
						
			posted_by.href = jsconfig.site.root+jsconfig.profile_lookup+info.posted_by;
			posted_by.appendChild(document.createTextNode(info.posted_by));
			posted_by.appendChild(online_image);
			
			date_posted.appendChild(document.createTextNode(info.time_passed));
			date_posted.className = small_text_class;
			date_posted.style.marginLeft = '5px';
	
			the_table.appendChild(the_tbody);
			the_tbody.appendChild(the_row);
			the_row.appendChild(left_cell);
			the_row.appendChild(right_cell);
	
			the_table.className 	= rel_container_class;
			left_cell.className 	= 'left';
			right_cell.className 	= 'right';		
					
			rel_image.src						= info.rel_image;		
	
			rel_link.appendChild(document.createTextNode(info.rel_name));
			rel_link.href = info.rel_link;
	
			topic_name.appendChild(document.createTextNode(info.name));
			topic_name.className = topic_name_class;
	
			textarea_title.appendChild(document.createTextNode(info.name));
	
			rel_info.appendChild(document.createTextNode(info.rel_type + ': '));
			rel_info.appendChild(rel_link);
			rel_info.appendChild(document.createElement('BR'));
			rel_info.appendChild(document.createTextNode('Topic: '));
			rel_info.appendChild(topic_name);
			rel_info.appendChild(document.createElement('BR'));
			rel_info.appendChild(document.createTextNode('Added By: '));
			rel_info.appendChild(posted_by);
			rel_info.appendChild(date_posted);
	
			left_cell.appendChild(rel_image);
			right_cell.appendChild(rel_info);

			container.appendChild(the_table);
			container.appendChild(textarea_title);
		}

		post.appendChild(document.createTextNode('post'));
		post.onclick = function() {
			if (textarea.value == '') return;
			//eval(instance+'.post(textarea.value,0)');
			postIt(textarea.value,0);
			textarea.value = '';
			textarea.className = textarea_class_blur;
		}

		clear.appendChild(document.createTextNode('clear'));
		clear.onclick = function() {
			if (confirm('Are you sure you want to clear your post?'))
			{
				textarea.value = '';
				textarea.className = textarea_class_blur;
			}
		}

		textarea.className = textarea_class_blur;
		textarea.onfocus = function() {
			this.className = textarea_class;
		}
		
		if (jsconfig.loggedIn) {
			new_post_container.appendChild(textarea);
			new_post_container.appendChild(document.createElement('BR'));
			new_post_container.appendChild(post);
			new_post_container.appendChild(clear);
		}
	}
	
	this.post = function(comment,parent)
	{
		comment = urlencode(comment);
		var poststr = 'action=post1&comment=' + comment + '&parent=' + parent +'&topic_id=' + topic;
		xmlhttp.open("POST", jsconfig.site.root+"library/forum_actions.php",true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(poststr);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				if (xmlhttp.status == 200) {
					var response = JSON.parse(xmlhttp.responseText);
					if (response == false) alert(xmlhttp.responseText);
					//alert(xmlhttp.responseText);
					else	{ 
					posts = response.posts; 
					//eval(instance+'.display_posts('+parent+')'); 
					display_posts(parent);
					}
				}
			}
		}	
	}	

	var sendeditpost = function(comment,post_id)
	{
		$('post'+post_id).innerHTML = '<h2 style="color:red">saving...</h2>';
		comment = urlencode(comment);
		var poststr = 'action=editpost&comment=' + comment + '&post_id=' + post_id;
		xmlhttp.open("POST", jsconfig.site.root+"library/forum_actions.php",true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(poststr);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				if (xmlhttp.status == 200) {
					var response = JSON.parse(xmlhttp.responseText);
					// alert(xmlhttp.responseText);					
					if (response == false) alert(xmlhttp.responseText);					
					else
					{
						if (!$('post'+post_id)) return false;
						var replace_container = $('post'+post_id);
						var new_container = build_post_div(response.post);
								new_container.style.marginLeft = replace_container.style.marginLeft;
						replace_container.parentNode.replaceChild(new_container,replace_container);
					}
				}
			}
		}	
	}	

	this.delete_post = function(post)
	{	
		var poststr = 'action=deletepost1&post=' + post;
		xmlhttp.open("GET", jsconfig.site.root+"library/forum_actions.php?"+poststr,true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) 
			{
				var response = JSON.parse(xmlhttp.responseText);
				if (response == false) alert(xmlhttp.responseText);
				if (response.error != false) { alert(response.error); return; }				
				else 
				{ 
					var post_container = xGetElementById('post'+post);
					post_container.parentNode.removeChild(post_container);
					if (xGetElementById('parent'+post))
					{
						var parent_container = xGetElementById('parent'+post);
						parent_container.parentNode.removeChild(parent_container);
					}
				}
			}
		}
		xmlhttp.send(null);
	}

	this.display_posts = function(parent)
	{
		if (!parent) parent = 0;
		for (var i in posts)
		{
			var p = posts[i];
			if (p.parent != parent) continue;
			if (!xGetElementById('parent'+parent))
			{
				parent_container = document.createElement('DIV');
				parent_container.id = 'parent'+parent;				
				parent_container.style.marginLeft = indent;
				if (xGetElementById('post'+parent))	
				{
					var parent_post = xGetElementById('post'+parent);
					parent_post.parentNode.insertBefore(parent_container, parent_post.nextSibling);
				}
				else 
				{					
					container.appendChild(parent_container);
				}
			}
			else 
			{
				parent_container = xGetElementById('parent'+parent);
			}
			
			post_container = p.deleted ? build_deleted_post_div() : build_post_div(p);
			
			if (info.rel_type == 'User') Element.insertFirst(post_container,parent_container);
			else parent_container.appendChild(post_container);
				
			display_posts(i);
		}
	}		

	var build_deleted_post_div = function()
	{
		var deleted_post = Builder.node('DIV',{className:'deleted_post'},['This comment has been deleted.']);
		return deleted_post;
	}

	var build_post_div = function(p)
	{
			var post_container = document.createElement('DIV');
			var posted_by			 = document.createElement('a');
			var date_posted		 = document.createElement('SPAN');
			var user_image		 = Builder.node('IMG',{src:jsconfig.site.root + 'images/user/profile/a_' + p.user_image,className:'float_left'});
			var post					 = document.createElement('DIV');
					post.id				 = p.id+'text';
			if (jsconfig.loggedIn) var actions = create_post_actions(p.id,p.can_delete,p.posted_by,p.editcomment);
			else var actions = document.createTextNode(' ');
			var time_diff			 = p.time_passed;
			var online_image	 = document.createElement('IMG');
					
			online_image.className = 'user_online_image indent5px';
			if (p.online == true) online_image.src = jsconfig.user_online_image;
			else									online_image.src = jsconfig.user_offline_image;
						
			posted_by.href = jsconfig.site.root+jsconfig.profile_lookup+p.posted_by;
			posted_by.appendChild(document.createTextNode(p.posted_by));
			posted_by.appendChild(online_image);
			
			date_posted.appendChild(document.createTextNode(time_diff));
			if (p.last_edit > p.date_posted) date_posted.appendChild(document.createTextNode('*'));
			date_posted.className = small_text_class;
			date_posted.style.marginLeft = '5px';
			post.innerHTML = p.comment;

			var rpostcontainer = Builder.node('DIV',{className:'forumRCp'},[posted_by,date_posted,post,actions]);

			post_container.className = post_container_class;
			post_container.id = 'post'+p.id;
			post_container.appendChild(user_image);
			post_container.appendChild(rpostcontainer);
			post_container.appendChild(Builder.node('DIV',{className:'spacer'}));			
	
			return post_container;
	}

	var create_post_actions = function(id,can_delete,posted_by,editcomment)
	{
		var actions = document.createElement('SPAN');
		var reply		= document.createElement('A');
		var flag		= document.createElement('A');
		if (!id)			id = 0;

		reply.appendChild(document.createTextNode('reply'));
		reply.className = small_text_class;
		reply.href = 'javascript:void(0)';
		reply.onclick = function() {
			if (xGetElementById('reply'+id)) return;
			var textarea 	= document.createElement('TEXTAREA');
			var save		 	= document.createElement('BUTTON');
			var cancel	 	= document.createElement('BUTTON');			
			var container = document.createElement('DIV');

			save.appendChild(document.createTextNode('post'));
			save.onclick = function() {
				//eval(instance+'.post(textarea.value,id)');
				postIt(textarea.value,id);
				this.parentNode.parentNode.removeChild(this.parentNode);
			}

			cancel.appendChild(document.createTextNode('cancel'));
			cancel.onclick = function() {
				if (confirm('Are you sure you want to clear your post?'))
				{
					this.parentNode.parentNode.removeChild(this.parentNode);
				}
			}
			textarea.className = textarea_class;
			container.id = 'reply'+id;
			container.appendChild(textarea);
			container.appendChild(document.createElement('BR'));
			container.appendChild(save);
			container.appendChild(cancel);
			this.parentNode.appendChild(container);
		}
		
		flag.appendChild(document.createTextNode('flag as inappropriate'));
		flag.className = small_text_class + ' indent5px';
		flag.href = 'javascript:void(0)';
		flag.id		= 'flag_'+id;
		flag.name	= 'flag_'+id; // so we can find it with getAnchorPosition
		flag.onclick = function() {
			ShowReportAbuseWindow('where=3&who='+posted_by,this.id);
		}
		
		// should not create reply node at all - but this is fast! :-)
		if (info['rel_type'] != 'Chat' && info['rel_type'] != 'User') actions.appendChild(reply);

		if (editcomment != false) actions.appendChild(build_edit_post_link(id,editcomment));

		if (can_delete == true)
		{
			var delete_post = document.createElement('A');
			delete_post.className = small_text_class + ' indent5px';
			delete_post.href = 'javascript:void(0)';
			delete_post.appendChild(document.createTextNode('delete'));
			delete_post.onclick = function() {
				if (xGetElementById('are_you_sure'+id)) return;
				var are_you_sure = document.createElement('SPAN');
						are_you_sure.id = 'are_you_sure'+id;
				var yes = document.createElement('A');
				var no	= document.createElement('A');
				yes.href = 'javascript:void(0);';
				no.href  = 'javascript:void(0);';
				no.onclick = function() {
					this.parentNode.parentNode.removeChild(this.parentNode);
				}
				yes.onclick = function() {
					//eval(instance+'.delete_post(id)');
					deleteIt_post(id);
				}
				are_you_sure.className = small_text_class + ' indent5px';
				yes.appendChild(document.createTextNode('yes'));
				no.appendChild(document.createTextNode('no'));
				are_you_sure.appendChild(document.createTextNode('Are you sure? '));
				are_you_sure.appendChild(yes);
				are_you_sure.appendChild(document.createTextNode(' or '));
				are_you_sure.appendChild(no);
				this.parentNode.appendChild(are_you_sure);
			}
			actions.appendChild(delete_post);
		}
		actions.appendChild(flag);		
		return actions;
	}
	
	var build_edit_post_link = function(id,editcomment)
	{
		var edit_link = commonjs.jslink('edit');
				edit_link.className = small_text_class  + ' indent5px';
				edit_link.onclick = function() {

					var save		 	= Builder.node('BUTTON',{},['save']);
					var cancel	 	= Builder.node('BUTTON',{},['cancel']);
					
					var edit_textarea = Builder.node('TEXTAREA',{className:textarea_class});
							edit_textarea.value = editcomment;
					var edit_textarea_div = Builder.node('DIV',{},[edit_textarea,Builder.node('BR'),save,cancel]);
					
					save.onclick = function() {
						sendeditpost(edit_textarea.value,id);
					}
			
					cancel.onclick = function() {
						if (confirm('Are you sure you want to cancel your edit?'))
						{
							edit_textarea.value = editcomment;
							edit_textarea_div.parentNode.removeChild(edit_textarea_div);
							$(id+'text').style.display = '';
						}
					}
							


					$(id+'text').style.display = 'none';
					$(id+'text').parentNode.insertBefore(edit_textarea_div,$(id+'text'));					
				}
				
		return edit_link;		
	}
	
  // until we get rid of instance, let's do this:
		var display_header = this.display_header;
		var display_posts = this.display_posts;
		var postIt = this.post;
    var deleteIt_post = this.delete_post;
	
	this.load_topic();	
}