// Javascript Functions for use in the Messaging Pages
// Copyright 2009 Penn State Snowboard Club. All Rights Reserved.
// Author: Jason Wagner

var messages = [];
var _currentMsgId = 0;
var _currentPage = 1;
var _currentLimit = 20;
var _currentSort = 'to';
var _currentToId;
var _currentView;

function loadInitialView() {
	//see if there is anything in the hash
	var hash = window.location.hash;
	if(hash && hash != "") {
		if(hash == "#inbox") 
			switchView('inbox'); 
		else if(hash == "#compose")
			switchView('compose');
		else if(hash == "#sent")
			switchView('sent');
		else if(hash == "#viewmessage")
			showMessage();		
		else
			switchView('inbox');
		
	} else {
		switchView('inbox'); 
	}
	
}

function sendMessage(to_id) {
		tinyMCE.triggerSave();

		var msg = $("Message").value;
		var isCompose = false;
		
		var el_notify = $('notify');
		var el_loader = $('loader');
		
		//used when sending a message from the inbox
		if(to_id == "compose") {
			isCompose = true;
			to_id = _currentToId;
			if(_currentToId == null || _currentToId == 0) {
				//Get the username
				to_id = $('query').value;
			}
			msg = $("ComposeMessage").value;
			el_notify = $('notify_compose');
			el_loader = $('loader_compose');
		} else if(!to_id) {
			var in_reply_to = _currentMsgId;
			var to_id = messages[in_reply_to].from_id;			
		}
		
		el_loader.toggleClassName("noDisplay");
		
		msg = encodeURIComponent(msg);
		
		var bingArgs = {
			method: 'post',
			postBody: "To=" + to_id + "&Message=" + msg,
			onSuccess: function(data) {				
				if(isCompose) fadeBlock("notify_box_compose","open"); else fadeBlock("notify_box","open");
				el_loader.style.display = "none";
				el_loader.toggleClassName("noDisplay");
				var response = data.responseText;
				if(response.indexOf("OK") != -1) {
					//Success! Display success message and redirect.
					tinyMCE.getInstanceById('Message').getBody().innerHTML=""; 
					if($('ComposeMessage')) tinyMCE.getInstanceById('ComposeMessage').getBody().innerHTML=""; 
					if($('query')) $('query').value = '';
					el_notify.style.color = "green";
					el_notify.update("Sent.");
					$('compose-chk').show();
					_currentToId = 0;
				} else {
					//Display error message from the server.
					el_notify.style.color = "red";
					el_notify.update(response);
					$('compose-chk').hide();
				}
			}
		}
		
		new Ajax.Request('/PHP/post_message.php', bingArgs);
	}
	
function nextPage() { //older
	_currentPage++;
	getMessages();
}
function prevPage() { //newer
	_currentPage--;
	getMessages();
}

function setToId(id) {
	_currentToId = id;
}


