var userAgent = navigator.userAgent;
var isIE =  navigator.appVersion.match(/MSIE/);
var isChrome = userAgent.match(/chrome/i);
var isFireFox = userAgent.match(/firefox/i);
var isFireFoxOld = isFireFox && (userAgent.match(/firefox\/2./i) || userAgent.match(/firefox\/1./i));
var isFireFoxNew = isFireFox && !isFireFoxOld;

var contractDataUpdated = false;

var allPopupMenus = new Array();

var activeControlName;
var openDDLB = new Array();
var nameTimer = '';

var clients = new ClientArray();

var timer = null;
var newTimer = null;

var signableBlocksArray = new Array();


// ------------------ Common.js - STARTS ------------------- //

function flashDiv(targetDivId, color1, color2, counter)
{
	if (counter == null)
	{
		counter = 0;
	}
	
	counter++;
	
	if (counter < 10)
	{
		if (document.getElementById(targetDivId).style.backgroundColor == color1)
		{
			document.getElementById(targetDivId).style.background = color2;
		}
		else
		{
			document.getElementById(targetDivId).style.background = color1;
		}
		setTimeout("flashDiv('" + targetDivId + "','" + color1 + "','" + color2 + "'," + counter + ")", 100);
	}
	else
	{
		setTimeout("document.getElementById('" + targetDivId + "').style.background = '" + color1 + "'", 100);
				
	}
}

function ajaxFunction()
{
	var xmlHttp = null;

	try {    // Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}	catch (e)	{    // Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
			}
		}
	}
	return xmlHttp;
}

function scrollToBottom(targetDiv)
{
	if (targetDiv)
	{
		targetDiv.scrollTop = targetDiv.scrollHeight;	
	}
}

function openChatWindow()
{
	var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	var windowHeight = 510;
	var windowWidth = 550;
	var toolbar = 0;
	var resizeable = 1;
	
	if (isChrome)
	{
		windowHeight += 35;
	}
	
	
	childWindow = window.open('/Chat.action','LiveChat', 'left=20,top=20,width=' + windowWidth + ',height=' + windowHeight + ',toolbar=' + toolbar + ',resizable=' + resizeable);
}

function hideTipPopups()
{
	var url = '/foundation/HideTipPopups_HideTipPopups.action?&tm=' + (new Date()).getTime();

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			try
			{
				var formFieldContainer = JSON.parse(xmlHttp.responseText);

				if(formFieldContainer.jsonStatus == 'OK')
				{
					window.location.reload(true);
				}

			}catch(err){
				alert('AJAX Error: ' + err.name);
			}
		}
	}

	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function replaceContnetAJAX(divName, url)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var divObject = document.getElementById(divName);

			divObject.innerHTML=xmlHttp.responseText;
		}
	}

	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function replaceTxt(obj, text, equalsText)
{
	if(equalsText == obj.value)
	{
		obj.value = text;
	}
}

function clearSelectOptions(optionList)
{
	 for (x = optionList.length; x >= 0; x--)
	 {
			optionList[x] = null;
	 }
}


function addSelectOption(optionList, optionValue, optionText)
{
	 optionList[optionList.length] = new Option(optionText, optionValue);
}

function findPos(obj) 
{
	var point = new Object();
	
	var curTop = 0;
	var curLeft = 0;
	
	if(obj.offsetParent)
	{
		while(true) 
		{
//			alert(obj.nodeName + ' Top:' + obj.offsetTop + ' Left:' + obj.offsetLeft);

			if(obj.nodeName == 'INPUT')
			{
				if(isIE)
				{
//					curTop += parseInt(obj.offsetTop) + 15;
					curLeft += parseInt(obj.offsetLeft);
				}
				else if(isChrome)
				{
//					curTop += parseInt(obj.offsetTop);
					curLeft += parseInt(obj.offsetLeft);
				}
				else if(isFireFox)
				{
					curTop += parseInt(obj.offsetTop) + 4;
					curLeft += parseInt(obj.offsetLeft);
				}else{
					curTop += parseInt(obj.offsetTop);
					curLeft += parseInt(obj.offsetLeft);
				}
			}else{
				curTop += parseInt(obj.offsetTop);
				curLeft += parseInt(obj.offsetLeft);
			}
			
			if(!obj.offsetParent)
			{
				break;
			}
			obj = obj.offsetParent;
		}
	}else if(obj.x){
		curTop += obj.y;
		curLeft += obj.x;
	}

	point.y = curTop;
	point.x = curLeft;
	
	return point;
}

function openModalPopup(id)
{
	if (document.getElementById(id))
	{
		disableBackground();
		showDiv(id);
	}
}

function closeModalPopup(id)
{
	enableBackground();
	hideDiv(id);
	
}

function disableBackground()
{
	if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
	{
			var pageWidth = document.body.scrollWidth+'px';
			var pageHeight = document.body.scrollHeight;
	}
	else if( document.body.offsetWidth )
	{
		var pageWidth = document.body.offsetWidth+'px';
		var pageHeight = document.body.offsetHeight;
	}
	
	//Make sure full height in FF
	if (pageHeight && window.innerHeight && window.innerHeight > pageHeight)
	{
		pageHeight = window.innerHeight;
	}
	else if (!pageHeight && window.innerHeight && window.innerHeight > 0) 
	{
		pageHeight = window.innerHeight;
	}
	//Make sure full height in IE
	if (pageHeight && document.documentElement.clientHeight && document.documentElement.clientHeight > pageHeight)
	{
		pageHeight = window.innerHeight;
	}
	else if (!pageHeight && document.documentElement.clientHeight && document.documentElement.clientHeight > 0) 
	{
		pageHeight = window.innerHeight;
	}
	
	if (pageHeight)
	{
		pageHeight += 'px';
	}
	
	if (!pageHeight || !pageWidth)
	{
		var pageWidth='100%';
		var pageHeight='100%';
	}

	document.getElementById('greyPopupBG').style.height = pageHeight;
	document.getElementById('greyPopupBG').style.width = pageWidth;
	document.getElementById('greyPopupBG').style.display='block';
}

function enableBackground()
{
	document.getElementById('greyPopupBG').style.display='none';
}

function disableBackground1550()
{
	if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
	{
			var pageWidth = document.body.scrollWidth+'px';
			var pageHeight = document.body.scrollHeight+'px';
	}
	else if( document.body.offsetWidth )
	{
		var pageWidth = document.body.offsetWidth+'px';
		var pageHeight = document.body.offsetHeight+'px';
	}
	else
	{
		var pageWidth='100%';
		var pageHeight='100%';
	}

	document.getElementById('greyPopupBG_1550').style.height = pageHeight;
	document.getElementById('greyPopupBG_1550').style.width = pageWidth;
	document.getElementById('greyPopupBG_1550').style.display='block';
}

function enableBackground1550()
{
	document.getElementById('greyPopupBG_1550').style.display='none';
}

function toggleSection(link, div) 
{
	var linkOne = '[-]';
	var linkTwo = '[+]';
	if (div && link)
	{
		if (link.innerHTML == linkOne) 
		{
			link.innerHTML = linkTwo;
		}
		else
		{
			link.innerHTML = linkOne;
		}
		var divObj = document.getElementById(div);
		
		if(divObj.style.display == 'none')
		{
			divObj.style.display = '';
			divObj.style.height = 0;
		}else{
			divObj.style.display = 'none';
		}
	}
}

function toggleDivCloseText(link, divName)
{
	var linkOne = link;
	var linkTwo = '<strong>Close</strong>';
	if (divName && link)
	{
		if (link == linkOne) 
		{
			link.innerHTML = linkTwo;
		}
		else
		{
			link.innerHTML = linkOne;
		}
		
		var divObj = document.getElementById(divName);
		if(divObj.style.display == 'none')
		{
			divObj.style.display = 'block';
		}else{
			divObj.style.display = 'none';
		}
	}
}

function toggleDiv(divName)
{
	var divObj = document.getElementById(divName);
	
	if(divObj.style.display == 'none')
	{
		divObj.style.display = 'block';
	}else{
		divObj.style.display = 'none';
	}
}

function hideDiv(divName)
{
	var divObj = document.getElementById(divName);

	if(divObj != null)
	{
		divObj.style.display = 'none';
	}
}

function showDiv(divName)
{
	var divObj = document.getElementById(divName);

	if(divObj != null)
	{
		divObj.style.display = 'block';
	}
}

function toggleSpan(divName)
{
	var divObj = document.getElementById(divName);
	
	if(divObj.style.display == 'none')
	{
		divObj.style.display = 'inline';
	}else{
		divObj.style.display = 'none';
	}
}

function popupHelp(helpId)
{	
	var popupDiv = document.getElementById('popoverListDiv');
	if(popupDiv != null)
	{
		replaceContnetAJAX('popoverListDiv', '/PopupHelp.action?helpId=' + helpId + '&js=true&time=' + (new Date().getTime()));

		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 300) + 'px';
		popupDiv.style.border = '';
		
		popupDiv.style.display = 'block';
		
		disableBackground();		
	}
}

function closeHelp()
{	
	var popupDiv = document.getElementById('popoverListDiv');
	if(popupDiv != null)
	{
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 300) + 'px';
		popupDiv.style.border = '';
		
		popupDiv.innerHTML = '';
		popupDiv.style.display = 'none';
		
		enableBackground();		
	}
}

function popupWorkflowHelp(workflowId)
{	
	var popupDiv = document.getElementById('popoverListDiv');
	if(popupDiv != null)
	{
		if(workflowId == 'all-either_agent')
		{
			replaceContnetAJAX('popoverListDiv', '/help/all-either_agent.jsp');
		}
		else if(workflowId == 'buyer-buyers_agent')
		{
			replaceContnetAJAX('popoverListDiv', '/help/buyer-buyers_agent.jsp');
		}
		else if(workflowId == 'seller-sellers_agent')
		{
			replaceContnetAJAX('popoverListDiv', '/help/seller-sellers_agent.jsp');
		}
		else if(workflowId == 'agent-eithers_agent')
		{
			replaceContnetAJAX('popoverListDiv', '/help/agent-eithers_agent.jsp');
		}
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 500) + 'px';
		popupDiv.style.border = '';
		
		popupDiv.style.display = 'block';
		
		disableBackground();
	}
}

function closeWorkflowHelp()
{	
	var popupDiv = document.getElementById('popoverListDiv');
	if(popupDiv != null)
	{
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 300) + 'px';
		popupDiv.style.border = '';
		
		popupDiv.innerHTML = '';
		popupDiv.style.display = 'none';
		
		enableBackground();		
	}
}

function dialogBoxShow(divId)
{
	var popupDiv = document.getElementById(divId);
	if(popupDiv != null && document.getElementById('popoverListDiv'))
	{
		var afterDiv = document.getElementById('popoverListDiv');
		afterDiv.innerHTML = popupDiv.innerHTML;
		showDiv(afterDiv.id);
		
		disableBackground();
		
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;


		afterDiv.style.top = (yOffset + 50) + 'px';
		afterDiv.style.left = ((pageWidth / 2) - 500) + 'px';
		afterDiv.style.border = '';
		
		afterDiv.style.display = 'block';		
	}
}


function dialogBoxClose(divId)
{	
	var popupDiv = document.getElementById('popoverListDiv');
	if(popupDiv != null)
	{
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 300) + 'px';
		popupDiv.style.border = '';
		
		//popupDiv.innerHTML = '';
		popupDiv.style.display = 'none';
		
		enableBackground();		
	}
}

function popupCreateLoopExplain(loopDivId)
{	
	var popupDiv = document.getElementById(loopDivId);
	if(popupDiv != null)
	{
		showDiv(loopDivId);
		
		disableBackground();
		
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;


		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 500) + 'px';
		popupDiv.style.border = '';
		
		popupDiv.style.display = 'block';		
	}
}

