var sendBox;
var sendButton;
var messageForm;
var messageBody;
var textNode;
var colleagueBox;

dojo.addOnLoad(function() {
	  sendBox = dojo.byId("sendBox");
	  sendButton = dojo.byId("sendButton");
	  messageForm = dojo.byId("msgform");
	  messageBody = dojo.byId("msgbody");
	  colleagueBox = dojo.byId("colleagueBox");
	  textNode = document.createTextNode("");
});


function trimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

function sendMessage() {
	if(!sendBox) { // fix safari bug
	  sendBox = dojo.byId("sendBox");
	  sendButton = dojo.byId("sendButton");
	  messageForm = dojo.byId("msgform");
	  messageBody = dojo.byId("msgbody");
	  colleagueBox = dojo.byId("colleagueBox");	
	  textNode = document.createTextNode("");  
	}
	var msg = trimString(messageBody.value);
	if (msg.length > 0) {
		showText("sending....");	
		setTimeout(doSend, 500);
	}
}


function doSend() {
	dojo.io.bind({
	    url: "/postMessage.do",
	    handle: function(type, evaldObj){
//	    	alert("sent!");
	    	messageBody.value = "";
	    	setText("sent!");
	    	setTimeout(showButton, 300);
	    },
	    formNode: messageForm
	});

}


function setText(text) {
	textNode.nodeValue = text;
}

function showText(text) {
	setText(text);
	sendBox.removeChild(sendButton);
	sendBox.appendChild(textNode);
}

function showButton() {
	sendBox.removeChild(textNode);
	sendBox.appendChild(sendButton);
}

function addColleague(uid) {
  dojo.io.bind({
    url: "/addColleague.do",
    sync: true,
    load: function(type, evaldObj){
    	colleagueBox.innerHTML = "<strong>(request sent for approval)<strong>";    	
    },
    error: function(type, errObj) {
    	colleagueBox.innerHTML = "error adding colleague";    	
    },
    content: {
    	accountId : uid
    }
  });	
}

function searchAccount(obj) {
	keyword = trimString(obj.value);
	if (isValidWaterMarkText(keyword,"enter name")) {
		var form = dojo.byId("searchAccountForm");
		form.keyword.value = keyword;
		form.submit();
	}
	else {
		alert("Please enter a name");
		obj.focus();
	}
}