function getMessages(sortp,limit,page) {
	
	if(page) _currentPage = page;
	if(limit) _currentLimit = limit;
	if(sortp) _currentSort = sortp;
	
	getTotalMessagesCount(_currentSort);
	
	var entries_from = (_currentPage - 1) * _currentLimit + 1;
	var entries_to = _currentPage * _currentLimit;
	
	$$("#mailbox .pages").each(function(elem) { elem.update("<strong>" + entries_from + " - " + entries_to + "</strong>")});
	if(_currentPage == 1) {
		$$("#mailbox .link-newer").each(function(elem) { elem.hide(); });
	} else  {
		$$("#mailbox .link-newer").each(function(elem) { elem.show(); }); 
	}
	
	messages = [];
	
		
	var bingArgs = {
		method: 'get',
		onSuccess: function(data) {	
			var response = data.responseText;
			if(response) {
				var x = data.responseText.evalJSON();
				clearTbody($('messages-tbody'));
				var count = 1;
				x.each( function(s) { 
					messages[s.id] = s;
					var label = "";
					if(_currentSort == "from") {
						var who = "To: " + s.to_user;
						label = "<span class='sentlabel'>sent</span>";
					} else if(_currentSort == "to") {
						var who = s.from_user;
					} 

					var row_class = (s.isRead == 1 || _currentSort=="from") ? "read" : "not-read";
					var row = new Element("tr",{'class': row_class, 'id': s.id});	
					var message = s.message;
					var shortmessage = s.message.replace(/(<([^>]+)>)/ig,""); 
					var len = shortmessage.length;
					if(len > 85) shortmessage = shortmessage.substring(0,85) + "...";

					var td = new Element('td', {})
					td.appendChild(new Element('input', { 'type': 'checkbox','id':'chk_'+count,'value':s.id}));
					row.appendChild(td);
					row.appendChild(new Element('td', { 'class': 'who'}).update(who));
					row.appendChild(new Element('td', { 'class': 'shortmessage'}).update(label + " " + shortmessage).observe('click',showMessage));
					row.appendChild(new Element('td', { 'class': 'created'}).update(s.short_date).observe('click',switchView));
					$('messages-tbody').appendChild(row);
					count++;
				});
				if(count == 1) { //User does not have any messages
					var row = new Element("tr",{'class': 'read'});
					var td = new Element('td', {'class': 'no-messages','colspan': 4}).update("You do not have any messages yet. Make some friends!");
					row.appendChild(td);
					$('messages-tbody').appendChild(row);
				}
			
			} 
		}
	}	
	new Ajax.Request('/bin/Message.php?method=getMessages&sort=' + _currentSort + "&limit=" + _currentLimit + "&page=" + _currentPage, bingArgs);
}

function getTotalMessagesCount(sortp) {

	var bingArgs = {
		method: 'get',
		onSuccess: function(data) {	
			var response = data.responseText;
			if(response) {
				var count = data.responseText;
				$$("#mailbox .totalCount").each(function(elem) { elem.update(count); });		
			} 
		}
	}	
	new Ajax.Request('/bin/Message.php?method=getTotalMessagesCount&sort=' + sortp, bingArgs);
}


function showMessage(evnt) {
	//First do the SwitchView stuff that we would normally delegate to there..
	$("currentSectionTitle").update("View Message");
	$("mailbox").addClassName("noDisplay");
	$("compose-view").addClassName("noDisplay");
	$("message-details").removeClassName("noDisplay");
	
	var row = this.parentNode; //IE8 BUG
	var id = row.id;
	_currentMsgId=id;
	var msg = messages[id];

	if(msg.isRead == "0") markRead(id);
	switchView();
	
	$("m_to").update("<strong>To: </strong> " + msg.to_user);
	$("m_from").update("<strong>From: </strong> " + msg.from_user);
	$("m_message").update(msg.message);
	$("m_created").update("<strong>Sent: </strong> " + msg.created);

}

function cleanUp() {
	//Hide the Sent messages
	$('notify_box').hide();
	$('notify_box_compose').hide();		
}

function switchView(section) {
	cleanUp();
	if(section == "inbox") {
		$("currentSectionTitle").update("Inbox");	
		getMessages('to',20,1);	
		$("mailbox").removeClassName("noDisplay");
		$("compose-view").addClassName("noDisplay");
		$("message-details").addClassName("noDisplay");
		_currentView = "inbox";
		
	} else if(section == "sent") {
		$("currentSectionTitle").update("Sent Messages");
		getMessages('from',20,1);
		$("mailbox").removeClassName("noDisplay");
		$("compose-view").addClassName("noDisplay");
		$("message-details").addClassName("noDisplay");
		_currentView = "sent";
		
	} else if(section == "compose") {
		$("currentSectionTitle").update("Compose Message");	
		$("mailbox").addClassName("noDisplay");
		$("compose-view").removeClassName("noDisplay");
		$("message-details").addClassName("noDisplay");	
		
	} else if(section == "goback") {
		switchView(_currentView);
	} 

}