function closePopupLoopExplain(loopDivId)
{	
	var popupDiv = document.getElementById(loopDivId);
	if(popupDiv != null)
	{
		var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		popupDiv.style.top = (yOffset + 50) + 'px';
		popupDiv.style.left = ((pageWidth / 2) - 300) + 'px';
		popupDiv.style.border = '';
		
		//popupDiv.innerHTML = '';
		popupDiv.style.display = 'none';
		
		enableBackground();		
	}
}

function textLineValidation(control, charsPerLine, maxLines)
{
	if(countLines(control, charsPerLine) > maxLines)
	{
		if(control.style.backgroundColor.toUpperCase() != '#EFD8E5' && control.style.backgroundColor.toUpperCase() != 'RGB(239, 216, 229)')
		{
			alert('There may be more text in this field than will print on the physical form.');
			
		}
		control.style.backgroundColor = '#EFD8E5';
	}else{
		control.style.backgroundColor = '#fffebd';
	}
}

function countLines(control, charsPerLine)
{
	var text = control.value;
	var lineCount = 0;

	if(text != null)
	{
		text = trim(text);

		var lineArray = text.split("\n");		

		for(var x = 0 ; x < lineArray.length ; x++)
		{
			var line = trim(lineArray[x]);
			lineCount += line.length / charsPerLine;
		}
	}
	return lineCount;
}

function trim(text)
{
	return text.replace(/^\s+|\s+$/g,"");
}


function checkAllInForm(form, checked, name, idBeginsWith) 
{
	if (checked != true && checked != false && checked != 'invert')
	{
		checked = true;
	}
	
	if (document.getElementById(form))
	{
		form = document.getElementById(form);
	}
	if (form && form.elements)
	{
		for (i=0; i<form.elements.length; i++)
		{
			if (form.elements[i].type == "checkbox" && 
					(!name || form.elements[i].name == name) && 
					(!idBeginsWith || form.elements[i].id.substr(0, form.elements[i].id.indexOf('_')) == idBeginsWith))
			{
				if (!form.elements[i].disabled)
				{
					if (checked == 'invert') 
					{
						form.elements[i].checked = !form.elements[i].checked;
					}
					else
					{
						form.elements[i].checked = checked;
					}
				}
			}
		}
	}
}


function addSelectClearInvertToTbody(tbodyElementId) 
{
	if (tbodyElementId && document.getElementById(tbodyElementId)) 
	{
		var tbody = document.getElementById(tbodyElementId);
		var newRow = document.createElement('selectOptions');
		
		string = '<tr style="background: rgb(10,100,200); color: white;">' +
				'<td colspan="2" class="txtSm">' +
					'<div id="javascriptCheckAllLink" class="dspN">' +
						'<a href="#" onclick="checkAllInForm(\'allNotesList\'); return false;" style="color:white;">Select All</a>' +
						'-' +
						'<a href="#" onclick="checkAllInForm(\'allNotesList\', false); return false;" style="color:white;">Clear All</a>' +
						'-' +
						'<a href="#" onclick="checkAllInForm(\'allNotesList\', \'invert\'); return false;" style="color:white;">Invert</a>' +
					'</div>' +
				'</td>' +
				'<td></td>' +
			'</tr>' + tbody.innerHTML; 
		
	}
}

function checkAllInTable(table, checked)
{
	if (checked != true && checked != false)
	{
		checked = true;
	}
	
	if (document.getElementById(table))
	{
		table = document.getElementById(table);
	}
	
	if (table && table.rows)
	{
		for (i=0; i<table.rows.length; i++)
		{
			currentRow = table.rows[i];
			if (currentRow.cells)
			{
				for (x=0; x<currentRow.cells.length; x++)
				{
					currentCell = currentRow.cells[x];
					for (y=0; y<currentCell.childNodes.length; y++)
					{
						currentNode = currentCell.childNodes[y];
						if (currentNode.checked == true || currentNode.checked == false)
						{
							currentNode.checked = checked;
						}
					}
				}
			}
		}
	}
}

function popupMenu(menuWidth, menuText, divID)
{
	if (!divID || divID == '') 
	{
		divID = "popUpMenu" + Math.floor(Math.random()*1000+1);
	}
	
	if (!menuText)		    { menuText          = "<span class=\"bold\" style=\"text-decoration: underline;\">More Options</span>"; }
	if (!menuWidth)			{ menuWidth         = "200px";  }
	menuBackground    = "#375A80";
	menuOpenLinkClass = "noline"; 
	menuOpenLinkStyle = "";       

	
	outerMostDivAdditionalParams = 'class="fltR" id="javaScriptButton" style="margin-left: 50px;"';
	//alert(divID);
	if (divID) 
	{
		this.linksAsArray = new Array();
		this.divID = divID;
		
		this.preHTML = '';
		this.preHTML += ("<div " + outerMostDivAdditionalParams + ">");
		this.preHTML += (	"<div class=\"posR\">");
		this.preHTML += (		"<div class=\"posA dspN\" " + 
								    " style=\"bottom:0; right:0; background-color:" + menuBackground + "; width:" + menuWidth + "\" " +
								    " onmouseout=\"popupMouseOut(this, " + allPopupMenus.length + ");\" id='" + divID + "'\"/>");
		this.preHTML += (			"<div onmouseover=\"openMenu(" + allPopupMenus.length + ");\">");
		
		this.postHTML = '';
		this.postHTML += (			"</div>");
		this.postHTML += (		"</div>");
		this.postHTML += (	"</div>");
		this.postHTML += (	"<a href=\"#\" onclick=\"openMenu(" + allPopupMenus.length + ", '" + divID + "'); return false;\" class='" + menuOpenLinkClass + "'>" + menuText + "</a>");
		this.postHTML += ("</div>");
		
		this.addLink=popupAddLink;
		this.write=writePopupMenu;
		this.open=popupMenuOpen;
		this.close=popupClose;
		this.addItem=popupAddItem;
		
		
		allPopupMenus[allPopupMenus.length] = this;
	}
}

function openMenu(menuID, setTimeoutElement) 
{
	if (allPopupMenus[menuID]) 
	{
		menuToOpen = allPopupMenus[menuID];
		menuToOpen.open();
		if (setTimeoutElement) 
		{
			menuToOpen.timer = setTimeout("popupMouseOut(document.getElementById('" + setTimeoutElement + "'), " + menuID + ");", 4000);
		}
		else 
		{
			clearTimeout(menuToOpen.timer);
		}
	}
}

function popupMenuOpen() 
{
	if (document.getElementById(this.divID)) 
	{
		div = document.getElementById(this.divID);
		div.style.display='block';
	}
}

function popupClose()
{
	if (document.getElementById(this.divID))
	{
		document.getElementById(this.divID).style.display = 'none';
	}
}

function popupMouseOut(element, menuID) 
{
	if (allPopupMenus[menuID] && element.id == allPopupMenus[menuID].divID) 
	{
			allPopupMenus[menuID].close();
			return true;
	}
}

function popupAddItem(text, onclick) 
{
	this.linksAsArray[this.linksAsArray.length] = "<div " + "style='color:#375A80; background-color:#D8E5EF; padding: 5px; margin: 2px;'" + 
												  " onmouseover=\"popupMenuOpen('" + this.divID + "');\">" + 
												  "<a href='#' onclick=\"" + onclick + "; document.getElementById('" + this.divID + "').style.display = 'none';\" class='noline blueTextLink'>" +
												  text + 
												  "</a></div>";
}

function popupAddLink(text, url, css) 
{
	this.linksAsArray[this.linksAsArray.length] = "<div " + "style='color:#375A80; background-color:#D8E5EF; padding: 5px; margin: 2px;'" + 
												  " onmouseover=\"popupMenuOpen('" + this.divID + "');\">" + 
												  "<a href='" + url + "' onclick=\"document.getElementById('" + this.divID + "').style.display = 'none';\" class='noline blueTextLink'>" +
												  text + 
												  "</a></div>";
}

function writePopupMenu()
{
		document.write(this.preHTML);
		for(i=0;i<this.linksAsArray.length;i++)
		{
			document.write(this.linksAsArray[i]);
		}
		document.write(this.postHTML);
}

//End popup menus


function checkEnter(e)
{
	if (e && e.keyCode) 
	{
		charCode = e.which;
	}
	else if (e)
	{
		charCode = e.keyCode;
	}
	
	
	if (!charCode)
	{
		if (event && event.keyCode)
		{
			charCode = event.keyCode;
		}
		else if (e && e.keyCode) 
		{
			charCode = e.which;
		}
		else if (e)
		{
			charCode = e.keyCode;
		}
	}

	if (charCode && charCode == 13)
	{
		return false;
	}
	return true;
}

function getInitials(name)
{
	var initials = '';
	var writeChar = true;
	for(x = 0 ; x < name.length ; x++)
	{
		var character = name.charAt(x);

		if(writeChar && character != ' ' && character != '.')
		{
			initials += character;
			writeChar = false;
		}
		if(character == ' ' || character == '.')
		{
			writeChar = true;
		}
	}

	return initials;
}

function disableTrainingPreference(preference, hideDivId)
{
	var url = '/user/TrainingPrefs_TurnOff.action?preference=' + preference + '&tm=' + (new Date()).getTime();

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			try
			{
				var formFieldContainer = JSON.parse(xmlHttp.responseText);

				if(formFieldContainer.status == 'OK')
				{
					var divObj = document.getElementById(hideDivId);
					if(divObj != null)
					{
						divObj.style.display = 'none';
					}
				}

			}catch(err){
				alert('AJAX Error: ' + err.name);
			}
		}
	}

	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function disableClientTrainingPreference(preference, hideDivId)
{
	var url = '/clientPortal/TrainingPrefs_TurnOff.action?preference=' + preference + '&tm=' + (new Date()).getTime();

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			try
			{
				var formFieldContainer = JSON.parse(xmlHttp.responseText);

				if(formFieldContainer.status == 'OK')
				{
					var divObj = document.getElementById(hideDivId);
					if(divObj != null)
					{
						divObj.style.display = 'none';
					}
				}

			}catch(err){
				alert('AJAX Error: ' + err.name);
			}
		}
	}

	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}


// ------------------ Common.js - ENDS ------------------- //

// ------------------ Contract.js - STARTS ------------------- //


function getRoleTypeName(roleId)
{
	switch(parseInt(roleId))
	{
		case 1:
			return 'Listing Agent';
			break;
		case 2:
			return 'Buyers Agent';
			break;
		case 3:
			return 'Listing Client';
			break;
		case 4:
			return 'Buying Client';
			break;
	}
	return '';
}

function showSignatureOptions(control)
{
	var point = findPos(control);
	var controlName = control.name;
	var baseControlName = controlName.replace(/\-\d+$/,'');
	var roleId = document.getElementById(baseControlName + 'RoleId').value;
	
	if(isChrome)
	{
		try
		{
			var offsetLeft = document.getElementById(controlName).offsetLeft;
			point.x -= offsetLeft;
		}catch(Err){}
	}
	else if(isIE)
	{
		
	}else{
	
	}

	var popoverListDiv = document.getElementById('popoverListDiv');
	
	popoverListDiv.innerHTML = '';
	
	if(editable || signable)
	{
		popoverListDiv.style.position = 'absolute';
		popoverListDiv.style.display = 'block';
		popoverListDiv.style.left = point.x + 'px';
		popoverListDiv.style.top = (point.y + 13) + 'px';

		if(editable && roleId == 0)
		{
			populateSignatureType(popoverListDiv, controlName, roleId);
			resetSignatures(controlName);
		}
		else if((roleId == 1 && listingAgent == true) || (roleId == 2 && sellingAgent == true))
		{
			populateSignaturesAgents(popoverListDiv, controlName, roleId);
		}
		else if((roleId == 3 && listingClient == true) || (roleId == 4 && buyingClient == true))
		{
			populateSignaturesClients(popoverListDiv, controlName);
		}else if(listingAgent == true || sellingAgent == true){
			if(editable)
			{
				populateClearOnly(popoverListDiv, controlName, roleId);
			}
		}
	}
}

