// JavaScript Document
//spg   -- serverpage
//eid   -- elementid
//postData -- can be empty
function getAJAX(spg, eid, postData, callback)
{
 if (!postData) postData = null;
 if (!callback && eid) callback = 'changeInner';


 var xmlhttp=false;

 try {  xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');   }
    catch (e) 
    {
        try {   xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');    }
        catch (e2) 
        {
          try {  xmlhttp = new XMLHttpRequest();     }
          catch (e3) {  xmlhttp = false;   }
        }
     }
	 
	if(!xmlhttp && typeof XMLHttpRequest !='undefined'){
		xmlhttp = new XMLHttpRequest();
	}

	var obj;
	if (eid)
		obj = document.getElementById(eid);
	
	serverPage = spg;
	xmlhttp.open("POST", serverPage, true);
	
	if (postData)
	{
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", postData.length);
		xmlhttp.setRequestHeader("Connection", "close");
	}
	
	xmlhttp.onreadystatechange  = function()
    { 
         if(xmlhttp.readyState  == 4)
         {
			 if (callback)
			 {
				if (typeof callback == 'string')
					eval(callback+'(obj, xmlhttp)');
				else if (typeof callback == 'function')
					callback(obj, xmlhttp);
			 }
         }
    }

	xmlhttp.send(postData);
}

function changeInner(obj, xmlhttp)
{
	try {
		if(xmlhttp.status  == 200) 
			obj.innerHTML=xmlhttp.responseText; 
		else 
			obj.innerHTML="Error code " + xmlhttp.status;
	} catch (e) {
	}
}

function reactToPost(obj, xmlhttp)
{
	var response = eval("(" + xmlhttp.responseText + ")");

	if (xmlhttp.status == 200) {	
		if (response.postType == 'WallPost')
			getWallPosts(xmlhttp.recipientID);
		else if (response.postType == 'BlogPost')
			getBlogPosts(xmlhttp.recipientID);
		else if (response.postType == 'MailPost')
			getMailPosts(xmlhttp.recipientID);
	}

	switch (xmlhttp.status)
	{
		case 200:
			break;
		case 403:
			alert("You do not have permission to post on this wall");
			break;
		case 406:
			alert("Invalid post");
			break;
		default:
			alert("There was an error. Please try again.");
	}
}

function reactToComment(obj, xmlhttp)
{
	var response = xmlhttp.responseText;
	response = eval("("+response+")");
	if (response.postType == "WallPost")
		window.opener.getWallPosts(response.recipientID, response.rcptType);
	else if (response.postType == "BlogPost")
		window.opener.getBlogPosts(response.recipientID);
		
	window.opener.setTimeout('show(\'comments'+response.postID+'\', \'showcomments'+response.postID+'\', \'%s Comments('+response.postCount+')\')', 1000);
	self.close();
}

function refreshDiv(obj, xmlhttp)
{
	document.location.reload();
}

function messageAndRedirect(obj, xmlhttp)
{
	var response = $H(xmlhttp.responseText.evalJSON(true));

	obj.innerHTML = response.get('Message');
	
	if (response.get('href'))
		win = openWindow(response.get('href'), 400, 600);
}

function getProvinces(id)
{
	getAJAX("/ajax/get_provinces?c=" + id, "ProvinceDiv");
}

function getCourses(id)
{
	getAJAX("/ajax/get_courses?s=" + id, "CourseSpan", null, "changeInner");
}

function doWallPost(text, memberID, isGroup, uploadID)
{
	text = "text=" + text;
	if (uploadID) text += "&uploadID=" + uploadID;
	rcptType = (isGroup == 0) ? 'Member' : 'Group';
	getAJAX("/ajax/do_post?type=WallPost&memberID=" + memberID + "&rcptType=" + rcptType, null, text, 
				function(obj, xmlhttp)
				{
					if (!xmlhttp || !xmlhttp.responseText)
						return;

					var response = eval('(' + xmlhttp.responseText + ')');
					var row = $('WallPostsTable').insertRow(0);
					var cell = row.insertCell(0);
					
					row.id = "post" + response.postID;
					cell.innerHTML = response.html;
					
					recolourTable();
					
					$('walltext').value = '';
					showFileInput('formHolder');
					$('attachmentHolder').innerHTML = '';
					$('uploadID').value = '';
				}
			);
}

function recolourTable()
{
	var table = $('WallPostsTable');
	if (!table)
		return;
	
	for (var i = 0; i < table.rows.length; i++)
	{
		for (var j = 0; j < table.rows[i].cells.length; j++)
		{
			var image = 'images/' + ((i % 2 == 0) ? 'blue' : 'grey') + '_';
			table.rows[i].cells[j].innerHTML = table.rows[i].cells[j].innerHTML.replace(/images\/(grey|blue)_/g, image);
		}
	}
}
function doBlogPost(text, memberID, uploadID)
{
	text = "text=" + text;
	if (uploadID) text += "&uploadID=" + uploadID;
	getAJAX("/ajax/do_post?type=BlogPost&memberID=" + memberID + "&rcptType=Member", null, text, 
				function(obj, xmlhttp)
				{
					if (!xmlhttp || !xmlhttp.responseText)
						return;

					var response = eval('(' + xmlhttp.responseText + ')');
					var row = $('WallPostsTable').insertRow(0);
					var cell = row.insertCell(0);
					
					row.id = "post" + response.postID;
					cell.innerHTML = response.html;
					
					recolourTable();
					
					$('walltext').value = '';
					showFileInput('formHolder');
					$('attachmentHolder').innerHTML = '';
					$('uploadID').value = '';
				}
			);
}

function doComment(text, postID)
{
	text = "text=" + text;
	getAJAX("/ajax/do_comment?id=" + postID, null, text,
				function(obj, xmlhttp)
				{
					if (xmlhttp.responseText)
					{
						var response = eval('(' + xmlhttp.responseText + ')');
						
						var table = $('CommentTable' + postID);
						var length = table.rows.length;
						var row = table.insertRow(length);
						row.id = "Comment" + response.commentID;
						var cell = row.insertCell(0);
						cell.style.width = "462px";
						cell.style.height = "30px";
						cell.style.textAlign = "center";
						cell.style.verticalAlign = "top";
						cell.innerHTML = response.html;
						row.appendChild(cell);
						$('textarea' + postID).value = '';
						
						var anchor;
						if (anchor = $('ViewAll' + postID))
						{
							anchor.setAttribute('numComments', parseInt(anchor.getAttribute('numComments'), 10) + 1);
							showComments(table.id, anchor);
						}
					}
				}
			);
}

function deleteComment(commentID, postID)
{
	if (confirm("Are you sure you want to delete this comment?"))
		getAJAX("/ajax/delete_comment?id=" + commentID, null, null,
					function(obj, xmlhttp)
					{
						if (!xmlhttp.responseText)
							return;
							
						var row = $('Comment' + commentID);
						if (row)
						{	
							var parentNode = row.parentNode;
							parentNode.removeChild(row);
							
							for (var i = 0; i < 3; i++)
								if (parentNode.rows.length > i)
									parentNode.rows[i].style.display = "block";
															
							var anchor;
							if (anchor = $('ViewAll' + postID))
							{
								anchor.setAttribute('numComments', parseInt(anchor.getAttribute('numComments'), 10) - 1);
								showComments(parentNode.parentNode.id, anchor);
							}
						}
					}
				);
}

function doMailPost(text, subject, id, at, isGroup, istoemail)
{
	var mailto = at;
	if (at.search(/@/) == -1) { mailto = id; }
	text = "text=" + text;
	var rcptType = (isGroup == 0) ? 'Member' : 'Group';
	var isToEmail = (istoemail==true) ? '&toemail=y' : '';
	getAJAX("/ajax/do_mailpost?type=MailPost&subject="+subject+"&mailto=" + mailto + "&rcptType=" + rcptType + isToEmail, null, text, 'reactToPost');
}

function readMailPost(id)
{
	var sj = document.getElementById('subject'+id);
	sj.className = 'mail_read';
	getAJAX("/ajax/read_mailpost?id="+id, null, null, null);
}

function deletePost(id)
{
	if (confirm("Are you sure you want to delete this post?"))
		getAJAX("/ajax/delete_post", null, "id=" + id,
					function(obj, xmlhttp)
					{
						var row;
						if (row = $('post' + id))
						{
							row.parentNode.removeChild(row);
							recolourTable();
						}
					}
				);
}

function deleteMailPost(id)
{
	if (confirm("Are you sure you want to delete this post?")) {
		getAJAX("/ajax/delete_mailpost", null, "id=" + id, 
				function() {
					var row = document.getElementById('mailpost_'+id);
					row.parentNode.removeChild(row);
				});
	}
}

function getWallPosts(id, type)
{
	if (!type) type = 'Member';
	getAJAX("/ajax/get_wallposts?rcptType=" + type + "&id=" + id, "WallPostsTable", null, 'changeInner');
}

function getBlogPosts(id)
{
	getAJAX("/ajax/get_blogposts?id=" + id, "BlogPostsTable", null, 'changeInner');
}

function getMailPosts(id)
{
	getAJAX("/ajax/get_mailposts?id=" + id, "MailPostsTable", null, 'changeInner');
}

function finishUpload(success)
{
	var anim = $('loadingAnimation');
	if (!anim)
		return;

	anim.parentNode.removeChild(anim);
}

function deleteUpload(id, caller)
{
	if (confirm("Are you sure you want to delete this upload?"))
	{
		text = "id=" + id + "&action=delete";
		getAJAX("/ajax/delete_upload", 'ExistingUploadsTable', text, 
					function() { var row = caller.parentNode.parentNode; row.parentNode.removeChild(row); }
				);
	}
}

function unlinkUpload(id, caller)
{
	text = "id=" + id + "&action=unlink";
	getAJAX("/ajax/delete_upload", 'ExistingUploadsTable', text,
				function() { var row = caller.parentNode.parentNode; row.parentNode.removeChild(row); }
			);
}

function getEventMembers(tp, id)
{
	getAJAX("/ajax/get_event_members?tp=" + tp + "&id=" + id, "DivEventMembers");
}

function deleteMessage(id)
{
	text = "action=delete";
	
	if (confirm("Are you sure you want to delete this message?"))
		getAJAX("/student/message_board_post?messageID=" + id, null, text, 'refreshPage');
}

function chatInvite(memberID)
{
	getAJAX("/ajax/join_chat?id=" + memberID + "&type=Private", "ChatInviteDiv", null, 'messageAndRedirect');
}

function joinChat(chatID)
{
	getAJAX("/ajax/join_chat?id=" + chatID, null, null, null);
}

function leaveChat(chatID)
{
	getAJAX("/ajax/join_chat?action=leave&id=" + chatID, null, null, null);
}

function getEventTargets(eventType)
{
	getAJAX("/ajax/get_event_targets?type=" + eventType, "EventTarget", null, 'changeInner');
}

function refreshPage()
{
	document.location.reload();
}

function updateProfile(input, memberID)
{
	var text = input.parentNode.id + "=" + input.value;
	getAJAX('/ajax/profile?id=' + memberID, input.parentNode.id, text, reactToProfile);
}

function reactToProfile(obj, xmlhttp)
{
	obj.innerHTML = xmlhttp.responseText;
	
	if (xmlhttp.responseText != "Error")
	{
		obj.style.backgroundColor = "#CCFFCC";
		obj.style.border = "1px solid #AADDAA";
	}
	else
	{
		obj.style.backgroundColor = "#FFCCCC";
		obj.style.border = "1px solid #DDAAAA";
	}
	
	window.setTimeout('$("' + obj.id + '").style.backgroundColor="#ebebeb";', 1000);
	window.setTimeout('$("' + obj.id + '").style.border="";', 1000);
}

function groupProfileUpload(success, upload)
{
	if (success == 1)
	{
		$('uploadedImage').innerHTML = '<img src="/viewfile?id=' + upload.uploadID + '&size=100" />';
	}
}

function linkPostUpload(success, upload)
{
	if (success == 1)
	{
		if ($('uploadID').value == "")
			$('uploadID').value = upload.uploadID;
		else
			$('uploadID').value += "," + upload.uploadID;
			
		var cell = $('attachmentHolder');
		var textValue = $('walltext').value;

		if (cell.innerHTML.strip() != "")
			cell.innerHTML += '<br />'

		cell.innerHTML += '&nbsp;&nbsp;<strong>' + upload.uploadName + '</strong>';
		showFileInput('formHolder');
		$('walltext').value = textValue;
	}
}

function note(object, id, action, note)
{
	if (id == 0 && note.strip() == "")
		return;
	
	var text = '';
	if (note) text = "text=" + note.strip();

	getAJAX("/ajax/notes?id=" + id + "&action=" + action, "notes", text, 
			 function(obj, xmlhttp)
			 {
				 if (!xmlhttp.responseText)
				 {
					object.value = 'Error';
					object.style.backgroundColor = "#FFCCCC";
					window.setTimeout('$("' + object.id + '").style.backgroundColor="#FFFFFF"', 1000);
				 }
				 if (action == 'delete')
					object.parentNode.removeChild(object);
				 else
				 {
				 	if (id == 0)
						var row = obj.insertRow(obj.rows.length - 1);
					else
						var row = $('note'+id).parentNode;
					
					while (row.cells && row.cells.length > 0)
						row.deleteCell(0);
						
					try {
						var cell_1 = row.insertCell(0);
					} catch (e) {
						alert(row);
					}
					var cell_2 = row.insertCell(1);
					var response = $H(xmlhttp.responseText.evalJSON(true));

					cell_1.id = $H(response.get('cell_1')).get('id');
					cell_1.onclick = function() { eval($H(response.get('cell_1')).get('onclick')); };
					cell_1.innerHTML = $H(response.get('cell_1')).get('innerHTML');
					cell_1.className = "note_txt";
					cell_1.style.width = "95%";
					
					cell_2.id = $H(response.get('cell_2')).get('id');
					cell_2.align = $H(response.get('cell_2')).get('align');
					cell_2.innerHTML = $H(response.get('cell_2')).get('innerHTML');
					cell_2.className = "note_txt";
					cell_2.style.width = "5%";
					
					cell_1.style.backgroundColor = "#BEBEBE";
					window.setTimeout('$("' + cell_1.id + '").style.backgroundColor="#EBEBEB"', 1000);
					
					cell_2.style.backgroundColor = "#BEBEBE";
					window.setTimeout('$("' + cell_2.id + '").style.backgroundColor="#EBEBEB"', 1000);
					
					$('note').value = '';
					$('note').onblur = function() { if (this.value == '') this.value = "Write a note..."; };
				 }
			 });
}

function uploadName(uploadID, name, caller)
{
	getAJAX("/ajax/uploads?id=" + uploadID + "&name=" + name, null, null,
			 	function(obj, xmlhttp)
				{
					if (xmlhttp.responseText && xmlhttp.responseText != "")
					{
						caller.innerHTML = xmlhttp.responseText;
						caller.style.backgroundColor = "#CCFFCC";
					}
					else
					{
						caller.innerHTML = 'Error';
						caller.style.backgroundColor = "#FFCCCC";
					}
					window.setTimeout('$("' + caller.id + '").style.backgroundColor="#FFFFFF"', 1000);
				}
			);
}

function group(action, memberID, groupID)
{
	if (action == 'add' || (action == 'remove' && ((memberID == 0 && confirm('Are you sure you want to leave this group?')) || (memberID != 0 && confirm('Are you sure you want to remove this member?')))))
		getAJAX("/ajax/groups?action=" + action + "&memberID=" + memberID + "&groupID=" + groupID, null, null, 
				 function(obj, xmlhttp) { document.location.reload(); }
				);
}

function friend(action, memberID)
{
	getAJAX("/ajax/friends?action=" + action + "&id=" + memberID, null, null, 
			 function(obj, xmlhttp) { document.location.reload(); }
			);
}