function markBatchRead() {
	$$("input:checked").each(function(s) {
		markRead(s.value);							  
	});
	bulkCheck('none');
}

function markBatchUnread() {
	$$("input:checked").each(function(s) {
		markUnRead(s.value);							  
	});
	bulkCheck('none');
}


function markRead(id) {
	var bingArgs = {
			method: 'post',
			postBody: "method=markRead&id=" + id,
			onSuccess: function(data) {
				var x = data.responseText.evalJSON();	
				var status = 0;
				var message = "";
				x.each( function(s) { status = s.status; message=s.message; });
				if(status == 200) {
					$(id).removeClassName("not-read").addClassName("read");
					updateInboxCount();
				} else {
					alert("Error " + status + ": " + message);
				}
				var response = data.responseText;
				if(response.indexOf("OK") != -1) {
					//now mark it read in the js UI
					$(id).removeClassName("not-read").addClassName("read");
				}
			}
		}		
		new Ajax.Request('/bin/Message.php', bingArgs);
}

function markUnRead(id) {
	var bingArgs = {
		method: 'post',
		postBody: "method=markUnread&id=" + id,
		onSuccess: function(data) {
			var x = data.responseText.evalJSON();	
			var status = 0;
			var message = "";
			x.each( function(s) { status = s.status; message=s.message; });
			if(status == 200) {
				$(id).removeClassName("read").addClassName("not-read");
				updateInboxCount();
			} else {
				alert("Error " + status + ": " + message);
			}
			var response = data.responseText;
			if(response.indexOf("OK") != -1) {
				//now mark it read in the js UI
				$(id).removeClassName("read").addClassName("not-read");
			}
		}
	}		
	new Ajax.Request('/bin/Message.php', bingArgs);
}

function deleteBatch() {
	//see if any messages are checked
	var anyChecked = false;
	$$("input:checked").each(function(x) { anyChecked=true; return; });
	if(anyChecked) {									  
		var sanity = confirm("Are you sure you want to move these messages to the trash?");
		if(sanity) {
			$$("input:checked").each(function(s) {
				deleteMessage(s.value,true);
			});
		}
	} else {
		alert("You must select a message before you can delete.");
	}
	
}
//Don't show confirm dialog for EVERY message when doing a batch deletion
function deleteMessage(id,sanity) {
	sanity = sanity || confirm("Are you sure you want to move this message to the trash?");
	if(sanity) {
		var bingArgs = {
			method: 'post',
			postBody: "method=deleteMessage&id=" + id,
			onSuccess: function(data) {
				var x = data.responseText.evalJSON();	
				var status = 0;
				var message = "";
				x.each( function(s) { status = s.status; message=s.message; });
				if(status == 200) {
					fadeBlock(id,"close");
				} else {
					alert("Error " + status + ": " + message);
				}
			}
		}
		new Ajax.Request('/bin/Message.php', bingArgs);
	}
}

function bulkCheck(x) {	
	$$("input[type='checkbox']").each(function(s) {
		s.checked = (x == "all") ? "checked" : "";
	});
}

function updateInboxCount() {
	var bingArgs = {
		method: 'get',
		onSuccess: function(data) {
			var count = data.responseText;
			if(count == 0 || count == "403 Forbidden") {
				$("inboxCount").update("Inbox");
			} else {
				$("inboxCount").update("Inbox (" + count + ")");
				//If we're on the inbox page, also update the view!
				if(window.location.hash == "#inbox") {
					getMessages('to',20,1);	
				}
			}
			
		}
	}		
	new Ajax.Request('/bin/Message.php?method=getUnreadMessageCount', bingArgs);
	
	
}

function CheckForHash(){
	if(document.location.hash){
		var hash = document.location.hash;
		hash = hash.replace("#","");
		if(hash == "inbox") {
			
		}
	}
}
//var hashCheck = setInterval("CheckForHash()", 500);
//window.onload = CheckForHash;