function resetSignatures(controlName)
{	
	for(x = 1 ; x <= 20 ; x++)
	{
		var signatureObj = document.getElementById(controlName + '-' + x);
		var signatureId  = document.getElementById(controlName + '-' + x + 'SignedById');
		if(signatureObj != null && signatureId != null)
		{
			signatureId.value = 0;

			var className = signatureObj.className;
			
			className = className.replace(/formFieldSigned/g, "formFieldSign");
			className = className.replace(/\battention\b/g, "");
			signatureObj.className = className.replace(/formFieldSelected/g, "formFieldSign");
			
			signatureObj.value = '';
		}
	}
	
}

function showSignatureSide(controlObj)
{
	var baseControlName = controlObj.name.replace(/\-\d+$/,'');

	var roleId = document.getElementById(baseControlName + 'RoleId').value;
	var signedById = document.getElementById(controlObj.name + 'SignedById').value;
	
	if(roleId > 0 && signedById == '0')
	{
		controlObj.value = getSignatureRoleName(roleId, false);
	}
}

function hideSignatureSide(controlObj)
{
	var baseControlName = controlObj.name.replace(/\-\d+$/,'');

	var roleId = document.getElementById(baseControlName + 'RoleId').value;
	var signedById = document.getElementById(controlObj.name + 'SignedById').value;
	
	if(roleId > 0 && signedById == '0')
	{
		controlObj.value = '';
	}
}

function getSignatureRoleName(roleId, initials)
{
	if(initials == false)
	{
		if(roleId == 1)
		{
			return 'Listing Agent';
		}
		else if(roleId == 2)
		{
			return 'Buyers Agent';
		}
		else if(roleId == 3)
		{
			return 'Listing Client';
		}
		else if(roleId == 4)
		{
			return 'Buying Client';
		}
	}else{
		if(roleId == 1)
		{
			return 'LA';
		}
		else if(roleId == 2)
		{
			return 'BA';
		}
		else if(roleId == 3)
		{
			return 'LC';
		}
		else if(roleId == 4)
		{
			return 'BC';
		}
	}
	return '';
}

function selectedSignatures(controlName, signable)
{
	for(x = 1 ; x <= 20 ; x++)
	{
		var signatureObj = document.getElementById(controlName + '-' + x);
		var signatureId  = document.getElementById(controlName + '-' + x + 'SignedById');
		if(signatureObj != null && signatureId != null)
		{
			signatureId.value = 0;

			var className = signatureObj.className;
			
			if(signable)
			{
				className = className + ' attention';
			}
			className = className.replace(/formFieldSignError/g, "formFieldSelected").replace(/formFieldSign/g, "formFieldSelected");
			signatureObj.className = className.replace(/formFieldSigned/g, "formFieldSelected");
			
			signatureObj.value = '';
		}
	}
}

function populateClearOnly(popoverListDiv, controlName, roleId)
{
	popoverListDiv.innerHTML = '<div style="background-color:#FFF;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer();">' + 
					'<div class="pd2 brdBlackB blue" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><strong>Signature/Initials(s) for<br />the ' + getRoleTypeName(roleId) + '(s)</strong></div>' +
					'<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 0); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">Clear</a></div>' +
				    '</div>';
	startCloseTimer();
}


function populateSignatureType(popoverListDiv, controlName)
{
	popoverListDiv.innerHTML = '<div style="background-color:#FFF;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">' + 
					'<div class="pd2 brdBlackB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><strong>Select the party that <br />will initial or sign.</div></strong>' +
					'<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 3); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">Listing Client</a></div>' +
					'<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 1); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">Listing Agent</a></div>' +
					'<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 4); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">Buying Client</a></div>' +
					'<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 2); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">Buyers Agent</a></div>' +
				    '</div>';
	startCloseTimer();
}

function startCloseTimer()
{
	if(nameTimer != null)
	{
		clearTimeout(nameTimer);
	}
	nameTimer = setTimeout("document.getElementById('popoverListDiv').style.display = 'none';",1000);
}

function cancelCloseTimer()
{
	if(nameTimer != null)
	{
		clearTimeout(nameTimer);
	}
}

function updateSignatureRoleType(controlName, roleId)
{
	var popoverListDiv = document.getElementById('popoverListDiv');

	var baseControlName = controlName.replace(/\-\d+$/,'');
	
	document.getElementById(baseControlName + 'RoleId').value = roleId;

	var popoverListDiv = document.getElementById('popoverListDiv');

	if(roleId == 0)
	{
		resetSignatures(baseControlName);
		
		popoverListDiv.innerHTML = '';
		popoverListDiv.style.display = 'none';
	}
	else if((roleId == 1 && listingAgent == true) || (roleId == 2 && sellingAgent == true))
	{
		populateSignaturesAgents(popoverListDiv, controlName);
		selectedSignatures(baseControlName, true);
	}
	else if((roleId == 3 && listingClient == true) || (roleId == 4 && buyingClient == true))
	{
		populateSignaturesClients(popoverListDiv, controlName);
		selectedSignatures(baseControlName, true);
	}
	else
	{
		popoverListDiv.innerHTML = '';
		popoverListDiv.style.display = 'none';
		selectedSignatures(baseControlName, false);
	}	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function populateSignaturesAgents(popoverListDiv, controlName, roleId)
{
	var currentAgentIdArray = new Array();
	var baseControlName = controlName.replace(/\-\d+$/,'');
	var x = 0;
	for(var i = 1 ; i <= 20 ; i++)
	{
		var signedByIdObj = document.getElementById(baseControlName + '-' + i + 'SignedById');
		if(signedByIdObj != null)
		{
			if(signedByIdObj.value != '0')
			{
				currentAgentIdArray[x++] = signedByIdObj.value;
			}
		}
	}

	var content = '<div style="background-color:#FFF;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer();"><div class="pd2 brdBlackB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><strong>Select your name to<br />initial or sign.</div></strong>';
	
	for(var i = 0 ; i < agentList.length ; i++)
	{
		var agentMaster = agentList[i];
		var alreadyUsed = false;
		
		for(var j = 0 ; j < currentAgentIdArray.length ; j++)
		{
			if(currentAgentIdArray[j] == agentMaster.agentId)
			{
				alreadyUsed = true;
			}
		}
		
		if(alreadyUsed == false)
		{
			content += '<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureId(\'' + controlName + '\',' + agentMaster.agentId + ',\'' + escape(agentMaster.firstName) + ' ' + escape(agentMaster.lastName) + '\'); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">' + agentMaster.firstName + ' ' + agentMaster.lastName + '</a></div>';
		}
	}
	
	if(editable)
	{
		content += '<div class="pd5" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 0); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">Clear</a></div>';
	}

	content += '</div>';
	
	popoverListDiv.innerHTML = content;

	startCloseTimer();
}

function populateSignaturesClients(popoverListDiv, controlName, roleId)
{
	var currentClientIdArray = new Array();
	var baseControlName = controlName.replace(/\-\d+$/,'');
	var x = 0;
	for(var i = 1 ; i <= 20 ; i++)
	{
		var signedByIdObj = document.getElementById(baseControlName + '-' + i + 'SignedById');
		if(signedByIdObj != null)
		{
			if(signedByIdObj.value != '0')
			{
				currentClientIdArray[x++] = signedByIdObj.value;
			}
		}
	}

	var content = '<div style="background-color:#FFF;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><div class="pd2 brdBlackB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><strong>Select your name to<br />initial or sign.</div></strong>';

	for(var i = 0 ; i < clientList.length ; i++)
	{
		var clientMaster = clientList[i];
		var alreadyUsed = false;
		
		for(var j = 0 ; j < currentClientIdArray.length ; j++)
		{
			if(currentClientIdArray[j] == clientMaster.clientId)
			{
				alreadyUsed = true;
			}
		}
		
		if(alreadyUsed == false)
		{
			content += '<div class="pd5 brdGrayB" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()"><a href="#" class="noline" onclick="updateSignatureId(\'' + controlName + '\',' + clientMaster.clientId + ',\'' + escape(clientMaster.firstName) + ' ' + escape(clientMaster.lastName) + '\'); return false;" onmouseover="cancelCloseTimer()" onmouseout="startCloseTimer()">' + clientMaster.firstName + ' ' + clientMaster.lastName + '</a></div>';
		}
	}

	// content += '<div class="pd5"><a href="#" class="noline" onclick="updateSignatureRoleType(\'' + controlName + '\', 0); return false;">Clear</a></div>';
	
	content += '</div>';
	
	popoverListDiv.innerHTML = content;

	startCloseTimer();
}

function updateSignatureId(controlName, signedById, signedByName)
{
	document.getElementById(controlName + 'SignedById').value = signedById;

	var baseControlName = controlName.replace(/\-\d+$/,'');
	var signatureType = document.getElementById(baseControlName + 'Type').value;

	if(signatureType == 'I')
	{
		document.getElementById(controlName).value = getInitials(unescape(signedByName));
	}else{
		document.getElementById(controlName).value = unescape(signedByName);
	}

	var popoverListDiv = document.getElementById('popoverListDiv');
	
	popoverListDiv.innerHTML = '';
	popoverListDiv.style.display = 'none';
	
	
	for(x = 1 ; x <= 20 ; x++)
	{
		var signatureObj = document.getElementById(baseControlName + '-' + x);
		if(signatureObj != null)
		{
			var className = signatureObj.className;
			
			signatureObj.className = className.replace(/attention/g, "");
		}
	}
}

function setContractDataUpdated()
{
	contractDataUpdated = true;
}

function confirmContractDataUpdated()
{
	if(contractDataUpdated)
	{
		return confirm('You have made changes to this form that have not been saved. Are you sure you want to leave this page without saving it first?');
	}else{
		return true;
	}
}

function confirmContractDataPrint()
{
	if(contractDataUpdated)
	{
		return confirm('You have made changes to this form that have not been saved. Are you sure you want to print this page without saving it first?');
	}else{
		return true;
	}
}

function confirmContractDataSend()
{
	if(contractDataUpdated)
	{
		return confirm('You have made changes to this form that have not been saved. Are you sure you want to send this page without saving it first?');
	}else{
		return true;
	}
}

function clickFieldHistory(clickEvent, contractId, fieldId, fieldType)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonResults = JSON.parse(xmlHttp.responseText);
			if(jsonResults.status == 'OK')
			{
				displayFieldHistory(jsonResults);
			}
		}
	}

	xmlHttp.open('GET', '/contract/FieldHistory_Json.action?contractId=' + contractId + '&fieldId=' + fieldId + '&fieldType=' + fieldType + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function clickClientFieldHistory(clickEvent, contractId, fieldId, fieldType)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonResults = JSON.parse(xmlHttp.responseText);
			if(jsonResults.status == 'OK')
			{
				displayFieldHistory(jsonResults);
			}
		}
	}

	xmlHttp.open('GET', '/clientPortal/FieldHistory_Json.action?contractId=' + contractId + '&fieldId=' + fieldId + '&fieldType=' + fieldType + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function displayFieldHistory(jsonResults)
{
	var popupDiv = document.getElementById('fieldHistoryPopup');
	var popupDivContents = document.getElementById('fieldHistoryContents');

	var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
	var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
	
	popupDiv.style.top = (yOffset + 50) + 'px';
	popupDiv.style.left = ((pageWidth / 2) - 500) + 'px';
	
	popupDiv.style.display = 'block';
	
	var divContents='';
	
	for(var x = 0 ; x < jsonResults.fieldHistoryList.length ; x++)
	{
		divContents += '<div class="pd5" style="background-color:white;">';
		
		var friendlyAgentName = '';
		
		if(jsonResults.fieldHistoryList[x].friendlyAgentType != undefined && jsonResults.fieldHistoryList[x].friendlyAgentType != '')
		{
			friendlyAgentName = '&nbsp;&nbsp;(' + jsonResults.fieldHistoryList[x].friendlyAgentType + ')';
		}
		
		divContents += '<div class="fltL" style="color:#7F7F7F"><strong>Edited By: </strong>' + jsonResults.fieldHistoryList[x].enteredByName + friendlyAgentName + '</div><div class="fltR" style="color:#7F7F7F"><strong> Date: </strong>' + jsonResults.fieldHistoryList[x].enteredDate + '</div><br class="clrB" />';
		
		if(x == 0 && x != jsonResults.fieldHistoryList.length-1)
		{
			divContents += '<div class="clrB contentRowOdd" style="color:#00ADEF; padding-bottom:7px;"><strong>' + jsonResults.fieldHistoryList[x].textValue + '</strong></div>';
		}else if(x == jsonResults.fieldHistoryList.length-1){
			divContents += '<div class="clrB" style="color:#00ADEF;">' + jsonResults.fieldHistoryList[x].textValue + '</div>';
		}else{
			divContents += '<div class="clrB contentRowOdd" style="color:#00ADEF; padding-bottom:7px;">' + jsonResults.fieldHistoryList[x].textValue + '</div>';
		}
		
		divContents += '</div>';
		
	}
	
	popupDivContents.innerHTML=divContents;
}

function closeFieldHistory()
{
	var popupDiv = document.getElementById('fieldHistoryPopup');
	var popupDivContents = document.getElementById('fieldHistoryContents');
	
	popupDiv.style.display = 'none';
	
	popupDivContents.innerHTML='<h2 align="center">Loading...</h2>';
}

function checkContractWarnings(contractId)
{
	if(contractId != undefined && contractId > 0)
	{
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				var jsonResults = JSON.parse(xmlHttp.responseText);
				if(jsonResults.status == 'OK')
				{
					var warnings = jsonResults.warningList;
					var errorMessages = '<div><table width="100%" cellpadding="5">';

					for(var x = 0 ; x < warnings.length ; x++)
					{
						errorMessages += '<tr><td>' + warnings[x].message + '</td></tr>';
					}

					errorMessages += '</table></div>';

					var warningListDiv = document.getElementById('warningListDiv');
					warningListDiv.innerHTML = errorMessages;
					if(warnings.length > 0)
					{
						warningListDiv.style.display = 'block';
					}else{
						warningListDiv.style.display = 'none';
					}
				}
			}
		}
	}

	xmlHttp.open('GET', '/contract/ContractWarnings.action?contractId=' + contractId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function addMissingAgent(contractId, agentId, agentType)
{
	var url;
	
	if(agentType == 'S')
	{
		url = '/contract/ContractAgentList_AddSellerJson.action?contractId=' + contractId + '&sellingAgentNameId=' + agentId;
	}else{
		url = '/contract/ContractAgentList_AddBuyerJson.action?contractId=' + contractId + '&buyingAgentNameId=' + agentId;
	}	

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonResults = JSON.parse(xmlHttp.responseText);
			if(jsonResults.status == 'OK')
			{
				checkContractWarnings(contractId);
			}else{
				alert('This agent could not be added at this time.');
			}
		}
	}

	xmlHttp.open('GET', url + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function addMissingClient(contractId, clientId, clientType)
{
	var url;
	
	if(clientType == 'S')
	{
		url = '/contract/ContractClientList_AddSellerJson.action?contractId=' + contractId + '&sellingClientNameId=' + clientId;
	}else{
		url = '/contract/ContractClientList_AddBuyerJson.action?contractId=' + contractId + '&buyingClientNameId=' + clientId;
	}	

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonResults = JSON.parse(xmlHttp.responseText);
			if(jsonResults.status == 'OK')
			{
				checkContractWarnings(contractId);
			}else{
				alert('This client could not be added at this time.');
			}
		}
	}

	xmlHttp.open('GET', url + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function updatePropertyStatus(propertyId, statusId, contractId)
{
	var url = '/property/Property_StatusJson.action?propertyId=' + propertyId + '&statusId=' + statusId;

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonResults = JSON.parse(xmlHttp.responseText);
			if(jsonResults.status == 'OK')
			{
				checkContractWarnings(contractId);
			}else{
				alert('This property could not be updated at this time.');
			}
		}
	}

	xmlHttp.open('GET', url + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}


// ------------------ Contract.js - ENDS ------------------- //


// ------------------ Names.js - STARTS ------------------- //

function addClientBox(controlName)
{
	var obj = document.getElementById(controlName + 'Div');
	var firstTextbox = document.getElementById(controlName + '-1');
	var textboxContDiv = document.getElementById(controlName + 'ContDiv');

	var cssClass = firstTextbox.className;
	var cssStyle = ''; //firstTextbox.style;
	
	var index = 1;
	
	while(document.getElementById(controlName + '-' + (index++)) != undefined){}
	
	index -= 1;
	
	var name = controlName + '-' + index;
	var value = '';

	var newControl = '<input type="text" name="' + name + '" id="' + name + '" value="' + value + '" onkeyup="lookupName(this);" autocomplete="off" onchange="try{ setContractDataUpdated(); }catch(err){}" class="' + cssClass + '" style="' + cssStyle + '" /><input type="hidden" name="' + name + 'Id" id="' + name + 'Id" value="0" />';
	
	textboxContDiv.innerHTML = textboxContDiv.innerHTML + newControl;
}

function lookupName(controlObj, objOffset)
{
	
	if(controlObj.value != null && controlObj.value.length > 0)
	{
		var nameEntered = controlObj.value;
		
		if(nameEntered == '')
		{
			document.getElementById(controlObj.name + 'Id').value = '0';
		}
		
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				var clientSearch = JSON.parse(xmlHttp.responseText);
				if(clientSearch.status == 'OK')
				{
					var nameArray = clientSearch.clientList;
					
					dropDownNames(controlObj.name, nameArray, objOffset);
				}
			}
		}

		if(nameEntered != '')
		{
			xmlHttp.open('GET', '/client/ClientList_Json.action?name=' + escape(nameEntered) + '&time=' + (new Date().getTime()), true);
			xmlHttp.send(null);
		}
	}else{
		closeNames(controlObj.name);
	}
}

function dropDownNames(controlName, nameArray, objOffset)
{
	var controlObj = document.getElementById(controlName);
	var hiddenObj = document.getElementById(controlName + 'Id');

	if(objOffset == undefined)
	{
		objOffset = 0;
	}
	
	var divContents='<a href="#" target="newClient" onmouseout="closeList(\'' + controlName +'\');" onmouseover="stopCloseList(\'' + controlName +'\');" onclick="newClient(\'' + controlName +'\'); return false;" class="nameBox"><div class="nameBox"><strong>Add New Client</strong></div></a>';
	for(var x = 0 ; x < nameArray.length ; x++)
	{
		divContents += '<a href="#" onmouseout="closeList(\'' + controlName +'\');" onmouseover="stopCloseList(\'' + controlName +'\');" onclick="updateName(\'' + controlName +'\',\'' + nameArray[x].clientId + '\',\'' + nameArray[x].firstName + ' ' + nameArray[x].lastName + '\'); return false;" class="nameBox"><div class="nameBox">' + nameArray[x].firstName + ' ' + nameArray[x].lastName + '</div></a>';
	}

	if(nameArray.length == 1)
	{
		controlObj.style.backgroundColor = '#FFFFFF';
		hiddenObj.value = nameArray[0].clientId;
	}else{
		controlObj.style.backgroundColor = '#FDB0B0';
		hiddenObj.value = '0';
	}
	var clientList = document.getElementById('popoverListDiv');
	
	clientList.innerHTML = divContents;
	

	clientList.style.display = 'block';
	clientList.style.width = controlObj.offsetWidth;
	clientList.style.zIndex = "1705";

	var point = findPos(controlObj);

	if(isChrome)
	{
		var firstControl = controlName.replace(/\d+$/,'1');
		if(firstControl != null)
		{
			var firstControlObj = document.getElementById(firstControl);
			if(firstControlObj != null)
			{
				point.x -= firstControlObj.offsetLeft;
			}
		}
	}


	clientList.style.left = point.x + 'px';
	clientList.style.top = (point.y + objOffset + 13) + 'px';
}

function closeList(controlName)
{
	openDDLB[controlName] = setTimeout('closeNames(\'' + controlName + '\');', 800);
}

function stopCloseList(controlName)
{
	if(openDDLB[controlName] != null)
	{
		clearTimeout(openDDLB[controlName]);
	}
}

function closeNames(controlName)
{
	var popupDiv = document.getElementById('popoverListDiv');
	var controlObj = document.getElementById(controlName);
	var hiddenObj = document.getElementById(controlName + 'Id');
	
	popupDiv.style.display='none';

	if(hiddenObj.value != undefined && hiddenObj.value > 0)
	{
		controlObj.style.backgroundColor = '#FFFFFF';
	}else{
		controlObj.style.backgroundColor = '#FDB0B0';
	}
}

function updateName(controlName, clientId, clientName)
{
	var controlObj = document.getElementById(controlName);
	var hiddenObj = document.getElementById(controlName + 'Id');
	var popupDiv = document.getElementById('popoverListDiv');

	controlObj.value=clientName;
	hiddenObj.value=clientId;
	popupDiv.style.display='none';
	
	if(clientId > 0)
	{
		controlObj.style.backgroundColor = '#FFFFFF';
	}else{
		controlObj.style.backgroundColor = '#FDB0B0';
	}
}

function newClient(controlName)
{
	activeControlName = controlName;

	document.getElementById('nc_firstName').value = '';
	document.getElementById('nc_lastName').value = '';
	document.getElementById('nc_emailAddress').value = '';
	document.getElementById('nc_telephone').value = '';
	document.getElementById('nc_fax').value = '';

	var newClientDiv = document.getElementById('newClientDiv');

	var popoverListDiv = document.getElementById('popoverListDiv');

	var yOffset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
	var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
	
	newClientDiv.style.top = (yOffset + 50) + 'px';

	newClientDiv.style.display = 'block';
	
	disableBackground();
}

function saveNewContact()
{
	var fName = document.getElementById('nc_firstName').value;
	var lName = document.getElementById('nc_lastName').value;
	var email = document.getElementById('nc_emailAddress').value;
	var phone = document.getElementById('nc_telephone').value;
	var fax = document.getElementById('nc_fax').value;
	
	var xmlHttp = ajaxFunction();
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var results = JSON.parse(xmlHttp.responseText);
			
			if(results.status == 'OK')
			{
				addClient(results.clientId, fName + ' ' + lName);
				closeClient();
			}else{
				if (results.message == null || results.message == "")
				{
					alert('Error');
				}
				else
				{
					alert(results.message);
				}
			}
		}
	}

	var sendUrl = '/client/EditClient_SaveJSON.action?clientId=-1&firstName=' + fName + '&lastName=' + lName + '&emailAddress=' + email + '&phoneNumber=' + phone + '&faxNumber=' + fax
	xmlHttp.open('GET', sendUrl, true);
	xmlHttp.send(null);

}

function closeClient()
{
	document.getElementById('newClientDiv').style.display='none';

	enableBackground();
}

function addAgentBox(controlName)
{
	var obj = document.getElementById(controlName + 'Div');
	var firstTextbox = document.getElementById(controlName + '-1');
	
	var cssClass = firstTextbox.className;
	var cssStyle = firstTextbox.style;
	
	var index = 1;
	
	while(document.getElementById(controlName + '-' + (index++)) != undefined){}
	
	index -= 1;
	
	var node = document.createElement('input');

	node.setAttribute('id',controlName + '-' + index);
	node.setAttribute('type','text');
	node.setAttribute('name',controlName + '-' + index);
	
	if(cssClass != undefined)
	{
		node.setAttribute('class',cssClass);
		node.setAttribute('className',cssClass);
	}else{
		node.setAttribute('class','formField');
		node.setAttribute('className','formField');
	}

	if(cssStyle != undefined)
	{
		node.setAttribute('style',cssStyle);
	}
		
	node.onkeyup=function(){lookupAgentName(this)};

	obj.appendChild(node);
	
	node = document.createElement('input');
	
	node.setAttribute('id',controlName + '-' + index + 'Id');
	node.setAttribute('type','hidden');
	node.setAttribute('name',controlName + '-' + index + 'Id');

	obj.appendChild(node);
}

function dropDownAgentNames(controlName, nameArray, objOffset, selectFunction)
{
	var controlObj = document.getElementById(controlName);
	var hiddenObj = document.getElementById(controlName + 'Id');
	
	if(controlObj.value == '')
	{
		document.getElementById(controlObj.name + 'Id').value = '0';
	}

	var divContents='';
	
	if(objOffset == undefined)
	{
		objOffset = 14;
	}
	
	if(selectFunction == undefined)
	{
		selectFunction = '';
	}

	for(var x = 0 ; x < nameArray.length ; x++)
	{
		divContents += '<a href="#" onmouseout="closeList(\'' + controlName +'\');" onmouseover="stopCloseList(\'' + controlName +'\');" onclick="updateAgentName(\'' + controlName +'\',\'' + nameArray[x].agentId + '\',\'' + nameArray[x].firstName + ' ' + nameArray[x].lastName + '\',\'' + selectFunction + '\'); updatePropertyList(); return false;" class="nameBox"><div class="nameBox"><strong>' + nameArray[x].firstName + ' ' + nameArray[x].lastName + '</strong><br/>' + nameArray[x].brokerageIdName + '<br />' + nameArray[x].officeCity + ', ' + nameArray[x].officeState + '</div></a>';
	}

	if(nameArray.length == 1)
	{
		controlObj.style.backgroundColor = '#FFFFFF';
		hiddenObj.value = nameArray[0].agentId;
	}else{
		hiddenObj.value = '0';
		controlObj.style.backgroundColor = '#FDB0B0';
	}

	var agentList = document.getElementById('popoverListDiv');

	agentList.innerHTML = divContents;

	agentList.style.display = 'block';
	agentList.style.width = controlObj.offsetWidth;

	var point = findPos(controlObj);

	agentList.style.top = (point.y + objOffset) + 'px';
	agentList.style.left = point.x + 'px';
}

function lookupAgentName(controlObj, objOffset, selectFunction)
{
	if(controlObj.value != null && controlObj.value.length > 0)
	{
		try
		{
			clearTimeout(nameTimer);
			nameTimer = setTimeout("openAgentNameList('" + controlObj.name + "', '" + controlObj.value + "', " + objOffset + ", '" + selectFunction + "');",500);
		}catch(err){
			alert("Error description: " + err.description);
		}
	}else{
		clearTimeout(nameTimer);
		closeAgentNames(controlObj.name);
		try
		{
			document.getElementById(controlObj.id + 'Id').value = '0';
		}catch(err){ 
			alert("Error description: " + err.description);			
		}
	}
}

function openAgentNameList(controlName, controlValue, objOffset, selectFunction)
{
	var xmlHttp = ajaxFunction();
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			if(xmlHttp.status == 200)
			{
				var results = JSON.parse(xmlHttp.responseText);
				if(results.status == 'OK')
				{
					nameTimer = null;
					dropDownAgentNames(controlName, results.agentMasterList, objOffset, selectFunction);
				}else{
					nameTimer = null;
					closeAgentNames(controlName);
				}
			}
		}
	}

	xmlHttp.open('GET', '/agent/AgentList_Json.action?name=' + controlValue + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function closeAgentNames(controlName)
{
	var hiddenObj = document.getElementById(controlName + 'Id');
	var popupDiv = document.getElementById(controlName + 'Popup');
	
	if(hiddenObj.value != undefined && hiddenObj.value != 0)
	{
		controlObj.style.backgroundColor = '#FFFFFF';
	}else{
		controlObj.style.backgroundColor = '#FDB0B0';
	}

	popupDiv.style.display='none';
}

function updateAgentName(controlName, agentId, agentName, selectFunction)
{
	var controlObj = document.getElementById(controlName);
	var hiddenObj = document.getElementById(controlName + 'Id');
	var popupDiv = document.getElementById('popoverListDiv');

	controlObj.value=agentName;
	hiddenObj.value=agentId;
	popupDiv.style.display='none';

	if(hiddenObj.value != undefined && hiddenObj.value != 0)
	{
		controlObj.style.backgroundColor = '#FFFFFF';
	}else{
		controlObj.style.backgroundColor = '#FDB0B0';
	}
	
	if(selectFunction != '')
	{
		eval(selectFunction);
	}
}

function popupAgentName(controlObj)
{
	activeControlName = controlObj.name;
	var hiddenObj = document.getElementById(activeControlName + 'Ids');
	
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var agentListPopup = document.getElementById('popoverListDiv');

			agentListPopup.innerHTML = xmlHttp.responseText;

			var yOffset = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
			var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
	
			agentListPopup.style.top = (yOffset + 100);
			agentListPopup.style.left = (pageWidth / 2) - 300;

			agentListPopup.style.display = 'block';
			
			disableBackground();
		}
	}

	xmlHttp.open('GET', '/contract/ContractAgentList_Popup.action?agentIds=' + hiddenObj.value + '&name=&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function updateAgentNamePopup()
{
	var hiddenObj = document.getElementById(activeControlName + 'Ids');
	var agentNameObj = document.getElementById('agentName');

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var results = JSON.parse(xmlHttp.responseText);
			if(results.status == 'OK')
			{
				updateAgentNameAgents(results.agentMasterList);
				updateAgentNameSuggestions(results.suggestedAgentList);
			}else{
				alert('Error');
			}
		}
	}

	xmlHttp.open('GET', '/contract/ContractAgentList_Json.action?agentIds=' + hiddenObj.value + '&name=' + escape(agentNameObj.value) + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function closeAgentName()
{
	var agentListPopup = document.getElementById('popoverListDiv');

	agentListPopup.innerHTML = '';

	agentListPopup.style.display = 'none';

	enableBackground();
}

function updateAgentNameSuggestions(suggestedAgentList)
{
	var suggestedAgentDiv = document.getElementById('suggestedAgentList');
	
	var content = '<table width="275" class="contentListTable" cellpadding="0" cellspacing="0">';
		
	for(var x = 0 ; x < suggestedAgentList.length ; x++)
	{
		content += '<tr>' +

		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		suggestedAgentList[x].firstName + ' ' + suggestedAgentList[x].lastName + 
		'</td>' +
		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		'<a href="#' + suggestedAgentList[x].agentId + '" onclick="addAgent(\'' + suggestedAgentList[x].agentId + '\'); return false;">Add</a>' +
		'</td>' +
		'</tr>';
	}

	content += '</table>';

	suggestedAgentDiv.innerHTML = content;
}

function updateAgentNameAgents(agentMasterList)
{
	var agentMasterDiv = document.getElementById('agentMasterList');
	var controlObj = document.getElementById(activeControlName);
	
	var content = '<table width="275" class="contentListTable" cellpadding="0" cellspacing="0">';
	
	controlObj.value = '';
	
	for(var x = 0 ; x < agentMasterList.length ; x++)
	{
		content += '<tr>' +
		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		agentMasterList[x].firstName + ' ' + agentMasterList[x].lastName + 
		'</td>' +
		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		'<a href="#' + agentMasterList[x].agentId + '" onclick="removeAgent(\'' + agentMasterList[x].agentId + '\'); return false;">Remove</a>' +
		'</td>' +
		'</tr>';
		
		if(x > 0)
		{
			controlObj.value += ', ';
		}
		controlObj.value += agentMasterList[x].firstName + ' ' + agentMasterList[x].lastName;
	}

	content += '</table>';

	agentMasterDiv.innerHTML = content;
}

function addAgent(agentId)
{
	var hiddenObj = document.getElementById(activeControlName + 'Ids');
	
	if(hiddenObj.value != undefined && hiddenObj.value.length > 0)
	{	
		var ids = new Array();
		ids = hiddenObj.value.split(',');
		
		ids[ids.length] = agentId;

		var hiddenValue = '';
		for(var x = 0 ; x < ids.length ; x++)
		{
			if(x > 0)
			{
				hiddenValue += ',';
			}
			hiddenValue += ids[x];
		}
	}else{
		hiddenValue = agentId;
	}
	
	hiddenObj.value = hiddenValue;
	
	updateAgentNamePopup();
}

function removeAgent(agentId)
{
	var hiddenObj = document.getElementById(activeControlName + 'Ids');
	
	if(hiddenObj.value != undefined && hiddenObj.value.length > 0)
	{	
		var ids = new Array();
		ids = hiddenObj.value.split(',');
		
		ids[ids.length] = agentId;

		var hiddenValue = '';
		for(var x = 0 ; x < ids.length ; x++)
		{
			if(ids[x] != agentId)
			{
				if(hiddenValue.length > 0)
				{
					hiddenValue += ',';
				}
				hiddenValue += ids[x];
			}
		}
	}
	
	hiddenObj.value = hiddenValue;
	
	updateAgentNamePopup();
}

/*******************************************************************************/


function popupClientName(controlObj)
{
	activeControlName = controlObj.name;
	var hiddenObj = document.getElementById(activeControlName + 'Id');
	
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var clientListPopup = document.getElementById('popoverListDiv');

			clientListPopup.innerHTML = xmlHttp.responseText;

			var yOffset = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
			var pageWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth;
	
			clientListPopup.style.top = (yOffset + 100);
			clientListPopup.style.left = (pageWidth / 2) - 300;

			clientListPopup.style.display = 'block';
			
			disableBackground();
		}
	}

	xmlHttp.open('GET', '/contract/ContractClientList_Popup.action?clientIds=' + hiddenObj.value + '&name=&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function updateClientNamePopup()
{
	var hiddenObj = document.getElementById(activeControlName + 'Id');
	var clientNameObj = document.getElementById('clientName');

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var results = JSON.parse(xmlHttp.responseText);
			if(results.status == 'OK')
			{
				updateClientNameClients(results.clientMasterList);
				updateClientNameSuggestions(results.suggestedClientList);
			}else{
				alert('Error');
			}
		}
	}

	xmlHttp.open('GET', '/contract/ContractClientList_Json.action?clientIds=' + hiddenObj.value + '&name=' + escape(clientNameObj.value) + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function closeClientName()
{
	var clientListPopup = document.getElementById('popoverListDiv');

	clientListPopup.innerHTML = '';

	clientListPopup.style.display = 'none';

	enableBackground();
}

function updateClientNameSuggestions(suggestedClientList)
{
	var suggestedClientDiv = document.getElementById('suggestedClientList');
	
	var content = '<table width="275" class="contentListTable" cellpadding="0" cellspacing="0">';
		
	for(var x = 0 ; x < suggestedClientList.length ; x++)
	{
		content += '<tr>' +

		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		suggestedClientList[x].firstName + ' ' + suggestedClientList[x].lastName + 
		'</td>' +
		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		'<a href="#' + suggestedClientList[x].clientId + '" onclick="addClient(\'' + suggestedClientList[x].clientId + '\',\'' + suggestedClientList[x].firstName + ' ' + suggestedClientList[x].lastName + '\'); return false;">Add</a>' +
		'</td>' +
		'</tr>';
	}

	content += '</table>';

	suggestedClientDiv.innerHTML = content;
}

function updateClientNameClients(clientMasterList)
{
	var clientMasterDiv = document.getElementById('clientMasterList');
	var controlObj = document.getElementById(activeControlName);
	
	var content = '<table width="275" class="contentListTable" cellpadding="0" cellspacing="0">';
	
	controlObj.value = '';
	
	for(var x = 0 ; x < clientMasterList.length ; x++)
	{
		content += '<tr>' +
		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		clientMasterList[x].firstName + ' ' + clientMasterList[x].lastName + 
		'</td>' +
		'<td class="contentRow' + ((x%2==0)?'':'Odd') + '">' +
		'<a href="#' + clientMasterList[x].clientId + '" onclick="removeClient(\'' + clientMasterList[x].clientId + '\'); return false;">Remove</a>' +
		'</td>' +
		'</tr>';
		
		if(x > 0)
		{
			controlObj.value += ', ';
		}
		controlObj.value += clientMasterList[x].firstName + ' ' + clientMasterList[x].lastName;
	}

	content += '</table>';

	clientMasterDiv.innerHTML = content;
}

function addClient(clientId, name)
{
	var nameObj = document.getElementById(activeControlName);
	var hiddenObj = document.getElementById(activeControlName + 'Id');
	
	hiddenObj.value = clientId;
	
	nameObj.value = name;
}

function removeClient(clientId)
{
	var hiddenObj = document.getElementById(activeControlName + 'Id');
	
	hiddenObj.value = '0';
	
	updateClientNamePopup();
}

// ------------------ Names.js - ENDS ------------------- //


// ------------------ addClient.js - STARTS ------------------- //

function ClientMaster() 
{
	this.clientId = 0;
	this.firstName = "";
	this.middleName = "";
	this.lastName = "";
	this.emailAddress = "";
	this.approvalId = 0;
	this.signedAttachment = false;
	
	this.toHTML = function()
	{
		var returnString = "";
		returnString += "<div style='border-bottom: 1px gray solid; padding: 5px;'>";
		
		if (this.approvalId > 0 || this.signedAttachment == true)
		{
			returnString += 	"<div class='bold redDk'>" + this.firstName + ' ' + this.lastName + "</div>";
		}
		else
		{
			returnString += 	"<div class='bold'>" + this.firstName + ' ' + this.lastName + "</div>";
		}
		returnString += 	"<div class='fltL w200'>" + this.emailAddress + "</div>";
		
		if (this.approvalId < 1 && this.signedAttachment == false)
		{
			returnString += 	"<div class='fltR w100'><a href='#' onclick='acRemoveClient(" + this.clientId + "); return false;'>remove</a></div>";
		}
		else
		{
			returnString += 	"<div class='fltR w125'><em>Has signed contract.</em></div>";
		}
		
		returnString += 	"<div class='clrB'></div>";
		returnString += "</div>";
		return returnString;
	};
	
	this.setFromDocument = function() {
		if (document.getElementById('firstName_' + this.clientId)) {
			this.firstName = document.getElementById('firstName_' + this.clientId).innerHTML;
		}
		if (document.getElementById('lastName_' + this.clientId)) {
			this.lastName = document.getElementById('lastName_' + this.clientId).innerHTML;
		}
		if (document.getElementById('emailAddress_' + this.clientId)) {
			this.emailAddress = document.getElementById('emailAddress_' + this.clientId).innerHTML;
		}
		if (document.getElementById('apId_' + this.clientId)) {
			this.approvalId = document.getElementById('apId_' + this.clientId).innerHTML;
		}
		if (document.getElementById('aSig_' + this.clientId)) {
			this.signedAttachment = true;
		}
	};
}

function ClientArray()
{
	this.array = Array();
	
	this.add = function(clientMaster)
	{
		var clientId = clientMaster.clientId;
		for (i=0; i < this.array.length; i++) 
		{
			if (this.array[i].clientId == clientId) {
				return false;
			}
		}
		this.array[this.array.length] = clientMaster;
	};
	
	this.remove = function(clientId)
	{
		var newArray = Array();
		for (i=0; i<this.array.length; i++)
		{
			var clientMaster = this.array[i];
			if (clientMaster.clientId != clientId)
			{
				newArray[newArray.length] = clientMaster;
			}
			
			//can this client not be deleted?
			//Even though this should not happen as the "Remove" link is not displayed...
			if (clientMaster.clientId == clientId && clientMaster.approvalId > 0)
			{
				alert('Client has signed contracts and cannot be deleted.');
				newArray[newArray.length] = clientMaster;
			}
		}
		this.array = newArray;
	};
	
	this.asHTML = function()
	{
		var returnString = "";
		for (i=0; i<this.array.length;i++)
		{
			var clientMaster = this.array[i];
			returnString += "<span id='clientId_" + clientMaster.clientId + "'>";
			returnString += clientMaster.toHTML();
			returnString += "</span>";
		}
		return returnString;
	};
	
	this.toString = function()
	{
		var returnString = "";
		var first = true;
		for (i=0; i<this.array.length; i++)
		{
			var clientMaster = this.array[i];
			if (!first) {
				returnString += "-";
			} else {
				first = false;
			}
			returnString += clientMaster.clientId;
		}
		return returnString;
	};
	
	
}

function initClients()
{
	var hidden = document.getElementById('clientIds');
	if (hidden) {
		var clientIdString = hidden.value;
		var parts = clientIdString.split("-");
		for (i=0; i<=parts.length; i++)
		{
			var clientMaster = new ClientMaster();
			clientMaster.clientId = parts[i];
			clientMaster.setFromDocument();
			if (clientMaster.clientId > 0)
			{
				clients.add(clientMaster);
			}
		}
	} 
	document.getElementById('submitButton').style.display='none';
	refresh();
}



function acLookupClientName(controlObj, objOffset)
{
	var outputBox = document.getElementById('clientList');
	
	if(controlObj.value != null && controlObj.value.length > 0)
	{
		var nameEntered = controlObj.value;

		if(nameEntered == '' || nameEntered.length < 1)
		{
			document.getElementById('clientList').innerHTML = "";
		}
		
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				var clientSearch = JSON.parse(xmlHttp.responseText);

				var nameArray = clientSearch.clientMasterList;
				//=====
				var divContents = "";
				for(var x = 0 ; x < nameArray.length ; x++)
				{
					divContents += '<div style="border-bottom: 1px gray solid; padding-left: 20px;" class="pd5">';
					divContents += 	'<a href="#" onclick="addClient('+ nameArray[x].clientId + '); return false;" class="bold">' + nameArray[x].firstName + ' ' + nameArray[x].lastName + '</a>';
					divContents +=  '<br/>' + nameArray[x].emailAddress;
					divContents += '</div>';
				}
				if (nameArray.length == 0)
				{
					divContents = "<strong>No clients found</strong>";
				}
				
				outputBox.innerHTML = divContents;
				//++
			}
		};

		if(nameEntered != '')
		{
			xmlHttp.open('GET', '/client/ClientJson_Search.action?name=' + escape(nameEntered) + '&limit=5' + '&time=' + (new Date().getTime()), true);
			xmlHttp.send(null);
		}
		document.getElementById('addNewClientLink').style.display = 'block';
		document.getElementById('helpText').style.display='none';
	}else{
		document.getElementById('clientList').innerHTML = "";
		//document.getElementById('addNewClientLink').style.display = 'none';
		document.getElementById('helpText').style.display='block';
	}
}

function refresh()
{
	var htmlString = clients.asHTML();
	document.getElementById('clientIds').value = clients.toString();
	document.getElementById('clientIdsTwo').value = clients.toString();
	if (htmlString == null || htmlString == '') 
	{
		document.getElementById('attachedClientList').innerHTML = "No clients attached";
		document.getElementById('submitButton').style.display='none';
	}
	else
	{
		document.getElementById('attachedClientList').innerHTML = htmlString;
		document.getElementById('submitButton').style.display='inline';
	}
}

function acRemoveClient(clientId)
{
	clients.remove(clientId);
	refresh();
}

function addClient(clientId)
{
	var attachedClientOut = document.getElementById('attachedClientList');
	var hiddenInput = document.getElementById('clientIds');

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonString = '{firstName":"Barry"}';

			var jsonResults = JSON.parse(xmlHttp.responseText);

			if (jsonResults && jsonResults.clientMaster)
			{
				clientResults = jsonResults.clientMaster;
			}
			
			var firstName;
			var lastName;
			
			var clientMaster = new ClientMaster();

			clientMaster.clientId = clientId;
			if (clientResults.firstName) { clientMaster.firstName = clientResults.firstName; }
			if (clientResults.lastName) { clientMaster.lastName = clientResults.lastName; }
//			if (clientResults.middleName) { middleName.innerHTML = clientResults.middleName; }
			if (clientResults.emailAddress) { clientMaster.emailAddress = clientResults.emailAddress; }
			
			clients.add(clientMaster);
			if (document.getElementById("actionMessageAlerts")) 
			{
				actionMessageContainer = document.getElementById("actionMessageAlerts");
				actionMessageContainer.innerHTML = "<div style='margin-left: 25px;'>Client added.  You can add additional clients, or click \"Continue\" to proceed.</div>";
				
				actionMessageContainer.style.display = 'block';
			}
			document.getElementById('clientList').innerHTML = "";
			document.getElementById('client-1').value = "";
			document.getElementById('helpText').style.display='block';
			refresh();
		}
	};

	if (!clientId)
	{
		var clientId = 0;
	}
	
	if(clientId > 0)
	{
		xmlHttp.open('GET', '/listing/AddListingClient_DetailJSON.action?clientId=' + escape(clientId) + '&time=' + (new Date().getTime()), true);
		xmlHttp.send(null);
	} else 
	{
		
	}
	
}


function returnToSearch()
{
	var outputBox = document.getElementById('clientDisplay');
	var firstName = document.getElementById('client_firstName');
	var lastName = document.getElementById('client_lastName');
	var middleName = document.getElementById('client_middleName');
	var emailAddress = document.getElementById('client_emailAddress');
	var homeNumber = document.getElementById('client_homeNumber');
	var smsNumber = document.getElementById('client_smsNumber');
	var faxNumber = document.getElementById('client_faxNumber');
	var officeNumber = document.getElementById('client_officeNumber');
	var address01 = document.getElementById('client_address01');
	var addressSuite = document.getElementById('client_addressSuite');
	var address02 = document.getElementById('client_address02');
	var addressCity = document.getElementById('client_addressCity');
	var addressState = document.getElementById('client_addressState');
	var addressZip = document.getElementById('client_addressZipcode');
	
	firstName.innerHTML = "";
	lastName.innerHTML = "";
	middleName.innerHTML = "";
	emailAddress.innerHTML = "";
	homeNumber.innerHTML = "";
	smsNumber.innerHTML = "";
	faxNumber.innerHTML = "";
	officeNumber.innerHTML = "";
	address01.innerHTML = "";
	addressSuite.innerHTML = "";
	address02.innerHTML = "";
	addressCity.innerHTML = "";
	addressState.innerHTML = "";
	addressZip.innerHTML = "";

	
	document.getElementById("searchDisplay").style.display='block';
	document.getElementById("resultsDisplay").style.display='none';
	//document.getElementById('clientList').innerHTML = "";
	//document.getElementById("client-1").value="";
	document.getElementById("client-1").focus();
}



function submitNewClient(inputFormId, baseSubmitUrl, divToCloseId)
{
	if (!document.getElementById(inputFormId))
	{
		alert('JavaScript Error');
		return false;
	}

	form = document.getElementById(inputFormId);
	allElements = form.elements;
	
	requestUrl = baseSubmitUrl + "?";
	
	for (i=0; i<allElements.length; i++)
	{
		if (allElements[i].name.length > 0 && allElements[i].name != 'action') {
			var value = allElements[i].value;
			value = value.replace("+", "%2B");
			requestUrl += allElements[i].name + "=" + value + "&";
		}
	}

	
	connection = ajaxFunction();
	
	connection.onreadystatechange=function()
	{

		if(connection.readyState==4)
		{
			var results = connection.responseText;
			//alert(results);
			try{
				var fieldResults = JSON.parse(connection.responseText);
				if(fieldResults.success=="false")
				{
					if (fieldResults.error != null)
					{
						alert(fieldResults.error);
					}
					var fieldArray = fieldResults.fieldError;
					
					for (i=0; i<fieldArray.length; i++)
					{
						if (document.getElementById("errorFor_" + fieldArray[i].name))
						{
							document.getElementById("errorFor_" + fieldArray[i].name).innerHTML = fieldArray[i].error;
						}
					}
				}
				else
				{
					closeModalPopup(divToCloseId);
					var clientId = fieldResults.clientId;
					addClient(clientId);
					if (document.getElementById('originalClientIds')) {
						var orig = document.getElementById('originalClientIds');
						if (orig.value == null || orig.value == '')
						{
							orig.value = clientId;
						}
						else
						{
							orig.value += "-" + clientId;
						}
						//alert(orig.value);
					}
					if (document.getElementById('originalClientIdsTwo')) {
						var orig = document.getElementById('originalClientIdsTwo');
						if (orig.value == null || orig.value == '')
						{
							orig.value = clientId;
						}
						else
						{
							orig.value += "-" + clientId;
						}
					}
					refresh();
				}
			}catch (Exception) {
				alert("JSON parse error");
			}
		}
	};
	connection.open('GET', requestUrl, true);
	connection.send(null);
}

// ------------------ addClient.js - ENDS ------------------- //


// ------------------ reminders.js - STARTS ------------------- //

function submitReminder(inputFormId, action) {
	if (!document.getElementById(inputFormId))
	{
		alert('fail');
		return false;
	}

	form = document.getElementById(inputFormId);
	allElements = form.elements;
	
	requestUrl = "/user/AddReminder_JSON.action?";
	
	for (i=0; i<allElements.length; i++)
	{
		if (allElements[i].name.length > 0 && allElements[i].name != 'action') {
			if (allElements[i].value.length > 0 && (allElements[i].type == null || allElements[i].type != 'checkbox')) 
			{
				requestUrl += allElements[i].name + "=" + allElements[i].value + "&";
			} 
			else if (allElements[i].type != null && allElements[i].type == 'checkbox' && allElements[i].checked == true)
			{
				requestUrl += allElements[i].name + "=" + 'true' + "&";
			}
		}
	}
	
	requestUrl += "action=" + action;
	
	connection = ajaxFunction();
	
	connection.onreadystatechange=function()
	{

		if(connection.readyState==4)
		{
			var results = connection.responseText;
			
			var fieldResults = new Object;
			fieldResults.success = null;

			try
			{
				var fieldResults = JSON.parse(connection.responseText);
			}
			catch(e)
			{
			}
			
			if(fieldResults.success != null)
			{
				if (fieldResults.success=="false")
				{
					if (fieldResults.error != null)
					{
						alert(fieldResults.error);
					}
					var fieldArray = fieldResults.fieldError;
					
					for (i=0; i<fieldArray.length; i++)
					{
						if (document.getElementById("errorFor_" + fieldArray[i].name))
						{
							document.getElementById("errorFor_" + fieldArray[i].name).innerHTML = fieldArray[i].error;
						}
					}
				}
				else
				{
					closeModalPopup('reminderPopupDiv');
					if (document.getElementById('noteReminderPopupDiv'))
					{
						closeModalPopup('noteReminderPopupDiv');
					}
//					document.getElementById("reminderPopupDiv").style.display='none';
//					document.getElementById("reminderAddedPopupDiv").style.display='block';
//					document.getElementById('reminderMessage').innerHTML = fieldResults.successString;
				}
			}
			else
			{
			}
		}
	};
	
	connection.open('GET', requestUrl, true);
	connection.send(null);
}

function submitClientReminder(inputFormId, action) {
	if (!document.getElementById(inputFormId))
	{
		alert('fail');
		return false;
	}

	form = document.getElementById(inputFormId);
	allElements = form.elements;
	
	requestUrl = "/client/EditClientReminder_JSON.action?";
	
	for (i=0; i<allElements.length; i++)
	{
		if (allElements[i].name.length > 0 && allElements[i].name != 'action') {
			if (allElements[i].value.length > 0 && (allElements[i].type == null || allElements[i].type != 'checkbox')) 
			{
				requestUrl += allElements[i].name + "=" + allElements[i].value + "&";
			} 
			else if (allElements[i].type != null && allElements[i].type == 'checkbox' && allElements[i].checked == true)
			{
				requestUrl += allElements[i].name + "=" + 'true' + "&";
			}
		}
	}
	
	requestUrl += "action=" + action;
	
	connection = ajaxFunction();
	
	connection.onreadystatechange=function()
	{

		if(connection.readyState==4)
		{
			var results = connection.responseText;
			var fieldResults = JSON.parse(connection.responseText);

			if(fieldResults.success=="false")
			{
				if (fieldResults.error != null)
				{
					alert(fieldResults.error);
				}
				var fieldArray = fieldResults.fieldError;
				
				for (i=0; i<fieldArray.length; i++)
				{
					if (document.getElementById("errorFor_" + fieldArray[i].name))
					{
						document.getElementById("errorFor_" + fieldArray[i].name).innerHTML = fieldArray[i].error;
					}
				}
			}
			else
			{
				closeModalPopup('reminderPopupDiv');
				var here = window.location.href.replace("addReminder=true", "");
				window.location.href = here;
				window.location.reload();
				history.go(0);
//				document.getElementById("reminderPopupDiv").style.display='none';
//				document.getElementById("reminderAddedPopupDiv").style.display='block';
//				document.getElementById('reminderMessage').innerHTML = fieldResults.successString;
			}
		}
	};

	connection.open('GET', requestUrl, true);
	connection.send(null);
}

function submitNoteReminder(inputFormId, action) {
	if (!document.getElementById(inputFormId))
	{
		alert('fail');
		return false;
	}

	form = document.getElementById(inputFormId);
	allElements = form.elements;
	
	requestUrl = "/client/EditNoteReminder_JSON.action?";
	
	for (i=0; i<allElements.length; i++)
	{
		if (allElements[i].name.length > 0 && allElements[i].name != 'action') {
			if (allElements[i].value.length > 0 && (allElements[i].type == null || allElements[i].type != 'checkbox')) 
			{
				requestUrl += allElements[i].name + "=" + escape(allElements[i].value) + "&";
			} 
			else if (allElements[i].type != null && allElements[i].type == 'checkbox' && allElements[i].checked == true)
			{
				requestUrl += allElements[i].name + "=" + 'true' + "&";
			}
		}
	}
	
	requestUrl += "action=" + action;
	
//	alert(requestUrl);
	
	connection = ajaxFunction();
	
	connection.onreadystatechange=function()
	{

		if(connection.readyState==4)
		{
			var results = connection.responseText;
//			alert(results);
			var fieldResults = JSON.parse(connection.responseText);
			if(fieldResults.success=="false")
			{
				if (fieldResults.error != null)
				{
					alert(fieldResults.error);
				}
				var fieldArray = fieldResults.fieldError;
				
				for (i=0; i<fieldArray.length; i++)
				{
					if (document.getElementById("errorFor_" + fieldArray[i].name))
					{
						document.getElementById("errorFor_" + fieldArray[i].name).innerHTML = fieldArray[i].error;
					}
				}
			}
			else
			{
				closeModalPopup('reminderPopupDiv');
				window.location.reload();
				history.go(0);
//				document.getElementById("reminderPopupDiv").style.display='none';
//				document.getElementById("reminderAddedPopupDiv").style.display='block';
//				document.getElementById('reminderMessage').innerHTML = fieldResults.successString;
			}
		}
	};

	connection.open('GET', requestUrl, true);
	connection.send(null);
}


function submitClientNote(inputFormId, action) {
	if (!document.getElementById(inputFormId))
	{
		alert('fail');
		return false;
	}

	form = document.getElementById(inputFormId);
	allElements = form.elements;
	
	requestUrl = "/client/EditNote_JSON.action?";
	
	for (i=0; i<allElements.length; i++)
	{
		if (allElements[i].name.length > 0 && allElements[i].name != 'action') {
			requestUrl += allElements[i].name + "=" + allElements[i].value + "&";
		}
	}
	
	requestUrl += "action=" + action;
	
	connection = ajaxFunction();
	
	connection.onreadystatechange=function()
	{

		if(connection.readyState==4)
		{
			var results = connection.responseText;
			var fieldResults = JSON.parse(connection.responseText);
			if(fieldResults.success=="false")
			{
				if (fieldResults.error != null)
				{
					alert(fieldResults.error);
				}
				var fieldArray = fieldResults.fieldError;
				
				for (i=0; i<fieldArray.length; i++)
				{
					if (document.getElementById("errorFor_" + fieldArray[i].name))
					{
						document.getElementById("errorFor_" + fieldArray[i].name).innerHTML = fieldArray[i].error;
					}
				}
			}
			else
			{
				closeModalPopup('notePopupDiv');
				window.location.reload();
				history.go(0);
				
//				document.getElementById("notePopupDiv").style.display='none';
//				document.getElementById("noteAddedPopupDiv").style.display='block';
//				document.getElementById('noteMessage').innerHTML = fieldResults.successString;
			}
		}
	};

	connection.open('GET', requestUrl, true);
	connection.send(null);
}



function submitSmsChange(inputFormId, action) {
	if (!document.getElementById(inputFormId))
	{
		alert('fail');
		return false;
	}

	form = document.getElementById(inputFormId);
	allElements = form.elements;
	
	requestUrl = "/user/ChangeSms_SubmitJSON.action?";
	
	for (i=0; i<allElements.length; i++)
	{
		if (allElements[i].name.length > 0 && allElements[i].name != 'action') {
			requestUrl += allElements[i].name + "=" + allElements[i].value + "&";
		}
	}
	
	requestUrl += "action=" + action;
	
	connection = ajaxFunction();
	
	connection.onreadystatechange=function()
	{

		if(connection.readyState==4)
		{
			var results = connection.responseText;
			var fieldResults = JSON.parse(connection.responseText);

			if(fieldResults.success=="false")
			{
				if (fieldResults.error != null)
				{
					alert(fieldResults.error);
				}
				var fieldArray = fieldResults.fieldError;
				
				for (i=0; i<fieldArray.length; i++)
				{
					if (document.getElementById("errorFor_" + fieldArray[i].name))
					{
						document.getElementById("errorFor_" + fieldArray[i].name).innerHTML = fieldArray[i].error;
					}
				}
			}
			else
			{
				closeModalPopup('changeSmsDiv');
				var here = window.location.href;
				window.location.href = here;
				window.location.reload();
				history.go(0);
			}
		}
	};

	connection.open('GET', requestUrl, true);
	connection.send(null);
}


function jsonTest() {}

function openSmsWindow()
{
	chileWindow=open('/user/ChangeSms.action', 'changeSmsNumber', 'height=200,width=400');
}

function openCalendarWindow()
{
	chileWindow=open('/user/ChangeCalendar.action', 'Change Calendar', 'height=200,width=400');
}

// ------------------ reminders.js - ENDS ------------------- //

// ------------------ property.js - STARTS ------------------- //

function lookupPropertiesDelayed(delayMs)
{
	if(timer != null)
	{
		clearTimeout(timer);
	}
	timer = setTimeout('lookupProperties()', delayMs);
}

function lookupProperties()
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			document.getElementById('propertyBox').innerHTML = xmlHttp.responseText;
		}
	}

	var agentId = document.getElementById('agentId').value;
	var addressNumber = document.getElementById('addressNumber').value;
	var addressStreet = document.getElementById('addressStreet').value;
	var addressCity = document.getElementById('addressCity').value;
	var addressState = document.getElementById('addressState').value;
	var addressZipcode = document.getElementById('addressZipcode').value;
	
	xmlHttp.open('GET', '/property/PropertyList_SearchFrag.action?agentId=' + agentId + '&addressNumber=' + addressNumber + '&addressStreet=' + addressStreet + '&addressCity=' + addressCity + '&addressState=' + addressState + '&addressZipcode=' + addressZipcode + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function openDisplayName(offerId)
{
	document.getElementById('nickname_' + offerId).style.display = 'inline';
	document.getElementById('nicknameText_' + offerId).style.display = 'none';
}

function updatePropertyName(textBox, event)
{
	var key = '';
	if (document.all) //Checks for IE 4.0 or later
	{
		key = event.keyCode;
	}
	else if (document.getElementById) //checks for Netscape 6 or later
	{
		key = key_event.which;
	}
	else if (document.layers) //Checks for Netscape 4
	{
		key = key_event.which;
	}

	if(key == 13)
	{
		updatePropertyDisplayName(textBox.id, textBox.value);
	}
}

function updatePropertyDisplayName(id, value)
{
	var offerId = id.substr(id.search('_') + 1);

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var jsonResults = JSON.parse(xmlHttp.responseText);
			if(jsonResults.status == 'OK')
			{
				document.getElementById('nickname_' + offerId).style.display = 'none';
				document.getElementById('nicknameText_' + offerId).style.display = 'inline';
				document.getElementById('nicknameText_' + offerId).innerHTML = value;
			}
		}
	}

	xmlHttp.open('GET', '/contract/UpdateOfferName.action?offerId=' + offerId + '&name=' + escape(value) + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

// ------------------ property.js - ENDS ------------------- //

// ------------------ foundation.js - STARTS ------------------- //

function populateBrokerageSelect(selectId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var selectObject = document.getElementById(selectId);

			clearSelectOptions(selectObject);
			addSelectOption(selectObject, optionValue, optionText);
		}
	}

	xmlHttp.open('GET', '/foundation/BrokerageList_SearchJSON.action?time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function populateOfficeSelect(brokerageId, selectId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var selectObject = document.getElementById(selectId);

			clearSelectOptions(selectObject);

			var results = JSON.parse(xmlHttp.responseText);

			if(results.status == 'OK')
			{
				var officeMasterList = results.officeMasterList;

				for(var x = 0 ; x < officeMasterList.length ; x++)
				{
					addSelectOption(selectObject, officeMasterList[x].officeId, officeMasterList[x].name);
				}
			}
		}
	}

	xmlHttp.open('GET', '/foundation/OfficeList_SearchJSON.action?brokerageId=' + brokerageId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function saveEmailAddress()
{
	var emailAddress = document.getElementById('emailAddress').value;
	
	if(emailAddress != undefined && emailAddress != '')
	{
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				document.getElementById('emailListDiv').innerHTML = xmlHttp.responseText;
			}
		}
		xmlHttp.open('GET', '/user/ContactInformation_EmailSaveFrag.action?emailAddress=' + escape(emailAddress) + '&time=' + (new Date().getTime()), true);
		xmlHttp.send(null);
	}
}

function deleteEmailAddress(emailId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			document.getElementById('emailListDiv').innerHTML = xmlHttp.responseText;
		}
	}

	xmlHttp.open('GET', '/user/ContactInformation_EmailDeleteFrag.action?emailId=' + emailId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}




function saveAgentTelephone()
{
	var telephoneNumber = document.getElementById('telephoneNumber').value;

	if(telephoneNumber != undefined && telephoneNumber != '')
	{
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				document.getElementById('telephoneListDiv').innerHTML = xmlHttp.responseText;
			}
		}

		xmlHttp.open('GET', '/user/ContactInformation_TelephoneSaveFrag.action?telephoneNumber=' + escape(telephoneNumber) + '&time=' + (new Date().getTime()), true);
		xmlHttp.send(null);
	}
}

function deleteAgentTelephone(telephoneId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			document.getElementById('telephoneListDiv').innerHTML = xmlHttp.responseText;
		}
	}

	xmlHttp.open('GET', '/user/ContactInformation_TelephoneDeleteFrag.action?telephoneId=' + telephoneId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function saveAgentFax()
{
	var telephoneNumber = document.getElementById('faxNumber').value;

	if(telephoneNumber != undefined && telephoneNumber != '')
	{
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				document.getElementById('faxListDiv').innerHTML = xmlHttp.responseText;
			}
		}

		xmlHttp.open('GET', '/user/ContactInformation_FaxSaveFrag.action?telephoneNumber=' + escape(telephoneNumber) + '&time=' + (new Date().getTime()), true);
		xmlHttp.send(null);
	}
}

function deleteAgentFax(telephoneId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			document.getElementById('faxListDiv').innerHTML = xmlHttp.responseText;
		}
	}

	xmlHttp.open('GET', '/user/ContactInformation_FaxDeleteFrag.action?telephoneId=' + telephoneId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function saveAgentMobile()
{
	var telephoneNumber = document.getElementById('mobileNumber').value;

	if(telephoneNumber != undefined && telephoneNumber != '')
	{
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				document.getElementById('mobileListDiv').innerHTML = xmlHttp.responseText;
			}
		}

		xmlHttp.open('GET', '/user/ContactInformation_MobileSaveFrag.action?telephoneNumber=' + escape(telephoneNumber) + '&time=' + (new Date().getTime()), true);
		xmlHttp.send(null);
	}
}

function deleteAgentMobile(telephoneId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			document.getElementById('mobileListDiv').innerHTML = xmlHttp.responseText;
		}
	}

	xmlHttp.open('GET', '/user/ContactInformation_MobileDeleteFrag.action?telephoneId=' + telephoneId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

function saveAgentWebsite()
{
	var website = document.getElementById('website').value;

	if(website != undefined && website != '')
	{
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				document.getElementById('websiteListDiv').innerHTML = xmlHttp.responseText;
			}
		}

		xmlHttp.open('GET', '/user/ContactInformation_WebsiteSaveFrag.action?website=' + encodeURI(website) + '&time=' + (new Date().getTime()), true);
		xmlHttp.send(null);
	}
}

function deleteAgentWebsite(websiteId)
{
	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			document.getElementById('websiteListDiv').innerHTML = xmlHttp.responseText;
		}
	}

	xmlHttp.open('GET', '/user/ContactInformation_WebsiteDeleteFrag.action?websiteId=' + websiteId + '&time=' + (new Date().getTime()), true);
	xmlHttp.send(null);
}

// ------------------ foundation.js - ENDS ------------------- //


// ------------------ agentDashboard.js - STARTS ------------------- //

function rowMouseOver() { }
function rowMouseOut() { }
function linkMouseOver() { }
function linkMouseOut() { }

function lookupClientName(controlObj, objOffset)
{
	var outputBox = document.getElementById('clientList');
	
	if(controlObj.value != null && controlObj.value.length > 0)
	{
		var nameEntered = controlObj.value;

		if(nameEntered == '' || nameEntered.length < 1)
		{
			document.getElementById('clientList').innerHTML = "";
		}
		
		var xmlHttp = ajaxFunction();

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				var clientSearch = JSON.parse(xmlHttp.responseText);

				var nameArray = clientSearch.clientList;
				//=====
				var divContents = "";
				for(var x = 0 ; x < nameArray.length ; x++)
				{
					divContents += '<a href="#" onclick="getClientInfo('+ nameArray[x].clientId + '); return false;"><div>' + nameArray[x].firstName + ' ' + nameArray[x].lastName + '</div></a>';
				}
				if (nameArray.length == 0)
				{
					divContents = "<strong>No clients found</strong>";
				}
				
				outputBox.innerHTML = divContents;
				//++
			}
		};

		if(nameEntered != '')
		{
			xmlHttp.open('GET', '/client/ClientList_Json.action?name=' + escape(nameEntered) + '&limit=5' + '&time=' + (new Date().getTime()), true);
			xmlHttp.send(null);
		}
		document.getElementById('searchHelpText').style.display = 'none';
	}else{
		document.getElementById('clientList').innerHTML = "";
		document.getElementById('searchHelpText').style.display = 'block';
	}
}

function getClientInfo(clientId)
{
	var outputBox = document.getElementById('clientDisplay');
	var firstName = document.getElementById('client_firstName');
	var lastName = document.getElementById('client_lastName');
	var middleName = document.getElementById('client_middleName');
	var emailAddress = document.getElementById('client_emailAddress');
	var homeNumber = document.getElementById('client_homeNumber');
	var smsNumber = document.getElementById('client_smsNumber');
	var faxNumber = document.getElementById('client_faxNumber');
	var officeNumber = document.getElementById('client_officeNumber');
	var address01 = document.getElementById('client_address01');
	var addressSuite = document.getElementById('client_addressSuite');
	var address02 = document.getElementById('client_address02');
	var addressCity = document.getElementById('client_addressCity');
	var addressState = document.getElementById('client_addressState');
	var addressZip = document.getElementById('client_addressZipcode');
	
	firstName.innerHTML = "";
	lastName.innerHTML = "";
	middleName.innerHTML = "";
	emailAddress.innerHTML = "";
	homeNumber.innerHTML = "";
	smsNumber.innerHTML = "";
	faxNumber.innerHTML = "";
	officeNumber.innerHTML = "";
	address01.innerHTML = "";
	addressSuite.innerHTML = "";
	address02.innerHTML = "";
	addressCity.innerHTML = "";
	addressState.innerHTML = "";
	addressZip.innerHTML = "";

	var xmlHttp = ajaxFunction();

	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var clientResults = JSON.parse(xmlHttp.responseText);


			//alert(addressState.emailAddress);

			if (clientResults.firstName) { firstName.innerHTML = clientResults.firstName; }
			if (clientResults.lastName) { lastName.innerHTML = clientResults.lastName; }
			if (clientResults.middleName) { middleName.innerHTML = clientResults.middleName; }
			if (clientResults.emailAddress) { emailAddress.innerHTML = clientResults.emailAddress; }
			if (clientResults.homeNumber) { 
				homeNumber.innerHTML = clientResults.homeNumber; 
				document.getElementById("label_homeNumber").style.display = 'block';
			} else {
				document.getElementById("label_homeNumber").style.display = 'none';
			}
			if (clientResults.smsNumber) { 
				smsNumber.innerHTML = clientResults.smsNumber; 
				document.getElementById("label_smsNumber").style.display = 'block';
			} else {
				document.getElementById("label_smsNumber").style.display = 'none';
			}
			if (clientResults.faxNumber) { 
				faxNumber.innerHTML = clientResults.faxNumber; 
				document.getElementById("label_faxNumber").style.display = 'block';
			} else {
				document.getElementById("label_faxNumber").style.display = 'none';
			}
			if (clientResults.officeNumber) { 
				officeNumber.innerHTML = clientResults.officeNumber; 
				document.getElementById("label_officeNumber").style.display = 'block';
			} else {
				document.getElementById("label_officeNumber").style.display = 'none';
			}
			if (clientResults.address01) { address01.innerHTML = clientResults.address01; }
			if (clientResults.addressSuite) { addressSuite.innerHTML = clientResults.addressSuite; }
			if (clientResults.address02) { address02.innerHTML = clientResults.address02; }
			if (clientResults.addressCity) { addressCity.innerHTML = clientResults.addressCity; }
			if (clientResults.addressState) { addressState.innerHTML = clientResults.addressState; }
			if (clientResults.addressZip) { addressZip.innerHTML = clientResults.addressZip; }

			document.getElementById('editClientLink').href = '/client/EditClient.action?clientId=' + clientId;
			document.getElementById("searchDisplay").style.display='none';
			document.getElementById("resultsDisplay").style.display='block';
			
			

			//alert('end');

		}
	};

	if(clientId)
	{
		xmlHttp.open('GET', '/client/ClientDetail_JSON.action?clientId=' + escape(clientId), true);
		xmlHttp.send(null);
	}
	
}

// ------------------ agentDashboard.js - ENDS ------------------- //
