

// ****************************************************
// *****************  Table Object  *******************
// ****************************************************

// sorted column arrows
var upArrow = new Image;
upArrow.src="img/bgSortableHeadArrowUp.gif";
var dnArrow = new Image;
dnArrow.src="img/bgSortableHeadArrowDn.gif";
var noArrow = new Image;
noArrow.src="img/bgSortableHeadArrowNo.gif";

var nDefaultLetterTabNum = 11;
var sDefaultColumnSort = "FirstName";

var table = new Array;
function TableObject(obj, type, xTblConfig)
{
	this.type = type;
	this.curSort = xTblConfig.getAttribute('curSort');
	this.prevSort = this.curSort;
	this.curName =  xTblConfig.getAttribute('curName');
	this.prevSortIndex = 0;
	var aHeads = xTblConfig.selectNodes('head'), i=0;
	while (aHeads[i])
	{
		if (aHeads[i].getAttribute('sort1')== this.curSort)
			this.curSortIndex = i;
		i++;
	}
	this.sortAscend			= parseFloat(xTblConfig.getAttribute('sortAscend'));
	this.curDisplayIndex 	= xTblConfig.getAttribute('curDisplayIndex');
	this.curFilterProperty 	= xTblConfig.getAttribute('curFilterProp');
	this.curFilterValue		= xTblConfig.getAttribute('curFilterValue');
	this.node = obj;
	this.head = obj.children['tableHeadRow'];
	if (obj.children['tableHeadRow'])
		this.head.onmousedown = HandleMousedown;

	this.body = obj.children['tableBody'];
	this.footer = obj.children['tableFooter'];
	if (obj.children['tableFooter'])
	{
		this.footer.onmousedown = HandleMousedown;
		if (obj.children['tableFooter'].children['tabs'])
			this.tabs = obj.children['tableFooter'].children['tabs'].children;
	}
	this.resized = false;
	this.refresh = SortXML;
}

function GetCellStyle(type)
{
	var style_rules = "width:{0}%";
	if (type!='DV' && type!='CS')
		style_rules+= ";height:20px;overflow-y:hidden;vertical-align:middle";
	else
		style_rules+= ";vertical-align:top;margin-top:5px";
	return style_rules;
}

function BuildTable(type)
{
	var c="", i=0;
	var xTblConfig = GetTableConfig(type);//returns a pointer to the table/tbl
	var aHeadCells = (xTblConfig) ? xTblConfig.selectNodes("head") : 0;
	var oStyleSheet = document.styleSheets("GlobalStyles");
	while (aHeadCells[i])
	{
		var selector_name = "SPAN.cell"+type+i;
		var index = GetStyleSheetIndex(selector_name);
		var style_rules = Insert(aHeadCells[i].getAttribute('width') , GetCellStyle(type))
		if (index)
			oStyleSheet.rules[index].style.cssText = style_rules;
		else
			oStyleSheet.addRule(selector_name, style_rules);
		i++;
	}
	c += "<div id='tableHeadRow' class='tableHeadRow'></div>";
	
	c += "<div id='tableBody' class='tableBody'";
	if (type=="GPAB")
		c += " style='height:205px;float:left;width:85%;' ";
	c += "></div>";

//  *** Remove Vertical Resize function on Content area ***
//	var m = BuildFooter(GetFooterCode(type), type, eval(xTblConfig.getAttribute("heightResizeable")), xTblConfig.getAttribute("footerLayout"));
	var m = BuildFooter(GetFooterCode(type), type, false, xTblConfig.getAttribute("footerLayout"));

	var tbl = getObj("table"+type);
	tbl.innerHTML = c+m;
	table[type] = new TableObject(tbl, type, xTblConfig);

//	if (type=="RR" || type=="DV")
//	{
//		table[type].body.style.height="285px";	
//	}
//	else if (type=="CS" || type=="MS" || type=="CG" || type=="CL")
//		table[type].body.style.height="335px";	
//	else if( type=="GT")
//	else 
//		table[type].body.style.height="205px";
	switch(type)
	{
		case "CS":
		case "MS":
		case "CG":
		case "CL": table[type].body.style.height="335px";break;
		case "RR": table[type].body.style.height="285px";break;
		case "DV": table[type].body.style.height="265px";break;	
		case "GT": table[type].body.style.height="230px";break;	
		default  : table[type].body.style.height="285px";break;
		
	}

	
	if (aHeadCells.length>0)
		tbl.children["tableHeadRow"].innerHTML = BuildHeadRow(type, xTblConfig);
	if(type != "DV")
		SetButtons(type);
	table[type].refresh();
}


function SetButtons(id, xpath)
{	
	if (id=='GPLS'||id=='GPAB')
		return;
	var sBtnCode = '', obj;
	switch (id)
	{		
		case 'MS':	xpath = (!oMsgNode.selectSingleNode('MSG_WAITING[Mailbox=""]') && !oMsgNode.selectSingleNode('SYSTEM_MESSAGE')) ? '(@method!="DeleteHighlightedRows(#)")' : ''; break;
			
		case 'NAUN':
		case 'NAPI':
		case 'NADV':
		case 'NACS': id='NA'; break;
	}
	if (id)
		sBtnCode = GetButtonCode(id, xpath)
	
	// if a synch operation is in progress - reset the id to use ABEX to find the buttons div
	switch (id)
	{
		case 'SYSO':
		case 'SYCF':
		case 'SYCS':
		case 'SYAS':  
		case 'SYRE':
		case 'SYPB': id='CT'; break;
		case 'RREDWO':
		case 'RREDWA':
		case 'RREDWE':
		case 'RREDWASA': id='RL';break;
	}
	obj = getObj(id);
		
	// this walks down from the current section object to find the buttons div - only use if !bReadOnly - otherwise use the id for the tab
	if (!obj || (obj && !obj.children['buttons']))
		obj = getObj(id.substring(0,2));

	if (obj && obj.children && obj.children['buttons'])
	{	
		obj = obj;
	}
	// this walks up from a table or tab id
	else
	{
		obj = getObj('table'+id);
		while (obj && (!obj.children || (obj.children && !obj.children['buttons'])))
			obj = obj.parentElement;
	}

	if (obj)
		obj.children['buttons'].innerHTML = sBtnCode;
}

function GetButtonCode(obj_id, opt_xpath)
{
	var x='', x_path='buttons/button[@for="'+obj_id+'"';
	if(obj_id == "CB")											//don't show lower content function button area on Collaborate Tab
		return x;
	if (opt_xpath)
	{
		x_path += ' and '+ opt_xpath;
	/*	if (node.indexOf('not(')==0)
			x_path += node;
		else
			x_path += '$any$ '+node+'="'+value+'"';
	*/
	}
	x_path += ']';
	var btnNodes = oObjConfig.selectNodes(x_path);
	var i=0;
	
	x+= "<div class='button_container'>";
	x+= "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	
	while (btnNodes[i])
	{
		x+= MakeButton(btnNodes[i].getAttribute('img'), btnNodes[i].getAttribute('text'), btnNodes[i].getAttribute('method').replace('#', '\"'+obj_id+'\"'), '', btnNodes[i].getAttribute('key'));
		i++;
	}	
	
	x += "</div>";
	return x;
}


function GetFooterCode(type)
{
	var x='';
	if (type=='AB')
		x+= MakeTableFilterSelect(type);
	if (type=='AB' || type=='GPAB' || type=='DSRS')
		x+= MakeLetterFilterTabs(type);
	if (type=='DV')
	{
		x+= "<div id=\"dv_add_form\" class=\"footer_form\" style=\"display:none;\" onkeydown=\"HandleKeydown('device')\">";
		x+= 	"<div class=\"footer_form_title\">"+ text('DV/ADD') +" (+)</div>";
		x+= 	"<div>";
		x+= 		"<span style=\"width:30%\">"+ text('DV/NAME') +"<br/><input type=\"text\" id=\"add_device_name\" size=\"15\" maxlength=\""+ INPUT_LIMIT_64 +"\" /></span>";
		x+= 		"<span style=\"width:30%\">"+ text('DV/EXT') +"<br/><input type=\"text\" id=\"add_device_ext\" size=\"15\" maxlength=\""+ INPUT_LIMIT_64 +"\" /></span>";
		x+= 		"<span style=\"width:30%\">"+ text('DV/PASS') +"<br/><input type=\"password\" id=\"add_device_pass\" size=\"15\" maxlength=\""+ INPUT_LIMIT_64 +"\" /></span>";
		x+= 	"</div>";
		x+= 	"<div style=\"margin-top:10px\">";
		x+= 		MakeButton("iSave", text('BUTN/ADD'), "SaveDevice(1)", "", "A");
		x+= 		MakeButton("iClose", text('BUTN/CLO'), "ToggleDeviceForm(0)", "", "C");
		x+= 	"</div>";
		x+= "</div>";
		x+= "<div id=\"dv_feature_codes\" style=\"display:none;width:95%;padding:10px 0px 0px 10px;background-repeat:no-repeat;background-position:bottom right;\"></div>";
	}
	if (type=='GT')
	{
		x+= "<div id=\"GTFM\" class=\"footer_form\" style=\"display:none;height:10%\" onkeydown=\"HandleKeydown('greeting')\">"; //background-color:#eec;padding-bottom:20px;
		x+= 	"<div class=\"footer_form_title\"></div>";
		x+= 	"<div>"+text('GT/DES')+"<br/><input id=\"gt_description\"/></div>";
		x+= 	"<div style=\"margin-top:10px\">";
		x+= 		MakeButton("iSave", text('BUTN/SAVE'), "SaveGreeting()", "", "S");
		x+= 		MakeButton("iClose", text('BUTN/CLO'), "ToggleGreetingsForm(0)", "", "C");
		x+= 	"</div>";
		x+= "</div>";
	}
//	if (type=='RR')
//		x+= "<span style=\"width:100%;padding:0px 10px;color:#fff;\"><input type=\"checkbox\" id=\"rr_enabled_toggle\" onclick=\"SetAccountFlag('RoutingEnabled', this.checked)\" style=\"vertical-align:middle\"> "+text('RR/ENA_CKBX')+"</span>";
	return x;
}

/*function MakeCustomFooterElements(type)
{
	var x="";
	switch (type)
	{
	}
	return x;
}*/

function GetTableConfig(type)
{
	return oObjConfig.selectSingleNode("tables/tbl[@type='"+ type +"']");
}

function GetTabConfig(type)
{
	return oObjConfig.selectSingleNode("tabs/tab[@type='"+ type +"']");
}

function GetProcessConfig(sType)
{
	return oObjConfig.selectSingleNode("processes/process[@type='"+ sType +"']");
}

function BuildHeadRow(type, tblConfigNode)
{
	var x="", i=0;
	var style = "style='width:@%;{0}"+ ((type=="GPAB")?"background-color:#369;float:left;":"") +"'";
	var aHeadNodes = tblConfigNode.selectNodes("head");

	while (aHeadNodes[i])
	{
		var curProp =  aHeadNodes[i].getAttribute("sort1");
		var curString =  aHeadNodes[i].text;
		if (curString == "Name" && aHeadNodes[i].getAttribute("sort2"))
		{
			var tbl = table[type];
			curProp = tbl.curName;
			curString = FormatNameColumnHead(type, tbl.curName, tblConfigNode);
		}
		
		var width = aHeadNodes[i].getAttribute("width");
		if (type=="GPAB")
			width="101";
		
		x+= "<span class='"+((!aHeadNodes[i].getAttribute("sort1"))?"tableHeadNoSort":"tableHead")+"' ";
		
		var cur_style = Insert(((i==0) ? "background-image:none;" : ""), style);
		x+= cur_style.replace("@", width) +" cellindex='"+ i +"' type='"+ type +"'";
		if (curProp)
			x+= " propertyName='"+ curProp +"' onclick='BeginTableColumnSort()'";
		if (aHeadNodes[i].getAttribute("sort1"))
			x+= " title='"+ text('TBL/SORT_BY')+" "+aHeadNodes[i].text +"'";
		x+= ">";

		
		if (aHeadNodes[i].getAttribute("sort1") && aHeadNodes[i].text != "Name")
			x+= "<span id='sort_ind'></span>";

		x+= curString +"</span>";
		i++;
	}
	return x;
}

function FormatNameColumnHead(type, curNameProp, tblConfigNode)
{
	var sSortProp1 = tblConfigNode.selectSingleNode("head[.='Name']").getAttribute("sort1");
	var sSortProp2 = tblConfigNode.selectSingleNode("head[.='Name']").getAttribute("sort2");
	var curString = (curNameProp == sSortProp1) ? "First" : "Last";
	var altString = (curNameProp == sSortProp1) ? "Last" : "First";
	var sep = (curNameProp == sSortProp1) ? " " : ", ";
	var altProp = (curNameProp == sSortProp1) ? sSortProp2 : sSortProp1;
	var x="<span id='sort_ind'></span>";
			
	return x+= "Name ("+ curString + sep+ "<a href='javascript://' onclick='SwitchColumnPropertyName(\""+ altProp +"\", this);return false'>"+ altString +"</a>)";
}

function SwitchColumnPropertyName(sProp, oSpan)
{
	var oColHead = oSpan.parentElement;
	oColHead.propertyName = sProp;
	oColHead.click();
}

function BuildFooter(sFooterContent, type, bIsHeightResizeable, sFooterLayout)
{
	var x= "";
	if (sFooterContent || bIsHeightResizeable)
	{
//		var sVerticalLayoutStyle = (eval(sFooterLayout)) ? " style='margin:0px;width:14%;float:left;height:205px;border-top:none;display:inline;background-color:#69c;'" :""
		var sVerticalLayoutStyle = (eval(sFooterLayout)) ? " style='margin:0px;width:14%;float:left;height:205px;border-top:none;display:inline;background-color:#EFEFF7;'" :""
		x+= "<div id='tableFooter' class='tableFooter'" +sVerticalLayoutStyle+">";
		if (bIsHeightResizeable)
			x+= "<div class='corner' type='"+ type +"'></div>";
		x+= sFooterContent +"</div>";
	}
	return x;
}
/*
function GetWidth(num)
{
	var tblRows = getObj("tableBody").childNodes;
	return parseInt((tblRows.offsetWidth - 16)/4);
}
*/
var bReverse = false;
var lastclick = "0";

function BeginTableColumnSort()
{
	var clickObj = window.event.srcElement;
	if (!clickObj) // || clickObj.className == "resize"
		return false;
	while (clickObj.className != "tableHead")
		clickObj = clickObj.parentElement;
	
	var type = clickObj.type;
	var tblObj = table[type];
	
	// determine next sort
	var new_sort = clickObj.propertyName;
	if (!new_sort)
		return false;

	var prev_sort = tblObj.curSort;

	// if were resorting the current sort, reverse the direction
	var bSortAscend =  (tblObj.curSort && tblObj.curSort == new_sort) ? (1 - eval(tblObj.sortAscend)) : 1;
	
	if ((new_sort.indexOf('FirstName')==0 || new_sort.indexOf('LastName')==0) && 
		(type=='AB' || type=='TA' || type=='DSRS' || type=='GPAB' || type.indexOf('TARR')==0))
	{
		tblObj.curName = new_sort;
		clickObj.innerHTML = FormatNameColumnHead(type, tblObj.curName, GetTableConfig(type));
	}
	
	// update the table props for next time
	tblObj.curSort = new_sort;
	tblObj.prevSort = prev_sort;
	tblObj.prevSortIndex = tblObj.curSortIndex;
	tblObj.curSortIndex = clickObj.cellindex;
	tblObj.sortAscend = bSortAscend;

	var prefs = DelimitList(new Array(tblObj.curSort, tblObj.curSortIndex, tblObj.sortAscend, tblObj.curName));
	SaveDisplayPreference('TABLE', type, prefs);
	
	tblObj.refresh();
}


function SortXML()
{

	var type = this.type;
	var tbl=table[type], sort_mod="", oData = oSys, sSortString, order_by='';
	var cur_filter, sPropName, output='', label;
	
	switch (type)
	{
		case "AB":
		case "GPAB":
		cur_filter = BuildXMLFilterForTable(type, tbl.curDisplayIndex, tbl.curFilterProperty, tbl.curFilterValue);
		oABNode.setAttribute(('name'+type), tbl.curName);
		break;

		case "FCUSER":
		cur_filter = "R/NODES/NODE[NodeNameElements//NodeID='"+ getObj('dv_feature_codes').Node +"'][0]/FeatureCodes/FEATURE_CODE[Admin='FALSE']";
		sPropName = tbl.curSort;
		break;
		
		case "FCADMN":
		cur_filter = "R/NODES/NODE[NodeNameElements//NodeID='"+ getObj('dv_feature_codes').Node +"'][0]/FeatureCodes/FEATURE_CODE[Admin='TRUE']";
		sPropName = tbl.curSort;
		break;
		
		case "FCFAVS":
		cur_filter = "R/DEVICES/DEVICE[NodeID='"+ getObj('dv_feature_codes').Node +"' and Extension='"+getObj('dv_feature_codes').Extension+"']/FeatureCodeFavoritesList/LIST/*/FEATURE_CODE";
		sPropName = tbl.curSort;
		break;
		
		case "CG":
		cur_filter = "R/CALL_LOGS/CALLLOG";
		break;
		
		case "CL":
		cur_filter = "R";
		var selected_rows = GetHighlightedRows(table['CL'].body);
		break;
		
		case "CS":
		cur_filter = "R/COMPOSITES/COMPOSITE_STATUS";
		break;
		
		case "DV":
		cur_filter = "R";
		break;
		
		case "GPLS":
		cur_filter = "R/GROUPS/GROUP";
		break;
		
		case "GT":
		cur_filter = "R/GREETINGS/GREETING";
		break;
		
		case "MS":
		cur_filter = "R/MESSAGES/*";
		//sort_mod += "@";
		break;
		
		case "NADL":
		cur_filter = "R/SEARCH_RESULTS/NA/CONTACT";
		break;
		
		case "DSFM":
		cur_filter = "R";
		break;
		
		case "DSRS":
		case "TA":
		case "TARRWA":
		case "TARRWO":
		cur_filter = "R/SEARCH_RESULTS/"+type+"/CONTACT";
		oSearchNode.setAttribute(('name'+type), tbl.curName);
		break;
		
		case "RR":
		cur_filter = "R/RULES/RULE";
		break;
		
		case "RREDWA":
		cur_filter = "R/STEPS/STEP[@for='"+getObj('formRREDWA').curRule+"' and not(@deleted)]";
		break;
	}
	
	bSortAscend = tbl.sortAscend;
	sPropName = (tbl.curSort!=null)?tbl.curSort:'';
	sort_string = sort_mod+sPropName;

	var re = new RegExp(';', 'g');
	var op = (bSortAscend) ?"+":"-";
	var x = "<?xml version=\"1.0\"?>";
	x+= "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/TR/WD-xsl\">";
	x+= "<xsl:template match=\"/\">";
	
	switch (type)
	{
		// if sorting by name, add the other name as a secondary sort parameter
		case 'AB':
		case 'GPAB':
		case 'DSRS':
		case 'TA':
		case 'TARRWA':
		case 'TARRWO':
			order_by = op + sort_string;
			if (sPropName=='FirstName' || sPropName=='LastName')
				order_by += ((sPropName=='FirstName')? ';LastName;Company;LinkType': ';FirstName;Company;LinkType');
			order_by = order_by.replace(re, ';'+op);
			break;
			
		case 'RR':
		case 'GPLS':
			order_by = op + 'number(Rank)';
			break;
			
		case 'RREDWA':
			order_by = op + 'number(@index)';
			break;
			
		case 'FCUSER':
		case 'FCADMN':
		case 'FCFAVS':
			if (sPropName=='Code')
				order_by = op + Insert(sort_string, 'number({0})');
			else
				order_by = op + sort_string.replace(re, ';'+op);
			break;
			
		default:
			if (sort_string)
				order_by = op + sort_string.replace(re, ';'+op);
			break;
	}
	
	if (cur_filter)
	{	
		x+= "<xsl:for-each select=\""+ cur_filter +"\"";
		if (order_by)
			x+= " order-by=\""+ order_by +"\"";
		x+= ">";		
		x+= 		"<xsl:apply-templates select=\".\" />";
		x+= 	"</xsl:for-each>";
		x+= "</xsl:template>";
	}
	x+= GetRowXSL(type);
	x+= "</xsl:stylesheet>";
	
	xTmp.loadXML(x);
	CheckError(xTmp);

	output = oData.transformNode(xTmp);

	if (output.length == 0)
	{
		switch(tbl.curName)
		{
			case'FirstName':label='First Name';break;
			case'LastName': label='Last Name'; break;
			default: label=sPropName;
		}
		var row = "<div class='tableRow'><span style=\"height:20px;width:100%\">{0}</span></div>", msg="";
		var infoIconHTML = '<img src="img/iInfo.gif" class="icon" style="margin-right:5px"/>'
		var sCurTableName = GetComponentConfigValue(type, "text");
		
		if (type == 'DSRS' || type == 'TA' || type == 'TARRWO' || type == 'TARRWA')
		{
				msg = infoIconHTML;
				if (b_MAX_TYPE_AHEAD_EXCEEDED)
					msg += AddNestedBoldTags(InsertMultiple(new Array("<a href=\"javascript:ForceTypeAhead('"+type+"')\" style=\"color:#69c\">","</a>"), text('TBL/TOO_MANY')));
				else if (search_query)
					msg += AddNestedBoldTags(Insert(search_query, text('TBL/NO_MATCH')));
				else
					msg += text('TBL/NO_SEARCH');
		}
		else if (tbl.curDisplayIndex!=null && tbl.curSort!=null)
		{
			if (tbl.curDisplayIndex==11)
				tbl.curDisplayIndex=10;
				
			var oCurTab = oTabs.selectSingleNode("TAB[@index='"+ tbl.curDisplayIndex +"']");
			// if the ALL tab is selected
			if (tbl.curDisplayIndex==10)
			{
				var group = (type=='AB' && tbl.curFilterValue) ? AddNestedBoldTags(Insert(tbl.curFilterValue, text('TBL/GROUP'))) : '';
				msg += Insert(group, text('TBL/NONE'));
			}
			else
			{
				var insert, target;
				
				if (tbl.curDisplayIndex>0 && tbl.curDisplayIndex<10)
				{
					msg = " "; 
					insert = FormatMultiCharTabDisplay(oCurTab.getAttribute('display'));
					target = text('TBL/BEGIN');
				}
				else if (tbl.curDisplayIndex==0)
				{
					insert = (type=='GPAB') ? label : oCurTab.nextSibling.getAttribute('beg');
					target = (type=='GPAB') ? text('TBL/BEGIN_NO_ALPHA_GPAB') : text('TBL/BEGIN_NO_ALPHA');
				}

				msg += AddNestedBoldTags(Insert(insert, target));
				if (type!='GPAB' || (type=='GPAB' && tbl.curDisplayIndex!=0))
					msg = (AddNestedBoldTags(Insert(label, ((type=="GPAB")?text('TBL/GPAB'):text('TBL/SORT')))) +' '+ msg);
					
				if (type=='AB')
				{
					if (tbl.curFilterValue)
						msg = AddNestedBoldTags(Insert(tbl.curFilterValue, text('TBL/GROUP'))) +' '+ msg;
					msg = Insert(msg, text('TBL/AB'));
				}
			}
		}
		else
			msg = infoIconHTML + Insert(text('ITEM/'+type), text('TBL/DEFAULT'));
			
		output += AddNestedBoldTags(Insert(msg, row));
	}
	
	tbl.body.innerHTML = output;
	
	// if the table has columns
	if (tbl.curSort)
	{
		// if a previous sort exists and it's a different column, reset it's background image
		if (tbl.prevSort && (tbl.curSort != tbl.prevSort))
		{
			var oPrevCell = tbl.head.children[tbl.prevSortIndex];
			if (oPrevCell)
			{
				oPrevCell.children['sort_ind'].style.backgroundImage = '';
				oPrevCell.style.color = '';
			}
		}
		var oCurCell = tbl.head.children[tbl.curSortIndex];
		if (oCurCell)
			oCurCell.children['sort_ind'].style.backgroundImage = 'url(img/bgSortableHeadArrow'+ (bSortAscend ? 'Up':'Dn') +'2.gif)';
	}
	
	// table clean up
	var tbl = table[type];
	switch (type)
	{
		case 'AB':
			if (!tbl.resized)
				tbl.body.style.height='241px';
			break;
		
		case 'CL':	
			tbl.body.ondragover=overDrag;
			HighlightCallList(selected_rows);
			break;

		case 'DSFM':
			tbl.body.style.backgroundImage='none';
//			tbl.body.style.backgroundColor='#eec';
			tbl.body.style.backgroundColor='#EEE';
			tbl.body.style.overflowY='visible';
			tbl.head.outerHTML = '';
			CheckLocalSearchOptions();
			break;
			
		case 'DSRS':
			if (!tbl.resized)
				tbl.body.style.height='215px';
			break;
			
		case 'DV':
			UpdateDeviceInterface(oDevNode.firstChild, true);
			break;
			
		case 'GPAB':
			tbl.head.style.backgroundColor = '#369';
			if (!tbl.resized)
				tbl.body.style.height='218px';
			break;
			
		case 'GPLS':
			var child = tbl.body.firstChild;
			while (child)
			{
				if (child.className=='cssMenuItem')
					SetTableStyle(child.lastChild);
				child=child.nextSibling;
			}
			if (!tbl.resized)
				tbl.body.style.height='218px';
			break;
			
		case 'MS':
			if (getObj('MSEX').style.display=='none')
				SetButtons('MS');
			break;
			
		case 'NADL':
			if (!tbl.resized)
				tbl.body.style.height='100px';
			break;
			
		case 'RREDWA':
			tbl.ondragover=overDrag;
			tbl.ondrop=dropStep;
			if (!tbl.resized)
				tbl.body.style.height='215px';
			break;
			
		case 'TA':
			tbl.body.ondragover=overDrag;
			break;
			
		case 'TARRWA':
		case 'TARRWO':
			if (!tbl.resized)
				tbl.body.style.height='100px';
			break;
			
/*		default:
			SetTableBodyHeight(tbl, type);
			break;
			*/
	}
	SetTableStyle(tbl.body);
	HighlightCurrentLetterTab(type);
}

function SetTableBodyHeight(tbl, type)
{
	var menu_body = getObj('menu1').lastChild;
	tbl.body.style.height = 300 - tbl.footer.offsetHeight - tbl.head.offsetHeight + 'px';
}

function UpdateSingleTableRow(type, obj, old_unique_id, oldObj)
{
	var row, unique_id, html, open_devices=false;
	switch (type)
	{
		case 'CL':
			if (obj.nodeName == 'CONFERENCE_CALL')
			{
				// make sure to remove the child rows of a conference call for an update
				var children = oldObj.selectNodes('*/CALL'), i=0;
				while (children[i])
				{
					var child_row = getObj('rowCL' + children[i].selectSingleNode('NodeID').text + children[i].selectSingleNode('Extension').text + children[i].selectSingleNode('CallID').text);
					if (child_row)
						child_row.outerHTML = '';
					i++;
				}
			}
			unique_id = obj.selectSingleNode('NodeID').text + obj.selectSingleNode('Extension').text + obj.selectSingleNode('CallID').text;
			break;
			
		default:
			unique_id = obj.selectSingleNode('UniqueID').text;
			break;
	}
	row = getObj('row' + type + unique_id);
	// when a search result is added the UniqueID changes, use the previous to locate the row to be updated
	if (!row)
		row = getObj('row' + type + old_unique_id);
	if (row)
	{
		var color = row.style.backgroundColor;
		var prevColor = row.prevColor;
		var first_icon = row.firstChild.firstChild;
		if (type == 'AB' && GetImgSrc(first_icon) == 'iExpMinus')
			open_devices = true;
				
		row.outerHTML = CreateSingleRowHTML(type, obj);
	
		// reset the reference to the new document object
		row = getObj('row' + type + unique_id);
		row.style.backgroundColor = color;
		row.prevColor = prevColor;
		first_icon = row.firstChild.firstChild;
		if (open_devices)
			ToggleCollapseableSection(first_icon, row.lastChild);
	}
}

function CreateSingleRowHTML(type, obj)
{
	switch (type)
	{
		case 'AB':
		case 'GPAB':	xpath = "R/AB/CONTACT[UniqueID='"+obj.selectSingleNode('UniqueID').text+"']"; break;
		
		case 'CG':	xpath = "R/CALL_LOGS/CALLLOG[UniqueID='"+obj.selectSingleNode('UniqueID').text+"']"; break;
		
		case 'CL':	xpath = "R/CALL_LIST/*[CallID='"+obj.selectSingleNode('CallID').text+"' and NodeID='"+obj.selectSingleNode('NodeID').text+"' and Extension='"+obj.selectSingleNode('Extension').text+"']"; break;
		
		case 'NADL':	xpath = "R/SEARCH_RESULTS/NA/CONTACT[UniqueID='"+obj.selectSingleNode('UniqueID').text+"']"; break;
		
		case 'RR':	xpath = "R/RULES/RULE[UniqueID='"+obj.selectSingleNode('UniqueID').text+"']"; break;
		
		case 'TA':
		case 'DSRS':	xpath = "R/SEARCH_RESULTS/"+type+"/CONTACT[UniqueID='"+obj.selectSingleNode('UniqueID').text+"']"; break;
	}
	
	var x="<?xml version=\"1.0\"?>";
	x+= "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/TR/WD-xsl\">";
	x+= "<xsl:template match=\"/\">";
	x+= 	"<xsl:for-each select=\""+xpath+"\"><xsl:apply-templates select=\".\" /></xsl:for-each>";
	x+= "</xsl:template>";
	x+= GetRowXSL(type);
	x+= "</xsl:stylesheet>";
	xTmp.loadXML(x);
	return oSys.transformNode(xTmp);
}

function AddNewRow(type, obj)
{
	table[type].body.insertAdjacentHTML('beforeEnd', CreateSingleRowHTML(type, obj));
	if (type=='NADL')
	{
		var re = new RegExp('º','g');
		if (table[type].body.firstChild.innerText == Insert(text('ITEM/'+type), text('TBL/DEFAULT')).replace(re,''))
			table[type].body.removeChild(table[type].body.firstChild);
		SetTableStyle(table[type].body);
	}
}

function UpdateUserButton(obj, old_unique_id)
{
	var button, html, node;
	button = getObj('ub'+obj.selectSingleNode('UniqueID').text);
	if (!button)
		button = getObj('ub'+old_unique_id);
	if (button)
	{
		var xsl = GetSectionXSL('UB', 1, oSys);
		var append = " and UniqueID='"+ obj.selectSingleNode('UniqueID').text +"'";
		var re = new RegExp("(Groups//String='"+config('SPEED_DIAL')+"')");
		var new_xsl = xsl.replace(re, '$1'+append);
		xTmp.loadXML(new_xsl);
		html = oSys.transformNode(xTmp);
		button.outerHTML = html;
	}
}

function UpdateAllDisplaysForThisContact(xpath)
{
	// update linked contacts in Personal Contacts
	var aABobjs = oABNode.selectNodes('CONTACT'+xpath), i=0;
	if (aABobjs)
	{		
		while(aABobjs[i])
			UpdateObjectDisplay('AB', aABobjs[i++]);
	}
	// update search results
	var aSRobjs = oSearchNode.selectNodes('.//CONTACT'+xpath), i=0;
	if (aSRobjs)
	{		
		while(aSRobjs[i])
			UpdateObjectDisplay(aSRobjs[i].parentNode.nodeName, aSRobjs[i++]);
	}
	// update call logs
	var aCLobjs = oCallLogNode.selectNodes('CALLLOG'+xpath), i=0;
	if (aCLobjs)
	{		
		while(aCLobjs[i])
			UpdateObjectDisplay('CG', aCLobjs[i++]);
	}
}

function UpdateObjectDisplay(type, obj, b_NON_STATUS_UPDATE, old_unique_id)
{
	switch (type)
	{
		case 'AB':
			var unique_id = obj.selectSingleNode('UniqueID').text;
			UpdateSingleTableRow(type, obj, old_unique_id);
			if (obj.selectSingleNode("Groups[//String='"+config('SPEED_DIAL')+"']"))
				UpdateUserButton(obj, old_unique_id);
			if (b_NON_STATUS_UPDATE)
			{
				UpdateSingleTableRow('GPAB', obj, old_unique_id);
				if (getObj('rowGP'+unique_id) || getObj('rowGP'+old_unique_id))
					table['GPLS'].refresh();
				// update the display for any rules that use this object
				var oStepReferencingObj = oStepsNode.selectSingleNode('STEP[Destination="'+unique_id+'"]');
				if (oStepReferencingObj)
				{
					var owning_rule = FindOwningRule(oStepReferencingObj.selectSingleNode('UniqueID').text);
					UpdateSingleTableRow('RR', owning_rule);
				}
			}
			break;
			
		case 'CG':
			var id = 'rowCG'+ obj.selectSingleNode('UniqueID').text;
			var row = getObj(id);
			if (row)
			{
				var img = row.childNodes(2).firstChild;
				if (img.tagName=='IMG')
					img.src = GetStatusImgSrc(obj);
			}
			break;	
		
		case 'DSRS':
		case 'TA':
			UpdateSingleTableRow(type, obj);
			break;
	}

}

function GetStatusImgSrc(obj)
{
	var oStatus;
	switch (obj.nodeName)
	{
		case 'CALLLOG':
			switch (obj.selectSingleNode('LinkType').text)
			{
				case 'A':
					status_path = 'ACC_STATUS[OwnerUniqueID="'+ obj.selectSingleNode('LinkParameter').text +'"]';
					oStatus = oStatusListNode.selectSingleNode(status_path);
					if (oStatus)
					{
						if (boolVal(oStatus.selectSingleNode('OnACall')))
							return 'img/iActCALL.gif';
						else if (boolVal(oStatus.selectSingleNode('Available')))
							return 'img/iAct.gif';
						else
							return 'img/iActUNAV.gif';
					}
					return 'img/iActUNKN.gif';
					break;
					
				case 'D':
					status_path = 'DEVICE_STATUS[NodeColonExtension = "'+ obj.selectSingleNode('LinkParameter').text +'"]';
					oStatus = oStatusListNode.selectSingleNode(status_path);
					if (oStatus)
					{
						if (boolVal(oStatus.selectSingleNode('OnACall')))
							return 'img/iKeysetCALL.gif';
						else if (oStatus.selectSingleNode('PrimaryMessage').text)
							return 'img/iKeysetDND.gif';
						else
							return 'img/iKeyset.gif';
					}
					return 'img/iKeysetUNKN.gif';
					break;
			}
			break;
	}
}

function UpdateAllContactDisplays()
{
	UpdateAddressBookLists();
	table['GPLS'].refresh();
	table['CG'].refresh();
	BuildDiv('UB', oSys);
}

function UpdateAddressBookLists()
{
	table['AB'].refresh();
	table['GPAB'].refresh();
}

function UpdateContactDisplaysWithRealTimeStatus()
{
	table['AB'].refresh();
	BuildDiv('UB', oSys);
}

function UpdateGroupDisplays(group_name)
{
	// update filtered Personal Contacts display
	var oABFilterSelect = getObj('table_filter_select_AB');
	if (oABFilterSelect.options[oABFilterSelect.selectedIndex].text == group_name)
		table['AB'].refresh();
	// update speed dial buttons
	if (group_name == config('SPEED_DIAL'))
		BuildDiv('UB', oSys);
}

function AddLinkedContactsDone() {}

function RequestStatusForObject(type, unique_id)
{
	var obj;
	switch (type)
	{
		case 'DSRS':
		case 'TA':
		case 'TARRWO':
		case 'TARRWA':
			obj = oSearchNode.selectSingleNode(type+'/CONTACT[UniqueID="'+unique_id+'"]');
			break;
			
		case 'CG':
			obj = oCallLogNode.selectSingleNode('CALLLOG[UniqueID="'+unique_id+'"]');
			break;
	}
	if (obj)
	{
		var link_type = obj.selectSingleNode('LinkType').text;
		var link_param = obj.selectSingleNode('LinkParameter').text;
		var request_obj;
		switch (link_type)
		{
			case 'A':
				request_obj = GetTemplate('ACC_STATUS');
				request_obj.selectSingleNode('OwnerUniqueID').text = link_param;
				break;
				
			case 'D':
				request_obj = GetTemplate('DEVICE_STATUS');
				var t_vals = link_param.split(':');
				request_obj.selectSingleNode('NodeID').text 	= t_vals[0];
				request_obj.selectSingleNode('Extension').text 	= t_vals[1];
				break;
		}
		if (request_obj)
			CallControlMethod('GetObject', request_obj);
	}
}

function AddNodeColonExtension(obj)
{
	var oNodeColonExt = oSys.createElement('NodeColonExtension');
	oNodeColonExt.text =  obj.selectSingleNode('NodeID').text +':'+ obj.selectSingleNode('Extension').text;
	obj.appendChild(oNodeColonExt);
}

function RemoveContactFromInterface(unique_id, type)
{
	// remove ab rows in case this was called by a synch or admin operation
	var oABrow = getObj('rowAB'+unique_id);
	if (type != 'AB' && oABrow)
	{
		oABrow.parentElement.removeChild(oABrow);
		ResetRows(table['AB'].body);
	}
	
	// remove all rows from the groups list - may be multiple
	var oGProw = getObj('rowGP'+unique_id);
	while (oGProw)
	{
		oGProw.parentElement.removeChild(oGProw);
		oGProw = getObj('rowGP'+unique_id);
	}
	
	// Group Personal Contacts display
	var oGPABrow = getObj('rowGPAB'+unique_id);
	if (oGPABrow)
	{
		oGPABrow.parentElement.removeChild(oGPABrow);
		ResetRows(table['GPAB'].body);
	}
	
	// User button
	var oUserButton = getObj('ub'+unique_id);
	if (oUserButton)
		oUserButton.parentElement.removeChild(oUserButton);
}

function GetRowXSL(type)
{
	var tbl = table[type], x="", custom_style="";
	var rowHTML = "<div class=\"tableRow\" type=\""+type+"\" {0} onclick='HandleRowClick(this);return false' ondblclick='HandleRowDoubleClick(this);return false' onmouseover='HandleRowMouseover(this);return false' onselect='ReturnFalse()'>";
	
	switch (type)
	{
		case "AB":
		x+= "<xsl:template match=\"CONTACT\">";
		
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= "]]></xsl:script>";
		
		x+=	Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">row"+ type +"<xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 		"<span class=\"cellAB0\">";
		x+= 			"<xsl:choose>";
		x+=				"<xsl:when test=\".[LinkType='A' and Devices/LIST//String]\"><img src=\"img/iExpPlus.gif\" class=\"icon_hot\"/></xsl:when>";
		x+= 				"<xsl:otherwise><img src=\"img/pix.gif\" class=\"icon\"/></xsl:otherwise>";
		x+= 			"</xsl:choose>";
		x+= 			GetXSLStatusLogic(type);
		x+= 		"</span>";
		x+= 		"<span class=\"cellAB1\">"+ GetXSLSortedNameLogic(type) +"</span>";
		x+= 		"<span class=\"cellAB2\">";
		x+= 			"<xsl:choose>";
		x+=					"<xsl:when test=\".[LinkType='D']\"><xsl:for-each select=\"/R/STATUS_LIST/DEVICE_STATUS[NodeColonExtension = context(-1)/LinkParameter][0]\"><xsl:choose><xsl:when test=\".[@inactive]\">"+text('GBL/UNKN')+"</xsl:when><xsl:otherwise><xsl:value-of select=\"PrimaryMessage\"/> <xsl:value-of select=\"SecondaryMessage\"/></xsl:otherwise></xsl:choose></xsl:for-each></xsl:when>";
		//x+=					"<xsl:otherwise><xsl:for-each select=\"/R/STATUS_LIST/ACC_STATUS[OwnerUniqueID = context(-1)/LinkParameter][0]\"><xsl:value-of select=\"CurrentCompositeStatus\"/> <xsl:value-of select=\"CurrentDynamicStatus\"/></xsl:for-each></xsl:otherwise>"
		x+= 				"<xsl:when test=\".[LinkType='A']\"><xsl:for-each select=\"/R/STATUS_LIST/ACC_STATUS[OwnerUniqueID = context(-1)/LinkParameter][0]\"><xsl:value-of select=\"CurrentCompositeStatus\"/> <xsl:value-of select=\"CurrentDynamicStatus\"/></xsl:for-each></xsl:when>";
		x+= 				"<xsl:otherwise>&#160;</xsl:otherwise>";
		x+= 			"</xsl:choose>";
		x+= 			"&#160;";
		x+= 		"</span>";
		x+= 		"<span class=\"cellAB3\">";
		x+= 			GetXSLNoPhoneNumberLogic(type);
		x+= 			"<xsl:choose><xsl:when test=\"Emails/LIST//String\"><img src=\"img/iEmail.gif\" class=\"icon_hot\"/></xsl:when><xsl:otherwise><img src=\"img/pix.gif\" class=\"icon\"/></xsl:otherwise></xsl:choose>";
		x+= 			"<img src=\"img/iView.gif\" class=\"icon_hot\"/><img src=\"img/iCopy.gif\" class=\"icon_hot\"/><img src=\"img/iEdit.gif\" class=\"icon_hot\"/>";
		x+= 		"</span>";
		x+= 		"<div class=\"tableRowDeviceDetail\" style=\"display:none;width:100%;\">";
		x+=				"<xsl:for-each select=\"Devices//String\">";
		x+= 				"<div style=\"width:100%;height:20px;line-height:14px;color:#666\">";
		x+= 				"<xsl:choose>";
		x+= 				"<xsl:when test=\"/R/STATUS_LIST/DEVICE_STATUS[NodeColonExtension = context(-1)!value()]\">";
		x+=						"<xsl:for-each select=\"/R/STATUS_LIST/DEVICE_STATUS[NodeColonExtension = context(-1)!value()][0]\">";
		x+= 						"<span class=\"cellAB0\" style=\"padding-left:21px;\">";
		x+= 							"<xsl:choose>";
		x+= 							"<xsl:when test=\"@inactive\"><img src=\"img/iKeysetUNKN.gif\" class=\"icon\" /></xsl:when>";
		x+= 							"<xsl:when test=\"OnACall[.='true' or .='True' or .='TRUE']\"><img src=\"img/iKeysetCALL.gif\" class=\"icon\" /></xsl:when>";
		x+= 							"<xsl:when test=\"PrimaryMessage[. != '']\"><img src=\"img/iKeysetDND.gif\" class=\"icon\" /></xsl:when>";
		x+= 							"<xsl:otherwise><img src=\"img/iKeyset.gif\" class=\"icon\" /></xsl:otherwise>";
		x+= 							"</xsl:choose>";
		x+= 						"</span>";
		x+= 						"<span class=\"cellAB1\" style=\"font-style:italic;\"><xsl:eval>removeNodePrefix(this, 'NodeColonExtension')</xsl:eval></span>";
		x+= 						"<span class=\"cellAB2\">";
		x+= 							"<xsl:choose>";
		x+= 							"<xsl:when test=\"@inactive\">"+text('GBL/UNKN')+"</xsl:when>";
		x+= 							"<xsl:otherwise><xsl:value-of select=\"PrimaryMessage\"/> <xsl:value-of select=\"SecondaryMessage\"/></xsl:otherwise>";
		x+= 							"</xsl:choose>";
		x+= 						"</span>";
		x+= 					"</xsl:for-each>";
		x+= 				"</xsl:when>";
		x+= 				"<xsl:otherwise>";
		x+= 					"<span class=\"cellAB0\" style=\"padding-left:21px;\"><img src=\"img/iKeysetUNKN.gif\" class=\"icon\"/></span>";
		x+= 					"<span class=\"cellAB1\" style=\"font-style:italic;\"><xsl:eval>removeNodePrefix(this)</xsl:eval></span>";
		x+= 					"<span class=\"cellAB2\" style=\"font-style:italic;\">[retrieving status...]</span>";
		x+= 				"</xsl:otherwise>";
		x+= 				"</xsl:choose>";
		x+= 					"<span class=\"cellAB3\">&#160;</span>";
		x+= 				"</div>";
		x+=				"</xsl:for-each>";
		x+= 		"</div>";
		x+= "</div>";
		break;

		case "CG":
		x+= "<xsl:template match=\"CALLLOG\">";
		x+= "<xsl:script><![CDATA[";
		x+= "function buildPlaceCallLink(e, xpath) {";
		x+= 	"var num = removeNodePrefix(e, xpath);";
		x+=		"var link = '<a href=\"javascript://\" onclick=\"PlaceCall({0})\">{1}</a>';";
		x+=		"return InsertMultiple(new Array(num, num), link);";
		x+= "}";
		x+= "function formatActionParameter(e) {";
		x+= 	"var param = e.selectSingleNode('Parameter').text;";
		x+= 	"var action = e.selectSingleNode('Action').text;";
		x+=		"switch (action)";
		x+=		"{";
		x+=			"case 'G':";
		x+=			"	break;";
		x+=			"default:";
		x+=				"param = (param && !isNaN(param)) ? formatPhoneNumber(param,e) : param;";
		x+=		"}";
		x+=		"return param;";
		x+= "}";
		x+= GetEmbeddedInsertMultipleScript();
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= GetEmbeddedStripPhoneNumberLogic();
		x+= GetEmbeddedPhoneNumberExistsInObjectLogic();
		x+= "]]></xsl:script>";
		
		x+= Insert(custom_style, rowHTML);
		x+= "<xsl:attribute name=\"id\">rowCG<xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= "<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<span class=\"cellCG0\"><img src=\"img/iExpPlus.gif\" class=\"icon_hot\"/>";
		x+= 		"<xsl:choose>";
		x+= 			"<xsl:when test=\"Incoming[.='true' or .='True' or .='TRUE']\"><img src=\"img/iCLAnswer.gif\" class=\"icon\"/></xsl:when>";
		x+= 			"<xsl:otherwise><img src=\"img/iCLOrig.gif\" class=\"icon\"/></xsl:otherwise>";
		x+= 		"</xsl:choose>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellCG1\"><xsl:value-of select=\"CallActions//CALLLOG_ACTION[0]/TimeStamp\" /></span>";
		x+= 	"<span class=\"cellCG2\">";
		x+= 		GetXSLStatusLogic(type);
		x+= 			"<xsl:choose>";
		x+=				"<xsl:when test=\".[CallerIDFirstName!='' or CallerIDLastName!='']\">&#160;&#160;<xsl:value-of select=\"CallerIDFirstName\"/> <xsl:value-of select=\"CallerIDLastName\"/></xsl:when>";
		x+= 			"<xsl:when test=\".[CallerIDCompanyName!='']\">&#160;&#160;<xsl:value-of select=\"CallerIDCompanyName\"/></xsl:when>";
		x+= 			"</xsl:choose>";
		x+=				"&#160;&#160;<xsl:element name=\"A\"><xsl:attribute name=\"href\">javascript://</xsl:attribute><xsl:attribute name=\"onclick\">PlaceCall(\"<xsl:value-of select=\"CallerIDNumber\" />\")</xsl:attribute><xsl:eval>removeNodePrefix(this, 'CallerIDNumber')</xsl:eval></xsl:element>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellCG3\">";
		x+= 		"<xsl:if expr=\"displayPhoneNumberImportFlag(this)\"><img src=\"img/iFlag.gif\" class=\"icon_hot\"/></xsl:if>";
		x+= 		"&#160;"
		x+= 	"</span>";
		x+= 	"<span class=\"cellCG4\"><xsl:value-of select=\"Results\" /></span>";
		x+= 	"<div class=\"tableRowCallLogActions\" style=\"display:none;width:100%;height:10px;border-bottom:1px solid #ccc;color:#666\">";
		x+= 		"<xsl:for-each select=\"CallActions/LIST//CALLLOG_ACTION\">";
		x+= 			"<div style=\"width:100%;\"><span class=\"cellCG0\"></span><span class=\"cellCG1\"><xsl:value-of select=\"TimeStamp\" /></span><span class=\"cellCG2\" style=\"padding-left:30px;\"><xsl:value-of select=\"/R/CALL_STATES/STATE[@code = context(-1)/Action]/@string\"/></span><span class=\"cellCG3\"></span><span class=\"cellCG4\"><xsl:eval>formatActionParameter(this, 'Parameter')</xsl:eval></span></div>";
		x+= 		"</xsl:for-each>";
		x+= 	"</div>";
		x+= "</div>";
		break;
		
		case "CL":
		x+= "<xsl:template match=\"R\">";
		x+= "<xsl:script><![CDATA[";
		x+= "function isCallingInternalExtMyDevice(e) {";
		x+=		"var oDeviceMatchingInternalCallingInfo;";
		x+= 	"var sDeviceID = e.selectSingleNode('NodeID').text +':'+ e.selectSingleNode('Extension').text;";
		x+= 	"var sCallIntExt = e.selectSingleNode('CallingInternalExt').text;";
		x+= 	"return (sDeviceID == sCallIntExt);";
		x+= "}";
		x+= GetEmbeddedDeviceFlagsScript();
		x+= GetEmbeddedDeviceNameLookupScript();
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= GetEmbeddedInsertScript();
		x+= GetEmbeddedAccountFieldValueScript();
		x+= "]]></xsl:script>";

		x+= 	"<xsl:for-each select=\"CALL_LIST/*\"><xsl:apply-templates select=\".\" /></xsl:for-each>";
		x+= "</xsl:template>";
		
		x+= "<xsl:template match=\"CONFERENCE_CALL\">";
		x+= 	Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">rowCL<xsl:value-of select=\"NodeID\"/><xsl:value-of select=\"Extension\"/><xsl:value-of select=\"CallID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"CallID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"EndpointID\"><xsl:value-of select=\"NodeID\"/>:<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"call_type\">root</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragenter\">HighlightCallRow(this)</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragleave\">HighlightCallRow(this)</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragover\">overDrag()</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondrop\">this.style.backgroundColor=this.prevColor;ConferenceDragAndDrop(this)</xsl:attribute>";
		x+= 		"<span class=\"cellCL0\">";
		x+=				getXSLCallStateWhenOptions();
		x+=				"<xsl:if expr=\"evalDeviceFlags(this, 'mute')\"><img src=\"img/iMute.gif\" class=\"icon\" /></xsl:if>";
		x+=				"<xsl:if expr=\"evalDeviceFlags(this, 'listen')\"><img src=\"img/iSpeaker.gif\" class=\"icon\" /></xsl:if>";
		x+=				"<xsl:if expr=\"evalDeviceFlags(this, 'record')\"><img src=\"img/iVoicemail.gif\" class=\"icon\" /></xsl:if>";		
		x+= 		"</span>";
		x+= 		"<span class=\"cellCL1\" style=\"font-weight:bold\">CONFERENCE CALL</span>";
		x+= 		"<span class=\"cellCL2\">&#160;</span>";
		x+=			getXSLActiveRuleLogic();
		x+= 	"</div>";
		
		x+= 	"<xsl:for-each select=\"*/CALL\"><xsl:apply-templates select=\".\" /></xsl:for-each>";
		x+= "</xsl:template>";
		
		x+= "<xsl:template match=\"CALL\">";
		x+= 	Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">rowCL<xsl:value-of select=\"NodeID\"/><xsl:value-of select=\"Extension\"/><xsl:value-of select=\"CallID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"CallID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"EndpointID\"><xsl:value-of select=\"NodeID\"/>:<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"call_type\">";
		x+=			"<xsl:choose>";
		x+=			"<xsl:when test=\".[ancestor(CONFERENCE_CALL)]\">conference_member</xsl:when>";
		x+=			"<xsl:otherwise>root</xsl:otherwise>";
		x+=			"</xsl:choose>";
		x+=		"</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragenter\">HighlightCallRow(this)</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragleave\">HighlightCallRow(this)</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragover\">overDrag()</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondrop\">this.style.backgroundColor=this.prevColor;ConferenceDragAndDrop(this)</xsl:attribute>";
		x+= 		"<span class=\"cellCL0\">";
		x+=				"<xsl:choose>";
		x+=				"<xsl:when test=\".[not(ancestor(CONFERENCE_CALL))]\">";
		x+=					getXSLCallStateWhenOptions();
		x+=					"<xsl:if expr=\"evalDeviceFlags(this, 'mute')\"><img src=\"img/iMute.gif\" class=\"icon\" /></xsl:if>";
		x+=					"<xsl:if expr=\"evalDeviceFlags(this, 'listen')\"><img src=\"img/iSpeaker.gif\" class=\"icon\" /></xsl:if>";
		x+=					"<xsl:if expr=\"evalDeviceFlags(this, 'record')\"><img src=\"img/iVoicemail.gif\" class=\"icon\" /></xsl:if>";
		x+=				"</xsl:when>";
		x+=				"<xsl:otherwise><img src=\"img/pix.gif\" class=\"icon\"/></xsl:otherwise>";
		x+=				"</xsl:choose>";
		x+=				"&#160;";
		x+= 		"</span>";
		x+= 		"<span class=\"cellCL1\">";
		x+=				"<xsl:if test=\".[ancestor(CONFERENCE_CALL)]\">"+ getXSLCallStateWhenOptions() +"&#160;&#160;</xsl:if>";
		x+=				"<xsl:choose>";
		x+=					"<xsl:when test=\".[(OtherPartyFirstName!='' or OtherPartyLastName!='') and OtherPartyFirstName!='Ambiguous']\"><xsl:value-of select=\"OtherPartyFirstName\"/> <xsl:value-of select=\"OtherPartyLastName\"/> <img src=\"img/iPosCallerID.gif\" class=\"icon\"/></xsl:when>";
		x+=					"<xsl:when test=\".[OtherPartyCompany!='']\"><xsl:value-of select=\"OtherPartyCompany\"/> <img src=\"img/iPosCallerID.gif\" class=\"icon\"/></xsl:when>";
		x+=					"<xsl:when test=\".[CallingOutsideNumber!='']\"></xsl:when>";
		x+=					"<xsl:when test=\".[CallingDeviceType='E']\"><xsl:value-of select=\"CallingInternalName\"/></xsl:when>";
		x+=					"<xsl:when test=\".[AnsweringDeviceType='E']\"><xsl:value-of select=\"AnsweringInternalName\"/></xsl:when>";
		x+=					"<xsl:when expr=\"isCallingInternalExtMyDevice(this)\"><xsl:value-of select=\"AnsweringInternalName\"/></xsl:when>";
		x+=					"<xsl:otherwise><xsl:value-of select=\"CallingInternalName\"/></xsl:otherwise>";
		x+=				"</xsl:choose>";
		x+=				"<xsl:if test=\".[OtherPartyFirstName='Ambiguous']\"> (Ambiguous)</xsl:if>";
		x+=				"&#160;";
		x+= 		"</span>";
		x+= 		"<span class=\"cellCL2\">";
		x+=				"<xsl:choose>";
		x+=					"<xsl:when test=\".[OtherPartyNumber!='']\"><xsl:eval>removeNodePrefix(this, 'OtherPartyNumber')</xsl:eval></xsl:when>";
		x+=					"<xsl:when test=\".[AnsweringOutsideNumber!='' and ActiveRuleID='']\"><xsl:eval>removeNodePrefix(this, 'AnsweringOutsideNumber')</xsl:eval></xsl:when>";
		x+=					"<xsl:when test=\".[CallingOutsideNumber!='']\"><xsl:eval>removeNodePrefix(this, 'CallingOutsideNumber')</xsl:eval></xsl:when>";
		x+=					"<xsl:when test=\".[CallingDeviceType='E' or AnsweringDeviceType='E']\">&#160;</xsl:when>";
		x+=					"<xsl:when expr=\"isCallingInternalExtMyDevice(this)\"><xsl:eval>removeNodePrefix(this, 'AnsweringInternalExt')</xsl:eval></xsl:when>";
		x+=					"<xsl:otherwise><xsl:eval>removeNodePrefix(this, 'CallingInternalExt')</xsl:eval></xsl:otherwise>";
		x+=				"</xsl:choose>";
		x+=				"&#160;";
		x+= 		"</span>";
		x+=			getXSLActiveRuleLogic();
		x+= 	"</div>";
		
		// closing template added below
		//x+= "</xsl:template>";
		
		/*
		
	<CALL flow="out">
		<NodeID>1</NodeID> 
		<Extension>1003</Extension> 
		<CallID>P1P01</CallID> 
		<State>a</State> 
		<AnswerTimeStamp>
		<SYSTEM_TIME>
			<Year>2003</Year> 
			<Month>10</Month> 
			<DayOfWeek>4</DayOfWeek> 
			<Day>9</Day>
			<Hour>23</Hour>
			<Minute>11</Minute>
			<Second>59</Second>
			<Milliseconds>333</Milliseconds> 
		</SYSTEM_TIME>
		</AnswerTimeStamp>
		<AnsweringInternalExt>1:1004</AnsweringInternalExt> 
		<AnsweringInternalName>Wayne Ung</AnsweringInternalName> 
		<AnsweringOutsideNumber /> 
		<AnsweringDeviceType>I</AnsweringDeviceType> 
		<CallingInternalExt>1:1003</CallingInternalExt> 
		<CallingInternalName>Toby Ambrose</CallingInternalName> 
		<CallingOutsideNumber /> 
		<CallingDeviceType>I</CallingDeviceType>
		<TrunkOutsideNumber />
		<OriginallyCalledDevice>1:1004</OriginallyCalledDevice> 
		<LastRedirectionExt />
		<HuntGroupID />
		<ActiveRuleID />
		<ActiveStepID />
		<Flags>774</Flags> 
		<OtherPartyFirstName>Ambiguous</OtherPartyFirstName> 
		<OtherPartyLastName />
		<OtherPartyCompany />
		<OtherPartyLinkedTo />
		<OtherPartyContactUniqueID />
	</CALL>
		
		*/
		
		function getXSLActiveRuleLogic()
		{
			// _ACTION_PLAY_GREETING_CALL = 1;
			// _ACTION_GET_NAME           = 3;
			// _ACTION_GET_NUMBER         = 4;
			// _ACTION_SCREEN_CALL        = 5;
			var y="";
			y+=   	"<xsl:if test=\".[ActiveRuleID != '']\">";
			y+= 	"<div style=\"width:100%;height:20px;\">";
			y+= 		"<span class=\"cellCL0\"></span>";
			y+= 		"<span style=\"font-weight:bold;color:#693;\">"+text('CL/ROUTING_CALL')+"&#160;";
			y+=				"<xsl:choose>";
							// if the ActiveRuleID of the call is -1, this is a dynamic rule created for the application platform
			y+=				"<xsl:when test=\".[ActiveRuleID='-1']\">";
			y+=					"<xsl:choose>";
			y+=					"<xsl:when test=\".[ActiveStepID = '3']\">"+text('CL/APP_PLAT_STEP3')+"</xsl:when>";
			y+=					"<xsl:when test=\".[ActiveStepID = '4']\">"+text('CL/APP_PLAT_STEP4')+"</xsl:when>";
			y+=					"<xsl:when test=\".[ActiveStepID = '-200']\">"+text('CL/SEND_TO_OWNING_DEVICE')+"</xsl:when>";
			y+=					"<xsl:when test=\".[ActiveStepID = '-201']\">"+text('CL/TRANSFER_TO_VOICEMAIL')+"</xsl:when>";
			y+=					"<xsl:when test=\".[ActiveStepID = '-202']\">"+text('CL/HANG_UP')+"</xsl:when>";
			y+=					"</xsl:choose>";
			y+=				"</xsl:when>";
			y+=				"<xsl:otherwise>";
								//  find the active step for the rule specified by ActiveRuleID
			y+=   				"<xsl:for-each select=\"/R/STEPS/STEP[(@for = context(-1)/ActiveRuleID) and (UniqueID = context(-1)/ActiveStepID)]\" order-by=\"number(@index)\">... ";
			y+=					GetStepDescriptionLogic();
			y+=   				"</xsl:for-each>";
			y+=				"</xsl:otherwise>";
			y+=				"</xsl:choose>";
			y+= 			"</span>";
			y+=		"</div>";
			y+=   	"</xsl:if>";
			return y;
		}
		
		function getXSLCallStateWhenOptions()
		{
			var y="", drag_methods = "ondragstart=\"startDrag()\" ondragend=\"endDrag()\" type=\"CL\" style=\"cursor:move\"";
			y+=	"<xsl:choose>";
			y+=	"<xsl:when test=\".[State='a']\"><img src=\"img/iAlertOut.gif\" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='A']\"><img src=\"img/iAlertIn.gif\" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='C' and nodeName()='CALL' and ancestor(CONFERENCE_CALL)]\"><img src=\"img/iCLCallOn.gif\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='C' and nodeName()='CALL']\"><img src=\"img/iCLCallOn.gif\" "+drag_methods+" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='C' and nodeName()='CONFERENCE_CALL']\"><img src=\"img/iConf0.gif\" "+drag_methods+" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='F']\"><img src=\"img/iErr.gif\" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='h']\"><img src=\"img/iHeld.gif\" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='H']\"><img src=\"img/iHolding.gif\" "+drag_methods+" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='O']\"><img src=\"img/iCLOrig.gif\" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='r']\"><img src=\"img/iHeldRecall.gif\" class=\"icon\"/></xsl:when>";
			y+=	"<xsl:when test=\".[State='R']\"><img src=\"img/iHoldingRecall.gif\" "+drag_methods+" class=\"icon\"/></xsl:when>";
			y+=	"</xsl:choose>";
			return y;
		}
		break;
		
		case "CS":
		x+= "<xsl:template match=\"COMPOSITE_STATUS\">";
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= GetEmbeddedAccountFieldValueScript();
		x+= "]]></xsl:script>";
		x+=		Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">rowCS<xsl:value-of select=\"DN\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"DN\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"type\">"+ type +"</xsl:attribute>";
		x+= 		"<span class='cellCS0'><xsl:choose><xsl:when test=\"Available[.='true' or .='True' or .='TRUE']\"><img src=\"img/iCompStatusAV.gif\" class=\"icon\" /></xsl:when><xsl:otherwise><img src=\"img/iCompStatusUNAV.gif\" class=\"icon\" /></xsl:otherwise></xsl:choose></span>";
		x+= 		"<span class='cellCS1'><span style=\"font-weight:bold;padding-left:0px\"><xsl:value-of select=\"Description\" /></span></span>";
		x+= 		"<span class='cellCS2'>";
		x+=				"<xsl:choose>";
		x+=				"<xsl:when test=\".[number(LocationType) = 0]\"><span style=\"font-weight:bold;padding-left:0px\"><xsl:value-of select=\"LocationName\" /></span><br/><xsl:eval>removeNodePrefix(this, 'LocationNumber')</xsl:eval></xsl:when>";
		x+=				"<xsl:when test=\".[number(LocationType) = 1]\">";
		x+= 				"<span style=\"font-weight:bold;padding-left:0px\"><xsl:value-of select=\"/R/DEVICES/DEVICE[DeviceStatus//NodeColonExtension = context(-1)/LocationNumber]/Name\" /></span><br/><xsl:eval>removeNodePrefix(this, 'LocationNumber')</xsl:eval>";
		x+=				"</xsl:when>";
		x+=				"<xsl:otherwise>";
		x+= 				"<xsl:for-each select=\"/R/CONTACT_FIELDS/FIELD[@locType = context(-1)/LocationType][0]\"><span style=\"font-weight:bold;padding-left:0px\"><xsl:value-of select=\".\" /></span><br/><xsl:eval>getAccountValue(this)</xsl:eval></xsl:for-each>"; //<xsl:eval>removeNodePrefix(this, '/R/ACCOUNT//*[nodeName() = context(-1)/@name]')</xsl:eval>  //<xsl:value-of select=\"/R/ACCOUNT//*[nodeName() = context(-1)/@name]\" />
		x+=				"</xsl:otherwise>";
		x+=				"</xsl:choose>";
		x+= 		"&#160;</span>";
		x+= 		"<span class='cellCS3'>";
		x+= 			"<xsl:for-each select=\"DeviceSettings//DEVICE_STATUS\" order-by=\"Extension\">";
		x+= 			"<div style=\"width:100%;vertical-align:top;\">";
		x+= 				"<span style=\"width:22%;height:16px;line-height:14px;padding:0px;\">";
		x+= 					"<xsl:value-of select=\"Extension\" />";
		x+= 				"</span>";
		x+= 				"<span style=\"width:76%;height:16px;line-height:14px;padding:0px;\">[";
		x+= 					"<xsl:choose>";
		x+= 					"<xsl:when test=\".[PrimaryMessage='']\">"+text('DV/DND_OFF')+"</xsl:when>";
		x+= 					"<xsl:otherwise><xsl:value-of select=\"PrimaryMessage\" /> <xsl:value-of select=\"SecondaryMessage\" /></xsl:otherwise>";
		x+= 					"</xsl:choose>";
		x+= 				"]</span>";
		x+= 			"</div>";
		x+= 			"</xsl:for-each>";
		if (b_MARGARITA_LICENSED)
		{
			x+= 			"<div style=\"width:100%\">";
			x+= 				"<span style=\"width:22%;height:16px;line-height:14px;padding:0px;\">"+text('CS/MSN')+"</span>";
			x+= 				"<span style=\"width:76%;height:16px;line-height:14px;padding:0px;\">[";
			x+= 					"<xsl:choose>";
									var aIM_msgs = oText.selectNodes("LABELS/IM/STATUS"), k=0;
									while(aIM_msgs[k])
										x+=	"<xsl:when test=\".[MsnStatus='"+ aIM_msgs[k].getAttribute('abbr') +"']\">"+ aIM_msgs[k++].text +"</xsl:when>";
			x+= 					"</xsl:choose>";
			x+= 				"]</span>";
			x+= 			"</div>";
		}
		x+= 		"</span>";
		x+= 		"<span class='cell"+ type +"4'><img src=\"img/iEdit.gif\" class=\"icon_hot\"/></span>";
		x+=		"</div>";
		break;
		
		case "DSFM":
		x+= "<xsl:template match=\"R\">";
//		x+= "<div id=\"SearchForm\" class=\"edit_form\" onkeydown=\"HandleKeydown('search')\">";
		x+= "<div id=\"SearchForm\" class=\"edit_form\" style=\"overflow-y:hidden;\" onkeydown=\"HandleKeydown('search')\">";
//		x+= 	"<div>"+text('DS/FMTI')+"</div>";
		x+= 	"<div class=\"ds_form_header\">"+text('DS/FMTI')+"</div>";
//		x+= 	"<div style=\"padding:5px 20px\"><input type=\"text\" id=\"SearchSourceName\" onfocus=\"cur_search_type='DSRS'\" size=\"30\" maxlength=\"50\" style=\"border:1px solid #666;\"/></div>";
		x+= 	"<div style=\"padding:0px 0px 0px 40px\"><input type=\"text\" id=\"SearchSourceName\" onfocus=\"cur_search_type='DSRS'\" size=\"30\" maxlength=\"50\" style=\"border:1px solid #666;\"/></div>";
//		x+=		 "<div>"+text('DS/FMSO')+"</div>";
		x+=		 "<div class=\"ds_form_header\">"+text('DS/FMSO')+"</div>";
//		x+=		 "<div style=\"padding:5px 20px\">";
		x+=		 "<div style=\"padding:2px 0px 0px 40px\">";
		x+=			 "<span class=\"ds_form_section\">";
		x+=			 	"<div class=\"generic_title\" style=\"text-align:center;\">"+text('DS/LOCL')+"</div>";
		x+= 			"<div><input type=\"checkbox\" id=\"SearchSourceCheckBox_SysSpeedDial\" /><label for=\"SearchSourceCheckBox_SysSpeedDial\">"+text('DS/SPDL')+"</label></div>";
		x+= 			"<div><input type=\"checkbox\" id=\"SearchSourceCheckBox_MyAddressBook\" /><label for=\"SearchSourceCheckBox_MyAddressBook\">"+text('DS/MYAB')+"</label></div>";
		x+= 			"<div><input type=\"checkbox\" id=\"SearchSourceCheckBox_Devices\" /><label for=\"SearchSourceCheckBox_Devices\">"+text('DS/DEVI')+"</label></div>";
		x+= 			"<div><input type=\"checkbox\"><xsl:attribute name=\"id\">SearchSourceCheckBox_ACCOUNTS</xsl:attribute></input><label for=\"SearchSourceCheckBox_ACCOUNTS\">"+text('DS/ACTS')+"</label></div>";
		x+= 		"</span>";
		x+= 		"<span class=\"ds_form_section\">";
		x+= 			"<div class=\"generic_title\" style=\"text-align:center;\">"+text('DS/REMT')+"</div>";
		x+=				"<xsl:choose>";
		x+=				"<xsl:when test=\"DIRECTORIES/DIRECTORY[Enabled='true' or Enabled='True' or Enabled='TRUE'][0]\">";
		x+= 			"<xsl:for-each select=\"DIRECTORIES/DIRECTORY[Enabled='true' or Enabled='True' or Enabled='TRUE']\">";
		x+= 				"<div>";
		x+= 					"<xsl:element name=\"input\">";
		x+= 						"<xsl:attribute name=\"type\">checkbox</xsl:attribute>";
		x+= 						"<xsl:attribute name=\"id\">SearchSourceCheckBox_Ext_<xsl:value-of select=\"Description\"/></xsl:attribute>";
		x+= 					"</xsl:element><label><xsl:attribute name=\"for\">SearchSourceCheckBox_Ext_<xsl:value-of select=\"Description\"/></xsl:attribute><xsl:value-of select=\"Description\" /></label>";
		x+= 				"</div>";
		x+=	 			"</xsl:for-each>";
		x+=				"</xsl:when>";
		x+=				"<xsl:otherwise><span style=\"width:100%;text-align:center\">"+text('DS/NO_REMT')+"</span></xsl:otherwise>";
		x+=				"</xsl:choose>";
		x+= 		"</span>";
		x+= 	"</div>";
		x+= "</div>";
		break;
		
/*
FWD ALL CALLS OAI
FWD IF NO ANSWER OAI
FWD IF BUSY OAI
FWD IF NA/BUSY OAI
*/

		case "DV":
		custom_style = "style=\"cursor:auto;\"";
		x+= "<xsl:template match=\"R\">";
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedInsertScript();
		x+= GetEmbeddedFeatureSupportScript();
		x+= "]]></xsl:script>";
		x+= "<xsl:for-each select=\"DEVICES/DEVICE[OwnerAccount = context(-1)/ACCOUNT//UniqueID]\" order-by=\"Extension\">";
		x+= Insert(custom_style, rowHTML);
		x+= "<xsl:attribute name=\"id\">row"+ type +"<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= "<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= "<xsl:attribute name=\"style\">padding:3px:0px;</xsl:attribute>";
		x+= 	"<span class=\"cellDV0\" style=\"vertical-align:top;padding-top:5px\">";
		x+= 		"<xsl:if test=\"DeviceStatus/DEVICE_STATUS[PrimaryMessage != '']\"><img src=\"img/iKeysetDND.gif\" class=\"icon\"/></xsl:if>";
		x+= 		"<xsl:if test=\"DeviceStatus/DEVICE_STATUS[PrimaryMessage = '']\"><img src=\"img/iKeyset.gif\" class=\"icon\"/></xsl:if>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellDV1\">";
		x+= 		"<input type=\"text\" class=\"dv_name\" onfocus=\"this.select()\" onchange=\"TextChange()\" onkeydown=\"HandleKeydown('device_fwd', this)\" >";
		x+= 			"<xsl:attribute name=\"value\"><xsl:value-of select=\"Name\"/></xsl:attribute>";
		x+= 			"<xsl:attribute name=\"id\">dv_name_<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= 		"</input><br/>";
		x+= 		"<span style=\"width:100%;text-align:right;color:#666;padding:3px 10px;font-family:Tahoma;\">x <xsl:value-of select=\"Extension\"/></span>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellDV2\">";
		x+= 		"<select class=\"dv_select\" onchange=\"TextChange()\" prop=\"DND\">";
		x+= 		"<xsl:attribute name=\"id\">dv_DND_select_<xsl:value-of select=\"Extension\"/></xsl:attribute>"
		x+= 			"<option>----- "+ text('DV/OFF') +" -----</option>";
		x+= 			"<xsl:choose>";
						// device supports extended DND message list
		x+= 			"<xsl:when expr=\"FeatureCodeIsSupportedForThisStationType(this, 'DND OAI EXTENDED')\">";
		x+= 				"<xsl:for-each select=\"/R/NODES/NODE[NodeNameElements//NodeID = context(-1)/NodeID]/DNDMessages/LIST//String\"><option><xsl:attribute name=\"value\"><xsl:value-of select=\".\"/></xsl:attribute><xsl:value-of select=\".\"/></option></xsl:for-each>";
		x+= 			"</xsl:when>";
						// device in SIP mode and only supports on/off
		x+= 			"<xsl:when expr=\"FeatureCodeIsSupportedForThisStationType(this, 'DND OAI BASIC')\">";
		x+= 				"<xsl:for-each select=\"/R/NODES/NODE[NodeNameElements//NodeID = context(-1)/NodeID]/DNDMessages/LIST/*[STR][0]//String\"><option><xsl:attribute name=\"value\"><xsl:value-of select=\".\"/></xsl:attribute><xsl:value-of select=\".\"/></option></xsl:for-each>";
		x+= 			"</xsl:when>";
		x+= 			"</xsl:choose>";
		x+= 			"</select>";
		x+= 		"<input type=\"text\" class=\"dv_extra_text\" onfocus=\"this.select()\" onchange=\"TextChange()\" onkeydown=\"HandleKeydown('device_dnd', this)\" prop=\"DND\" maxlength=\"16\">";
		x+= 			"<xsl:attribute name=\"id\">dv_DND_input_<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= 			"<xsl:attribute name=\"value\"><xsl:value-of select=\"DeviceStatus/DEVICE_STATUS/SecondaryMessage\"/></xsl:attribute>"
		x+= 		"</input>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellDV3\">";
		x+= 		"<select class=\"dv_select\" onchange=\"TextChange()\" prop=\"FWD\">";
		x+= 		"<xsl:attribute name=\"id\">dv_FWD_select_<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= 			"<option value=\"N\">----- "+ text('DV/NONE') +" -----</option>";
		x+= 			"<xsl:if expr=\"FeatureCodeIsSupportedForThisStationType(this, 'FWD ALL CALLS OAI')\">";
		x+= 				"<option value=\"I\">" + text('DV/FAL') +"</option>";
		x+= 			"</xsl:if>";
		x+= 			"<xsl:if expr=\"FeatureCodeIsSupportedForThisStationType(this, 'FWD IF NO ANSWER OAI')\">";
		x+= 				"<option value=\"NA\">"+ text('DV/FNO') +"</option>";
		x+= 			"</xsl:if>";
		x+= 			"<xsl:if expr=\"FeatureCodeIsSupportedForThisStationType(this, 'FWD IF BUSY OAI')\">";
		x+= 				"<option value=\"B\">" + text('DV/FBU') +"</option>";
		x+= 			"</xsl:if>";
		x+= 			"<xsl:if expr=\"FeatureCodeIsSupportedForThisStationType(this, 'FWD IF NA/BUSY OAI')\">";
		x+= 				"<option value=\"NB\">"+ text('DV/FNB') +"</option>";
		x+= 			"</xsl:if>";
		x+= 		"</select>";
		x+= 		"<input type=\"text\" class=\"dv_extra_text\" onfocus=\"this.select()\" onchange=\"TextChange()\" onkeydown=\"HandleKeydown('device_fwd', this)\" prop=\"FWD\">";
		x+= 			"<xsl:attribute name=\"id\">dv_FWD_input_<xsl:value-of select=\"Extension\"/></xsl:attribute>";
		x+= 			"<xsl:attribute name=\"value\"><xsl:value-of select=\"ForwardingSettings//ForwardDestination\"/></xsl:attribute>";
		x+= 		"</input>"; 
		x+= 	"</span>";
		x+= 	"<span class=\"cellDV4\" style=\"vertical-align:top;font-size:10px;font-weight:bold;color:#999\">";
		x+= 		"<input type=\"radio\" onclick=\"SetPrimaryDevice(this)\" name=\"PrimaryDeviceRadio\" style=\"vertical-align:middle\"><xsl:attribute name=\"id\">dv_primary_<xsl:value-of select=\"Extension\"/></xsl:attribute><xsl:attribute name=\"extension\"><xsl:value-of select=\"Extension\"/></xsl:attribute></input> "+text('DV/PRI') +"<br/>";
		x+=			"<span style=\"width:100%;padding-top:3px;vertical-align:middle;\">";
		x+=				"<xsl:choose>";
		x+= 			"<xsl:when test=\"/R/NODES/NODE[NodeNameElements//NodeID = context(-1)/NodeID]/NodeNameElements//Active[.='true' or .='True' or .='TRUE']\">";
		x+= 				"<img src=\"img/iFCArrowDn.gif\" class=\"icon_hot\"/>";
		x+= 				"<img src=\"img/iSetPass.gif\" class=\"icon_hot\"/>";
		x+= 			"</xsl:when>";
		x+=				"<xsl:otherwise>";
		x+= 				"<img src=\"img/iFCArrowDnDISABLED.gif\" class=\"icon\"/>";
		x+= 				"<img src=\"img/iSetPassDISABLED.gif\" class=\"icon\"/>";
		x+= 			"</xsl:otherwise>";
		x+=				"</xsl:choose>";
		x+= 		"<img src=\"img/iClose.gif\" class=\"icon_hot\"/>";
		x+=			"</span>";
		x+= 	"</span>";
		x+= "</div>";
		x+= "</xsl:for-each>";
		break;
		
		case "GPAB":
		x+= "<xsl:template match=\"CONTACT\">";
		x+= "<div class=\"cssMenuItemLine\" type=\""+type+"\" onclick=\"ChangeRowColorForClick(this)\" style=\"background-color:#fff\">";
		x+= 	"<xsl:attribute name=\"id\">rowGPAB<xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 	"<xsl:choose>";
		x+= 		"<xsl:when test=\".[LinkType='A']\"><img src=\"img/iAct.gif\" type=\"GPAB\" style=\"cursor:move\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" alt=\""+text('GP/DRAG')+"\" /></xsl:when>";
		x+= 		"<xsl:when test=\".[LinkType='D']\"><img src=\"img/iKeyset.gif\" type=\"GPAB\" style=\"cursor:move\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" alt=\""+text('GP/DRAG')+"\" /></xsl:when>";
		x+= 		"<xsl:when test=\".[FirstName='' and LastName='' and Company!='']\"><img src=\"img/iBusiness.gif\" type=\"GPAB\" style=\"cursor:move\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" alt=\""+text('GP/DRAG')+"\" /></xsl:when>";
		x+= 		"<xsl:otherwise><img src=\"img/iContact.gif\" type=\"GPAB\" style=\"cursor:move\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" alt=\""+text('GP/DRAG')+"\" /></xsl:otherwise>";
		x+= 	"</xsl:choose>";
		x+= 	"<span style=\"height:16px;padding-left:10px\">"+ GetXSLSortedNameLogic(type) +"</span>";
		x+= "</div>";
		break;
		
		case "GPLS":
		x+= "<xsl:template match=\"GROUP\">";
		x+=		"<div class=\"cssMenuItem\" type=\""+type+"\" ondragenter=\"enterDragMenu()\" ondragover=\"overDrag()\" ondrop=\"dropMenu()\">";
		x+=			"<xsl:attribute name=\"id\">group_<xsl:value-of select=\"Name\" /></xsl:attribute>";
		x+=			"<xsl:attribute name=\"name\"><xsl:value-of select=\"Name\" /></xsl:attribute>";
		x+=			"<xsl:attribute name=\"rank\"><xsl:value-of select=\"Rank\" /></xsl:attribute>";
		x+=			"<div class=\"cssMenuItemHead\" type=\""+type+"\" onclick=\"ChangeGroupNameColorForClick(this)\">";
		x+= 			"<img src=\"img/iGroup.gif\" type=\"GP\" style=\"float:right;cursor:move\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" alt=\"Drag icon up or down to re-order Groups\"/>";
		x+= 			"<xsl:choose>";
		x+= 				"<xsl:when test=\"/R/AB/CONTACT[Groups/LIST//String = context(-1)/Name][0]\">";
		x+= 					"<xsl:if test=\"context(-1)[@open='false']\"><img src=\"img/iExpPlus.gif\" class=\"icon_hot\" style=\"float:left;margin-right:5px;\"/></xsl:if>";
		x+= 					"<xsl:if test=\"context(-1)[@open='true']\"><img src=\"img/iExpMinus.gif\" class=\"icon_hot\" style=\"float:left;margin-right:5px;\"/></xsl:if>";
		x+= 				"</xsl:when>";
		x+= 				"<xsl:otherwise><img src=\"img/pix.gif\" class=\"icon\" style=\"float:left;margin-right:5px;cursor:default\"/></xsl:otherwise>";
		x+= 			"</xsl:choose>";
		x+=				"<xsl:value-of select=\"Name\" />";
		x+=			"</div>";
		x+=			"<div class=\"cssMenuItemBody\">";
		x+= 			"<xsl:if test=\"context(-1)[@open='false']\"><xsl:attribute name=\"style\">display:none</xsl:attribute></xsl:if>";
		x+= 			"<xsl:for-each select=\"/R/AB/CONTACT[Groups/LIST//String = context(-1)/Name]\" order-by=\"FirstName\">";
		x+=					"<div class=\"cssMenuItemLine\" type=\""+type+"\" onclick=\"ChangeRowColorForClick(this)\" style=\"cursor:hand;padding-left:20px\">";
		x+= 					"<xsl:attribute name=\"id\">rowGP<xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 					"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 					"<xsl:choose>";
		x+= 						"<xsl:when test=\".[LinkType='A']\"><img src=\"img/iAct.gif\" type=\"GPLS\" deletePermitted=\"true\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" /></xsl:when>";
		x+= 						"<xsl:when test=\".[LinkType='D']\"><img src=\"img/iKeyset.gif\" type=\"GPLS\" deletePermitted=\"true\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" /></xsl:when>";
		x+= 						"<xsl:when test=\".[FirstName='' and LastName='' and Company!='']\"><img src=\"img/iBusiness.gif\" type=\"GPLS\" deletePermitted=\"true\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" /></xsl:when>";
		x+= 						"<xsl:otherwise><img src=\"img/iContact.gif\" type=\"GPLS\" deletePermitted=\"true\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" /></xsl:otherwise>";
		x+= 					"</xsl:choose>";
		x+=						"<span style=\"height:16px;padding-left:15px;overflow:hidden\">"+ GetXSLSortedNameLogic(type) +"</span>";
		x+=					"</div>";
		x+=				"</xsl:for-each>";
		x+=			"</div>";
		x+=		"</div>";
		break;
		
		case "GT":
		x+= "<xsl:template match=\"GREETING\">";
		x+=		Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">rowGT<xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+=		"<xsl:if test=\".[Filename='']\">";
		x+= 		"<span class=\"cellGT0\"><img src=\"img/iConstruction.gif\" class=\"icon\"/></span>";
		x+= 		"<span class=\"cellGT1\">"+text('GT/CREATE')+" [ <xsl:value-of select=\"Description\"/> ]</span>";
		x+= 		"<span class=\"cellGT2\"></span>";
		x+= 	"</xsl:if>";
		x+=		"<xsl:if test=\".[Filename!='']\">";
		x+= 		"<span class=\"cellGT0\"><img src=\"img/iGreeting.gif\" class=\"icon\"/></span>";
		x+= 		"<span class=\"cellGT1\"><xsl:value-of select=\"Description\"/></span>";
		x+= 		"<span class=\"cellGT2\"><img src=\"img/iPlayGreeting.gif\" class=\"icon_hot\"/><img src=\"img/iRecordGreeting.gif\" class=\"icon_hot\"/><img src=\"img/iEdit.gif\" class=\"icon_hot\"/></span>";
		x+= 	"</xsl:if>";
		x+= "</div>";
		break;
		
		case "FCUSER":
		case "FCADMN":
		case "FCFAVS":
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedInsertScript();
		x+= GetEmbeddedFeatureSupportScript();
		x+= "]]></xsl:script>";
		x+= "<xsl:template match=\"FEATURE_CODE\">";
		x+= "<xsl:if expr=\"FeatureCodeIsSupportedForThisStationType(this)\">";
		x+= 	Insert(custom_style, rowHTML);
		x+= 		"<xsl:attribute name=\"id\">rowFC<xsl:value-of select=\"Description\" /></xsl:attribute>";
		x+= 		"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"Description\" /></xsl:attribute>";
		x+= 		"<xsl:attribute name=\"description\"><xsl:value-of select=\"Description\" /></xsl:attribute>";
		x+= 			"<span class='cell"+ type +"0' style=\"width:30%\"><a href=\"javascript://\" class=\"FeatCodeLink\"><xsl:attribute name=\"onclick\">ExecuteFeatureCodeFromDeviceView('<xsl:value-of select=\"Code\" />')</xsl:attribute><xsl:value-of select=\"Code\" /></a></span>";
		x+= 			"<span class='cell"+ type +"1' style=\"width:65%\"><a href=\"javascript://\" class=\"FeatCodeLink\"><xsl:attribute name=\"onclick\">ExecuteFeatureCodeFromDeviceView('<xsl:value-of select=\"Code\" />')</xsl:attribute><xsl:value-of select=\"Description\" /></a></span>";
		x+= 	"</div>";
		x+= "</xsl:if>";
		break;
		
		case "MS":
		//<MSG_WAITING><NodeID></NodeID><Extension></Extension><SourceName></SourceName><SourceNodeExtension></SourceNodeExtension><Mailbox></Mailbox><NumberOfMessages>-842150451</NumberOfMessages></MSG_WAITING>
		x+= "<xsl:template match=\"MSG_WAITING | SYSTEM_MESSAGE\">";
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= "]]></xsl:script>";
		x+=	Insert(custom_style, rowHTML);
		x+=		"<xsl:attribute name=\"msg_type\"><xsl:eval>this.nodeName</xsl:eval></xsl:attribute>";
		x+= 	"<xsl:choose>";
		x+=		"<xsl:when test=\".[nodeName()='SYSTEM_MESSAGE']\"><xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute></xsl:when>";
		x+=		"<xsl:otherwise><xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"SourceNodeExtension\" /></xsl:attribute></xsl:otherwise>";
	  	x+=		"</xsl:choose>";
		x+= 	"<span class=\"cellMS0\">";
		x+= 		"<xsl:choose>";
		x+=			"<xsl:when test=\".[nodeName()='SYSTEM_MESSAGE']\"><img src=\"img/iSystemMessage.gif\" class=\"icon\"/></xsl:when>";
		x+=			"<xsl:when test=\".[Mailbox = '']\"><img src=\"img/iKeysetSM.gif\" class=\"icon\"/></xsl:when>";
		x+=			"<xsl:otherwise><img src=\"img/iVoicemail.gif\" class=\"icon\"/></xsl:otherwise>";
	  	x+=		"</xsl:choose>"
		x+= 	"</span>";
		x+= 	"<span class=\"cellMS1\">";
		x+= 		"<xsl:choose>";
		x+=			"<xsl:when test=\".[nodeName()='SYSTEM_MESSAGE']\"><xsl:value-of select=\"Translation\"/></xsl:when>";
		x+=			"<xsl:otherwise>";
		x+= 			"<a href=\"#\"><xsl:attribute name=\"onclick\">CheckMessage('<xsl:value-of select=\"SourceNodeExtension\"/>', '<xsl:value-of select=\"Mailbox\"/>');return false</xsl:attribute>";
		x+= 				"<xsl:value-of select=\"SourceName\"/>";
		x+= 				"<xsl:if test=\".[Extension!='']\"> (<xsl:eval>removeNodePrefix(this,'SourceNodeExtension')</xsl:eval>)</xsl:if>";
		x+= 			"</a>";
		x+=			"</xsl:otherwise>";
		x+=			"</xsl:choose>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellMS2\"><xsl:value-of select=\"Mailbox\"/>&#160;</span>";
		x+= 	"<span class=\"cellMS3\"><xsl:value-of select=\"NumberOfMessages\"/></span>";
		x+= 	"<span class=\"cellMS4\">";
		x+= 		"<xsl:choose>";
		x+=			"<xsl:when test=\".[nodeName() = 'SYSTEM_MESSAGE']\"><img src=\"img/iView.gif\" class=\"icon_hot\"/></xsl:when>";
		x+=			"<xsl:otherwise>&#160;</xsl:otherwise>";
		x+=			"</xsl:choose>";
		x+= 	"</span>";
		x+= "</div>";
		break;
		
		case "NADL":
		x+= "<xsl:template match=\"CONTACT\">";
		x+=		"<div class=\"tableRow\" style=\"height:25px\">";
		x+= 		"<xsl:attribute name=\"id\">rowNADL<xsl:value-of select=\"WorkNumber1\" /></xsl:attribute>";
		x+=			"<span class=\"cellNADL0\"><input type=\"checkbox\"><xsl:attribute name=\"id\">na_device_add_<xsl:value-of select=\"WorkNumber1\" /></xsl:attribute><xsl:attribute name=\"nodeInfo\"><xsl:value-of select=\"LinkedTo\" /></xsl:attribute></input></span>";
		x+=			"<span class=\"cellNADL1\"><input type=\"text\"><xsl:attribute name=\"class\">na_input</xsl:attribute><xsl:attribute name=\"id\">na_device_name_<xsl:value-of select=\"WorkNumber1\" /></xsl:attribute><xsl:attribute name=\"value\"><xsl:value-of select=\"FirstName\" /><xsl:if test=\".[LastName!='']\">&#160;<xsl:value-of select=\"LastName\" /></xsl:if></xsl:attribute></input></span>";
		x+=			"<span class=\"cellNADL2\"><xsl:value-of select=\"WorkNumber1\" /></span>";
		x+=			"<span class=\"cellNADL3\"><input type=\"password\"><xsl:attribute name=\"class\">na_input</xsl:attribute><xsl:attribute name=\"id\">na_device_pass_<xsl:value-of select=\"WorkNumber1\" /></xsl:attribute><xsl:attribute name=\"value\"><xsl:value-of select=\"CallerIDNumber\" /></xsl:attribute><xsl:attribute name=\"nodeInfo\"><xsl:value-of select=\"LinkedTo\" /></xsl:attribute></input></span>";
		x+=			"<span class=\"cellNADL4\"><input type=\"radio\" name=\"na_device_primary\"><xsl:attribute name=\"ext\"><xsl:value-of select=\"WorkNumber1\" /></xsl:attribute></input></span>";
		x+=		"</div>";
		break;
		
		case "RR":
		x+= "<xsl:template match=\"RULE\">";
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedDeviceNameLookupScript();
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= GetEmbeddedInsertScript();
		x+= GetEmbeddedAccountFieldValueScript();
		x+= "]]></xsl:script>";
		x+=	Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">rowRR<xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<span class=\"cellRR0\">";
		x+= 		"<xsl:choose>";
		x+=				"<img src=\"img/iExpPlus.gif\" class=\"icon_hot\"/>";
		x+=				"<xsl:when test=\"Enabled[.='true' or .='True' or .='TRUE']\"><img src=\"img/iRuleOn.gif\" class=\"icon_hot\"/></xsl:when>";
		x+= 			"<xsl:otherwise><img src=\"img/iRuleOff.gif\" class=\"icon_hot\"/></xsl:otherwise>";
		x+= 		"</xsl:choose>";
		x+= 	"</span>";
		x+= 	"<span class=\"cellRR1\"><xsl:value-of select=\"Description\" /></span>";
		x+= 	"<span class=\"cellRR2\"><img src=\"img/iEdit.gif\" class=\"icon_hot\"/><img src=\"img/iCopy.gif\" class=\"icon_hot\"/></span>";
		x+= 	"<div class=\"tableRowRuleDetail\" style=\"display:none;width:100%;\">";
		x+=			"<xsl:for-each select=\"/R/STEPS/STEP[@for = context(-1)/UniqueID]\" order-by=\"number(@index)\">";
		x+= 			"<div style=\"width:100%;height:20px;line-height:14px;color:#666\">";
		x+= 				"<span class=\"cellRR0\">&#160;</span>";
		x+= 				"<span class=\"cellRR1\">&#160;&#160;-&#160;&#160;"+ GetStepDescriptionLogic() +"</span>";
		x+= 				"<span class=\"cellRR2\">&#160;</span>";
		x+= 			"</div>";
		x+=			"</xsl:for-each>";
		x+= 	"</div>";
		x+= "</div>";
		break;
		
		case "RREDWA":
		x+= "<xsl:template match=\"STEP\">";
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedDeviceNameLookupScript();
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= GetEmbeddedInsertScript();
		x+= GetEmbeddedRowNumberScript();
		x+= GetEmbeddedAccountFieldValueScript();
		x+= "]]></xsl:script>";
		x+=	Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">rowRREDWA<xsl:value-of select=\"UniqueID\"/></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragenter\">enterStepDrag(this)</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragover\">overDrag()</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondragleave\">leaveDrag()</xsl:attribute>";
		x+= 	"<xsl:attribute name=\"ondrop\">dropStep(this)</xsl:attribute>";
		x+= 	"<span class=\"cellRREDWA0\"><img src=\"img/iStep.gif\" type=\"RREDWA\" style=\"cursor:move\" ondragstart=\"startDrag()\" alt=\"Drag icon up or down to re-order steps\" /></span>";
		x+= 	"<span class=\"cellRREDWA1\"><xsl:eval>GetRowNumber()</xsl:eval>.&#160;&#160;";
		x+=			GetStepDescriptionLogic();
		x+= 	"</span>";
		x+= 	"<span class=\"cellRREDWA2\"><img src=\"img/iEdit.gif\" class=\"icon_hot\"/></span>";
		x+= "</div>";
		//<ACCOUNT_NAME><UniqueID>setz</UniqueID><FirstName>Ron</FirstName><LastName>Setzer</LastName><TenantGroup>0</TenantGroup></ACCOUNT_NAME>
		//<DEVICE_NAME><DeviceType>0</DeviceType><NodeID>1</NodeID><Extension>1003</Extension><PBXSynchedDesc>Toby Ambrose</PBXSynchedDesc><PBXSynchedUsername>TOBY A.</PBXSynchedUsername></DEVICE_NAME>
		break;
		
		case "TA":
		case "DSRS":
		x+= "<xsl:template match=\"CONTACT\">";
		x+= "<xsl:script><![CDATA[";
		x+= GetEmbeddedRemoveNodePrefixScript();
		x+= GetEmbeddedFormatPhoneNumberScript();
		x+= "function isCallActive(e) {";
		x+= 	"var oActiveCall = e.selectSingleNode('/R/CALL_LIST/*[0]');";
		x+=     "return (oActiveCall) ? true: false;";
		x+=	"}";
		x+= "function isNumber(e, path) {";
		x+=     "return !isNaN(e.selectSingleNode(path).text);";
		x+=	"}";
		x+= "function isAddressBook(e, path) {";
		x+=     "return (e.selectSingleNode(path).text == \"Address Book\")? false: true;";
		//x+=     "return !isNaN(e.selectSingleNode(path).text);";
		x+=	"}";
		x+= "]]></xsl:script>";
		x+=	Insert(custom_style, rowHTML);
		if (type=="TA")
		{
			x+= "<xsl:attribute name=\"ondragover\">overDrag()</xsl:attribute>";
			x+= "<xsl:attribute name=\"ondragenter\">this.style.backgroundColor='#ff9'</xsl:attribute>";
			x+= "<xsl:attribute name=\"ondragleave\">this.style.backgroundColor=this.prevColor</xsl:attribute>";
			x+= 	"<xsl:attribute name=\"ondrop\">this.style.backgroundColor=this.prevColor;TransferDragAndDrop(this)</xsl:attribute>";
		}
		x+= 	"<xsl:attribute name=\"id\">row"+ type +"<xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"type\">"+ type +"</xsl:attribute>";
		x+= 	"<span class=\"cell"+type+"0\">";
		x+= 		GetXSLStatusLogic(type);
		x+= 	"</span>";
		x+= 	"<span class=\"cell"+type+"1\">";
		x+= 		GetXSLSortedNameLogic(type);
		x+= 	"</span>";
		x+= 	"<span class=\"cell"+type+"2\">";
		x+= 		"<xsl:choose>"
		x+= 		"<xsl:when expr=\"isNumber(this, 'ModifyTimeStamp')\">";
		x+= 			"<xsl:choose>"
						// when there's more than one tenant group
		x+= 			"<xsl:when test=\"/R/TENANT_GROUPS/TENANT_GROUP[1]\"><xsl:value-of select=\"/R/TENANT_GROUPS/TENANT_GROUP[UniqueID = context(-1)/ModifyTimeStamp]/Name\" /></xsl:when>";
		x+= 			"<xsl:otherwise>"+text('GBL/ACC')+"</xsl:otherwise>";
		x+= 			"</xsl:choose>";
		x+= 		"</xsl:when>";
		x+= 		"<xsl:otherwise>";//<xsl:value-of select=\"ModifyTimeStamp\" /></xsl:otherwise>";
		x+=         "<xsl:choose><xsl:when expr=\"isAddressBook(this, 'ModifyTimeStamp')\"><xsl:value-of select=\"ModifyTimeStamp\" /></xsl:when><xsl:otherwise>"+text('GBL/PRSNL_CTS')+"</xsl:otherwise></xsl:choose></xsl:otherwise>";
		x+= 		"</xsl:choose>";
		x+= 	"</span>";
		x+= 	"<span class=\"cell"+type+"3\">";
		x+= 		GetXSLNoPhoneNumberLogic(type);
		x+= 		"<xsl:choose><xsl:when test=\"Emails/LIST//String[0]\"><img src=\"img/iEmail.gif\" class=\"icon_hot\"/></xsl:when></xsl:choose>";
		x+= 	"</span>";
		x+= "</div>";
		break;
		
		case "TARRWA":
		case "TARRWO":
		x+= "<xsl:template match=\"CONTACT\">";
		x+=		Insert(custom_style, rowHTML);
		x+= 	"<xsl:attribute name=\"id\">row"+ type +"<xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"UniqueID\"><xsl:value-of select=\"UniqueID\" /></xsl:attribute>";
		x+= 	"<xsl:attribute name=\"type\">"+ type +"</xsl:attribute>";
		x+= 	"<span class=\"cell"+type+"0\">";
		x+= 		"<xsl:choose>";
		x+= 			"<xsl:when test=\".[ModifyTimeStamp='Personal Contacts']\">";
		x+= 				"<xsl:choose>";
		x+= 				"<xsl:when test=\".[LinkType='A']\"><img src=\"img/iContactA.gif\" class=\"icon\"/></xsl:when>";
		x+= 				"<xsl:when test=\".[LinkType='D']\"><img src=\"img/iContactD.gif\" class=\"icon\"/></xsl:when>";
		x+= 				"<xsl:when test=\".[LinkType='' and FirstName='' and LastName='']\"><img src=\"img/iContactB.gif\" class=\"icon\"/></xsl:when>";
		x+= 				"<xsl:otherwise><img src=\"img/iContact.gif\" class=\"icon\"/></xsl:otherwise>";
		x+= 				"</xsl:choose>";
		x+= 			"</xsl:when>";
		x+= 			"<xsl:when test=\".[LinkType='D']\"><img src=\"img/iKeyset.gif\" class=\"icon\"/></xsl:when>";
		x+= 			"<xsl:when test=\".[LinkType='A']\"><img src=\"img/iAct.gif\" class=\"icon\"/></xsl:when>";
		x+= 			"<xsl:otherwise>&#160;</xsl:otherwise>";//<img src=\"img/iContact.gif\" class=\"icon\"/>
		x+= 		"</xsl:choose>";
		x+= 	"</span>";
		x+= 	"<span class=\"cell"+type+"1\">";
		x+= 			GetXSLSortedNameLogic(type);
		x+= 	"</span>";
		x+= "</div>";	
		break;
	}
	x+= "</xsl:template>";
	return x;
}

function GetStepDescriptionLogic()
{
	var x="";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_PLAY_GREETING+"']\">"+text('RR/STEP_TYPE_GREET')+" (<xsl:value-of select=\"/R/GREETINGS/GREETING[UniqueID = context(-1)/Greeting]/Description\" />)</xsl:if>";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_SEND_TO_CURRENT_LOCATION+"']\">"+text('RR/STEP_TYPE_CUR_LOC')+"</xsl:if>";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_SEND_TO_LOCATION+"']\">"+text('RR/STEP_TYPE_SEND_LOC') +"&#160;";
	x+= 		"<xsl:choose>";
	x+=				"<xsl:when test=\".[number(LocationType)=0]\"><xsl:eval>removeNodePrefix(this, 'Destination')</xsl:eval></xsl:when>";
	x+=				"<xsl:when test=\".[number(LocationType)=1]\"><xsl:eval>getDeviceName(this, 'Destination')</xsl:eval> <xsl:eval>removeNodePrefix(this, 'Destination')</xsl:eval></xsl:when>";
	x+=				"<xsl:when test=\".[number(LocationType) $gt$ 1]\">";
	x+=					"<xsl:for-each select=\"/R/CONTACT_FIELDS/FIELD[@locType = context(-1)/LocationType][0]\"><xsl:value-of select=\".\" /> <xsl:eval>getAccountValue(this)</xsl:eval></xsl:for-each>"; //<xsl:eval>removeNodePrefix(this, '/R/ACCOUNT//*[nodeName() = context(-1)/@name]')</xsl:eval>
	x+=				"</xsl:when>";
	x+= 		"</xsl:choose>";
	x+=		"</xsl:if>";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_SEND_TO_CONTACT+"']\">"+text('RR/STEP_TYPE_SEND_CON')+ "&#160;";
	x+=			"<xsl:for-each select=\"/R/AB/CONTACT[UniqueID = context(-1)/Destination][0]\">";
	x+= 		"<xsl:choose>";
	x+=				"<xsl:when test=\".[FirstName!='' and LastName!='']\"><xsl:value-of select=\"FirstName\"/> <xsl:value-of select=\"LastName\"/></xsl:when>";
	x+=				"<xsl:otherwise><xsl:value-of select=\"Company\"/></xsl:otherwise>";
	x+= 		"</xsl:choose>";
	
	x+=			"<xsl:if test=\"context(-2)[number(LocationType) $gt$ 1]\">";
	x+=				"<xsl:for-each select=\"/R/CONTACT_FIELDS/FIELD[@locType = context(-2)/LocationType][0]\"> (<xsl:value-of select=\".\" />)</xsl:for-each>"; //<xsl:value-of select=\"context(-2)/*[nodeName()=context(-1)/@name]\" />
	x+=			"</xsl:if>";
	
	x+=			"</xsl:for-each>";
	x+=		"</xsl:if>";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_SEND_TO_DEVICE+"']\">"+text('RR/STEP_TYPE_SEND_DEV')+ "&#160;";
	x+=			"<xsl:for-each select=\"/R/TEMPORARY/DEVICE_NAME[NodeColonExtension = context(-1)/Destination][0]\">";
	x+= 			"<xsl:choose>";
	x+= 				"<xsl:when test=\".[PBXSynchedDesc!='']\"> <xsl:value-of select=\"PBXSynchedDesc\"/></xsl:when>";
	x+= 				"<xsl:when test=\".[PBXSynchedDesc='']\"> <xsl:value-of select=\"PBXSynchedUsername\"/></xsl:when>";
	x+= 			"</xsl:choose>";
	x+= 			" <xsl:eval>removeNodePrefix(this, './/Extension')</xsl:eval>";
	x+=			"</xsl:for-each>";
	x+=		"</xsl:if>";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_SEND_TO_ACCOUNT+"']\">"+text('RR/STEP_TYPE_SEND_ACT')+ "&#160;";
	x+=			"<xsl:for-each select=\"/R/TEMPORARY/ACCOUNT_NAME[UniqueID = context(-1)/Destination][0]\">";
	x+=				" <xsl:value-of select=\"FirstName\"/> <xsl:value-of select=\"LastName\"/>";
	x+=			"</xsl:for-each>";
	x+=			"<xsl:if test=\".[number(LocationType) $gt$ 1]\">";
	x+=				"<xsl:for-each select=\"/R/CONTACT_FIELDS/FIELD[@locType = context(-1)/LocationType][0]\"> (<xsl:value-of select=\".\" />)</xsl:for-each>"; //<xsl:value-of select=\"context(-2)/*[nodeName()=context(-1)/@name]\" />
	x+=			"</xsl:if>";
	x+=		"</xsl:if>";	
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_TRANSFER_TO_ACCOUNT+"']\">"+text('RR/STEP_TYPE_TRAN_ACT')+ "&#160;";
	x+=			"<xsl:for-each select=\"/R/TEMPORARY/ACCOUNT_NAME[UniqueID = context(-1)/Destination][0]\">";
	x+=				" <xsl:value-of select=\"FirstName\"/> <xsl:value-of select=\"LastName\"/>";
	x+=			"</xsl:for-each>";
	x+=		"</xsl:if>";		
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_TRANSFER_TO_VOICEMAIL+"']\">"+text('RR/STEP_TYPE_TRAN_VM')+"</xsl:if>";
	x+=		"<xsl:if test=\".[StepType='"+_STEPTYPE_HANG_UP+"']\">"+text('RR/STEP_TYPE_HANGUP')+"</xsl:if>";
	x+=		"<xsl:if test=\".[Duration!='0' and Duration!='']\"> <xsl:eval>Insert(this.selectSingleNode('Duration').text, '"+ (' '+text('RR/STEP_DURATION'))+"')</xsl:eval></xsl:if>";
	return x;
}

function GetEmbeddedRemoveNodePrefixScript()
{
	var x= "function removeNodePrefix(e, path) {";
	x+= 	"var re_nodeprefix = new RegExp('[0-9]{1,2}:');";
	x+= 	"var num = (path) ? e.selectSingleNode(path).text : e.text;";
	x+=		"num = num.replace(re_nodeprefix,'');";
	x+=		"var re_formatted = new RegExp('[^0123456789*#PF]');";
	x+= 	"return (re_formatted.test(num)) ? num : formatPhoneNumber(num, e);";
	x+= "}";
	return x;
}

function GetEmbeddedFormatPhoneNumberScript()
{
	var x= "function formatPhoneNumber(str,e) {";
	x+=		"var sub_node, format_node, re_is_string = new RegExp('[^0123456789*#PF]');";
	x+=		"if (re_is_string.test(str))";
	x+=			"sub_node = e.selectSingleNode(str);";
	x+=		"str = (e && sub_node) ? sub_node.text : str;";
	x+=		"format_node = e.selectSingleNode('/R/FORMATTING/PhoneNumberFormats/Phone_Number_Format_'+str.length);";
	x+=		"if (format_node && !re_is_string.test(str))";
	x+= 	"{";
	x+= 		"var format_string = format_node.text, i=0;";
	x+= 		"while (str.charAt(i))";
	x+= 			"format_string = format_string.replace('{'+i+'}', str.charAt(i++));";
	
	x+= 		"return format_string;";
	x+= 	"}";
	x+= 	"return str;";
	x+= "}";
	return x;
}

function GetEmbeddedFeatureSupportScript()
{
	// oObj may be the feature code itself or a device
	// in the device case, the description will be provided
	var x=	"function FeatureCodeIsSupportedForThisStationType(oObj, fc_description) {";
	x+= 	"var oDevice, oFC, oCfgDevice, oCfgCode, cur_ext, b_IS_INCLUSIVE=false;";
	
	// 		building Favorites list, oObj is a FEATURE CODE with a custom fc_description, walk up the parent tree to find the Device
	x+=     "if (fc_description == 'UC_FAVORITE')";
	x+=     "{";
	x+=    		"oFC 		= oObj;";
	x+= 		"oDevice 	= oObj.parentNode.parentNode.parentNode.parentNode;";
	x+= 		"fc_description = oFC.selectSingleNode('Description').text;"
	x+=     "}";
	//		feature code table, oObj is a FEATURE CODE
	x+=     "else if (!fc_description)";
	x+=     "{"
	x+= 		"cur_ext 	='"+ getObj('dv_feature_codes').Extension+"';";
	x+=    		"oFC 		= oObj;";
	x+= 		"oDevice 	= oObj.selectSingleNode(Insert(cur_ext, '/R/DEVICES/DEVICE[Extension=\"{0}\"]'));";
	x+=     "}"
	//		device table, oObj is a DEVICE
	x+=     "else";
	x+=     "{";
	x+=    		"oDevice 	= oObj;";
	x+=     "}";
	
	x+= 	"oCfgDevice	= oObj.selectSingleNode(Insert(oDevice.selectSingleNode('StationType').text, '/R/FEATURE_CODE_SUPPORT/*/DEVICE[@station_type=\"{0}\"]'));";
	x+=		"if (oCfgDevice)";
	x+=		"{";
	x+= 		"b_IS_INCLUSIVE = (oCfgDevice.getAttribute('format')=='inclusive');";
	x+= 		"fc_description = (fc_description) ? fc_description : oFC.selectSingleNode('Description').text;"
	x+= 		"oCfgCode = oCfgDevice.selectSingleNode(Insert(fc_description, 'FC[.=\"{0}\"]'));";
	x+=		"}";
	x+= 	"if (oCfgCode)";
	x+= 	"	return b_IS_INCLUSIVE;";
	//		if there's no feature code return the opposite of the b_IS_INCLUSIVE value
	x+= 	"else if (oCfgDevice)";
	x+= 	"	return !b_IS_INCLUSIVE;";
	x+= 	"return true;";
	x+=	"}";
	return x;
}

function GetEmbeddedAccountFieldValueScript()
{
	var x= "function getAccountValue(oField) {";
	x+= 	"var str='', path = '/R/ACCOUNT//' + oField.getAttribute('name');";
	x+= 	"var node = oField.selectSingleNode(path);";
	x+=		"if (node)";
	x+= 		"str = removeNodePrefix(node, path);";
	x+= 	"return str;";
	x+= "}";
	return x;
}

function GetEmbeddedDeviceNameLookupScript()
{
	var x= "function getDeviceName(e, path) {";
	x+= 	"var str='', dest = e.selectSingleNode(path).text;";
	x+= 	"var re = new RegExp('[0-9]{1,2}:');";
	x+= 	"var device = e.selectSingleNode('/R/DEVICES/DEVICE[Extension = \"'+ dest.replace(re,'') +'\"]');";
	x+=		"if (device)";
	x+= 		"str = device.selectSingleNode('Name').text;";
	x+= 	"return str;";
	x+= "}";
	return x;
}

function GetEmbeddedInsertScript()
{
	var x= "function Insert(str, target)";
	x+= 	"{";
	x+= 	"return target.replace('{0}', str);";
	x+= 	"}";
	return x;
}

function GetEmbeddedInsertMultipleScript()
{
	var x= "function InsertMultiple(str_array, string)";
	x+= 	"{";
	x+= 		"var i=0;";
	x+= 		"while (i < str_array.length)";
	x+= 			"string = string.replace(('{'+i+'}'), str_array[i++]);";
	x+= 		"return string;";
	x+= 	"}";
	return x;
}

function GetEmbeddedCounterScript()
{
	var x= "var count=-1;";
	x+= "function CheckCount(num)";
	x+= 	"{";
	x+= 		"count++;";
	x+= 		"return (count < num);";
	x+= 	"}";
	return x;
}

function GetEmbeddedRowNumberScript()
{
	var x= "var count=0;";
	x+= "function GetRowNumber()";
	x+= 	"{";
	x+= 		"return ++count;";
	x+= 	"}";
	return x;
}

function FormatPhoneNumber(str,e)
{
	var sub_node, format_node, re_is_string = new RegExp('[^0123456789*#PF]');
	e = (e) ? e : oSys;
	// if the string is not a number, check if it's an xsl xpath
	if (re_is_string.test(str))
		sub_node = e.selectSingleNode(str);
	str = (e && sub_node) ? sub_node.text : str;
	format_node = e.selectSingleNode('/R/FORMATTING/PhoneNumberFormats/Phone_Number_Format_'+str.length);
	// if a format node exists and the string is a number
	if (format_node && !re_is_string.test(str))
	{
		var format_string = format_node.text, i=0;
		while (str.charAt(i))
			format_string = format_string.replace('{'+i+'}', str.charAt(i++));

		return format_string;
	}
	return str;
}

function StripPhoneNumber(str)
{
	var re = new RegExp('[^0123456789*#PF]', 'g');
	return str.replace(re, '');
}

function GetEmbeddedStripPhoneNumberLogic()
{
	var x= "function stripPhoneNumber(str)";
	x+= "{";
	x+= 	"var re = new RegExp('[^0123456789*#PF]', 'g');";
	x+= 	"return str.replace(re, '');";
	x+=	"}";
	return x;
}

var DEVICE_FEATURESTATUS_ENHANCED_SPEAKERPHONE_ENABLE = new Number(0x00000001);
var DEVICE_FEATURESTATUS_BACKGROUND_MUSIC             = new Number(0x00000002);
var DEVICE_FEATURESTATUS_DO_NOT_DISTURB               = new Number(0x00000004);
var DEVICE_FEATURESTATUS_HANDSFREE                    = new Number(0x00000008);
var DEVICE_FEATURESTATUS_HEADSET                      = new Number(0x00000010);
var DEVICE_FEATURESTATUS_HUNT_GROUP                   = new Number(0x00000020);
var DEVICE_FEATURESTATUS_CALL_FORWARD_BUSY            = new Number(0x00000040);
var DEVICE_FEATURESTATUS_CALL_FORWARD_NA              = new Number(0x00000080);
var DEVICE_FEATURESTATUS_CALL_FORWARD_BUSY_NA         = new Number(0x00000100);
var DEVICE_FEATURESTATUS_CALL_FORWARD_BUSY_ALL        = new Number(0x00000200);
var DEVICE_FEATURESTATUS_MUTE                         = new Number(0x00000400);
var DEVICE_FEATURESTATUS_PAGE                         = new Number(0x00000800);
var DEVICE_FEATURESTATUS_RING_INTERCOM_ALWAYS         = new Number(0x00001000);
var DEVICE_FEATURESTATUS_MESSAGE                      = new Number(0x00002000);
var DEVICE_FEATURESTATUS_SYSTEM_FORWARD               = new Number(0x00004000);
var DEVICE_FEATURESTATUS_AUTO_CO_ACCESS               = new Number(0x00008000);
var DEVICE_FEATURESTATUS_AUTO_IC_ACCESS               = new Number(0x00010000);
var DEVICE_FEATURESTATUS_DIAGNOSTICS_MODE             = new Number(0x00020000);
var DEVICE_FEATURESTATUS_ACD_AGENT                    = new Number(0x00040000);
var DEVICE_FEATURESTATUS_STATION_MONITOR              = new Number(0x00080000);
var DEVICE_FEATURESTATUS_SWITCH_KEYMAP                = new Number(0x00100000);
var DEVICE_FEATURESTATUS_AGENT_HELP                   = new Number(0x00200000);
var DEVICE_FEATURESTATUS_RECORD_A_CALL                = new Number(0x00400000);
var DEVICE_FEATURESTATUS_GROUP_LISTEN                 = new Number(0x00800000);
var DEVICE_FEATURESTATUS_DISPLAY_OUTSIDE_PARTY_NAME   = new Number(0x01000000);

function DeviceFlagActive(ext, flag)
{
	var my_device = oDevNode.selectSingleNode('DEVICE[Extension=\"'+ext+'\" and OwnerAccount=/R/ACCOUNT//UniqueID]');
	if (my_device)
	{
		var device_flags = new Number(my_device.selectSingleNode('FeatureStatusMaskLoLong').text);
		return (device_flags & flag);
	}
	return false;
}

function GetEmbeddedDeviceFlagsScript()
{
	var x="";
	x+= "function evalDeviceFlags(e, str) {";
	x+=		"var owner_device = e.selectSingleNode('Extension').text;";
	x+=		"var my_device = e.selectSingleNode('/R/DEVICES/DEVICE[Extension=\"'+owner_device+'\" and OwnerAccount=/R/ACCOUNT//UniqueID]');"; //and OwnerAccount=R/ACCOUNT//UniqueID
	x+=		"var img = '';"; 
	x+= 	"if (my_device)";
	x+= 	"{";
	x+= 		"var flags = new Number(my_device.selectSingleNode('FeatureStatusMaskLoLong').text);";
	x+= 		"var DEVICE_FEATURESTATUS_MUTE = "+DEVICE_FEATURESTATUS_MUTE+";";
	x+= 		"var DEVICE_FEATURESTATUS_RECORD_A_CALL = "+DEVICE_FEATURESTATUS_RECORD_A_CALL+";";
	x+= 		"var DEVICE_FEATURESTATUS_GROUP_LISTEN = "+DEVICE_FEATURESTATUS_GROUP_LISTEN+";";
	x+= 		"if (str=='mute' && (flags & DEVICE_FEATURESTATUS_MUTE))";
	x+= 			"return true;";
	x+= 		"if (str=='listen' && (flags & DEVICE_FEATURESTATUS_GROUP_LISTEN))";
	x+= 			"return true;";
	x+= 		"if (str=='record' && (flags & DEVICE_FEATURESTATUS_RECORD_A_CALL))";
	x+= 			"return true;";
	x+= 	"}";
	x+= 	"return false;";
	x+= "}";
	return x;
}

var ON_CALL_STATUS_FOR_ACCOUNT = 2;
var ON_CALL_STATUS_FOR_DEVICE = 1;

function GetXSLSortedNameLogic(type)
{
	var x="", xpath="";
	switch (type)
	{
		case 'AB':
		case 'GPAB':
		case 'GPLS':
			xpath = '/R/AB'; break;
			
		case 'TA':
		case 'DSRS':
		case 'TARRWO':
		case 'TARRWA':
			xpath = '/R/SEARCH_RESULTS'; break;
	}
	
	x+= "<xsl:choose>";
	x+=	"<xsl:when test=\".[FirstName != '' or LastName != '']\">";
	x+= 	"<xsl:choose>";
	x+=			"<xsl:when test=\""+xpath+"[@name"+type+"]\">";
	x+=				"<xsl:if test=\""+xpath+"[@name"+type+" = 'FirstName']\"><xsl:value-of select=\"FirstName\"/> <xsl:value-of select=\"LastName\"/></xsl:if>";
	x+=				"<xsl:if test=\""+xpath+"[@name"+type+" = 'LastName']\"><xsl:value-of select=\"LastName\"/>, <xsl:value-of select=\"FirstName\"/></xsl:if>";
	x+=			"</xsl:when>";
	x+= 		"<xsl:otherwise><xsl:value-of select=\"FirstName\"/> <xsl:value-of select=\"LastName\"/></xsl:otherwise>";
	x+= 	"</xsl:choose>";
	x+=	"</xsl:when>";
	x+=	"<xsl:when test=\".[Company != '']\"><xsl:value-of select=\"Company\"/></xsl:when>";
	x+= "<xsl:otherwise>&#160;</xsl:otherwise>";
	x+= "</xsl:choose>";
	return x;		
}

function GetXSLStatusLogic(type)
{
	var class_name = (type=='CG'||type=='TA'||type=='DSRS') ? "icon_hot" : "icon";
	var drag_code = "class=\""+class_name+"\"";
	if (type=='AB'||type=='UB')
	{
		drag_code += " type=\""+type+"\" ondragstart=\"startDrag()\" ondragend=\"endDrag()\" {0}";
		var drag_insert = (type=='UB') ? "deletePermitted=\"true\"" : "";
		drag_code = Insert(drag_insert, drag_code);
	}
	
	var x="<xsl:choose>";
	x+= 	"<xsl:when test=\"LinkType[.='D']\">";
	x+= 		"<xsl:choose>";
	x+= 		"<xsl:when test=\"/R/STATUS_LIST/DEVICE_STATUS[NodeColonExtension = context(-1)/LinkParameter]\">";
	x+=				"<xsl:for-each select=\"/R/STATUS_LIST/DEVICE_STATUS[NodeColonExtension = context(-1)/LinkParameter][0]\">";
	x+= 				"<xsl:choose>";
	x+= 				"<xsl:when test=\"@inactive\"><img src=\"img/iKeysetUNKN.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:when>";
	x+= 				"<xsl:when test=\"OnACall[.='TRUE' or .='True' or .='true']\"><img src=\"img/iKeysetCALL.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:when>";
	x+= 				"<xsl:when test=\"PrimaryMessage[. != '']\"><img src=\"img/iKeysetDND.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:when>";
	x+= 				"<xsl:otherwise><img src=\"img/iKeyset.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:otherwise>";
	x+= 				"</xsl:choose>";
	x+= 			"</xsl:for-each>";
	x+= 		"</xsl:when>";
	x+= 		"<xsl:otherwise><img src=\"img/iKeysetUNKN.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:otherwise>";
	x+= 		"</xsl:choose>";
	x+= 	"</xsl:when>";
	x+= 	"<xsl:when test=\"LinkType[.='A']\">";
	x+= 		"<xsl:choose>";
	x+= 		"<xsl:when test=\"/R/STATUS_LIST/ACC_STATUS[OwnerUniqueID = context(-1)/LinkParameter][0]\">";
	x+=				"<xsl:for-each select=\"/R/STATUS_LIST/ACC_STATUS[OwnerUniqueID = context(-1)/LinkParameter][0]\">";
	x+= 				"<xsl:choose>";
	x+= 				"<xsl:when test=\"OnACall[.='TRUE' or .='True' or .='true']\"><img src=\"img/iActCALL.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:when>";
	x+= 				"<xsl:when test=\"Available[.='TRUE' or .='True' or .='true']\"><img src=\"img/iAct.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:when>";
	x+= 				"<xsl:when test=\"Available[.='FALSE' or .='False' or .='false']\"><img src=\"img/iActUNAV.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:when>";
	x+= 				"<xsl:otherwise><img src=\"img/iActUNKN.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:otherwise>";
	x+= 				"</xsl:choose>";
	x+= 			"</xsl:for-each>";
	x+= 		"</xsl:when>";
	x+= 		"<xsl:otherwise><img src=\"img/iActUNKN.gif\" onmouseover=\"HandleIconMouse(this)\" "+drag_code+"/></xsl:otherwise>";
	x+= 		"</xsl:choose>";
	x+= 	"</xsl:when>";
	x+=		"<xsl:when test=\".[FirstName='' and LastName='' and Company!='']\"><img src=\"img/iBusiness.gif\" "+drag_code+"/></xsl:when>";
	x+= 	"<xsl:when test=\".[LinkType='' and ModifyTimeStamp='Personal Contacts']\">";
	x+= 		"<img src=\"img/iContact.gif\" "+drag_code+"/>";
	x+= 	"</xsl:when>";
	x+= 	"<xsl:otherwise>";
	x+= 		(type=='UB' || type=='AB' || type=='TA' || type=='DSRS') ? ("<img src=\"img/iContact.gif\" "+drag_code+"/>") : "<img src=\"img/pix.gif\" class=\"icon\" />";
	x+= 	"</xsl:otherwise>";
	x+= "</xsl:choose>";
	return x;
}

function GetXSLNoPhoneNumberLogic(type)
{
	var aNumbers = oRoot.selectNodes("CONTACT_FIELDS/FIELD[@locType and @type='TYPE_STRING_PHONE']"), i=0, x="";
	x+= "<xsl:choose>";
	x+= "<xsl:when test=\".[(";
	while (aNumbers[i])
	{
		x+= aNumbers[i].getAttribute('name')+ " != '' ";
		if (aNumbers[i+1])
			x+= "or ";
		i++;
	}
	x+= ") or (Emails/LIST/*/STR/String[0]) or (Devices/LIST/*/STR/String[0])]\">";
	x+= "<img src=\"img/icon_contactPerson.gif\" class=\"icon_hot\"/>";

	if (type=='TA')
		x+= "<xsl:if expr=\"isCallActive(this)\"><img src=\"img/iTransfer.gif\" class=\"icon_hot\"/></xsl:if>";
	x+= "</xsl:when>";
	x+= "<xsl:otherwise><xsl:choose><xsl:when test=\".[LinkType='A']\"><xsl:for-each select=\"/R/STATUS_LIST/ACC_STATUS[OwnerUniqueID = context(-1)/LinkParameter]\"><xsl:choose><xsl:when test=\".[WebInvite/STR/String = 'true']\"><img src=\"img/icon_contactPerson.gif\" class=\"icon_hot\"/></xsl:when><xsl:otherwise><img src=\"img/pix.gif\" class=\"icon\"/></xsl:otherwise></xsl:choose></xsl:for-each></xsl:when>";
	x+= "<xsl:otherwise><img src=\"img/pix.gif\" class=\"icon\"/></xsl:otherwise></xsl:choose>";
	x+= "</xsl:otherwise>";
	x+= "</xsl:choose>";
	return x;
}

function GetEmbeddedPhoneNumberExistsInObjectLogic()
{
	var x = "function displayPhoneNumberImportFlag(call_log)";
	x+= "{";
			// prevent bad phone numbers dialed from Personal Contacts from
			// being flagged in call log after the number has been corrected
	x+= 	"if (!eval(call_log.selectSingleNode('Incoming').text.toLowerCase()))";
	x+= 		"return false;";
	x+= 	"var search_number = stripPhoneNumber(removeNodePrefix(call_log, 'CallerIDNumber'));";
	x+=		"var contact_unique_id = call_log.selectSingleNode('ContactUniqueID').text;";
	x+= 	"var abObj = call_log.selectSingleNode('/R/AB/CONTACT[UniqueID=\"'+ contact_unique_id +'\"]');";
	x+= 	"return (!abObj || (abObj && abObj.selectSingleNode('*[.=\"'+search_number+'\"]'))) ? false : true;";
	x+= "}";
	return x;
}

function GetNoPhoneNumberSelectNodesLogic()
{
	var aNumbers = oRoot.selectNodes("CONTACT_FIELDS/FIELD[@locType and @type='TYPE_STRING_PHONE']"), i=0, x="";
	x+= "*[";
	while (aNumbers[i])
	{
		x+= "(nodeName() = '" +aNumbers[i].getAttribute('name')+ "' and text() != '') ";
		if (aNumbers[i+1])
			x+= "or ";
		i++;
	}
	x+= "]";
	return x;
}

function FormatMultiCharTabDisplay(str)
{
	if (str.length==2)
		return str.charAt(0)+" or "+str.charAt(1);
	else if (str.length==3)
		return str.charAt(0)+", "+str.charAt(1)+" or "+str.charAt(2);
	else
		return str;
}

function SortTimeZoneInfoList()
{
	var oTimeZoneList = new ActiveXObject('Msxml.DOMDocument');
	oTimeZoneList.async = false;
	oTimeZoneList.validateOnParse = true;
	xTmp.loadXML(GetNodeConversionStyle('TIME_ZONE_INFO_SORT'));
	oSys.transformNodeToObject(xTmp, oTimeZoneList);
	oTimeZonesNode.parentNode.replaceChild(oTimeZoneList.firstChild, oTimeZonesNode);
	oTimeZonesNode = oRoot.selectSingleNode('TIMEZONES');
}

function SetTableStyle(tBody, bReset)
{
	var type = (tBody.firstChild) ? tBody.firstChild.type : null;
	if (!type ||  type=='DSFM')
		return;
		
	var colors = new Array('#fff','#e6e6e6');
	var index = 0;
	var child = tBody.firstChild;
	while (child)
	{
		if (bReset || child.style.backgroundColor != HIGHLIGHTED_ROW_COLOR)
		{
			var bg_color = (type=='CL' && child.call_type=='conference_member') ? child.previousSibling.prevColor : colors[index];
			child.style.backgroundColor = bg_color;
			child.prevColor = bg_color;
		}
		index = 1-index;
		child = child.nextSibling;
	}
}



// ****************************************************
// ******************  TAB OBJECT  ********************
// ****************************************************

var tab = new Array;

function TabObject(type, obj)
{
	var tabs = obj.firstChild;
	this.type = type;
	this.obj = tabs;
	this.head = tabs.firstChild;
	this.body = this.head.nextSibling;
	this.curTab = 0;
	this.prevTab = 0;
	this.refresh = ViewTab;
	this.readOnly = 1;
	tabs.parentElement.style.border='0px';
}

var bEditingRules = 0;
function ViewTab()
{
	var oEl = (window.event) ? window.event.srcElement : null;
	var type = (oEl && oEl.className.indexOf('tab_head')==0) ? oEl.type : this.type;
	var oTabObj = tab[type];
	var nCurTabIndex = (oEl && oEl.className.indexOf('tab_head')==0) ? (parseFloat(oEl.index)-1) : oTabObj.curTab;
	var nPrevTab = oTabObj.curTab;
	var curTab;
	if (type)
		curTab = oTabObj.body.children[nCurTabIndex];
	if (nCurTabIndex != nPrevTab)
	{
		oTabObj.body.children[nPrevTab].style.display = 'none';
		oTabObj.head.children[nPrevTab].className = 'tab_head';
	}
	if(oTabObj.body.children[nCurTabIndex].id == "CTAB")//can use curTab.id to do the similar checking
	{
		if(isSYNCDIVdisplayed < 1)//getObj('ABSY').style.display == "none")
		{
			// THis means that ABSY was not being displayed before displaying CTGP.
			oTabObj.body.children[nCurTabIndex].style.display = '';
		}
		else if(isSYNCDIVdisplayed != 6)
		{
			//If the trace() reaches here, that means the SYNC DIV was being displayed before 
			//the GROUPS DIV was displayed. SO when you come back to the Personal Contacts (CTAB) 
			// SYNC DIV should be displayed instead of Personal Contacts.			
			Show('ABSY');
		}
		else
		{
			//This means that when the user switches the tab to GP, the SYNC was in progress
			Show('ABEX');
		}
	}
	else
	{
		//THis means that the user has clicked on GP if Contacts tab was being displayed
		//otherwise it could be any other sub tab from another main tabs other than contacts.
		oTabObj.body.children[nCurTabIndex].style.display = '';
	}
	oTabObj.head.children[nCurTabIndex].className = 'tab_head_active';
	oTabObj.prevTab = nPrevTab;
	oTabObj.curTab = nCurTabIndex;
	if(curTab.id == 'CTGP')
	{
		if(isSYNCDIVdisplayed>=1)
		{
			//IF the user clicks on the Groups tab and the sync DIV is being displayed, 
			//only then hide the SYNC DIV.
			Hide('ABSY');
			// In this case HIDE ABSY, but do not set "isSYNCDIVdisplayed" to "0" because
			// the ABSY DIV has to be displayed back when user clicks on CTAB.
			// THis is the only case where you HIDE ABSY and do not set isSYNCDIVdisplayed to 0.
			// In all the other cases isSYNCDIVdisplayed goes with ABSY. i.e if ABSY is displayed
			// isSYNCDIVdisplayed will be set to 1. and vice-versa.
			Hide('ABEX');
		}
	}
	if(type == 'RL' || oTabObj.body.children[nCurTabIndex].id == 'RLGT')
	{
		//Hide('tableRREDWA');
		//Hide('formRREDWA');
		//you are editing/adding a routing rule. THerefore set bEditingRules to 1
		if(getObj('RREX').style.display == '')
		{
		    if(getObj('RREDWO').style.display == '')//you are editing the who step
		        bEditingRules = 1;
		    else if(getObj('RREDWE').style.display == '')// you are editing the when step
		        bEditingRules = 2;
		    else if(getObj('RREDWA').style.display == '' && getObj('formRREDWA').style.display!='')//you are editing the what steps(in this view you will see the list of all the steps in a rule)
		        bEditingRules = 3;
		    else if(getObj('RREDWA').style.display == '' && getObj('formRREDWA').style.display=='')//you are editing a step within a rule
		        bEditingRules = 4;
		    Hide('RREX');		        
		}
		//you were previously editing/adding a routing rules. 
		//THerefore display back that RREX tab which is the 2nd tab.
		else if(oTabObj.body.children[nCurTabIndex].id == "RLRR" && bEditingRules != 0)
    	{
    	    getObj('RREX').style.display = '';
    	    oTabObj.body.children[nCurTabIndex].style.display = "none";
            switch(bEditingRules)
            {
                case 1:SetButtons('RREDWO', "");break;
                case 2:SetButtons('RREDWE', "");break;
                case 3:SetButtons('RREDWA', "");break;
                case 4:SetButtons('RREDWASA', "");break;
            }
	        bEditingRules = 0;   
	        return; 	    
	    }
	}

	if (curTab && curTab.id)
	{
		var xpath, obj_id = curTab.id;
		if (type=='PI' || type=='ED')
		{	
			// reset the object id for EDNM and the rest to pick up the correct buttons
			obj_id = type;
			xpath = 'r="{0}"';
			xpath = Insert(oTabObj.readOnly, xpath);
		}
		if (type=='RRED' && oTabObj.curTab==2)//If i am switching sub-tabs within routing rule main tab, this will take care of showing the correct buttons
			obj_id = (getObj('formRREDWA').style.display=='') ? 'RREDWASA' : 'RREDWA';
		
		if(obj_id=='PI' && nCurTabIndex == 4)
		{
			SetButtons('DV', "");
		}
		else if(obj_id=='CTAB')
		{
			// With CTAB DIV container there are various scenarios of SYNC that use the same space.
			// Therefore depending upon what needs to be displayed, the buttons change accordingly.
			switch(isSYNCDIVdisplayed)
			{
				case 0 : SetButtons('AB', "");   break;
				case 1 : SetButtons('SYSO', ""); break;
				case 2 : SetButtons('SYAS', ""); break;
				case 3 : SetButtons('SYCS', ""); break;
				case 4 : SetButtons('SYRE', ""); break;
				case 5 : SetButtons('SYCF', ""); break;
				case 6 : SetButtons('SYPB', ""); break;
				default: SetButtons('AB', "");   break;
			}
		}
		else if(obj_id=='RLRR')
		{
			SetButtons('RR', "");
		}
		else if(obj_id=='RLGT')
		{
			SetButtons('GT', "");
		}
		else if(obj_id=='RREDWASA')
		{
			SetButtons(obj_id, xpath);
			if(table['RREDWA'].body.childNodes.length < 2)
			{
				getObj('RL').children['buttons'].firstChild.children[1].className = "button_disabled";
			}
		}
		else
		{
			SetButtons(obj_id, xpath);
		}
	}
}

// ****************************************************
// ****************  EVENT HANDLERS  ******************
// ****************************************************

function CaptureEvents()
{	
	document.onmouseup 		= HandleMouseup;
	document.onclick 		= HandleClick;
	document.onkeydown 		= HandleKeydown;
	document.onload			= HandleResize;
	document.body.onunload	= HandleUnload;
	document.body.onselectstart = HandleSelect;
	
	// no debug - let the browser window handle the errors
	if (!b_DEBUG_MODE)
		window.onerror = HandleError;
	// debug - enable collapsing the menus
	else
		getObj("menus").onclick = HandleMenuClick;
}

function HandleError(sMsg,sUrl,sLine) {
	var err = window.event, diag;
	var x="!! Javascript Error !!\n\n";
	x+="Error:\t"+ sMsg +"\n";
	x+="Source:\t"+ err.srcElement +"\n";
	x+="Type:\t"+ err.type +"\n";
	x+="Line:\t"+ sLine +"\n";
	x+="URL:\t"+ sUrl + "\n";
	x+="\n#### CALL STACK ####\n\n";
	x+= TraceCallStack();
	var nl = new RegExp('[\\n]','g');
	var tb = new RegExp('[\\t]','g');
	diag = x.replace(nl, ' | ');
	diag = diag.replace(tb, '')
	CallControlMethod('DIAG', diag);
	alert(x);
	return true;
}

function FunctionName(func) {
    var s = func.toString().match(/function (\w*)/);
    return s ? s[1] : "anonymous";
}
function TraceCallStack() {
	var string = "";
    for (var c = arguments.caller; c && (c.caller!=c); c = c.caller)
		string += "-> "+FunctionName(c.callee) + "\n";
    return string;
}

function HandleUnload()
{
	CloseOut();
}

var oRx, oRy, mTop, mLeft, oRxHeadRow;
var bDoMove = 0;


function HandleMousedown()
{
	if (bDoMove) 
		return;
	var eSrc = window.event.srcElement;
	if (eSrc.className == "corner")
	{
		bDoMove = 1;
		var type = eSrc.type;
		document.onmousemove = HandleMove;
		mLeft = window.event.x;
		mTop = window.event.y;
		oRx = table[type].body;
		oRy = table[type].body;
		table[type].resized = true;
		document.body.style.cursor = "move";
	}
}

function HandleMouseup()
{
	if (bDoMove)
	{
		bDoMove = 0;
		oRxHeadRow = null;
		document.onmousemove = null;
		document.body.style.cursor = "auto";
	}
}

function HandleClick()
{
	var oEl = window.event.srcElement;
	var type = sCurDiv;
	if (oEl)
	{
		if (oEl.tagName=='INPUT' || oEl.tagName=='TEXTAREA' || oEl.tagName=='SELECT')
			return true;
		var tbl = table[type];
		if (tbl && !tbl.body.contains(oEl) && GetHighlightedRows(tbl.body).length)
			ResetRows(tbl.body);
	}
}

function HandleSelect()
{
	var oEl = window.event.srcElement;
	if (oEl.tagName=='INPUT' || oEl.tagName=='TEXTAREA' || oEl.tagName=='SELECT')
			return true;

	window.event.cancelBubble = true;
	return false;
}

function HandleMove()
{
	var sx = window.event.x;
	var sy = window.event.y;
	dLeft = sx - mLeft;
	dTop = sy - mTop;
	if (bDoMove && dTop)
		ResizeObject(oRx, dLeft, oRy, dTop);
	document.selection.empty();
	mLeft = sx;
	mTop = sy;
}

function HandleResize()
{
	document.recalc(true);
}

function HandleRowMouseover(oRow)
{
	var oEl = window.event.srcElement;
	if (oEl)
	{
		if (oEl.tagName == 'IMG')
			ShowTooltip(oEl, oRow);
		if (oRow.type=='DV' && oEl.tagName =='INPUT' && oEl.type=='radio')
			ShowTooltip(oEl, oRow, tip('ICON/PRI_DV'));
	}
	return true;
}

function HandleIconMouse(oIcon)
{
	var unique_id, obj, type;
	type = oIcon.parentElement.parentElement.type;
	switch (type)
	{
		case 'AB':
			unique_id = oIcon.parentElement.parentElement.UniqueID;
			obj = oABNode.selectSingleNode('CONTACT[UniqueID="'+unique_id+'"]');
			break;
		
		case 'UB':
		 	unique_id = oIcon.parentElement.parentElement.id.replace('ub','');
			obj = oABNode.selectSingleNode('CONTACT[UniqueID="'+unique_id+'"]');
			break;
			
		case 'CG':
		 	unique_id = oIcon.parentElement.parentElement.UniqueID;
			obj = oCallLogNode.selectSingleNode('CALLLOG[UniqueID="'+unique_id+'"]');
			break;
			
		case 'TA':break;

		case 'DSRS':
			unique_id = oIcon.parentElement.parentElement.UniqueID;
			obj = oSearchNode.selectSingleNode('DSRS/CONTACT[UniqueID="'+unique_id+'"]');
			if (obj.selectSingleNode('ModifyTimeStamp').text=='Personal Contacts')
				obj = oABNode.selectSingleNode('CONTACT[UniqueID="'+unique_id+'"]');
			break;
			
		default:
			return;
	}
		
	switch (window.event.type)
	{
		case 'mouseover':
			ShowStatusTooltip(oIcon, obj, type);
			break;
	}
	
	window.event.cancelBubble=true;
}

function ShowStatusTooltip(oIcon, obj, type)
{	
	var msg='', string='{0}';
	if (obj)
	{
		var link_type = obj.selectSingleNode('LinkType').text;
		var link_param = obj.selectSingleNode('LinkParameter').text;
		switch (link_type)
		{
			case 'A':
				var oStatus = oStatusListNode.selectSingleNode('ACC_STATUS[OwnerUniqueID="'+link_param+'"]');
				msg += (oStatus) ? (oStatus.selectSingleNode('CurrentCompositeStatus').text +' '+oStatus.selectSingleNode('CurrentDynamicStatus').text) : text('GBL/UNKN');
				break;
				
			case 'D':
				var oStatus = oStatusListNode.selectSingleNode('DEVICE_STATUS[NodeColonExtension="'+link_param+'"]');
				msg += (oStatus) ? (oStatus.selectSingleNode('PrimaryMessage').text + ' ')  : text('GBL/UNKN');
				msg += (oStatus) ? oStatus.selectSingleNode('SecondaryMessage').text : '';
				if (msg==' ')
					msg = text('DV/DND_OFF');
				break;
				
			default:
				msg += tip('SIMPLE');
				break;
		}
		if ((type=='TA' || type=='CG') && !oStatus)
			string+= ' (click icon to retrieve current status)';
		else if (oStatus && boolVal(oStatus.selectSingleNode('OnACall')))
			string+=  Insert(text('GBL/CALL'), ' ({0})');
		if (msg)
			oIcon.title = Insert(msg, string);
	}
}

function HandleUserButtonMouse(oButton)
{
	switch (window.event.type)
	{
		case 'mouseover':
			oButton.style.backgroundImage = (expand_user_buttons) ? 'url(img/bgUserButtonExpanded_on.gif)' : 'url(img/bgUserButton_on.gif)';
			oButton.style.border = '1px solid #9ff';
			break;
			
		case 'mousedown':
			oButton.style.border = '1px solid #fff';
			break;
		
		case 'mouseout':
			oButton.style.backgroundImage = '';
			oButton.style.border = '1px solid #999';
			break;
	}
}

function HandleRowClick(oRow)
{
	var eSrc = window.event.srcElement;
	var type = oRow.type;
	if (type == 'TARRWA' || type == 'TARRWO')
		SetTypeAheadChoiceForRoutingRule(oRow);
	else if (eSrc.tagName=='IMG' && eSrc.className=='icon_hot')
		HandleFeatureIconClick(eSrc, oRow);
	else if (type && (eSrc.tagName=='SPAN' || (eSrc.tagName=='DIV' && type=='CS')) && (type!='DV'))
	{
		ChangeRowColorForClick(oRow);
	}
		
	if (type=='CL')
		ConfigureCallListButtons();
}

var curRow;
var curStepRow;
function HandleRowDoubleClick(oRow)
{
	var unique_id = oRow.UniqueID;
	var type = oRow.type
	if (type!='RREDWA')
		curRow = oRow;
	else
		curStepRow = oRow;

	switch (type)
	{
		case 'AB': 		EditObject(type, unique_id); break;
		case 'CL':		AnswerCall(unique_id); break;
		case 'CS':		EditCompositeStatus(unique_id); break;
		case 'GT':		EditGreeting(unique_id); break;
		case 'MS':		ViewSystemMessage(unique_id); break;
		case 'RR':		EditRoutingRule(unique_id); break;
		case 'RREDWA':	EditRuleStep(type, unique_id); break;
	}
}

function GetImgSrc(oIcon)
{
	return (oIcon && oIcon.src) ? oIcon.src.substring(oIcon.src.lastIndexOf('/')+1, oIcon.src.length).replace('.gif', '') : '';
}

function HandleFeatureIconClick(eSrc, oRow)
{
	// Save the select row so we bacn come back. 
	curRow = oRow;

	var msg='';
	var oIcon = eSrc, type = oRow.type, sUniqueID = oRow.UniqueID;
	var img_src = GetImgSrc(oIcon);

	switch(img_src)
	{
		case 'icon_contactPerson': 		ViewListMenu(type, sUniqueID, img_src); break;
		case 'iEmail': 			ViewListMenu(type, sUniqueID, img_src); break;
		case 'iView':
			switch (type) {
				case 'AB':		ViewObject(type, sUniqueID); break;
				case 'MS':		ViewSystemMessage(sUniqueID); break;
			}
			break;
		
		case 'iCopy':
			switch (type) {
				case 'AB':		CopyObject(type, sUniqueID); break;
				case 'RR':		CopyRoutingRule(sUniqueID); break;
			}
			break;
		
		case 'iEdit':
			switch (type) {
				case 'AB': 		EditObject(type, sUniqueID); break;
				case 'CS':		EditCompositeStatus(sUniqueID); break;
				case 'GT':		EditGreeting(sUniqueID); break;
				case 'RR':		EditRoutingRule(sUniqueID); break;
				case 'RREDWA':	EditRuleStep(type, sUniqueID); break;
			}
			break;
			
		case 'iExpPlus':
		case 'iExpMinus':
			if (type == 'AB' && img_src == 'iExpPlus')
				RequestDevicesList(sUniqueID);
			switch (type) {
				case 'AB':
				case 'CG':
				case 'RR': 		ToggleCollapseableSection(oIcon, oRow.lastChild); break;
			}
			break;
			
		case 'iClose':
			switch (type) {
				case 'CL': 		HangUp(sUniqueID); break;
				case 'DV': 		DeleteDevice(sUniqueID); break;
			}			 	
			break;
			
		case 'iRuleOn':
		case 'iRuleOff':
			case 'RR': 			ToggleRoutingRule(oIcon, sUniqueID); break;
			
		case 'iFCArrowDn':
		case 'iFCArrowUp': 		ToggleDeviceFeatureCodes(oIcon, oRow); break;
		
		case 'iTransfer':
			switch (type) { 
				case 'CL': 		BeginTransfer(sUniqueID); break;
				case 'TA': 		GetTransferTarget(sUniqueID); break;
			}
			break;
			
		case 'iFlag':			AddNumberToContact(type, sUniqueID); break;
			
		case 'iActUNKN':
		case 'iKeysetUNKN':		RequestStatusForObject(type, sUniqueID); break;
		
		case 'iKeysetSM':		AddStationMessage(type, sUniqueID, oIcon.NodeColonExt); break;
		case 'iSetPass':		SetDeviceVoicemailPassword(sUniqueID); break;
		case 'iPlayGreeting': 	CallControlMethod('PlayGreeting', sUniqueID); break;
		case 'iRecordGreeting':	CallControlMethod('RerecordGreeting', sUniqueID); break;
		
		case 'iCLAnswer': 		AnswerCall(sUniqueID); break;
		case 'iHold': 			HoldCall(sUniqueID); break;
		case 'iMute': 			MuteCall(sUniqueID); break;
	}
	if (msg)
		Dialog(msg,0);
}

function HandleMenuClick()
{
	var oEl = window.event.srcElement;
	if (oEl.className && oEl.className=='menuhead')
		oEl.nextSibling.style.display = (oEl.nextSibling.style.display == 'none') ? '':'none';
	
	/*var eSrc = window.event.srcElement;
	var ePar = eSrc;
	while (ePar.tagName && ePar.className != "menu")
		ePar = ePar.parentElement;
	var obj = ePar.childNodes(1);
	obj.style.display = (obj.style.display == "none") ? "":"none";*/
}

var genieCommand = "";
function HandleKeydown(str, obj)
{
	var oEl = window.event.srcElement;
	var key_code = window.event.keyCode;

	// enter
	if (key_code == 13)
		return HandleEnterKeydown(str, obj);
	// delete
	else if (key_code==46 && (sCurDiv!='DV'))
	{
		if (table[sCurDiv] && table[sCurDiv].body.contains(oEl))
		{	DeleteHighlightedRows(sCurDiv);}
		else if (sCurDiv=='RR' && table['RREDWA'].body.contains(oEl))
			DeleteHighlightedRows('RREDWA');
	}
	// esc
	else if (key_code == 27)
		return HandleEscKeydown(str, obj);

	if (event.ctrlKey)
	{
		// m
		if (key_code == 77)
			ToggleMenus();
		// tab
		else if (key_code == 9)
		{
			TabNextView(!event.shiftKey);
			event.cancelBubble=true;
			event.returnValue=false;
		}
		// genie
		else if (key_code == 123 && (b_DEBUG_MODE || (event.shiftKey && event.altKey)))
		{
			genieCommand = window.prompt("I am the Genie of the browser. Enter your command below, and I will execute it:", genieCommand);
			eval(genieCommand);
		}
	}
	return true;
}

function HandleEnterKeydown(str, obj)
{
	var oEl = window.event.srcElement;
	switch (str)
	{
		case 'button':
			LightObj(oEl,2);
			oEl.click();
			window.event.cancelBubble=true;
			return false;
			
		case 'composite_status':
			SaveCompositeStatus();
			return true;
		
		case 'edit_form':
			if (oEl.tagName!='TEXTAREA')
				SaveEdit();
			return true;
			
		case 'device_name':
			//TextChange();
			obj.blur();
			return true;
			
		case 'device_fwd':
			//TextChange();
			obj.blur();
			return true;
			
		case 'device_dnd':
			//TextChange();
			obj.blur();
			return true;
			
		case 'greeting':
			if (getObj('GTFM').contains(oEl))
				SaveGreeting();
			return true;
			
		case 'device':
			if (getObj('dv_add_form').contains(oEl))
			{
				SaveDevice(1);
				if (b_CREATING_NEW_ACCOUNT)
				{
					window.event.cancelBubble=true;
					getObj('add_device_name').focus();
				}
			}			
			return true;
			
		case 'logon':
			SubmitLogon();
			return true;
			
		case 'new_account':
			if (oEl.tagName!='TEXTAREA')
				SetNewAccountInfo();
			return true;
			
		case 'place_call':
			PlaceCall();
			return true;
			
		case 'routing_rule':
			if (getObj('RREX').style.display=='')
			{
				if (oEl.tagName && (oEl.tagName == 'INPUT' || oEl.tagName == 'SELECT'))
				{
					window.event.cancelBubble=true;
					return true;
				}
				if (getObj('formRREDWA').style.display=='')
					SaveRoutingRuleStep();
				else
					SaveRoutingRule();
			}
			return true;
		
		case 'search':
			if (getObj("SearchForm").contains(oEl))
				Search();
			return true;
	}
}

function HandleEscKeydown(str, obj)
{
	var oEl = window.event.srcElement;
	if (!str && sCurDiv=='ED')
		str = 'edit_form';
	switch (str)
	{	
		case 'edit_form':
			if (oEl.tagName!='TEXTAREA')
			{
				if (oXMLFormObj)
				{
					CancelEdit(1);
				}
				else
					CloseObjectView();
			}
			return true;
			
		case 'composite_status':	
			HideCompositeStatusForm();
			return true;
			
		case 'routing_rule':
			if (getObj('RREX').style.display=='')
			{
				if (getObj('formRREDWA').style.display=='')
					ToggleAddRoutingRuleStep();
				else
					CancelRoutingRule();
			}
			return true;
	}
}

function ToggleMenus()
{
	(getObj('menus').style.display=='') ? Hide('menus') :  Show('menus');
}

function HandleObjectLink(ret_val)
{
	var r_vals = ParseDelimitedList(ret_val)
	if (r_vals && eval(r_vals[0]) && r_vals[1])
	{
		var params = ParseDelimitedList(r_vals[1]);
		switch (params[0])
		{
			case 'AB':
				if (oABNode.selectSingleNode('CONTACT[UniqueID="'+params[1]+'"]'))
				{
					getObj('vl_CT').click();
					EditObject('AB', params[1]);
				}
				else
					Dialog(text('DLG/NO_ITEM'),0);
				break;
				
			case 'CS':
				if (oCompStatusNode.selectSingleNode('COMPOSITE_STATUS[DN="'+params[1]+'"]'))
				{
					getObj('vl_'+params[0]).click();
					EditCompositeStatus(params[1]);
				}
				else
					Dialog(text('DLG/NO_ITEM'),0);
				break;
			
			case 'RR':
				if (oRulesNode.selectSingleNode('RULE[UniqueID="'+params[1]+'"]'))
				{
					if (oCurRule)
						CancelRoutingRule();
					getObj('vl_RL').click();
					EditRoutingRule(params[1]);
					if (params[2])
						tab['RRED'].head.children[parseFloat(params[2])].click();
					if (params[3])
						setTimeout("getObj('rowRREDWA"+params[3]+"').firstChild.click()",500);
				}
				else
					Dialog(text('DLG/NO_ITEM'),0);
				break;
		}
	}
}


var b_MAX_TYPE_AHEAD_EXCEEDED=0;
var b_FORCE_TYPEAHEAD_RESULTS=0;

function HandleTypeAheadKeydown(b_FORCE)
{
	var typeahead_string = (cur_search_type=='TA') ?  getObj('cc_type_ahead_search').value : getObj(embedded_typeahead_input).value;
	b_MAX_TYPE_AHEAD_EXCEEDED = 0;
	
	// prevent a duplicate search from going up -
	// user may hit enter and trigger after timer expires
	if (!b_FORCE && typeahead_string==search_query)
		return;

	search_query = typeahead_string;
	var search_criteria = GetSearchCriteria(true, b_FORCE_TYPEAHEAD_RESULTS);
	if ((typeahead_string.length > 0) && (IsValid(typeahead_string)))
	{
		CallControlMethod('Search', typeahead_string, search_criteria);
	}
	else
	{
		if(cur_search_type=='TA'){
			RemoveChildNodes(oSearchNode.selectSingleNode('DSRS'));
			table['DSRS'].refresh();
		}
		else
		{
			RemoveChildNodes(oSearchNode.selectSingleNode(cur_search_type));
			ConfigureCallControlDisplay();
			table[cur_search_type].refresh();
			//we do this so that when the contents of type ahead search are deleted the results also should go away
		}

	}
	b_FORCE_TYPEAHEAD_RESULTS=0;
	return;
}

var timerKeypress1, timerKeypress2;

function HandleKeypressInterval()
{
	var oEl = window.event.srcElement, nInterval_1, nInterval_2, sFunction;
	if (oEl.id == "cc_type_ahead_search" || oEl.id == embedded_typeahead_input)
	{
		sFunction = "HandleTypeAheadKeydown()";
		nInterval_1=1000;
	}
	if (oEl.id.indexOf('textEmbeddedTypeAheadSearch')==0)
	{
		embedded_typeahead_input = oEl.id;
		cur_search_type = oEl.id.replace('textEmbeddedTypeAheadSearch', '');
	}
	if (sFunction && nInterval_1)
	{
		clearTimeout(timerKeypress1);
		timerKeypress1 = setTimeout(sFunction, nInterval_1);
	}
	return true;
}

var embedded_typeahead_input;

function HandleListMenuOut()
{
	var toEl = window.event.toElement;
	if (getObj('LIST').style.display=='' && !getObj('LIST').contains(toEl))
	{
		Hide('LIST');
		HideShadows();
		ResetListStyle();
	}
	return;
}

function ResetListStyle()
{
	var oList = getObj('LIST');
	oList.style.height = '';
	oList.style.width = '210px';
	oList.style.overflowY = '';
	ShowSelectBoxes();
}

function HideShadows()
{
	for (var i=0; i<global.aShadows.length; i++)
		global.aShadows[i].removeNode(true);
	global.aShadows = new Array;
}

function ForceTypeAhead(type)
{
	if (!cur_search_type || cur_search_type != type)
		cur_search_type = type;
	b_FORCE_TYPEAHEAD_RESULTS=1;
	HandleTypeAheadKeydown(1);
}

function GetParentRow(oEl)
{
	while (oEl.className != 'tableRow' && oEl.tagName != 'DIV')
		oEl = oEl.parentElement;
	return oEl;
}

var HIGHLIGHTED_ROW_COLOR = "#cf9";
var ACTIVE_ROW_COLOR = "#ff9"

function ChangeGroupNameColorForClick(oRow)
{
	if(window.event.srcElement.tagName!='IMG')
	{
		CurrentBgColor = oRow.style.backgroundColor;
		ResetGroupHeadRows(oRow.parentNode.parentNode.firstChild);
		DeHighlightAllRowsOfOtherGroups(oRow);
		if(CurrentBgColor != HIGHLIGHTED_ROW_COLOR)
		{
			HighlightAllRowsOfThisGroup(oRow);
			oRow.style.backgroundColor = (oRow.style.backgroundColor != HIGHLIGHTED_ROW_COLOR) ? HIGHLIGHTED_ROW_COLOR : oRow.prevColor;
		}
	}
}

function ResetGroupHeadRows(tBody)
{	
	var colors = new Array('#fff','#e6e6e6');
	var index = 0;
	var child = tBody;
	while (child)
	{
		if(child.firstChild.style.backgroundColor == HIGHLIGHTED_ROW_COLOR)
			child.firstChild.style.backgroundColor = colors[index];
		index = 1-index;
		child = child.nextSibling;
	}
}

function HighlightAllRowsOfThisGroup(tBody)
{
	var child = tBody;
	while(child.className != "cssMenuItemBody")
	{
		child = child.nextSibling;
	}
	child = child.firstChild;
	while(child)
	{
		child.style.backgroundColor = HIGHLIGHTED_ROW_COLOR;
		child = child.nextSibling;
	}
}

function DeHighlightAllRowsOfOtherGroups(tBody)
{
	var child = tBody.parentNode.parentNode.firstChild;
	while(child)
	{
		DeHighlightAllRowsOfThisGroup(child.firstChild);
		child = child.nextSibling;
	}
}

function DeHighlightAllRowsOfThisGroup(tBody)
{
	var colors = new Array('#fff','#e6e6e6');
	var index = 0;
	var child = tBody;
	while(child.className != "cssMenuItemBody")
	{
		child = child.nextSibling;
	}
	child = child.firstChild;
	while(child)
	{
		if(child.style.backgroundColor == HIGHLIGHTED_ROW_COLOR)
			child.style.backgroundColor = colors[index];
		index = 1-index;
		child = child.nextSibling;
	}
}

function ChangeRowColorForClick(oRow)
{	
	var bCtrlKey = window.event.ctrlKey;
	var bShftKey = window.event.shiftKey;
		
	var type = oRow.type;
	var tbl = table[type];
	tbl.curRow = GetRowIndex(oRow);
	CurrentBgColor = oRow.style.backgroundColor;
	if(oRow.type=="GPLS")
	{
		ResetGroupHeadRows(oRow.parentNode.parentNode.parentNode.firstChild);
		if (!bCtrlKey)
		{
			DeHighlightAllRowsOfOtherGroups(oRow.parentNode.parentNode.firstChild);
		}
	}
	if (!bCtrlKey)
		ResetRows(oRow.parentElement);

	if (bShftKey && tbl.prevRow != null)
	{
		var beg = (tbl.curRow > tbl.prevRow) ? tbl.prevRow : tbl.curRow;
		var end = (tbl.curRow > tbl.prevRow) ? tbl.curRow  : tbl.prevRow;
		end++;
		for (var i=beg; i < end; i++)
			oRow.parentElement.childNodes(i).style.backgroundColor = HIGHLIGHTED_ROW_COLOR;
	}
	else
		oRow.style.backgroundColor = (CurrentBgColor != HIGHLIGHTED_ROW_COLOR) ? HIGHLIGHTED_ROW_COLOR : oRow.prevColor;

	if (!bShftKey)
		tbl.prevRow = tbl.curRow;
}

function ResetRows(tBody)
{
	SetTableStyle(tBody, true);
}

function RemoveHighights(tBody)
{
	var child = tBody.firstChild;
	while (child)
	{
		child.style.backgroundColor = '';
		child = child.nextSibling;
	}
}	

function GetRowIndex(row)
{
	//var tBody = table[type].body, i=0;
	var tBody = row.parentElement, i=0;
	while (tBody.children[i])
	{
		if (tBody.children[i] == row)
			return i;
		i++;
	}
}

function GetStyleSheetIndex(sSelectorName)
{
	var oStyles = document.styleSheets('GlobalStyles').rules, i=0;
	while (oStyles[i])
	{
		if (oStyles[i].selectorText == sSelectorName)
			return i;
		i++;
	}
}

function SetRadio(sCollectionName, nIndex, sValue)
{
	if (!IsNum(nIndex) && sValue!=null)
		nIndex = GetRadiosIndex(sCollectionName, sValue);
	if (IsNum(nIndex))
		getObjects(sCollectionName)[nIndex].checked=true;
		
	switch (sCollectionName)
	{
		case 'rr_what_type':
			ToggleWhatSearchAndDuration(getObjects(sCollectionName)[nIndex]);
			break;
			
		case 'rr_who_type':
			ToggleWhoSearch(getObjects(sCollectionName)[nIndex]);
			break;
	}
}

function ShowTooltip(oIcon, oRow, tool_tip, stat, help)
{
	if (oIcon && !tool_tip)
	{
		var string, item='', type = oRow.type;
		switch (GetImgSrc(oIcon))
		{
			case 'icon_contactPerson': 		string = tip('ICON/PMEN'); break;
			case 'iEmail': 			string = tip('ICON/EMEN'); break;
			case 'iView':
				switch (type) {
					case 'AB':
					case 'MS':		string = tip('ICON/VIEW'); 
									item = text('ITEM/'+type); break;
				}
				break;
				
			case 'iCopy': 			string = tip('ICON/COPY');
									item = text('ITEM/'+type); break;
			
			case 'iEdit':
				switch (type) {
					case 'AB':
					case 'CS':
					case 'GT':
					case 'RR':
					case 'RREDWA':	string = tip('ICON/EDIT');
									item = text('ITEM/'+type); break;
				}
				break;
				
			case 'iCompStatusAV': 	string = tip('ICON/CS_AV'); break;
			case 'iCompStatusUNAV': string = tip('ICON/CS_UNAV'); break;
				
			case 'iFlag':		string = tip('ICON/FLAG_CG'); break;
				
			case 'iExpPlus':	string = tip('ICON/PLUS'); break;
			case 'iExpMinus':	string = tip('ICON/MINUS'); break;
			
			case 'iCLAnswer':	string = tip('ICON/IN'); break;
			case 'iCLOrig':		string = tip('ICON/OUT'); break;
				
			case 'iClose':
				switch (type) {
					case 'CS':
					case 'DV':
					case 'MS': 	string = tip('ICON/DEL');
								item = text('ITEM/'+type); break;
				}			 	
				break;
				
			case 'iRuleOn':
			case 'iRuleOff':
				case 'RR': 			break;
				
			case 'iFCArrowDn':		string = tip('ICON/SHOW_FC');break;
			case 'iFCArrowUp': 		string = tip('ICON/HIDE_FC');break;
			
			case 'iTransfer':
				switch (type) { 
					case 'CL': 		break;
					case 'TA': 		string = tip('ICON/TR'); break;
				}
				break;
			
			case 'iKeysetSM':
				switch (type) { 
						case 'MS': 		break;
						default: 		string = tip('ICON/SM'); break;
				}
				break;

			case 'iSetPass':		string = tip('ICON/VM_PASS'); break;
			
			case 'iPlayGreeting':	string = tip('ICON/PLAY'); item = text('ITEM/'+type); break;
			case 'iRecordGreeting':	string = tip('ICON/REREC'); item = text('ITEM/'+type); break;
			
			case 'iCLAnswer': 		break;
			case 'iHold': 			break;
			case 'iMute': 			break;
/*			
			case 'iAct':
			case 'iActUNAV':
			case 'iActUNKN':
			case 'iKeyset':
			case 'iKeysetDND':
			case 'iKeysetUNKN':
				switch (type) {
					case 'AB':
						var oObj = oABNode.selectSingleNode('CONTACT[UniqueID="'+oRow.UniqueID+'"]');
						ShowStatusTooltip(oIcon, oObj, type);
						return;
				}
				break;*/
		}
		if (string)
			tool_tip = string +' '+ item;
	}
	
	if (tool_tip || stat)
	{
		if (tool_tip)
			oIcon.title = tool_tip;
		if (stat)
			window.status = stat;
		if (help)
			oIcon.style.cursor	= "help";
	}
	else
	{
		if (oIcon)
			oIcon.title = '';
		window.status = PRODUCT_NAME_AND_VERSION;
		return true;
	}
}

function ShowCurrentStatus(oRow, eSrc)
{
	var id = oRow.UniqueID;
	var oObj = oSys.selectSingleNode('R/AB/CONTACT[UniqueID="'+id+'"]');
	var name = oObj.selectSingleNode('FirstName').text +' '+ oObj.selectSingleNode('LastName').text;
	var text, display, bShowStatus=1;
	if (eSrc.className.substring(eSrc.className.length-2,eSrc.className) == 'Un')
		display = 'UNKNOWN (A required node has gone down)';
	if (!display)
	{
		switch (eSrc.className.substring(0,4))
		{
			case'iAct':
				num = oObj.selectSingleNode('AccountStatus/ACC_STATUS').text;
				display=(num=='0')?'Logged Out':'Logged In';
				break;
			default:
				bShowStatus=0;
		}
	}
	if (bShowStatus)
	{
		eSrc.title = display;
		window.status = text +' for '+ name +' : ' + display;
		return true;
	}
}

function ToggleCollapseableSection(oIcon, oSection)
{
	switch (GetImgSrc(oIcon))
	{
		case 'iExpPlus':
			oIcon.src='img/iExpMinus.gif';
			oSection.style.display='';
			break;
		
		case 'iExpMinus':
			oIcon.src='img/iExpPlus.gif';
			oSection.style.display='none';
			break;
	}
}

function RedialMenu()
{
	ViewListMenu('Redial');
}

function PrioritizeGroup()
{
	ViewListMenu('PrioritizeGroup');
}

function HelpOnHowToAddGreeting()
{
	ViewListMenu('AddGreeting');
}


var nDIV_SHADOW_WIDTH = 4;

function ViewListMenu(type, cur_id, img_src)
{
	var oObj, style = 'PhoneList', html, list_width='210px';
	var sDeleteButtonForSpeedDial = '';
	switch (type)
	{
		case 'AB':
		case 'EmailList':
		case 'SpeedDial':
			oObj = oABNode.selectSingleNode('CONTACT[UniqueID="'+ cur_id +'"]');
			if (img_src == 'iEmail')
				style = 'EmailList';
			break;
			
		case 'Help':
			style = 'Help';
			list_width='150px';
			oObj = oSys;
			break;
			
		case 'TA':
		case 'DSRS':
			oObj = oSearchNode.selectSingleNode(type+'/CONTACT[UniqueID="'+ cur_id +'"]');
			if (img_src == 'iEmail')
				style = 'EmailList';
			break;
			
		case 'Redial':
			style = 'Redial';
			oObj = oSys;
			list_width='330px';
			break;

		case 'PrioritizeGroup':
			style = 'PrioritizeGroup';
			oObj = oSys;
			list_width='220px';
			break;

		case 'AddGreeting':
			style = 'AddGreeting';
			oObj = oSys;
			list_width='220px';
			break;
			
		case 'Transfer':
			style = 'Transfer';
			oObj = oCallListNode.selectSingleNode('.//*[CallID="'+ cur_id +'"]');
			break;
		
		case 'TransferSelect':
			style = 'TransferSelect';
			oObj = oSearchNode.selectSingleNode('TA/CONTACT[UniqueID="'+ cur_id +'"]');
			break;
			
		case 'UB':
			oObj = oABNode.selectSingleNode('CONTACT[UniqueID="'+ cur_id +'"]');
			var aPhoneNumbers = oObj.selectNodes(GetNoPhoneNumberSelectNodesLogic());
			if (!aPhoneNumbers.length && !oObj.selectSingleNode('Devices/LIST//String[0]'))
				return;
			sDeleteButtonForSpeedDial = "SpeedDial";
			break;
	}

	xTmp.loadXML(GetSectionXSL(style, 1, oObj, sDeleteButtonForSpeedDial));
	CheckError(xTmp);

	html = oObj.transformNode(xTmp);
	
	if (type == 'SpeedDial')
		return html;
		
	var oList = getObj('LIST');
	oList.innerHTML = html;
	oList.style.width = list_width;
	
	Show('LIST');
	HideShadows();

	PositionDivInViewableArea(oList, nDIV_SHADOW_WIDTH);
	
	HideSelectBoxes();
	
	MakeDivShadow('LIST', '#000', DIV_SHADOW_WIDTH, true);
}

function HideSelectBoxes()
{
	var selects = document.getElementsByTagName('SELECT'), i=0;
	while (selects[i])
	{
		if (b_toolbar_mode)
			selects[i].style.visibility = 'hidden';
		else if (selects[i].id != 'AccountCompositeStatusSelect')
			selects[i].style.visibility = 'hidden';
		i++;
	}

}

function ShowSelectBoxes()
{
	var selects = document.getElementsByTagName('SELECT'), i=0;
	while (selects[i])
		selects[i++].style.visibility = 'visible';
}

function SelectBehindListMenu(oSelect, oList)
{
	var lst_top = oList.offsetTop
	var lst_btm = oList.offsetTop + oList.offsetHeight + 10;
	var lst_lft = oList.offsetLeft;
	var lst_rgt = oList.offsetLeft + oList.offsetWidth + 10;
	var sel_top = oSelect.offsetTop
	var sel_btm = oSelect.offsetTop + oSelect.offsetHeight + 10;
	var sel_lft = oSelect.offsetLeft;
	var sel_rgt = oSelect.offsetLeft + oSelect.offsetWidth + 10;
	return (sel_btm > lst_top && sel_top < lst_btm && sel_rgt > lst_lft && sel_lft > lst_rgt)
}

function PositionDivInViewableArea(oDiv, OPT_OFFSET, X_MOVE, Y_MOVE)
{
	var xPos = event.clientX, yPos = event.clientY;
	OPT_OFFSET = (IsNum(OPT_OFFSET)) ? OPT_OFFSET : 0;
	var leftAdj = document.body.clientWidth - oDiv.offsetWidth - OPT_OFFSET - 2;
	var topAdj 	= document.body.clientHeight - oDiv.offsetHeight - OPT_OFFSET - 2;
	xPos = ((xPos < leftAdj) ? xPos : leftAdj) - 20 + document.body.scrollLeft + ((IsNum(X_MOVE)) ? X_MOVE : 0);
	yPos = ((yPos < topAdj) ? yPos : topAdj) - 20 + document.body.scrollTop + ((IsNum(Y_MOVE)) ? Y_MOVE : 0);
	oDiv.style.posLeft = xPos;
	oDiv.style.posTop = yPos;
	
	if (b_toolbar_mode)
	{
		oDiv.style.posTop += 17;
		if (oDiv.offsetHeight > (document.body.clientHeight - 10))
		{
			oDiv.style.posTop = 5;
			oDiv.style.height = document.body.clientHeight - 15;
			oDiv.style.width = '227px';
			oDiv.style.overflowY = 'scroll';
		}
	}
}

var global = window.document;
global.aShadows = new Array;
var DIV_SHADOW_WIDTH = 4;

function MakeDivShadow(divName, color, size, bIsHorizOffset)
{
	var oDiv = getObj(divName);
	var nPercent = 50/size;
	var sWidth = oDiv.offsetWidth + 'px';
	var sHeight = oDiv.offsetHeight + 'px';
	var nTop = oDiv.style.posTop+5;
	var nLeft = oDiv.style.posLeft+5;
	var nZIndex = oDiv.style.zIndex;
	for (var i=size; i>0; i--)
	{
		var oShadow = document.createElement('div');
		var oStyle = oShadow.style;
		var horzOff = (bIsHorizOffset) ? i : 0;
		oStyle.position = 'absolute';
		oStyle.top = (nTop + i) + 'px';
		oStyle.left = (nLeft + horzOff) + 'px';
		oStyle.width  = sWidth;
		oStyle.height = sHeight;
		oStyle.zIndex = nZIndex - i;
		oStyle.backgroundColor = color;
		oStyle.filter='alpha(opacity='+(50-(nPercent*i))+')';
		oDiv.insertAdjacentElement('afterEnd', oShadow);
		global.aShadows[global.aShadows.length] = oShadow;
	}
}

function ResizeObject(e, dLeft, f, dTop)
{
	//e.style.posWidth = e.offsetWidth + dLeft;
	f.style.posHeight = f.offsetHeight + dTop;
}

var nIndexToShorten;

function ResizeColumn(e, dLeft)
{
	nIndexToShorten = (!nIndexToShorten) ? e.parentElement.childNodes.length-1 : nIndexToShorten;
	f = e.parentElement.childNodes(nIndexToShorten);
	if (((e.offsetWidth + dLeft) > 50) && ((f.offsetWidth - dLeft) > 50))
	{
		e.style.pixelWidth = e.offsetWidth + dLeft;
		f.style.pixelWidth = f.offsetWidth - dLeft;
		nIndexToShorten = null;
	}
	else if (e != e.parentElement.childNodes(nIndexToShorten-1))
	{
		nIndexToShorten--
		ResizeColumn(e, dLeft);
	}
	else
		return false;
}

function ReturnFalse()
{
	event.returnValue = false;
	event.cancelBubble = true;
}

function AddToSpeedDial(type)
{
	AddHighlightedRows(type, config('SPEED_DIAL'));
	table['GPLS'].refresh();
	BuildDiv('UB', oSys);
}

function AddHighlightedRows(type, option)
{
	type = (type=='CTGP') ? 'GPAB' : type;
	var tblBody = table[type].body;
	var aRowsToAdd = GetHighlightedRows(tblBody);
	var aModifiedIds = new Array, i=0, j=0
	var msg = (type=='GPAB') ? text('DLG/GP/NO_SEL_AB') : text('DLG/NO_HIGH_ADD');
	while (aRowsToAdd[i])
		aModifiedIds[aModifiedIds.length] = aRowsToAdd[i++].UniqueID;
	if (aModifiedIds.length)
	{
		switch (type)
		{
			case "AB":
				if (!oGroupsNode.selectSingleNode('GROUP[Name="'+config('SPEED_DIAL')+'"]'))
					AddNewGroup(config('SPEED_DIAL'));
				while (aModifiedIds[j])
				{
					var oObj = oABNode.selectSingleNode('CONTACT[UniqueID="'+ aModifiedIds[j] +'"]');
					//if (!oObj.selectSingleNode('Groups/LIST//STR[String="'+config('SPEED_DIAL')+'"]'))
						AddContactToGroup(config('SPEED_DIAL'), aModifiedIds[j])
					j++;
				}
				table['GPLS'].refresh();
				BuildDiv('UB', oSys);
				break;
				
			case "CG":
				var b_ADDING_MULTIPLE_CONTACTS = true;
				var linked_user_ids = new Array;
				while (aModifiedIds[j])
				{
					oCallLog = oCallLogNode.selectSingleNode('CALLLOG[UniqueID="'+ aModifiedIds[j] +'"]');
					// if link information exists add it to the array to create linked contacts
					if (oCallLog.selectSingleNode('LinkType').text && oCallLog.selectSingleNode('LinkParameter').text)
						linked_user_ids[linked_user_ids.length] = DelimitList(new Array(oCallLog.selectSingleNode('LinkType').text, oCallLog.selectSingleNode('LinkParameter').text));
					// otherwise add simple contacts
					else if (oCallLog.selectSingleNode('CallerIDNumber').text)
					{
						var date = new Date(), oContact = GetTemplate('CONTACT');
						oContact.selectSingleNode('Owner').text = oActNode.selectSingleNode('.//UniqueID').text;
						oContact.selectSingleNode('UniqueID').text = date.getTime();
						oContact.selectSingleNode('WorkNumber1').text = RemoveNodePrefix(oCallLog.selectSingleNode('CallerIDNumber').text);
						if (!oCallLog.selectSingleNode('CallerIDFirstName').text && !oCallLog.selectSingleNode('CallerIDLastName').text && !oCallLog.selectSingleNode('CallerIDCompanyName').text)
							oContact.selectSingleNode('FirstName').text = RemoveNodePrefix(oCallLog.selectSingleNode('CallerIDNumber').text);
						else
						{
							oContact.selectSingleNode('FirstName').text = oCallLog.selectSingleNode('CallerIDFirstName').text;
							oContact.selectSingleNode('LastName').text 	= oCallLog.selectSingleNode('CallerIDLastName').text;
							oContact.selectSingleNode('Company').text 	= oCallLog.selectSingleNode('CallerIDCompanyName').text;
						}
						oABNode.appendChild(oContact.cloneNode(true));
						CallControlMethod('AddXMLObject', oContact);
						
					}
					j++;
				}
				if (linked_user_ids.length)
					CallControlMethod('AddLinkedContacts', DelimitList(linked_user_ids), false, oActNode.selectSingleNode('.//UniqueID').text, oActNode.selectSingleNode('.//TenantGroup').text);
				// reset the array to null so the table won't refresh below	
				aRowsToAdd=null;
				ResetRows(table[type].body);
				b_ADDING_MULTIPLE_CONTACTS = false;
				UpdateAddressBookLists();
				break;
			
			case "FCUSER":
			case "FCADMN":
				var oDeviceNode = oDevNode.selectSingleNode("DEVICE[Extension = "+ getObj('dv_feature_codes').Extension +"]");
				var oOldDevNode = oDeviceNode.cloneNode(true);
				var oDevFavoritesNode = oDeviceNode.selectSingleNode('FeatureCodeFavoritesList');
				
				while (aModifiedIds[j])
				{
					// for feature codes - the PBX description is used for the unique id,
					// the associated code may be changed on different nodes but the description should be unique
					var oMatchingNode = oDevFavoritesNode.selectSingleNode("LIST/*/FEATURE_CODE[Description='"+aModifiedIds[j]+"']");
					if (!oMatchingNode)
					{
						var oFav = oNodesNode.selectSingleNode('NODE[NodeNameElements//NodeID="'+ getObj('dv_feature_codes').Node +'"]/FeatureCodes/FEATURE_CODE[Description="'+ aModifiedIds[j] +'"]').cloneNode(true);
						AddChildNodeToListObject(oDevFavoritesNode, oFav);
					}
					j++;
				}
				
				if (oDeviceNode.selectSingleNode('FeatureCodeFavoritesList').xml != oOldDevNode.selectSingleNode('FeatureCodeFavoritesList').xml)
				{
					CallControlMethod('EditXMLObject', oOldDevNode, oDeviceNode);
					table['FCFAVS'].refresh();
					if (oFloatWin && !oFloatWin.closed)
						ShowFloater('FeatureCodeFavorites');
					ResetRows(table[type].body);
					return;
				}
				break;
			
			case "GPAB":
				var row='<row><select size="1">{0}</select></row>', options='', child = oGroupsNode.firstChild;
				if (child)
				{
					while (child)
					{
						var option='<option value="{0}">{0}</option>';
						var group_name = child.selectSingleNode('Name').text;
						group_name = group_name.replace('&', '&#38;');
						group_name = group_name.replace('<', '&#60;');
						group_name = group_name.replace('>', '&#62;');
						options += Insert(group_name, option);
						child = child.nextSibling;
					}
					var ret_val = ParseDelimitedList(Dialog(text('GP/MUL_ADD'), 1, Insert(options, row)));
					if (eval(ret_val[0]) && ret_val[1])
					{
						while (aModifiedIds[j])
							AddContactToGroup(ret_val[1], aModifiedIds[j++])
						table['GPLS'].refresh();
						UpdateGroupDisplays(ret_val[1]);
					}
				}
				break;
			
			// Adding type ahead results to Personal Contacts
			case "TA":
			case "DSRS":
				var b_ADDING_MULTIPLE_CONTACTS = true;
				while (aModifiedIds[j])
				{
					var now = new Date();
					oSearchResult = oSearchNode.selectSingleNode(type+'/CONTACT[UniqueID="'+ aModifiedIds[j] +'"]').cloneNode(true);
					oSearchResult.selectSingleNode('Owner').text = oActNode.selectSingleNode('.//UniqueID').text;
					oSearchResult.selectSingleNode('TenantGroup').text = oActNode.selectSingleNode('.//TenantGroup').text;
					oSearchResult.selectSingleNode('ModifyTimeStamp').text = '^'+ now.toUTCString();
					oSearchResult.selectSingleNode('UniqueID').text = now.getTime();
					if (option)
						AddChildNodeToListObject(oSearchResult.selectSingleNode("Groups"), option);
					AddChildNodes(oABNode, new Array(oSearchResult.cloneNode(true)));
					CallControlMethod('AddXMLObject', oSearchResult);
					j++;
				}
				// reset the array to null so the table won't refresh below
				aRowsToAdd=null;
				ResetRows(table[type].body);
				b_ADDING_MULTIPLE_CONTACTS = false;
				UpdateAddressBookLists();
				break;
			
		}
		if (aRowsToAdd)
			table[type].refresh();
	}
	else
		Dialog(msg,0);
}

function DeleteGroup(type)
{
	var child = table['GPLS'].body.firstChild;
	while(child.firstChild.style.backgroundColor != HIGHLIGHTED_ROW_COLOR)
	{
		if(child.nextSibling)
			child=child.nextSibling;
		else
		{
			Dialog(text('DLG/GP/NO_DEL_GP'),0);
			return;
		}
	}
	var sGroupName = child.firstChild.innerText;

	if (sGroupName == config('SPEED_DIAL'))
		Dialog(Insert(config('SPEED_DIAL'), text('DLG/GP/NO_DEL_SP')) ,0);
	else
	{
		if (Confirm('GP') && !CheckForObjectReferenceInRoutingRules('GP', sGroupName))
		{
			var aContacts = oABNode.selectNodes('CONTACT[Groups/LIST//String="'+sGroupName+'"]'), i=0;
			while (aContacts[i])
				RemoveContactFromGroup(sGroupName, aContacts[i++].selectSingleNode('UniqueID').text);
			var oNode = oGroupsNode.selectSingleNode('GROUP[Name="'+sGroupName+'"]');
			oGroupsNode.removeChild(oNode);
			CallControlMethod('DeleteXMLObject', oNode);
			var oABFilterSelect = getObj('table_filter_select_AB');
			if (oABFilterSelect.options[oABFilterSelect.selectedIndex].text == sGroupName)
			{
				MakeTableFilterSelect('AB', getObj('ab_filter_select'));
				table['AB'].curFilterProperty 	= '';
				table['AB'].curFilterValue		= '';
				table['AB'].refresh();
			}
		}
	}
	table['GPLS'].refresh();
}

function DeleteHighlightedRows(type,sSpeedDialUniqueID)
{
	type = (type=='CTGP') ? 'GPLS' : type;
	var tblBody = table[type].body;
	var deleted_rows = GetHighlightedRows(tblBody), j=0;
	var b_CONFIRM = false;
	if (deleted_rows.length && Confirm(type))
	{
		b_CONFIRM = true;
		while (deleted_rows[j])
		{
			var unique_id = deleted_rows[j].UniqueID;
			switch (type)
			{
				case 'AB':
					if (CheckForObjectReferenceInRoutingRules(type, unique_id))
						return;
					var child = oABNode.selectSingleNode('CONTACT[UniqueID="'+unique_id+'"]');
					oABNode.removeChild(child);
					CallControlMethod('DeleteXMLObject', child);
					RemoveContactFromInterface(unique_id, type);
					RemoveStatusListItem(child);
					break;
					
				case 'CG':
					var oLog = oCallLogNode.selectSingleNode('CALLLOG[UniqueID="'+unique_id+'"]');
					CallControlMethod('DeleteXMLObject', oLog.cloneNode(true));
					oCallLogNode.removeChild(oLog);
					break;
					
				case 'CS':
					var oCStatus = oCompStatusNode.selectSingleNode('COMPOSITE_STATUS[DN="'+unique_id+'"]');
					if (oActNode.selectSingleNode('.//AccountStatus//CurrentCompositeStatus').text == oCStatus.selectSingleNode('Description').text)
					{
						Dialog(text('DLG/CS/NODEL_CUR'),0);
						DisplayAccountStatus();
						return;
					}
					if (CheckForObjectReferenceInRoutingRules('CS', unique_id))
						return;
					oCompStatusNode.removeChild(oCStatus);
					CallControlMethod('DeleteXMLObject', oCStatus);
					break;
					
				case 'FCFAVS':
					var oDevice = oDevNode.selectSingleNode("DEVICE[Extension='"+ getObj('dv_feature_codes').Extension +"']");
					var oOldDevice = oDevice.cloneNode(true);
					var oDevFavorites = oDevice.selectSingleNode("FeatureCodeFavoritesList");
		
					var oMatchingDeviceFavorite = oDevFavorites.selectSingleNode('LIST/*/FEATURE_CODE[Description="'+unique_id+'"]');
					if (oMatchingDeviceFavorite)
						RemoveChildNodeFromListObject(oDevFavorites, oMatchingDeviceFavorite);
					break;
					
				case 'GT':
					if (CheckForObjectReferenceInRoutingRules(type, unique_id))
						return;

					var oGreeting = oGreetingsNode.selectSingleNode('GREETING[UniqueID="'+unique_id+'"]');
					CallControlMethod('DeleteXMLObject', oGreeting.cloneNode(true));
					oGreetingsNode.removeChild(oGreeting);
					break;
					
				case 'MS':
					switch (deleted_rows[j].msg_type)
					{
						case 'SYSTEM_MESSAGE':
							var oMsg = oMsgNode.selectSingleNode('SYSTEM_MESSAGE[UniqueID="'+ unique_id +'"]');
							CallControlMethod('DeleteXMLObject', oMsg.cloneNode(true));
							oMsgNode.removeChild(oMsg);
							break;
							
						case 'MSG_WAITING':
							var oMsg = oMsgNode.selectSingleNode('MSG_WAITING[SourceNodeExtension="'+unique_id+'"]');
							if (!oMsg.selectSingleNode('Mailbox').text)
							{
								CallControlMethod('DeleteXMLObject', oMsg.cloneNode(true));
								oMsgNode.removeChild(oMsg);
							}
							else
							{
								Dialog(text('DLG/MS/NO_DEL_VM'),0);
								return;
							}
							break;
					}
					break;
	
				case 'RR':
					var rule = oRulesNode.selectSingleNode("RULE[UniqueID='"+unique_id+"']");
					DeleteStepsForThisRule(rule);
					oRulesNode.removeChild(rule);
					CallControlMethod("DeleteXMLObject", rule);
					break;
					
				case 'RREDWA':
					var oStep = oStepsNode.selectSingleNode('STEP[UniqueID="'+unique_id+'"]');
					oStep.setAttribute('deleted', 'true');
					break;
			}
			if (deleted_rows[j])
				tblBody.removeChild(deleted_rows[j]);
			j++;
		}
	}
	else if (!deleted_rows.length && type != 'GPLS')
		Dialog(text('DLG/NO_HIGH_DEL'),0);
		
	if (b_CONFIRM && type=='CS')
		DisplayAccountStatus();
	
	if (type=='GPLS')
	{
		var child = table['GPLS'].body.firstChild;
		var IsRowSelected = 0;
		while (child)
		{
			var deleted_rows = GetHighlightedRows(child.lastChild,sSpeedDialUniqueID), k=0;
			while (deleted_rows[k])
			{
				IsRowSelected += 1;
				//If it is the first time, show the Confirm dialog. Else goahead and delete the contact directly without prompt.
				if(IsRowSelected == 1)
					if(Confirm(type))
						RemoveContactFromGroup(child.name, deleted_rows[k++].UniqueID);
					else
						return;
				else
					RemoveContactFromGroup(child.name, deleted_rows[k++].UniqueID);
			}
			UpdateGroupDisplays(child.name);
			child=child.nextSibling;
		}
		//If no row is selected display the error message.
		if(IsRowSelected==0)
		{
			Dialog(text('DLG/GP/NO_DEL_CT'),0);
			return;
		}
		table['GPLS'].refresh();
	}
	
	if (b_CONFIRM && type=='GT')
		UpdateGreetingsSelect();
	
	if (b_CONFIRM && type=='FCFAVS')
	{
		if (oDevFavorites && !oDevFavorites.selectSingleNode('LIST/*/FEATURE_CODE[0]'))
			table['FCFAVS'].refresh();
		if (oDevice.selectSingleNode('FeatureCodeFavoritesList').xml != oOldDevice.selectSingleNode('FeatureCodeFavoritesList').xml)
			CallControlMethod('EditXMLObject', oOldDevice, oDevice);
		if (oFloatWin && !oFloatWin.closed)
			ShowFloater('FeatureCodeFavorites');
	}
	
	if (b_CONFIRM && type=='RREDWA')
	{
		ReIndexSteps();
		table['RREDWA'].refresh();
	}
		
	SetTableStyle(tblBody);
}

function Confirm(type)
{
	var ret_vals, msg, op;
	switch (type)
	{
		case 'CLCF': msg=text('DLG/CL/CNFALL'); break;
		case 'GPLS': msg=text('DLG/GP/BAT_DEL'); break;
		
		default:
			msg = text('DLG/DEL/ROOT');
			op = text('ITEM/'+type);
			break;
	}
	if (msg && op)
		msg = Insert(op, msg);
	ret_vals = Dialog(msg,15);
	return eval(ParseDelimitedList(ret_vals)[0]);
}

function CheckForObjectReferenceInRoutingRules(type, unique_id)
{
	var step_path, rule_path, step_inserts = new Array, rule_inserts = new Array, oStep, oRule, tab_num=0, text_link, obj_link, msg;
	switch (type)
	{
		case 'AB':
			step_path = 'STEP[{0} = "{1}" and {2} = "{3}"]';
			step_inserts[0] = 'StepType';
			step_inserts[1] = _STEPTYPE_SEND_TO_CONTACT;
			step_inserts[2] = 'Destination';
			step_inserts[3] = unique_id;
			oStep = oStepsNode.selectSingleNode(InsertMultiple(step_inserts, step_path));
			
			rule_path = 'RULE[{0} = "{1}" and {2} = "{3}"]';
			rule_inserts[0] = 'WhoType';
			rule_inserts[1] = ROUTINGRULE_WHOTYPE_CONTACT;
			rule_inserts[2] = 'WhoParam';
			rule_inserts[3] = unique_id;
			oRule = oRulesNode.selectSingleNode(InsertMultiple(rule_inserts, rule_path));
			break;
			
		case 'CS':
			var oCompStatus = oCompStatusNode.selectSingleNode('COMPOSITE_STATUS[DN="'+unique_id+'"]');
			tab_num = 1;
			rule_path = 'RULE[{0} = "{1}"]';
			rule_inserts[0] = 'WhenCompStatus';
			rule_inserts[1] = oCompStatus.selectSingleNode('Description').text;
			oRule = oRulesNode.selectSingleNode(InsertMultiple(rule_inserts, rule_path));
			break;
			
		case 'DV':
			step_path = 'STEP[{0} = "{1}" and {2} = "{3}"]';
			step_inserts[0] = 'LocationType';
			step_inserts[1] = '1';
			step_inserts[2] = 'Destination';
			step_inserts[3] = unique_id;
			oStep = oStepsNode.selectSingleNode(InsertMultiple(step_inserts, step_path));
			break;
			
		case 'GP':
			rule_path = 'RULE[{0} = "{1}" and {2} = "{3}"]';
			rule_inserts[0] = 'WhoType';
			rule_inserts[1] = ROUTINGRULE_WHOTYPE_GROUP;
			rule_inserts[2] = 'WhoParam';
			rule_inserts[3] = unique_id;
			oRule = oRulesNode.selectSingleNode(InsertMultiple(rule_inserts, rule_path));
			break;
		
		case 'GT':
			step_path = 'STEP[{0} = "{1}"]';
			step_inserts[0] = 'Greeting';
			step_inserts[1] = unique_id;
			oStep = oStepsNode.selectSingleNode(InsertMultiple(step_inserts, step_path));
			break;
	}
	if (oStep)
	{
		var owning_rule = FindOwningRule(oStep.selectSingleNode('UniqueID').text);
		if (owning_rule)
		{
			text_link = '<link onclick=\"ValidateReturnValue(\'true\')\">'+  owning_rule.selectSingleNode('Description').text +'</link>';
			obj_link = '^true^|RR|'+ owning_rule.selectSingleNode('UniqueID').text +'|2|'+oStep.selectSingleNode('UniqueID').text;
			msg = text('DLG/'+type+'/USED_STEP')
		}
	}
	if (oRule)
	{
		text_link = '<link onclick=\"ValidateReturnValue(\'true\')\">'+ oRule.selectSingleNode('Description').text +'</link>';
		obj_link = '^true^|RR|'+ oRule.selectSingleNode('UniqueID').text +'|'+tab_num;
		msg = text('DLG/'+type+'/USED_RULE')
	}
	
	if (text_link && obj_link && msg)
	{
		if (eval(	ParseDelimitedList(	Dialog(Insert(text_link, msg),14))[0]	))
			HandleObjectLink(obj_link);
		return true;
	}
	return false;
}

function GetHighlightedRows(tblBody,sSpeedDialUniqueID)
{
	var a_highlighted_rows = new Array;
	for (var i=0; i < tblBody.children.length; i++)
	{	
		//other than selecting the highlighted row, added an additional comparision that would compare the id. 
		//This is applicable only for Groups as of now. This feature has been added to accomodate the 'Delete' feature specially on the speeddial buttons
		if ((tblBody.children[i].style.backgroundColor == HIGHLIGHTED_ROW_COLOR) || (("rowGP"+sSpeedDialUniqueID)==tblBody.children[i].id))
			a_highlighted_rows[a_highlighted_rows.length] = tblBody.children[i];
	}
	return a_highlighted_rows;
}

function GetRowByUniqueID(tblBody,uniqueID)
{
	var row = new Array;
	for (var i=0; i < tblBody.children.length; i++)
	{	
		//This is applicable only for Groups as of now. This feature has been added to accomodate the 'Delete' feature specially on the speeddial buttons
		if (tblBody.children[i].id == ("rowAB"+uniqueID)) 
		{
			row[row.length] = tblBody.children[i];
			return row;
		}
	}
	return row;
}

// ****************************************************
// **********************  GROUPS  ********************
// ****************************************************

function HandleStackableGroupMenuClick()
{
	var oEl=window.event.srcElement, img_src;
	if (oEl.tagName=='IMG')
	{
		img_src = GetImgSrc(oEl);
		if (img_src=="iExpPlus")
		{
			oEl.parentElement.nextSibling.style.display = "";
			oEl.src = "img/iExpMinus.gif";
			oGroupsNode.selectSingleNode("GROUP[Name='"+oEl.nextSibling.nodeValue+"']").setAttribute("open", "true");
		}	
		else if (img_src=="iExpMinus")
		{
			oEl.parentElement.nextSibling.style.display = "none";
			oEl.src = "img/iExpPlus.gif";
			oGroupsNode.selectSingleNode("GROUP[Name='"+oEl.nextSibling.nodeValue+"']").setAttribute("open", "false");
		}
	}
	else if (oEl.className=="cssMenuItemHead" && !oEl.active)
	{
		// reset the other div styles
		var oChild = oEl.parentElement.firstChild;
		while (oChild)
		{
			if (oChild.className=="cssMenuItemHead" && oChild.active && oChild != oEl)
				oChild.active = 0;
			oChild = oChild.nextSibling;
		}
		oEl.active = 1;
	}
	else if (oEl.className=="cssMenuItemHead" && oEl.active)
	{
		oEl.active = 0;
		oEl.style.border="2px solid #c93";
	}
}

// ****************************************************
// ******************  DRAG METHODS  ******************
// ****************************************************

var dragObj = new Object;

// string to hold source of object being dragged:
var dummyObj;

function startDrag()
{
	// get what is being dragged & set context specific properties:
	dragObj = window.event.srcElement;
	var effect;
	switch (dragObj.type)
	{
		case 'AB':
		case 'CL':
			dragObj.UniqueID = dragObj.parentElement.parentElement.UniqueID;
			effect='copyMove';
			break;
			
		case 'GP':
			dragObj.UniqueID = dragObj.parentElement.UniqueID;
			dragObj.groupName = dragObj.parentElement.innerText;
			effect='copyMove';
			break;
			
		case 'GPAB':
			dragObj.UniqueID = dragObj.parentElement.UniqueID;
			effect='copyMove';
			break;
			
		case 'GPLS':
			dragObj.UniqueID = dragObj.parentElement.UniqueID;
			dragObj.groupName = dragObj.parentElement.parentElement.previousSibling.innerText;
			effect='move';
			break;
			
		case 'RREDWA':
			dragObj.UniqueID = dragObj.parentElement.parentElement.UniqueID;
			effect='move';
			break;
			
		case 'UB':
			dragObj.UniqueID = dragObj.parentElement.parentElement.id.replace('ub','');
			dragObj.groupName = config('SPEED_DIAL');
			effect='move';
			break;
			
	/*	default:
			dragObj.UniqueID = dragObj.parentElement.UniqueID;
			dragObj.groupName = config('SPEED_DIAL');
			effect='copyMove';
			break;*/
		
	}
	//dragObj.UniqueID = (dragObj.type != 'CL' && dragObj.type != 'RREDWA') ? dragObj.parentElement.UniqueID : dragObj.parentElement.parentElement.UniqueID;
	dragObj.count=0;
		
    // store the source of the object into a string acting as a dummy object so we don't ruin the original object:
    dummyObj = dragObj.outerHTML;

    // post the data for Windows:
    var dragData = window.event.dataTransfer;

    // set the type of data for the clipboard:
	//var sObjData = DelimitList(new Array(srcObj.className, srcObj.groupName, srcObj.parentElement.id, srcObj.type));
    dragData.setData('Text', dragObj.src);
   
    // allow only dragging that involves moving the object:
    dragData.effectAllowed = effect;

    // use the special 'move' cursor when dragging:
    dragData.dropEffect = 'move';
	
	switch (dragObj.type)
	{
		case 'GPLS':
		case 'GP':
		case 'UB':
			var oBody = document.body;
			oBody.ondragend = endDragUI;
			oBody.ondrop = endDragUI;
			oBody.ondragenter = enterDragList;
			oBody.ondragover = overDrag;
			break;
		
		case 'RREDWA':
			var oBody = table['RREDWA'].body;
			oBody.ondrop = dropStep;
			oBody.ondragenter = dragEnterStepTable;
			oBody.ondragover = overDrag;
			oBody.ondragleave = leaveDrag;
			break;
	}
	
	if (dragObj.type=='AB' || dragObj.type=='GPAB')
	{
		var oUB = getObj('UB');
		oUB.ondragover = overDrag;
		oUB.ondrop = dropButtons;
	}
}

var sEventLog="";

function showLog()
{
	alert(sEventLog);
}

function clearLog()
{
	sEventLog="";
}

function showEvent()
{
	alert(window.event.type);
}

var sPrevMenuName="";

function enterDragMenu()
{
	window.event.cancelBubble=true;
	var oEl = window.event.srcElement;

	if (oEl.className == 'cssMenuItem' || oEl.className == 'cssMenuItemLine')
	{
		window.event.dataTransfer.getData('Text');
		var oMenu = oEl;
		while (oMenu.className != 'cssMenuItem')
			oMenu = oMenu.parentElement;
		var oPrevMenu = getObj(sPrevMenuName);

		if (dragObj.type=='GP')
		{
			if (oPrevMenu && (oMenu.id != sPrevMenuName))
				SetMenuColor(oPrevMenu,0);
	
			if ((oMenu.id.replace('group_','') != dragObj.groupName) && oMenu != getObj('group_'+dragObj.groupName).nextSibling)
				SetMenuColor(oMenu,1);
		}
		else if (dragObj.type=='GPAB' || dragObj.type=='GPLS')
		{
			if (oPrevMenu && (oMenu.id != sPrevMenuName))
				SetMenuColor(oPrevMenu,0);
	
			SetMenuColor(oMenu,1);
		
		}
		sPrevMenuName = oMenu.id;
	}
}

function enterDragList()
{
	window.event.cancelBubble=true;
	SetMenuColor(getObj(sPrevMenuName), 0);
}

function enterDrag()
{
	window.event.returnValue=false;
	window.event.cancelBubble=true;
}

// tell onDragOver handler not to do anything:
function overDrag()
{
	window.event.returnValue = false;
	window.event.cancelBubble=true;
}

// tell onDragLeave handler not to do anything:
function leaveDrag()
{
	window.event.cancelBubble=true;
	window.event.returnValue = false;
}

function SetMenuColor(menu, bIsOver)
{
	if (!menu)
		return false;

	if (dragObj.type=='GPAB' || dragObj.type=='GPLS')
		menu.firstChild.style.backgroundColor = (bIsOver) ? '#ff9' : '';
		
	else if (dragObj.type=='GP')
		menu.style.borderTop = (bIsOver) ? '2px solid #ff9' : '';

}

function endDrag()
{
	// when done remove clipboard data
	window.event.dataTransfer.clearData();
	var oBody = document.body;
	oBody.ondragend = null;
	oBody.ondrop = null;
	oBody.ondragenter = null;
	oBody.ondragover = null;
	SetMenuColor(getObj(sPrevMenuName), 0);
	var oUB = getObj('UB');
	oUB.ondragover = null;
	oUB.ondrop = null;
	//dragObj = null;
}

function endDragUI()
{
	var oEl = window.event.srcElement;
	var oGroupList = getObj("GroupList");
	if (!oGroupList.contains(oEl))
		HandleDroppedDragItems(oEl, oGroupList);
}

function dropMenu()
{
	window.event.cancelBubble=true;
	var oEl = window.event.srcElement;
	var img_src = GetImgSrc(dragObj);
	if ((img_src=='iAct' || img_src=='iKeyset'|| img_src=='iContact' || img_src=='iBusiness') && dragObj.UniqueID)
	{
		var oParent = oEl, tBody;
		while (oParent.className != 'cssMenuItem')
			oParent = oParent.parentElement;
		var group_name = oParent.id.replace('group_','');
		AddContactToGroup(group_name, dragObj.UniqueID);
		// add highlighted table rows
		if (dragObj.type == 'GPAB')
			tBody = table['GPAB'].body;
		else if (dragObj.type == 'GPLS')
		{
			var child = table['GPLS'].body.firstChild;
			while (child && child.name != dragObj.groupName)
				child = child.nextSibling;
			tBody = child.lastChild;
		}
		var rows = GetHighlightedRows(tBody), i=0;
		while (rows[i])
			AddContactToGroup(group_name, rows[i++].UniqueID);
		if (rows)
			ResetRows(table['GPAB'].body);
		table['GPLS'].refresh();
		UpdateGroupDisplays(group_name);
	}
	else if (img_src=='iGroup')
		ReorderGroups(oEl);

	endDrag();
}

function dropList()
{
    // eliminate default action of ondrop so we can customize:
	var evt = window.event;
    evt.returnValue = false;
	/*if (evt.className=='cssMenuItem')
		evt.srcElement.style.backgroundColor='';*/
	
	var oGroupList = getObj('GroupList');
	var oEl = evt.srcElement, bDoBuild=1;

	if (dragObj && dragObj.type)
	{
		var img_src = GetImgSrc(dragObj);
		if ((img_src=='iAct' || img_src=='iKeyset' || img_src=='iBusiness' || img_src=='iContact') && dragObj.UniqueID)
		{
			//if (dragObj.type=='GP')
			HandleDroppedDragItems(oEl, oGroupList);
			table['GPLS'].refresh();
		}
		// in this case the group icon has been drug to 
		else if (img_src=='iGroup')
			ReorderGroups(oEl);
	}
	
	endDrag();
}

function dropButtons()
{
	if (dragObj && (dragObj.type=='AB' || dragObj.type=='GPAB'))
	{
		var img_src = GetImgSrc(dragObj);
		if ((img_src=='iAct' 		|| img_src=='iActUNAV' 		|| img_src=='iActCALL' 		|| img_src=='iActUNKN' 		||
			 img_src=='iKeyset' 	|| img_src=='iKeysetDND' 	|| img_src=='iKeysetCALL' 	|| img_src=='iKeysetUNKN' 	||
			 img_src=='iContact' 	|| img_src=='iBusiness')
			 && dragObj.UniqueID)
		{
			AddContactToGroup(config('SPEED_DIAL'), dragObj.UniqueID);
			var aRows = GetHighlightedRows(table['AB'].body), k=0;
			while (aRows[k])
				AddContactToGroup(config('SPEED_DIAL'), aRows[k++].UniqueID);
			table['GPLS'].refresh();
			UpdateGroupDisplays(config('SPEED_DIAL'));
		}
	}
}
/*
function dropTrash()
{
	window.event.cancelBubble=true;
	DeleteDroppedDragItems(window.event.srcElement, getObj("GroupList"));
}*/

function ReorderGroups(oEl)
{
	// if oEl is an image - the drag was dropped on the group image walk up to the parent menu item
	if (oEl.tagName=='IMG')
		oEl=oEl.parentElement.parentElement;
	var oDivToMove = getObj('group_'+dragObj.groupName);
	// setting the following to null inserts the child at the end of the list\
	var oDivToInsertBefore = (oEl.className=='cssMenuItem') ? oEl : ((oEl.id=='GroupList'||oEl.id=='tableBody')? null : table['GPLS'].body.firstChild);
	var oParent = (oEl.className=='cssMenuItem') ? oEl.parentElement : oDivToMove.parentElement;
	oParent.insertBefore(oDivToMove, oDivToInsertBefore);
	UpdateGroupRanks(oDivToMove);
}

function HandleDroppedDragItems(oEl, oGroupList)
{
	var sGroupName = dragObj.groupName, bUpdate;
	if (dragObj.type=='GPLS' && dragObj.UniqueID)
	{
		if (oEl.id=='GroupList' || (oEl.id=='tableBody' && oGroupList.contains(oEl)) || 
		   (!oGroupList.contains(oEl) && dragObj.type=='GPLS' && dragObj.deletePermitted))
		{
			RemoveContactFromGroup(sGroupName, dragObj.UniqueID);
			// remove highlighted rows in the same table from the dragged object
			var child = table['GPLS'].body.firstChild;
			while (child && child.name != sGroupName)
				child=child.nextSibling;

			var aRows = GetHighlightedRows(child.lastChild), k=0;
			while (aRows[k])
			{
				RemoveContactFromGroup(child.name, aRows[k++].UniqueID.replace('rowGP', ''));
				UpdateGroupDisplays(child.name);
			}
		}
		UpdateGroupDisplays(sGroupName);
	}
	else if (dragObj.type=='UB' && !getObj('UB').contains(oEl))
	{
		RemoveContactFromGroup(config('SPEED_DIAL'), dragObj.UniqueID);
		UpdateGroupDisplays(config('SPEED_DIAL'));
	}
	else if (dragObj.type=='GP' && !oGroupList.contains(oEl))
	{
		if (sGroupName == config('SPEED_DIAL'))
			Dialog(Insert(config('SPEED_DIAL'), text('DLG/GP/NO_DEL_SP')) ,0);
		else
		{
			if (Confirm('GP') && !CheckForObjectReferenceInRoutingRules('GP', sGroupName))
			{
				var aContacts = oABNode.selectNodes('CONTACT[Groups/LIST//String="'+sGroupName+'"]'), i=0;
				while (aContacts[i])
					RemoveContactFromGroup(sGroupName, aContacts[i++].selectSingleNode('UniqueID').text);
				var oNode = oGroupsNode.selectSingleNode('GROUP[Name="'+sGroupName+'"]');
				oGroupsNode.removeChild(oNode);
				CallControlMethod('DeleteXMLObject', oNode);
				var oABFilterSelect = getObj('table_filter_select_AB');
				if (oABFilterSelect.options[oABFilterSelect.selectedIndex].text == sGroupName)
				{
					MakeTableFilterSelect('AB', getObj('ab_filter_select'));
					table['AB'].curFilterProperty 	= '';
					table['AB'].curFilterValue		= '';
					table['AB'].refresh();
				}
			}
		}
	}
	endDrag();
	table['GPLS'].refresh();
	//UpdateGroupRanks();
}

/*
m_csTenantGroup
m_csOwner
m_csDN
m_csName
m_nRank
*/

function AddNewGroup(name)
{
	var oInput = getObj("AddGroupInput"), b_RANK_MAX_EXCEEDED=0;
	if (!name)
	{
		var ret_vals = ParseDelimitedList(Dialog(text('GP/NEW'),11));
		if (eval(ret_vals[0]) && ret_vals[1])
		{
			name = ret_vals[1];
			var re_noquotes = new RegExp('[/\\\\,=+<>#;\"\']');
			if (re_noquotes.test(name))
			{
				Dialog(Insert('&#34;&#35;&#39;&#43;&#44;&#47;&#59;&#60;&#61;&#62;&#92;', text('DLG/GP/BAD_CHARS')),0);
				return;
			}
		}
		else
			return;
	}
	
	while (FindExistingNodeValue(oGroupsNode, 'Name', name))
	{
		var ret_vals = ParseDelimitedList(Dialog(text('DLG/GP/NM_MTCH'),11));
		if (eval(ret_vals[0]) && ret_vals[1])
			name = ret_vals[1];
		else
			return;
		//Dialog(text('DLG/GP/NM_MTCH'),0);
	}
	//`~!@#$%^&*()-_=+/*.;:?<>,
	if (name) //oInput.value
	{
		var oNode = GetTemplate("GROUP");
		oNode.selectSingleNode("Name").text = name;
		oNode.selectSingleNode("Owner").text = oActNode.selectSingleNode(".//UniqueID").text;
		oNode.selectSingleNode("TenantGroup").text = oActNode.selectSingleNode(".//TenantGroup").text;
		oNode.selectSingleNode("Rank").text = parseFloat(table['GPLS'].body.lastChild.rank) + RANK_PADDING;
		oNode.setAttribute("open", "false");
		oGroupsNode.appendChild(oNode);
		CallControlMethod("AddXMLObject", oNode);
		table['GPLS'].refresh();
		if (b_RANK_MAX_EXCEEDED)
			ReRankGroups();
	}
}

function AddContactToGroup(sGroupName, sContactID)
{
	var oNewObj = oABNode.selectSingleNode("CONTACT[UniqueID='"+sContactID+"']");
	var oOldObj = oNewObj.cloneNode(true);
	var oTargetGroup = oNewObj.selectSingleNode("Groups/LIST/*/STR[String='"+sGroupName+"']");
	if (!oTargetGroup)
	{
		AddChildNodeToListObject(oNewObj.selectSingleNode("Groups"), sGroupName);
		CallControlMethod("EditXMLObject", oOldObj, oNewObj);
	}
}

function RemoveContactFromGroup(sGroupName, sContactID)
{
	var oNewObj = oABNode.selectSingleNode("CONTACT[UniqueID='"+sContactID+"']");
	var oOldObj = oNewObj.cloneNode(true);
	RemoveChildNodeFromListObject(oNewObj.selectSingleNode("Groups"), sGroupName);
	CallControlMethod("EditXMLObject", oOldObj, oNewObj);
}

var RANK_PADDING = 100;
var RANK_MIN = 100;
var RANK_MAX = 999;
var RANK_ADJ;

function UpdateGroupRanks(oDiv)
{
	if (oDiv)
	{
		var low_rank, high_rank, new_rank, MIN_SPACING = 5;
		var oPrevGroup = oDiv.previousSibling, oNextGroup = oDiv.nextSibling;
		if (oPrevGroup)
			low_rank = parseFloat(oPrevGroup.rank);
		if (oNextGroup)
			high_rank = parseFloat(oNextGroup.rank);
		if (low_rank && high_rank && ((high_rank - low_rank)/2) > MIN_SPACING)
		{
			new_rank = parseInt((high_rank - low_rank)/2) + low_rank;
			EditGroupRank(oDiv, new_rank);
		}
		else if (low_rank && !high_rank)
			EditGroupRank(oDiv, low_rank + RANK_PADDING);
		else if (high_rank && !low_rank && high_rank > MIN_SPACING)
		{
			var new_rank = parseInt(high_rank/2);
			EditGroupRank(oDiv, new_rank);
		}
		else
			ReRankGroups();
	}
	else
		ReRankGroups();
}

function ReRankGroups()
{
	var tBody = table['GPLS'].body;
	var child = tBody.firstChild, RANK = RANK_MIN;
	while (child)
	{
		EditGroupRank(child, RANK);
		child = child.nextSibling;
		RANK += RANK_PADDING;
	}
}

function EditGroupRank(div, rank)
{
	div.rank = rank;
	var oNewObj = oGroupsNode.selectSingleNode('GROUP[Name="'+div.name+'"]');
	var oOldObj = oNewObj.cloneNode(true);
	oNewObj.selectSingleNode('Rank').text = rank;
	CallControlMethod('EditXMLObject', oOldObj, oNewObj);
}

// ****************************************************
// **********************  MISC  **********************
// ****************************************************

var oDialogWin;
var oDialogWin_ModeLess;

function Dialog(sMsg, type, sCustomRows, obj_setup, window_Height,window_width)
{
	var nHeight, nWidth, i=0, j=0, x="";

	if(window_Height)
		nHeight=window_Height;
	else 
		nHeight=217;

	if(window_width)
		nWidth=window_width;
	else 
		nWidth=400;

	var aButtons = oText.selectNodes('LABELS/DIALOG/button[$any$ t="'+type+'"]');
	var aRows = oText.selectNodes('LABELS/DIALOG/row[$any$ t="'+type+'"]');
	var re = new RegExp('¶', 'g');
	x+= '<params type="'+ type +'">';
	x+=	'<message>'+ sMsg.replace(re, '<line_break/>') +'</message>';
	while (aRows[i])
		x+= aRows[i++].xml;

	if (sCustomRows)
		x+= sCustomRows;

	while (aButtons[j])
		x+= aButtons[j++].xml;
	x+=	'</params>';
	
	var xStyle = new ActiveXObject('Msxml.DOMDocument');
	xStyle.loadXML(GetDialogStyle());
	xTmp.loadXML(x);
	
	var oSelectRows = xTmp.selectNodes('params/row[select]'), m=0;
	while (oSelectRows[m])
	{
		var nOptions = oSelectRows[m].selectNodes('select/option').length;
		if (oSelectRows[m].selectSingleNode('select').getAttribute('size')!='1')
		{
			oSelectRows[m].setAttribute('height', (nOptions*30));
			oSelectRows[m].selectSingleNode('select').setAttribute('size', nOptions);
		}
		m++;
	}

	var output = xTmp.transformNode(xStyle);
	var aArgs = new Array(PRODUCT_NAME_AND_VERSION, output, obj_setup);
	aArgs = DelimitList(aArgs);

	// adjust height for length of message and number of rows
	// find embedded link tags and replace them to prevent height from being over estimated
	var re = new RegExp('<[/]*[a-zA-Z]+[\s]*.*>', 'g');
	var message_minus_tags = sMsg.replace(re,'');
	var num_est_msg_rows = (parseInt(message_minus_tags.length/40)) ? parseInt(message_minus_tags.length/40) : 1;
	nHeight += (num_est_msg_rows*25);
	// add extra height for line breaks;
	var num_breaks = xTmp.selectNodes('params/message/line_break').length;
	nHeight += (num_breaks*10);
	var rows_with_height_param = xTmp.selectNodes('params/row[@height]'), k=0;
	var default_rows_height = xTmp.selectNodes('params/row').length - rows_with_height_param.length;
	while (rows_with_height_param[k])
		nHeight += parseFloat(rows_with_height_param[k++].getAttribute('height'));
	nHeight += (default_rows_height*40);
	var window_specs = 'dialogHeight:'+nHeight+'px; dialogWidth:'+nWidth+'px; edge:Raised; center:yes; help:no; resizable:no; status:no;'
	
	oDialogWin = window.showModalDialog('Dialog.htm', aArgs, window_specs);
	return oDialogWin;
}

function Dialog_Modeless(sMsg, type, sCustomRows, obj_setup)
{
	var nHeight=217, nWidth=400, i=0, j=0, x="";
	var aButtons = oText.selectNodes('LABELS/DIALOG/button[$any$ t="'+type+'"]');
	var aRows = oText.selectNodes('LABELS/DIALOG/row[$any$ t="'+type+'"]');
	var re = new RegExp('¶', 'g');
	x+= '<params type="'+ type +'">';
	x+=	'<message>'+ sMsg.replace(re, '<line_break/>') +'</message>';
	while (aRows[i])
		x+= aRows[i++].xml;

	if (sCustomRows)
		x+= sCustomRows;

	while (aButtons[j])
		x+= aButtons[j++].xml;
	x+=	'</params>';
	
	var xStyle = new ActiveXObject('Msxml.DOMDocument');
	xStyle.loadXML(GetDialogStyle());
	xTmp.loadXML(x);
	
	var oSelectRows = xTmp.selectNodes('params/row[select]'), m=0;
	while (oSelectRows[m])
	{
		var nOptions = oSelectRows[m].selectNodes('select/option').length;
		if (oSelectRows[m].selectSingleNode('select').getAttribute('size')!='1')
		{
			oSelectRows[m].setAttribute('height', (nOptions*30));
			oSelectRows[m].selectSingleNode('select').setAttribute('size', nOptions);
		}
		m++;
	}

	var output = xTmp.transformNode(xStyle);
	var aArgs = new Array(PRODUCT_NAME_AND_VERSION, output, obj_setup);
	aArgs = DelimitList(aArgs);
	
	// adjust height for length of message and number of rows
	// find embedded link tags and replace them to prevent height from being over estimated
	var re = new RegExp('<[/]*[a-zA-Z]+[\s]*.*>', 'g');
	var message_minus_tags = sMsg.replace(re,'');
	var num_est_msg_rows = (parseInt(message_minus_tags.length/40)) ? parseInt(message_minus_tags.length/40) : 1;
	nHeight += (num_est_msg_rows*25);
	// add extra height for line breaks;
	var num_breaks = xTmp.selectNodes('params/message/line_break').length;
	nHeight += (num_breaks*10);
	var rows_with_height_param = xTmp.selectNodes('params/row[@height]'), k=0;
	var default_rows_height = xTmp.selectNodes('params/row').length - rows_with_height_param.length;
	while (rows_with_height_param[k])
		nHeight += parseFloat(rows_with_height_param[k++].getAttribute('height'));
	nHeight += (default_rows_height*40);
	var window_specs = 'dialogHeight:'+nHeight+'px; dialogWidth:'+nWidth+'px; edge:Raised; center:yes; help:no; resizable:no; status:no;'
	
	oDialogWin_ModeLess = window.showModelessDialog('Dialog.htm', aArgs, window_specs);
	return oDialogWin;
}


function GetDialogStyle()
{
	var x= "<?xml version=\"1.0\" encoding=\"US-ASCII\"?>";
	x+= "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/TR/WD-xsl\">";
	
	x+= "<xsl:template match=\"/\">";
	x+= 	"<xsl:apply-templates select=\"params\"/>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"params\">";
	x+= 	"<xsl:apply-templates select=\"message\" />";
	x+= 	"<xsl:apply-templates select=\"label\" />";
	x+= 	"<xsl:apply-templates select=\"row\" />";
	x+=		"<div id='buttons'>";
	x+= 		"<xsl:apply-templates select=\"button\" />";
	x+=		"</div>";
	x+=		"<div id=\"footer\"></div>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"message\">";
	x+= 	"<div id=\"message\"><xsl:apply-templates /></div>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"row\">";
	x+= 	"<div id=\"inputs\">";
	x+= 		"<xsl:if test=\"style[@for='row']\"><xsl:attribute name=\"style\"><xsl:value-of select=\"style\"/></xsl:attribute></xsl:if>";
	x+= 		"<xsl:apply-templates select=\"label\" />";
	x+= 		"<xsl:apply-templates select=\"input\" />";
	x+= 		"<xsl:apply-templates select=\"select\" />";
	x+= 		"<xsl:apply-templates select=\"labelAtEnd\" />";
	x+= 		"<xsl:apply-templates select=\"inputAtEnd\" />";
	x+= 		"<xsl:apply-templates select=\"bar\" />";
	x+= 		"<xsl:apply-templates select=\"span\" />";
	x+= 		"<xsl:apply-templates select=\"HR\" />";
	x+=		"</div>";
	x+= "</xsl:template>";

	x+= "<xsl:template match=\"HR\">";
//	x+= 	"<div>";
	x+=		"<HR>";
	x+=		"</HR>";
//	x+=	"</div>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"label\">";
	x+=   "<label>";
	x+= 	"<xsl:if test=\"@style\"><xsl:attribute name=\"style\"><xsl:value-of select=\"@style\"/></xsl:attribute></xsl:if>";
	x+= 	"<xsl:if test=\"@id\"><xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute></xsl:if>";
	x+= 	"<xsl:value-of select=\".\"/>";
	x+=   "</label> ";
	x+= "</xsl:template>";

	x+= "<xsl:template match=\"labelAtEnd\">";
	x+=   "<label>";
	x+= 	"<xsl:if test=\"@style\"><xsl:attribute name=\"style\"><xsl:value-of select=\"@style\"/></xsl:attribute></xsl:if>";
	x+= 	"<xsl:if test=\"@id\"><xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute></xsl:if>";
	x+= 	"<xsl:value-of select=\".\"/>";
	x+=   "</label> ";
	x+= "</xsl:template>";

	x+= "<xsl:template match=\"labelInMiddle\">";
	x+=   "<label>";
	x+= 	"<xsl:if test=\"@style\"><xsl:attribute name=\"style\"><xsl:value-of select=\"@style\"/></xsl:attribute></xsl:if>";
	x+= 	"<xsl:if test=\"@id\"><xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute></xsl:if>";
	x+= 	"<xsl:value-of select=\".\"/>";
	x+=   "</label> ";
	x+= "</xsl:template>";

	x+= "<xsl:template match=\"input\">";
	x+= 	"<xsl:if test=\".[@type='password' or @type='text']\">";
	x+= 		"<span>";
	x+= 			"<xsl:if test=\"context(-2)[@style]\"><xsl:attribute name=\"style\"><xsl:value-of select=\"context(-2)/@style\"/></xsl:attribute></xsl:if>";//
	x+= 			"<xsl:value-of select=\".\"/>";
	x+= 		"</span>";
	x+= 		"<span>";
	x+= 			"<xsl:if test=\"context(-2)[@style]\"><xsl:attribute name=\"style\"><xsl:value-of select=\"context(-2)/@style\"/></xsl:attribute></xsl:if>";//
	x+= 			"<input>";
	x+= 				"<xsl:attribute name=\"type\"><xsl:value-of select=\"@type\"/></xsl:attribute>";
	x+= 				"<xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute>";
	x+= 				"<xsl:attribute name=\"value\"><xsl:value-of select=\"@value\"/></xsl:attribute>";
	x+= 				"<xsl:if test=\"@width\">";
	x+= 					"<xsl:attribute name=\"style\">width:<xsl:value-of select=\"@width\"/>px</xsl:attribute>";
	x+= 				"</xsl:if>";
	x+= 			"</input>";
	x+= 		"</span>";
	x+= 	"</xsl:if>";
	x+= 	"<xsl:if test=\".[@type='radio']\">";
	x+= 		"<span>";
	x+= 		"<input>";
	x+= 			"<xsl:attribute name=\"type\"><xsl:value-of select=\"@type\"/></xsl:attribute>";
	x+= 			"<xsl:attribute name=\"name\"><xsl:value-of select=\"@name\"/></xsl:attribute>";
	x+= 			"<xsl:attribute name=\"value\"><xsl:value-of select=\"@value\"/></xsl:attribute>";
	x+= 			"<xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute>";
	x+= 			"<xsl:if test=\"@checked\"><xsl:attribute name=\"checked\"><xsl:value-of select=\"@checked\"/></xsl:attribute></xsl:if>";
	x+= 			"<xsl:if test=\"@onclick\"><xsl:attribute name=\"onclick\"><xsl:value-of select=\"@onclick\"/></xsl:attribute></xsl:if>";
	x+= 		"</input> ";
	x+= 		"<xsl:value-of select='.'/>";
	x+= 		"</span>";
	x+= 	"</xsl:if>";
	x+= 	"<xsl:if test=\".[@type='checkbox']\">";
	x+= 		"<span>";
	x+= 		"<input>";
	x+= 			"<xsl:attribute name=\"type\"><xsl:value-of select=\"@type\"/></xsl:attribute>";
	x+= 			"<xsl:attribute name=\"id\"><xsl:value-of select=\"@name\"/></xsl:attribute>";
	x+= 		"</input> ";
	x+= 		"<xsl:value-of select='.'/>";
	x+= 		"</span>";
	x+= 	"</xsl:if>";
	x+= "</xsl:template>";

//Use this tag when you want the INPUT tag after the select TAG.
	x+= "<xsl:template match=\"inputAtEnd\">";
	x+= 		"<span>";
	x+= 			"<input>";
	x+= 				"<xsl:attribute name=\"type\"><xsl:value-of select=\"@type\"/></xsl:attribute>";
	x+= 				"<xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute>";
	x+= 				"<xsl:if test=\"@style\"><xsl:attribute name=\"style\"><xsl:value-of select=\"@style\"/></xsl:attribute></xsl:if>";
	x+= 				"<xsl:attribute name=\"value\"><xsl:value-of select=\"@value\"/></xsl:attribute>";
	x+= 				"<xsl:if test=\"@width\">";
	x+= 					"<xsl:attribute name=\"style\">width:<xsl:value-of select=\"@width\"/>px</xsl:attribute>";
	x+= 				"</xsl:if>";
	x+= 				"<xsl:if test=\"@maxlength\"><xsl:attribute name=\"maxlength\"><xsl:value-of select=\"@maxlength\"/></xsl:attribute></xsl:if>";
	x+= 			"</input>";
	x+= 		"</span>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"select\">";
	x+= 	"<select>";
	x+= 		"<xsl:attribute name=\"id\"><xsl:value-of select=\"@id\"/></xsl:attribute>";
	x+= 		"<xsl:if test=\"@size\"><xsl:attribute name=\"size\"><xsl:value-of select=\"@size\"/></xsl:attribute></xsl:if>";
	x+= 		"<xsl:if test=\"@onclick\"><xsl:attribute name=\"onclick\"><xsl:value-of select=\"@onclick\"/></xsl:attribute></xsl:if>";
	x+= 		"<xsl:if test=\"@onkeyup\"><xsl:attribute name=\"onkeyup\"><xsl:value-of select=\"@onkeyup\"/></xsl:attribute></xsl:if>";
	x+=		"<xsl:if test=\"@onchange\"><xsl:attribute name=\"onchange\"><xsl:value-of select=\"@onchange\"/></xsl:attribute></xsl:if>";
	x+=			"<xsl:for-each select=\"option\">";
	x+= 			"<option>";
	x+= 				"<xsl:attribute name=\"value\"><xsl:value-of select=\"@value\"/></xsl:attribute>";
	x+= 				"<xsl:if test=\"@onclick\"><xsl:attribute name=\"onclick\"><xsl:value-of select=\"@onclick\"/></xsl:attribute></xsl:if>";
	x+= 				"<xsl:value-of select=\".\"/>";
	x+= 			"</option>";
	x+=			"</xsl:for-each>";
	x+= 	"</select>";
	x+= "</xsl:template>";

	x+= "<xsl:template match=\"button\">";
	x+= "<input type=\"button\" class=\"button\" ";
//	x+= 	" onmouseover=\"this.style.backgroundColor='#9cf';this.style.color='#036';\" ";
	x+= 	" onmousedown=\"this.style.backgroundColor='#ffc';this.style.color='#000';\" ";
	x+= 	" onmouseup=\"this.style.backgroundColor='';this.style.color='';\" ";
	x+= 	" onmouseout=\"this.style.backgroundColor='';this.style.color='';\" >";
	x+= 	"<xsl:attribute name=\"onclick\">ValidateReturnValue(<xsl:value-of select=\"return\"/>)</xsl:attribute>";
	x+= 	"<xsl:attribute name=\"value\"><xsl:value-of select=\"label\"/></xsl:attribute>";
	x+= 	"</input>";
	x+= "</xsl:template>";

	x+= "<xsl:template match=\"link\">";
	x+=		"<xsl:element name=\"a\">";
	x+= 		"<xsl:attribute name=\"href\">";
	x+= 			"<xsl:choose>";
	x+= 			"<xsl:when test=\"@href\"><xsl:value-of select=\"@href\"/></xsl:when>";
	x+= 			"<xsl:otherwise>javascript://</xsl:otherwise>";
	x+= 			"</xsl:choose>";
	x+= 		"</xsl:attribute>";
	x+= 		"<xsl:if test=\"@onclick\"><xsl:attribute name=\"onclick\"><xsl:value-of select=\"@onclick\"/>;return false</xsl:attribute></xsl:if>";
	x+= 		"<xsl:attribute name=\"style\">color:blue;</xsl:attribute>";
	x+= 			"<xsl:value-of select=\".\"/>";
	x+=		"</xsl:element>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"line_break\">";
	x+=		"<xsl:element name=\"br\" />";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"span\">";
	x+=		"<span><xsl:attribute name=\"style\"><xsl:value-of select=\"@style\" /></xsl:attribute><xsl:value-of select=\".\" /></span>";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"text()\">"; 
	x+= 	"<xsl:script><![CDATA[";
	x+= 	"function replaceText(n) {";
	x+=			"var msg = n.text;";
	x+=			"var re = new RegExp('@', 'g');";
	x+= 		"return msg.replace(re, '<br>')";
	x+= 	"}";
	x+= 	"]]></xsl:script>";
	x+= 	"<xsl:value-of select=\".\"/>";
	x+= "</xsl:template>";
	
	x+= "</xsl:stylesheet>";

	return x;
}

function Goto()
{
	alert(window.event.srcElement);
}

function DoNothing(){}

function IsValid(obj)
{
	if (obj)
	{
		// obj may either be a text input form element or a string
		var strText = (obj.type == "text" || obj.type == "password") ? obj.value : obj;
		if (strText == "") { return false };
		if (strText)
		{
			var bVals = 0;
			for (var i = 0; i < strText.length; i++)
			{
				if (strText.charAt(i) == " ") { bVals++ };
			}
			if (bVals < strText.length)
				return true;
		}
	}
	return false;
}

function IsValidEmailAddress(obj)
{
	if (obj)
	{
		// obj may either be a text input form element or a string
		var strText = (obj.type == "text" || obj.type == "password") ? obj.value : obj;
		if (strText == "") { return false };
		if (strText)
		{
			var bVals = 0;
			var atChar = 0,SpecialChar = 0;
			for (var i = 0; i < strText.length; i++)
			{
				if (strText.charAt(i) == " ") { bVals++ };
				if (strText.charAt(i) == "@") { atChar = 1 };
				if (strText.charAt(i) == "~" || strText.charAt(i) == "!" || strText.charAt(i) == "#" || strText.charAt(i) == "%" || strText.charAt(i) == "^" || strText.charAt(i) == "+" || strText.charAt(i) == "$" || strText.charAt(i) == "{" || strText.charAt(i) == "}" || strText.charAt(i) == "[" || strText.charAt(i) == "]" || strText.charAt(i) == "|" || strText.charAt(i) == "?" || strText.charAt(i) == "/") { SpecialChar = 1 };
			}
			if (bVals >= strText.length || atChar == 0 || SpecialChar == 1 )
			{	
				return false;
			}
			else
			{
				return true;
			}
		}
	}
	return false;
}

function StringMatch(str1, str2)
{
	return (ToLower(str1+"") == ToLower(str2+""));
}

function GetComponentConfigValue(abbr, prop)
{
	var oNode = oComponents.selectSingleNode("CONTENT[@abbr='"+ abbr +"']"), val='';
	if (oNode)
	{
		if (prop=="text")
			val = oNode.text;
		else
			val = oNode.getAttribute(prop);
	}
	return val;
}

function BuildInput(type, name, value, size, maxLength, focusEvent, blurEvent, keydownEvent, mousedownEvent, className, accessKey, tabIndex)
{
	var inpTag = "<input type=\""+ type +"\"";
	//inpTag += (name) 			? (" name=\""+ name +"\" ") : "";
	inpTag += (name) 			? (" id=\""+ name +"\" ") : "";
	inpTag += (value) 			? (" value=\""+ value +"\"") : "";
	inpTag += (size) 			? (" size=\""+ size +"\"") : "";
	inpTag += (maxLength)		? (" maxlength=\""+ maxLength +"\"") : "";
	inpTag += (focusEvent) 		? (" onfocus=\""+ focusEvent +"\"") : "";
	inpTag += (blurEvent)		? (" onblur=\""+ blurEvent +"\"") : "";
	inpTag += (keydownEvent)	? (" onkeydown=\""+ keydownEvent +"\"") : "";
	inpTag += (mousedownEvent)	? (" onmousedown=\""+ mousedownEvent +"\"") : "";
	inpTag += (className) 		? (" class=\""+ className +"\"") : "";
	inpTag += (accessKey) 		? (" ACCESSKEY=\""+ accessKey +"\"") : "";
	inpTag += (tabIndex) 		? (" TABINDEX=\""+ tabIndex +"\"") : "";
	inpTag += " TABINDEX=\"0\" />";
	return inpTag;
}

function BuildBasicInput(type, name, size, maxLength, className, bIsAccount)
{
	var inpTag = "<input type=\""+ type +"\"";
	//inpTag += (name) 		? (" name=\""+ name +"\"") : "";
	inpTag += (name) 		? (" id=\""+ name +"\"") : "";
	inpTag += (size) 		? (" size=\""+ size +"\"") : "";
	inpTag += (maxLength)	? (" maxlength=\""+ maxLength +"\"") : "";
	inpTag += (className) 	? (" class=\""+ className +"\"") : "";
	//inpTag += (bIsAccount) 	? " disabled" : "";
	inpTag += " TABINDEX=\"0\" />";
	return inpTag;
}

function BuildPhoneInput(name, xmlPropName)
{
	return BuildXSLInput("text", name, xmlPropName, "15", INPUT_LIMIT_64, true);
}

function BuildXSLInput(type, name, value, size, maxLength, b_FORMAT_PHONE)
{
	var x = "<xsl:element name=\"input\">";
	if (type)
		x+= "<xsl:attribute name=\"type\">"+ type +"</xsl:attribute>";
	if (name)
		x+= "<xsl:attribute name=\"id\">"+ name +"</xsl:attribute>";
	if (size)
		x+= "<xsl:attribute name=\"size\">"+ size +"</xsl:attribute>";
	if (value)
	{
		var value_string = (b_FORMAT_PHONE) ? ("<xsl:eval>removeNodePrefix(this, '"+ value +"')</xsl:eval>") : ("<xsl:value-of select=\""+ value +"\" />");
		x+= "<xsl:attribute name=\"value\">"+ value_string +"</xsl:attribute>";
		x+= "<xsl:attribute name=\"defaultValue\">"+ value_string +"</xsl:attribute>"; //<xsl:value-of select=\""+ value +"\" />
	}
	if (maxLength)
		x+= "<xsl:attribute name=\"maxlength\">"+ maxLength +"</xsl:attribute>";
	if (type != "hidden")
	{
		x+= "<xsl:attribute name=\"TABINDEX\">0</xsl:attribute>";
		x+= "<xsl:attribute name=\"class\">edit_form_text</xsl:attribute>";
	}
	x+= "</xsl:element>";
	return x;
}

function BuildXSLTextarea(id, value, nCols, nRows, nMaxlength)
{
	var x = "<xsl:element name=\"textarea\">";
	if (nCols)
		x+=	"<xsl:attribute name=\"cols\">"+ nCols +"</xsl:attribute>";
	if (nRows)
		x+=	"<xsl:attribute name=\"rows\">"+ nRows +"</xsl:attribute>";
	x+=	"<xsl:attribute name=\"onchange\">TrimTextArea(this)</xsl:attribute>";
	x+=	"<xsl:attribute name=\"id\">"+ id +"</xsl:attribute>";
	x+=	"<xsl:attribute name=\"class\">edit_form_text</xsl:attribute>";
	x+=	"<xsl:attribute name=\"defaultValue\">";
	if (value)
		x+=		"<xsl:value-of select=\""+ value +"\" />";
	x+=		"</xsl:attribute>";
	x+=		"<xsl:attribute name=\"maxlength\">"+ ((nMaxlength)?nMaxlength:"<xsl:value-of select=\"@length\" />") +"</xsl:attribute>";
	x+=		"<xsl:value-of select=\""+ value +"\" /></xsl:element>";
	return x;
}

function BuildHTMLCheckBox(id, value, onclickEvent, bIsChecked, bAddDblClick)
{
	var boxTag = "<input type=\"checkbox\"";
	boxTag += (id) 				? (" id=\""+ id +"\"") : "";
	boxTag += (value) 			? (" value=\""+ value +"\"") : "";
	boxTag += (onclickEvent) 	? (" onclick=\""+ onclickEvent +"\"") : "";
	boxTag += (bAddDblClick) 	? (" ondblclick=\""+ onclickEvent +"\"") : "";
	if (bIsChecked == "disabled")
		boxTag += " disabled";
	else
		boxTag += (bIsChecked) 	? (" checked") : "";
	boxTag += " TABINDEX=\"0\" />";
	return boxTag;
}

function BuildCheckBox(id, value, onclickEvent, bIsChecked, bAddDblClick)
{
	var boxTag = "<input type=\"checkbox\"";
	boxTag += (id) 				? (" id=\""+ id +"\"") : "";
	boxTag += (value) 			? (" value=\""+ value +"\"") : "";
	boxTag += (onclickEvent) 	? (" onclick=\""+ onclickEvent +"\"") : "";
	boxTag += (bAddDblClick) 	? (" ondblclick=\""+ onclickEvent +"\"") : "";
	boxTag += " TABINDEX=\"0\" style=\"border:none\"/>";
	return boxTag;
}

function BuildRadioInput(name, value, clickEvent, flag, tabIndex)
{
	var radTag = "<input type=\"radio\"";
	radTag += (name) 	? (" name=\""+ name +"\"") : "";
	radTag += (value) 	? (" value=\""+ value +"\"") : "";
	radTag += (clickEvent)? (" onclick=\""+ clickEvent +"\"") : "";
	//radTag += (tabIndex) ? (" TABINDEX=\""+ tabIndex +"\"") : "";
	//radTag += (flag) 	? (" "+ flag) : "";
	radTag += " TABINDEX=\"0\" />";
	return radTag;
}

function BuildXSLEmailEdit(type)
{
	var x="", obj_id = type+"Emails";
	
	x += "<div><span>";
	x+= "<select id=\""+ obj_id +"\" size=\"4\" cols=\"60\" style=\"width:200px\" multiple=\"true\">";
	x+= 		"<xsl:attribute name=\"origLength\"><xsl:eval>countEmails(this)</xsl:eval></xsl:attribute>";
	if (type=='merge')
	{
		x+= "<xsl:attribute name=\"class\">edit_form_text</xsl:attribute>";
		x+= "<xsl:for-each select=\"context(0)/LOCAL/CONTACT\">";
	}

	x+= "<xsl:for-each select=\"Emails/LIST/*[STR/String != '']\">";
	x+= 	"<xsl:element name=\"option\">";
	x+= 		"<xsl:attribute name=\"defaultValue\"><xsl:value-of select=\"STR/String\" /></xsl:attribute>";
	x+= 		"<xsl:attribute name=\"value\"><xsl:value-of select=\"STR/String\" /></xsl:attribute>";
	x+= 		"<xsl:attribute name=\"origIndex\"><xsl:eval>formatOptionIndex(absoluteChildNumber(this), 3)</xsl:eval></xsl:attribute>";
	x+= 		"<xsl:value-of select=\"STR/String\" />";
	x+=			"<xsl:if test=\".[STR/String = ancestor(LIST)/*/STR/String]\"> [Primary]</xsl:if>";
	x+= 	"</xsl:element>";
	x+= "</xsl:for-each>";
	if (type=='merge')
		x+= "</xsl:for-each>";
		
	x+= "</select></span></div>";
	x+= "<div>"; 
	x+= 	MakeFormButton("iAdd", text('BUTN/ADD'), "AddEmail(\""+ type +"\")", "", "A");
	x+= 	MakeFormButton("iEdit", text('BUTN/EDIT'), "EditEmail(\""+ type +"\")", "", "E");
	x+= 	MakeFormButton("iClose", text('BUTN/DEL'), "DeleteEmail(\""+ type +"\")", "", "D");
	if (type == 'edit')
		x+= MakeFormButton("iPri", text('BUTN/PRI'), "SetPrimaryEmail()");
	x+= "</div>";
	return x;
}

function ExtendHTMLTag(tagHTML, delNameValuePairs)
{
	var dPairs 	= ParseMultiValueList(delNameValuePairs);
	var temp 	= tagHTML.substring(0, tagHTML.length-1);
	for (var i=0; i < dPairs.length; i++)
	{
		if (dPairs[i][0] != "" && dPairs[i][1] != "")
			temp += " "+ dPairs[i][0] +"='" +dPairs[i][1]+ "'";
	}
	return temp +">";
}

function MakeLetterFilterTabs(type)
{
	var x = "<span style='width:100%;overflow:hidden;";
	if (type != "GPAB")
		x+= "margin-left:5%;margin-right:0%;";
	x+= "' id='tabs'>";
	var nTabs = (type != "DSRS") ? oTabs.childNodes.length : ((nNumberOfPages > 1)?(nNumberOfPages+2):1);
	var width = (parseInt((100/nTabs)*10-1)/10);
	if (type != "DSRS")
	{
		var child = oTabs.firstChild;
		while (child)
		{
			x+= BuildLetterTab(type, child, width);
			child = child.nextSibling;
		}
	}
	else
	{
		if (nNumberOfPages > 1)
			x+= BuildLetterTab("-", type, "<<", width);
		for (var i=1; i < nNumberOfPages+1; i++)
			x+= BuildLetterTab(i, type, i, width);
		if (nNumberOfPages > 1)
			x+= BuildLetterTab("+", type, ">>", width);
	}
	return x+"</span>";
}

function BuildLetterTab(type, child, width)
{
	var num = child.getAttribute("index");
	var sDisplay = child.getAttribute("display");
	var sColors = 	(type!="GPAB") ? "HORZ_TAB_COLORS" : "VERT_TAB_COLORS";
	var sClass = 	(type!="GPAB") ? "letter_tab_horz" : "letter_tab_vert";
	var x = "<div class='"+ sClass +"' ";
	x+= "index='"+ num +"' ";
	x+= "type='"+ type +"' ";
	x+= "style='overflow:hidden;"
	if (type=="GPAB"){
		x+= "font-weight:bold;font-size:9px;height:19px;";
//		x+= "font-weight:bold;font-size:9px;height:19px;background-image:url(img/bgLetterTabVert.gif);background-position:bottom right;background-repeat:no-repeat;";
		x+= "background-color:"+ eval(sColors+"_DOWN")[0]+ ";";
		x+= "background-image:"+ eval(sColors+"_DOWN")[2]+ ";";
    }
	else
	{
		x+= "width:"+ width +"%;display:inline;";
		if (child.nextSibling){
			x+= "border-right:1px solid "+ eval(sColors+"_ACTIVE")[0]+ ";";
			x+= "background-color:"+ eval(sColors+"_DOWN")[0]+ ";";
			x+= "background-image:"+ eval(sColors+"_DOWN")[2]+ ";";
		}
	}
	x+= "' objtype='lightObj' ";
	x+= "onmouseover='LightObj(this, 1)' ";
	x+= "onmouseout='LightObj(this, 0)' ";
	x+= "onmousedown='LightObj(this, 2)' ";
	x+= "onmouseup='LightObj(this, 1)' ";
	x+= "onclick='FilterTableByLetter(this);return false' ";
	x+= "ondblclick='FilterTableByLetter(this);return false' ";
	x+= "colors='"+ sColors +"' ";
	x+= ">"+ sDisplay + "</div>";
	return x;
}

function FilterTableByLetter(oSpan)
{
	var num = oSpan.index;
	var type = oSpan.type;
	var oTbl = table[type];
	// set the reference to the now previous tab
	var oCurStyle = oTbl.tabs[oTbl.curDisplayIndex].style;
	oCurStyle.backgroundColor = '';
	oCurStyle.color = '';
	oCurStyle.backgroundImage = HORZ_TAB_COLORS_DOWN[2];	//non-selected state
		//reset the properties of the previous highlighted button

	if (type != 'DSRS')
		oTbl.curDisplayIndex = parseFloat(num);
	else
	{
		if (isNaN(num))
		{
			if (oTbl.curDisplayIndex > 1 && num == '-')
				oTbl.curDisplayIndex--;
			else if (oTbl.curDisplayIndex < nNumberOfPages && num == '+')
				oTbl.curDisplayIndex++;
		}
		else
			oTbl.curDisplayIndex = parseFloat(num);
		table['DSRS'].refresh();
		return;
	}	
	SaveDisplayPreference('TAB', type, oTbl.curDisplayIndex);
	oTbl.refresh();
}

function HighlightCurrentLetterTab(type)
{
	// set the reference to the active tab
	var oTable = table[type];
	var aCUR_TAB_COLOR_ARRAY = (type!='GPAB') ? HORZ_TAB_COLORS_ACTIVE : VERT_TAB_COLORS_ACTIVE;
	if (oTable.tabs && oTable.tabs.length)
	{
		if (!oTable.tabs[oTable.curDisplayIndex])
			oTable.curDisplayIndex=oTable.tabs.length-1;
		oCurStyle = oTable.tabs[oTable.curDisplayIndex].style;
		oCurStyle.backgroundColor = aCUR_TAB_COLOR_ARRAY[0];
		oCurStyle.color = aCUR_TAB_COLOR_ARRAY[1];
		oCurStyle.backgroundImage = aCUR_TAB_COLOR_ARRAY[2];
	}
}

function BuildXMLFilterForTable(type, index, prop_name, prop_val)
{
	var cur_sort = table[type].curName;
	var root_path, xsl_filter = "[{0}]", tab_filter="", inserts = new Array;
	switch(type)
	{	
		default:
		root_path = "R/AB/CONTACT";
		break
		
	}

	if (index == 0)
	{
		tab_filter = "({0} $lt$ '{1}' or {0} = '') or ({0} $gt$ '{2}')";
		inserts[0] = cur_sort;
		inserts[1] = oTabs.selectSingleNode("TAB[@index='1']").getAttribute("beg");
		inserts[2] = BuildTerminalString(oTabs.selectSingleNode("TAB[@index='9']").getAttribute("end"))
		tab_filter = InsertMultiple(inserts, tab_filter);
	}
/*	else if (index == 10)
	{
		tab_filter = "({0} $gt$ '{1}')";
		inserts[0] = cur_sort;
		inserts[1] = BuildTerminalString(oTabs.selectSingleNode("TAB[@index='9']").getAttribute("end"))
		tab_filter = InsertMultiple(inserts, tab_filter);
	}*/
	else if (index < 10)
	{
		var oTab = oTabs.selectSingleNode("TAB[@index='"+ index +"']");
		tab_filter = "({0} $gt$ '{1}' and {0} $lt$ '{2}')";
		inserts[0] = cur_sort;
		inserts[1] = oTab.getAttribute("beg");
		inserts[2] = ((oTab.getAttribute('index')!='9') ? oTab.nextSibling.getAttribute("beg") : BuildTerminalString(oTabs.selectSingleNode("TAB[@index='9']").getAttribute("end")));
		if (cur_sort == 'FirstName' || cur_sort == 'LastName')
		{
			tab_filter = "("+ tab_filter +" or ({0}='' and {3} $gt$ '{1}' and {3} $lt$ '{2}'))";
			inserts[3] = 'Company';
		}
		tab_filter = InsertMultiple(inserts, tab_filter);
	}
	
	if (prop_name && prop_val)
	{
		var property_filter = "({0} = '{1}')";
		property_filter = InsertMultiple(new Array(prop_name, prop_val.replace('&', '&#38;')), property_filter);
		if (tab_filter)
			tab_filter += " and " + property_filter;
		else
			tab_filter = property_filter;
	}
	var sub_path = (tab_filter) ? Insert(tab_filter, xsl_filter) : "";
	return root_path + sub_path;
}

function BuildTerminalString(sChar)
{
	var x="";
	while (x.length<10)
		x+=sChar;
	return x;
}

function MakeTableFilterSelect(type, obj)
{
	var x="", output;
	x+= "<?xml version=\"1.0\"?><xsl:stylesheet xmlns:xsl=\"http://www.w3.org/TR/WD-xsl\">";
	x+= "<xsl:template match=\"/\">";
	x+= 	"<xsl:apply-templates select=\"GROUPS\" />";
	x+= "</xsl:template>";
	
	x+= "<xsl:template match=\"GROUPS\">";
	x+= 	text('AB/FILTER_PREFIX');
	x+= 	"<select id=\"table_filter_select_"+type+"\" onchange=\"UpdateTableFilter(this)\" style=\"margin:0px 5px;font-size:10px;\">";//font-family:courier newcolor:#666;
	x+= 		"<xsl:attribute name=\"type\">"+type+"</xsl:attribute>";
	x+=			"<option>"+text('AB/FILTER_ALL')+"</option>";
	x+= 		"<xsl:for-each select=\"GROUP\">";
	x+= 			"<option><xsl:value-of select=\"Name\" /></option>";
	x+= 		"</xsl:for-each>";
	x+= 	"</select>";
	x+= 	text('AB/FILTER_SUFFIX');
	x+= "</xsl:template>";
	
	x+= "</xsl:stylesheet>";

	xTmp.loadXML(x);
	CheckError(xTmp);
	output = oGroupsNode.transformNode(xTmp);
	if (obj)
		obj.innerHTML = output;
	else
		return "<span id=\"ab_filter_select\" class=\"ab_filter_select\">"+output+"</span>";
}

function UpdateTableFilter(oSelect)
{
	var type = oSelect.type;
	var tbl = table[type];
	if (oSelect.selectedIndex && oSelect.selectedIndex>0)
	{
		tbl.curFilterProperty = 'Groups/LIST//String';
		tbl.curFilterValue = oSelect.options[oSelect.selectedIndex].text;
	}
	else
	{
		tbl.curFilterProperty = '';
		tbl.curFilterValue = '';
	}

	SaveDisplayPreference('SELECT', type, DelimitList(new Array(tbl.curFilterProperty, tbl.curFilterValue)))
	
	table[type].refresh();
}

function MakeFormButton(sImg, sButtonLabel, sCellMethod, sCustStyleProp, sAccessKey)
{
	return MakeButton(sImg, sButtonLabel, sCellMethod, sCustStyleProp, sAccessKey, "button_cell_form");
}

function MakeFeatureButton(sImg, sButtonLabel, sCellMethod, sCustStyleProp, sAccessKey)
{
	return MakeButton(sImg, sButtonLabel, sCellMethod, sCustStyleProp, sAccessKey, "button_cell_feature");
}

function MakeButton(sImg, sButtonLabel, sCellMethod, sCustStyleProp, sAccessKey, sAltClassName)
{
	var sClass = (sAltClassName) ? sAltClassName : "button_cell";
	var sColor;
	switch (sAltClassName)
	{
		case "button_cell_form": 		sColor="BUTTON_FORM_COLORS"; break;
		case "button_cell_feature": 	sColor="BUTTON_FEATURE_COLORS"; break;
		default:						sColor="BUTTON_COLORS";
	}
	var x = "<span class='"+ sClass +"' ";
	x+= "objtype='lightObj' ";
	x+= "onmouseover='LightObj(this, 1)' ";
	x+= "onmousedown='LightObj(this, 2)' ";
	x+= "onmouseup='LightObj(this, 1)' ";
	x+= "onmouseout='LightObj(this, 0)' ";
	x+= "onfocus='LightObj(this, 1);' "; //CaptureEvent(this,\"onkeydown\",HandleKeydown)
	x+= "onblur='LightObj(this, 0);' "; //ReleaseEvent(this,\"onkeydown\")
	x+= "onclick='"+ sCellMethod +";return false' ";
	x+= "ondblclick='"+ sCellMethod +";return false' ";
	x+= "onkeydown='HandleKeydown(\"button\")' ";
	x+= "colors='"+ sColor +"' ";
	if (sCustStyleProp)
		x+= "style='"+ sCustStyleProp +"' ";
	if (sAccessKey)
		x+= "ACCESSKEY='"+ sAccessKey +"' ";
	x+= " TABINDEX='0'>";

	if (sImg)
	{
		sImg += (sImg.indexOf('.gif')>0) ? '' : '.gif';  
		x+= "<img src='img/"+ sImg +"' class='button_cell_img' onerror='ReloadImage(this)' errs='0'/>";
	}
	
	return x+=  FormatAccessKey(sButtonLabel) +"</span>";
}

function ReloadImage(oImg)
{
	var nErrs = parseInt(oImg.errs);
	if (nErrs>0)
		return;

	var source = oImg.src;
	oImg.src = source;
	oImg.errs = nErrs+1;
}

//Horizontal Letter Tabs: parameters are: background color, text color, background image
var HORZ_TAB_COLORS_ACTIVE 	= new Array('#EFEFF7', '#069', 'url(img/b_button_5x20_selected.gif)');
var HORZ_TAB_COLORS_OVER 	= new Array('#EFEFF7', '#88F', 'url(img/b_button_5x20.gif)');
var HORZ_TAB_COLORS_DOWN 	= new Array('#EFEFF7', '#8AF', 'url(img/b_button_5x20.gif)');

//Vertical Letter Tabs: parameters are: background color, text color, background image
var VERT_TAB_COLORS_ACTIVE 	= new Array('#EFEFF7', '#069', 'url(img/b_button_5x20_selected.gif)');
var VERT_TAB_COLORS_OVER 	= new Array('#EFEFF7', '#88F', 'url(img/b_button_5x20.gif)');
var VERT_TAB_COLORS_DOWN 	= new Array('#EFEFF7', '#8AF', 'url(img/b_button_5x20.gif)');

//Content Function Buttons
var BUTTON_COLORS_OVER 	= new Array('#c63', '#369', '#369'); 
var BUTTON_COLORS_DOWN 	= new Array('#c63', '#369', '#369');	

//Left Panel Feature Buttons
var BUTTON_FEATURE_COLORS_OVER = new Array('#c63', '#369', '#369');	
var BUTTON_FEATURE_COLORS_DOWN = new Array('#c63', '#369', '#369');

var BUTTON_FORM_COLORS_OVER = new Array('#fc0', '#000');
var BUTTON_FORM_COLORS_DOWN = new Array('#c36', '#fff');

function LightObj(obj, num)
{
	while (!obj.objtype || (obj.objtype && obj.objtype!='lightObj'))
		obj = obj.parentElement;
		
	var b_LETTER_TAB = (obj.className.indexOf('letter_tab')==0)

	if ( (b_LETTER_TAB && obj.style.backgroundColor == eval(obj.colors+'_ACTIVE')[0]) || obj.className=='button_disabled') 
		return false;

	var oCurStyle = obj.style;
	switch (num)
	{
		case 0:
			oCurStyle.backgroundColor = '';
			if (!b_LETTER_TAB)
				oCurStyle.borderColor='';
			oCurStyle.color = '';
			return;
			
		case 1:
			// when a mousedown event occurs, a focus event immediately follows, 
			// overwriting the style for the mousedown event - this prevents it
			if (window.event.type == 'focus' && oCurStyle.backgroundColor == BUTTON_COLORS_DOWN[0])
				return;
			var oColors = eval(obj.colors+'_OVER');
			oCurStyle.backgroundColor = oColors[0];
			oCurStyle.color = oColors[1];
			if (!b_LETTER_TAB && oColors[2])
				oCurStyle.borderColor = oColors[2];
			return;
			
		case 2:
			var oColors = eval(obj.colors+'_DOWN');
			oCurStyle.backgroundColor = oColors[0];
			oCurStyle.color = oColors[1];
			if (!b_LETTER_TAB && oColors[2])
				oCurStyle.borderColor = oColors[2];
			return;
	}
}

function ShowHelp(XPath, msg, xShift, yShift)
{
	var oEvt = window.event;
	var oDiv = getObj('Help');
	oDiv.innerText = (!msg) ? oText.selectSingleNode('LABELS/HELP/'+XPath).text : msg;
	
	Show('Help');
	PositionDivInViewableArea(oDiv, null, xShift, yShift);
	MakeDivShadow('Help', '#000', DIV_SHADOW_WIDTH, true);
}


function HideHelp()
{
	var oDiv = getObj('Help');
	var oToEl = window.event.toElement;
	if (oDiv == oToEl)
		return false;
	oDiv.style.posTop = 0;
	oDiv.style.posLeft = 0;
	Hide('Help');
	HideShadows();
}


function GetClassRoot(name)
{
	var sLastTwoChars = name.substring(name.length-2, name.length);
	return (sLastTwoChars == "On" || sLastTwoChars == "Dn") ? name.substring(0,name.length-2) : name;
}
/*
function GetObjById(sElName)
{
	return document.getElementById(sElName);
}
*/
function CaptureEvent(obj, event, handler)
{
	obj[event] = eval(handler);
}

function ReleaseEvent(obj, event)
{
	obj[event] = null;
}

function ToggleLink(oDiv, sID)
{
	var sCurLink;
	var sTempDiv;
	//Toggle Tab Styles
	// The main DIV that holds the ED DIV would be either CT(contacts) or PI(profile)
	//When the sCurrDiv is ED, the main tab is the one which has to toggle.
	//sPreviousDiv is saved before we show the ED DIV. It should contain the mainmenu item that has to be toggled.
	//so we temporarily save the sCurDiv contents which is "ED" into a temp DIV and reassign it back to sCUrDiv after we toggle the main DIV for example CT or PI
	if (sCurDiv=='ED'){ sTempDiv = sCurDiv; sCurDiv = sPreviousDiv;}
	if (getObj('vl_'+sCurDiv))											
	{
		getObj('vl_' + sCurDiv).className = "view_link_tabdn_center";
		getObj('vl_tabup_left_' + sCurDiv).className = "view_link_tabdn_left";
		getObj('vl_tabup_right_' + sCurDiv).className = "view_link_tabdn_right";

		getObj('vl_' + sID).className = "view_link_tabup_center";
		getObj('vl_tabup_left_' + sID).className = "view_link_tabup_left";
		getObj('vl_tabup_right_' + sID).className = "view_link_tabup_right";
	} 
	//if we modified the scurdiv in the previous steps, set it back to what ever it was. 
	if (sTempDiv == 'ED') sCurDiv = sTempDiv;
	if (sCurDiv=='ED')
	{
		sCurLink = getObj('editObject').value;
		if(sCurLink == 'AB')sCurLink = 'CT';
		getObj('vl_'+sCurLink).firstChild.style.backgroundImage = '';
		getObj('vl_'+sCurLink).firstChild.style.backgroundColor = '';
		getObj('vl_'+sCurLink).firstChild.style.color = '';
		//Hide('ED');
	}
	if (sID=='MS' && GetImgSrc(getObj('act_notification'))=='iMessage')
		MessageNotification(false);
	if (oDiv)
	{
		//oDiv.firstChild.style.backgroundImage = 'url(img/bgViewLinkActive.gif)';
		//oDiv.childNodes(0).style.color = '#036';
	}
	// if another link is clicked while the 'ED' div is displayed - reset the background color for the link which the edit has initiated
	if (oXMLFormObj || (sPreviousDiv=='PI' && sCurDiv=='ED'))
	{
		//getObj('vl_'+getObj('editObject').value).firstChild.style.backgroundColor = '';
		CancelEdit(1);
	}
//	if(sPreviousDiv=='PI' && sCurDiv=='ED')
//	{
//		CancelEdit(1);
//	}
	Hide(sCurDiv);
	Show(sID);
	sCurDiv = sID;
} 

function TabNextView(b_MOVE_DOWN)
{
	var oMenu = getObj('view_link_list');
	var child = oMenu.firstChild;
	while (child && (child.tagName=='IMG' || (child.tagName=='DIV' && child.firstChild.style.backgroundImage!='url(img/bgViewLinkActive.gif)')))
		child=child.nextSibling;
	if (child)
	{
		var oNewLink = (b_MOVE_DOWN) ? child.nextSibling : child.previousSibling;
		while (oNewLink && oNewLink.tagName != 'DIV' && oNewLink.className!='view_link')
			oNewLink = (b_MOVE_DOWN) ? oNewLink.nextSibling : oNewLink.previousSibling;
		if (!oNewLink)
			oNewLink = (b_MOVE_DOWN) ? oMenu.firstChild : oMenu.lastChild.previousSibling;
		ToggleLink(oNewLink, oNewLink.id.replace('vl_',''));
	}
}

// method for tray client to call and change current view
function ChangeView(str, num)
{
   // EK: Always SetFocus to TypeAhead field, this will force the Web Client to come to the foreground 100%
   SetFocus('cc_type_ahead_search');
	var oLink = getObj('vl_'+str);
	if (oLink)
		oLink.click();

	if (str=='PI' && num)
	{
		tab['PI'].head.children[4].click();	
		Hide('dv_feature_codes');
		var oRow 	= getObj('rowDV'+num);
		var oIcon 	= oRow.lastChild.lastChild.firstChild;
		oIcon.src 	=  'img/iFCArrowDn.gif';
		ToggleDeviceFeatureCodes(oIcon, oRow);
	}
		
	if (b_toolbar_mode)
		SetToolbarDisplay('');
}

function IsEven(num)
{
	return ((num%2)==0);
}

function IsNum(sInput)
{
	if (isNaN(sInput) || sInput == null)
		return false;
	return true;
}

// ****************************************************
// ***************  OBJECT METHODS  *******************
// ****************************************************

function Show(sDiv)
{
	var obj = getObj(sDiv);
	if (obj)
		obj.style.display = "";
}

function Hide(sDiv)
{
	var obj = getObj(sDiv);
	if (obj)
		obj.style.display = "none";
}

function Move(sDiv, xNum, yNum)
{
	var obj = getObj(sDiv);
	if (obj)
	{
		if (xNum != null)
			obj.style.posLeft = obj.style.posLeft + xNum;
		if (yNum != null)
			obj.style.posTop = obj.style.posTop + yNum;
	}
}

function ToggleDiv(sID, oCheckbox)
{
	var oDiv = getObj(sID), display;
	if (oCheckbox)
		display = (oCheckbox.checked);
	else
		display = (oDiv.style.display) ? true : false;
	if (oDiv)
		(display) ? Show(sID) :  Hide(sID);
}

function InsertDiv(target, id)
{
    if(getObj(target) == null)
    {
        setTimeout("InsertDiv('CT', 'ABSY')", 1000);
        return;
    }
	var oParent = getObj(target);
	var oDiv = document.createElement("DIV");
	oDiv.setAttribute('id', id);
	// return the object in the document before setting the style property
	oDiv = oParent.insertBefore(oDiv, oParent.children['buttons']);
	oDiv.style.display ='none';
}

function WaitCursor()
{
	document.body.style.cursor="wait";
}

function AutoCursor()
{
	document.body.style.cursor="auto";
}

function getObj(sId)
{
	var obj;
	if (bIsIE5 || bIsIE55)
		obj = document.getElementById(sId);
	return obj;
}

function getObjects(sName)
{
	var objs;
	if (bIsIE5 || bIsIE55)
		objs = document.getElementsByName(sName);
	return objs;
}

function FindExistingNodeValue(oNode, path, value)
{
	var child = oNode.firstChild;
	while (child)
	{
		if (CompareNoCase(child.selectSingleNode(path).text, value))
			return child;
		child = child.nextSibling;
	}
	return false;
}

function GetSelectedRadio(sName)
{
	var aRadios = getObjects(sName); i=0;
	while (aRadios[i] && !aRadios[i].checked)
		i++;
	return (aRadios[i]) ? aRadios[i] : null;
}

function GetRadiosIndex(sName, sValue)
{
	var aRadios = getObjects(sName); i=0;
	while (aRadios[i] && (aRadios[i].value != sValue))
		i++;
	return (aRadios[i]) ? i : null;
}

function GetMatchingOptionIndex(oSelect, sMatch, type, sCustomProperty)
{
	// type 0 indicates to match on value, type 1 indicates to match text
	var opt = oSelect.options.firstChild;
	while (opt)
	{
		switch (type)
		{
			// value
			case 0:
				if (opt.value == sMatch)
					return opt.index;
				break;
			// text
			case 1:
				if (opt.text == sMatch)
					return opt.index;
				break;
			// custom
			case 2:
				if (opt[sCustomProperty] == sMatch)
					return opt.index;
				break;
		}
		opt = opt.nextSibling;
	}
	return 0;
}

function SetSelectIndex(oSelect, sMatch, type, sCustomProperty)
{
	oSelect.selectedIndex = GetMatchingOptionIndex(oSelect, sMatch, type, sCustomProperty);
}

function RemoveArrayElement(oArray, sIdentifier, oMultiValOrDelIndexOrPropName,  bIsDelimited)
{
	if (oArray.length)
	{
		var nIndex = GetObjectIndex(oArray, sIdentifier, oMultiValOrDelIndexOrPropName, bIsDelimited);
		if (IsNum(nIndex))
		{
			oArray = ShiftArray(nIndex, oArray);
			oArray.length--;
		}
	}
	return oArray;
}

function ShiftArray(nIndex, oArray)
{
	var i=nIndex;
	while (oArray[i])
	{
		if (oArray[i+1])
			oArray[i] = oArray[i+1];
		i++;
	}
	return oArray;
}

function GetObjectIndex(oArray, strObjectIdentifier, oIndexOrObjPropName, bIsDelimited)
{
	var temp = new Array, i=0;
	while (oArray[i])
	{
		temp = (bIsDelimited) ? ParseDelimitedList(oArray[i]) : oArray[i];
		var obj = (oIndexOrObjPropName != null) ? temp[oIndexOrObjPropName] : temp;
		if (obj == strObjectIdentifier)
			return i;
		i++;
	}
	return null;
}

// ****************************************************
// *************  String Manipulation  ****************
// ****************************************************

function RemoveNodePrefix(str)
{
	var re = new RegExp('[0-9]{0,2}:');
	return str.replace(re,'');
}

function PrependString(sOrig, sMod, nLength)
{
	while (!sOrig || sOrig.length < nLength)
	{
		sOrig = sMod + sOrig;
	}
	return sOrig;
}

function MergeString(sString, sFrag1, sFrag2, bPreserveCase)
{
	var sString1ToAdd = (bPreserveCase) ? sFrag1 : ToUpper(sFrag1);
	while (sString.indexOf("{0}") > -1)
		sString = sString.replace("{0}", sString1ToAdd);
	if (sFrag2)
	{
		var sString2ToAdd = (bPreserveCase) ? sFrag2 : ToUpper(sFrag2);
		while (sString.indexOf("{1}") > -1)
			sString = sString.replace("{1}", sString2ToAdd);
	}
	return sString;
}

var labels_spec_char = 'º';

function AddNestedBoldTags(string)
{
	var re = new RegExp('('+ labels_spec_char +')([^'+ labels_spec_char +']*)('+ labels_spec_char +')', 'g');
	return string.replace(re, ("<b>$2</b>"));
}

function AddLeadingZeros(num, len)
{
	num+='';
	while (num.length<len)
		num = '0'+num;
	return num;
}

function FormatAccessKey(string)
{
	var re = new RegExp(labels_spec_char +'([\\w])' +labels_spec_char);
	return string.replace(re, '<u>$1</u>');
}

/*function FormatMultilineAlert(sMsg)
{
	var re = new RegExp('\¶', 'g');
	return sMsg.replace(re, "\n");
}*/

function CompareNoCase(str1, str2)
{
	return (ToLower(str1+"") == ToLower(str2+""));
}

function TrimLength(string, length, bPreserveString)
{
	var nEndPoint = (bPreserveString) ? length : length-3;
	if (!string)
		return "";
	if (length && string.length > length)
		return string.substring(0, nEndPoint) + ((!bPreserveString)?"...":"");
	else
		return string;
}

function TrimTextArea(oTextArea)
{
	var str = oTextArea.value;
	oTextArea.value = str.substring(0, parseInt(INPUT_LIMIT_4096));
}

function ToLower(str)
{
	return str.toLowerCase();
}

function ToUpper(str)
{
	return str.toUpperCase();
}

// ****************************************************
// *******************  VALIDATION  *******************
// ****************************************************

function IgnoreUnsavedEdit(Type)
{
	var result = "true";
	var aChangedElements = GetChangedFormElementNames('edit');
	var bIgnore;
	if(sPreviousDiv=='CT')
	{
		if (!oXMLFormObj)
			return false;
		if (Type == 1 && IsAutoSaveEnabled())
			return result;
		if (Type == 2 && IsAutoSaveEnabled())  //  Logoff Button, save and exit
		{
			SaveEdit();
			return false;
		}
		if (IsAutoSaveEnabled())
			return false;
			
		if (Type == 0)  // Cancel Button
			return false;
		
		bIgnore  = (oXMLFormObj && aChangedElements.length) ? ParseDelimitedList(Dialog(text('ERR/AB/NOSAVE'),1))[0] : false;
		if (bIgnore=="true")
		{
		   SaveEdit(); 
		}

		//return bIgnore;
	}
	else if(sPreviousDiv=='PI' && aChangedElements.length > 2 && sCurDiv == 'ED')
	{
		//if (!oXMLFormObj)
			//return false;	
		if (Type == 1 && IsAutoSaveEnabled())
			return result;
			
		if (Type == 2 && IsAutoSaveEnabled())  // Logoff button, save and exit
		{
			SaveEdit();
			return false;
		}			
		if (IsAutoSaveEnabled())
			return false;
			
		if (Type == 0)  // Cancel Button
			return false;			
	
		// The reason we check if aChangedElements.length is greater than 2 is because,
		// for some reason TimeZone and WAPBridgeCallDelay are always comming back as changed. no matter what.
		// To completely fix it we have to change the getchangedFormElementNames() to check against 
		// whats already there in account instead of default values.
		// Also this temporary fix means that if the TimeZone and WAPBridgeCallDelay really change(these should be the only items that change),
		// and then if the user clicks on "cancel" or changes to a different tab, they wont be prompted to save their changes
		// and their changes will be lost by default.
		bIgnore  = (aChangedElements.length > 2) ? ParseDelimitedList(Dialog(text('ERR/AB/NOSAVE'),1))[0] : false;
		//return bIgnore;
		if (bIgnore=="true")
		{
		   SaveEdit();
		}
	}
	
	return false;
}

// ****************************************************
// *****************  Window Methods  *****************
// ****************************************************

var PRODUCT_NAME_AND_VERSION, BY_COMPANY_NAME;

function SetDocumentTitle()
{
	PRODUCT_NAME_AND_VERSION 	= config('PRODUCT_NAME') +'® '+ config('PRODUCT_VERSION');
	BY_COMPANY_NAME 			= ' '+text('GBL/HEAD_BY')+' '+ config('COMPANY_NAME')+'®';
	var str = PRODUCT_NAME_AND_VERSION; //String.fromCharCode(174)
	if (oActNode.selectSingleNode('.//FirstName'))
		str += " - "+ oActNode.selectSingleNode('.//FirstName').text +" "+ oActNode.selectSingleNode('.//LastName').text + " ("+ oActNode.selectSingleNode('.//UniqueID').text +")";
	document.title = str;
}

var bLogOffCalled = false;

var _WINDOW_MENU_BAR		= new Number(0x0001);
var _WINDOW_ADDRESS_BAR		= new Number(0x0002);
var _WINDOW_TOOL_BAR		= new Number(0x0004);
var _WINDOW_STATUS_BAR		= new Number(0x0008);
var _WINDOW_ALWAYS_ON_TOP	= new Number(0x0010);

function CloseOut(bIsLogoff)
{

	if (bLogOffCalled || IgnoreUnsavedEdit(2))
	{
		return false;
	}
		
	if (oFloatWin)
		oFloatWin.close();
		
	if (b_toolbar_mode)
		SetToolbarDisplay('');
	
	bLogOffCalled = true;
	
	CallControlMethod('OnUnload');
	if (bIsLogoff)
	{
		Hide('UI');
		//ResetAutoLogon();
		//setTimeout('document.location.reload()',500);
		BuildDiv('LOGOFF');
		Show("LOGOFF");
	}
}

var bBrowserWindowResizing = false;

function ResizeBrowserWindow()
{
	if (screen.availWidth > 730 && screen.availHeight > 500)
	{
		bBrowserWindowResizing = true;
		ResizeHeightAndWidth();
		bBrowserWindowResizing = false;
	}
}

var nCurHeight, nCurWidth;

function ResizeHeightAndWidth()
{
	nCurHeight = document.body.offsetHeight;
	if (document.body.offsetHeight < 565)
		window.resizeBy(0, 20);
	nCurWidth = document.body.offsetWidth;
	if (document.body.offsetWidth < 750)
		window.resizeBy(20, 0);
	if (nCurHeight == document.body.offsetHeight && nCurWidth == document.body.offsetWidth)
		DoNothing();
	else if (document.body.offsetHeight < 540 || document.body.offsetWidth < 750)
		ResizeHeightAndWidth()
}

function PopulateWindow(objWin, newHTML)
{
	objWin.document.open();
	objWin.document.write(newHTML);
	objWin.document.close();
	objWin.focus();
}

var b_toolbar_mode = 0;

function ToggleToolbarDisplay(oIcon)
{
	var display_prop = (getObj('strip1').style.display == '') ?'none':'';
	SetToolbarDisplay(display_prop);
}

function SetToolbarDisplay(display_prop, called_by_falcon_client)
{
	b_toolbar_mode = (display_prop=='none') ? 1 : 0;
	getObj('strip1').style.display = display_prop;
	getObj('strip4').style.display = (display_prop == '') ?'none':'';
	//getObj('ChromeLogo').style.display = display_prop;
	getObj('strip5').style.display = display_prop;
	getObj('content').style.display = display_prop;	
	SizeToolbarWindow(display_prop);
	/*if (!called_by_falcon_client)
		NotifyResized(GetCurrentDisplayConfig());*/
}

var tempDivBeforeSwitchingToAC;

function ToggleCallControl(display)
{
	var height = document.body.offsetHeight;
	ConfigureCallControlDisplay();
	if (display=="1")
	{
		Show('CC');
	}
	else
	{
		Hide('CC');
		b_CLOSE_CALLLIST_WHEN_EMPTY=0;
	}
	
	NotifyResized(GetCurrentDisplayConfig());
	
	if (getObj('strip1').style.display=='none')
		setTimeout('SetWindowHeightForOpenCallControl('+height+')', 100);
}

function CloseCallControl()
{
	b_CLOSE_CALLLIST_WHEN_EMPTY = 0;
	//var oIcon = getObj('cc_call_control_toggle_icon');
	ToggleCallControl(0);
}

function GetCurrentDisplayConfig()
{
	if (b_toolbar_mode)
		return (getObj('CC').style.display=='none') ? 0 : 1;	
	else
		return 2;
}

function SetToolbarHeightForCallControl(height)
{
	if (getObj('strip1').style.display=='none')
		setTimeout('SetWindowHeightForOpenCallControl('+height+')', 100);
}

function SetWindowHeightForOpenCallControl(start_height)
{
	var scroll_height = document.body.scrollHeight;
	if (start_height < scroll_height)
		window.resizeBy(0, scroll_height - start_height + 5);
	else
		window.resizeBy(0, GetToolbarElementsHeight() - start_height);
}

var CC_DISPLAY_STYLE_STATE;

function ConfigureCallControlDisplay()
{
	var oTAInput = getObj('cc_type_ahead_search');
	var oCLInput = getObj('cc_place_call_number');
	var new_state;
	
	if (IsValid(oTAInput) && oCallListNode.hasChildNodes())
		new_state = 0;
	else if (IsValid(oTAInput))
		new_state = 1;
	else 
		new_state = 2;
				
	if (CC_DISPLAY_STYLE_STATE == new_state)
		return;
		
	SetCallControlDisplay(new_state);
}

// 0 - shared, 1 - typeahead, 2 - call list

function SetCallControlDisplay(new_state)
{
	var oTASpanStyle = getObj('CC').firstChild.style;
	var oCLSpanStyle = getObj('CC').lastChild.style;
	var var_width = '48%';
	switch (new_state)
	{
		case 0:
//			oTASpanStyle.width = var_width;
			oCLSpanStyle.width = '100%';
			oTASpanStyle.display = 'none';
			oCLSpanStyle.display = '';
			break;
			
		case 1:
/*			oTASpanStyle.width = '100%';
			oTASpanStyle.display = '';
			oCLSpanStyle.display = 'none';*/
			break;
			
		case 2:
			oCLSpanStyle.width = '100%';
			oCLSpanStyle.display = '';
			oTASpanStyle.display = 'none';
			break;
	}
	CC_DISPLAY_STYLE_STATE = new_state;
}

// 0 - shared, 1 - typeahead, 2 - call list
function CloseCallControlElement(type)
{
	switch (type)
	{
		case 'CL': SetCallControlDisplay(1); break;
		case 'TA': SetCallControlDisplay(2); break;
	}
}

var orig_body_height=0, browser_menus_height=0;

function SizeToolbarWindow(display_prop, b_user_button_toogle)
{
	var oToolbarToggleIcon = getObj('ToolbarToggleIcon');
	var start_height, resize_value, bt_config = 15;
	// preserve flag is passed when the user toggles display size of the user buttons.
	// the resize of the buttons in toolbar mode sets the orig_body_height to be that
	// of toolbar mode, when toolbar mode is exited, the window won't be the correct height
	if (b_toolbar_mode && b_user_button_toogle)
		var preserve_orig_body_height = orig_body_height;
	
	start_height = document.body.offsetHeight;
	
	if (!b_user_button_toogle)
	{
		// make the call to remove the toolbars first - so the resize works correctly.
		// when the toolbars are removed, the body gets taller to make up the difference
		// this value needs to be included in the resize value to achieve the intended appearance
		if (display_prop=='none')
		{
			bt_config = 0;
			bt_config = (eval(ClientCookie(false, CLIENT_COOKIE_ToolbarOnTop))) ? (bt_config |= _WINDOW_ALWAYS_ON_TOP) : bt_config;
		}
		CallControlMethod('SetWindowConfiguration', bt_config);
	}
	
	browser_menus_height = document.body.offsetHeight - start_height;
	toolbar_adjusted_height = start_height + browser_menus_height;

	if (display_prop == 'none')
	{
		resize_value = GetToolbarElementsHeight();
		var val = (resize_value - toolbar_adjusted_height);
		oToolbarToggleIcon.src = 'img/ChromeToolbarButtonDn.gif';
		document.body.style.marginTop='0px';
		document.body.style.marginBottom='0px';
		window.resizeBy(0, val);
		orig_body_height = start_height;
	}
	else
	{
		resize_value = orig_body_height - toolbar_adjusted_height;
		oToolbarToggleIcon.src = 'img/ChromeToolbarButtonUp.gif';
		document.body.style.marginTop='';
		document.body.style.marginBottom='';
		window.resizeBy(0, resize_value);
	}
	if (b_toolbar_mode && b_user_button_toogle)
		orig_body_height = preserve_orig_body_height;
}

function GetToolbarElementsHeight()
{
	var oCallControl = getObj('CallControl'), oUserButtons = getObj('UB'), oHead = getObj('header'), oStrip = getObj('strip4');
	return (oHead.offsetHeight + oCallControl.offsetHeight + oUserButtons.offsetHeight + oStrip.offsetHeight + 5);
}

function ShowFloater(sTypeName)
{
	var oEl = window.event.srcElement;
	var title, style = 'height:230px;border:1px solid #000;background-color:#ccc;';
	switch (sTypeName)
	{
		case'FeatureCodeFavorites':
		title = text('FLOAT/FAVS');
		style += 'overflow-y:scroll;';
		break;
		
		case'SpeedDial':
		title = text('FLOAT/DIAL');
		style += 'overflow-y:scroll;';
		break;
		
		case'TypeAhead':
		title = 'Search';
		style += 'overflow-y:scroll;';
		break;
		
	}
	oRoot.setAttribute('title', title);
	oRoot.setAttribute('style', style);
	DisplayFloatDiv(oEl, window.event);
	oRoot.removeAttribute('title');
	oRoot.removeAttribute('style');
}

var oFloatWin;

var sFltSrc = "<html><head>";
sFltSrc += "<script>";
//sFltSrc += "document.onclick=HandleClick;";
sFltSrc += "var bIsIE5 = "+bIsIE5+";";
sFltSrc += "var bIsIE55 = "+bIsIE55+";";
sFltSrc += "var global = window.document;";
sFltSrc += "global.aShadows = new Array;";
sFltSrc += "var DIV_SHADOW_WIDTH = 4;";

sFltSrc += getObj.toString();
sFltSrc += Hide.toString();
sFltSrc += Show.toString();
sFltSrc += HideShadows.toString();
sFltSrc += IsNum.toString();
sFltSrc += MakeDivShadow.toString();
sFltSrc += HandleListMenuOut.toString();
sFltSrc += PositionDivInViewableArea.toString();

sFltSrc += "function HandleClick(){self.close()}";
sFltSrc += "function ExecuteFeatureCode(sCodeNum, sNodeId, sExt) {";
sFltSrc += "	opener.ExecuteFeatureCode(sCodeNum, sNodeId, sExt);";
sFltSrc += "}";
sFltSrc += "function PlaceCall(num, id) {";
sFltSrc += "	opener.PlaceCall(num, id);";
sFltSrc += "	Hide('LIST');";
sFltSrc += "	HideShadows();";
sFltSrc += "	HandleClick();";
sFltSrc += "}";
sFltSrc += "function PhoneMenu(unique_id) {";
sFltSrc += "	var html = opener.ViewListMenu('SpeedDial', unique_id);";
sFltSrc += "	var x_pos = event.clientX, y_pos = event.clientY;";
sFltSrc += "	var oList = getObj('LIST');";
sFltSrc += "	oList.innerHTML = html;";
sFltSrc += "	Show('LIST');";
sFltSrc += "	PositionDivInViewableArea(oList);";
sFltSrc += "	MakeDivShadow('LIST', '#000', DIV_SHADOW_WIDTH, true);";
sFltSrc += "}";
sFltSrc += "function HandleRowClick(oRow)";
sFltSrc += "{";
sFltSrc += "	var eSrc = window.event.srcElement;";
sFltSrc += "	if (eSrc.tagName=='IMG' && eSrc.className=='icon_hot')";
sFltSrc += "	{";
sFltSrc += "		switch (opener.GetImgSrc(eSrc))";
sFltSrc += "		{";
sFltSrc += "			case 'icon_contactPerson': PhoneMenu(oRow.UniqueID); break;";
sFltSrc += "		}";
sFltSrc += "	}";
sFltSrc += "}";
sFltSrc += "</script>";
sFltSrc += "<LINK REL='stylesheet' HREF='cStyles.css' type='text/css' ID='GlobalStyles'>";
sFltSrc += "</head>";
sFltSrc += "<body class='FloatBODY'>";
sFltSrc += "{0}";
sFltSrc += "<div id='LIST' style='position:absolute;z-index:20;display:none' onmouseout='HandleListMenuOut();'></div>";
sFltSrc += "</body></html>";

function DisplayFloatDiv(oEl, oEvent)
{
	var oButton = oEl, nX = 0, nY = 0;
	bToolbarMode = (getObj('header').style.display == 'none')
	var nX = oEvent.screenX - 125;
	var nY = oEvent.screenY + 20;
	
	var window_name = 'FloatWin'+oActNode.selectSingleNode('.//UniqueID').text;
	re_strip_inval = new RegExp("[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜƒáíóúñÑß]+", "g");
	window_name = window_name.replace(re_strip_inval, "");

	xTmp.loadXML(GetSectionXSL('Float',1,oSys));
	CheckError(xTmp);
	var output = oSys.transformNode(xTmp);
	if (!oFloatWin || oFloatWin.closed)
		oFloatWin = window.open('', window_name, 'width=300,height=275,top='+ nY +',left='+ nX +',toolbar=0,directories=0,menubar=0,status=0,resizable=0,location=0,scrollbars=1,copyhistory=0');
	else
		oFloatWin.moveTo(nX, nY);

	PopulateWindow(oFloatWin, Insert(output, sFltSrc));
	oFloatWin.document.title = PRODUCT_NAME_AND_VERSION + BY_COMPANY_NAME;
}

var bTypeAheadFloaterActive=0;

function ShowTip(obj, custTip, custStat, showHelp)
{
	if (custTip || custStat)
	{
		if (custTip)
			obj.title = custTip;
		if (custStat)
			window.status = custStat;
		if (showHelp)
			obj.style.cursor	= 'help';
	}
	else
	{
		if (obj)
			obj.title = "";
		window.status = PRODUCT_NAME_AND_VERSION + BY_COMPANY_NAME;
		return true;
	}
}

// ****************************************************
// ********************  Temporary  *******************
// ****************************************************

function timestamp(name)
{
	var date = new Date();
	var stamp = oSys.createElement('TIMESTAMP');
	stamp.setAttribute('time', date.getTime());
	stamp.setAttribute('name', name);
	oTimeNode.appendChild(stamp);
}

var oTSwin;

function ShowTimestamps()
{
	var stamp = oTimeNode.firstChild, msg='', prev_time=0, total_time=0;
	var msg = '<html><body>';
	var init_time = roundToTwoDecimals(convertSeconds(oTimeNode.firstChild.getAttribute('time')));
	while (stamp)
	{
		msg+= '<div style=\"padding:3px;font-family:Tahoma;font-size:11px\"><span style="width:50%;text-align:left;">'+stamp.getAttribute('name') +'</span>';
		var cur_time = roundToTwoDecimals(convertSeconds(stamp.getAttribute('time')));
		var cur_interval = (prev_time) ? roundToTwoDecimals(cur_time - prev_time) : 0;
		//total_time = parseFloat(cur_interval + total_time);
		msg+= '<span style="width:20%;text-align:left;">'+ cur_interval + ' sec</span>';
		msg+= '<span style="width:20%;text-align:left;">'+ roundToTwoDecimals(cur_time - init_time) + ' sec</span></div>';
		prev_time = cur_time;
		stamp = stamp.nextSibling;
	}
	msg += '</body></html>';
	oTSwin = window.open('','SummaryWin','width=500,height=500,toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=1,copyhistory=0');
	PopulateWindow(oTSwin, msg);
	
	function format(num)
	{
		num = num+'';
		if (num=='0')
			return '0.00';
		while (num.length < 4)
		{
			 num+='0';
		}
		return num;
	}
	
	function convertSeconds(num)
	{
		return parseFloat(num)/1000;
	}
	
	function roundToTwoDecimals(num)
	{
		return parseInt(num*100)/100;
	}
}

var oStyle = new ActiveXObject("Msxml.DOMDocument");
var oNewWin;
var oDisplayNode;

function xml(sNodeName)
{
	oStyle.load("xDefaultStyle.xsl");
	xTmp.loadXML("<?xml version=\"1.0\"?>"+((sNodeName)?oSys.selectSingleNode(sNodeName).xml:oSys.xml));
	CheckReadyState();
}

function CheckReadyState()
{
	if (oStyle.readyState==4)
	{
		if (!oNewWin || oNewWin.closed)
			oNewWin = window.open();
		//var output = ;
		oNewWin.document.open();
		oNewWin.document.write(xTmp.transformNode(oStyle));
		oNewWin.document.close();
		oNewWin.focus();
		//output = null;
		//xTmp = new ActiveXObject("Msxml.DOMDocument");
	}
	else
		setTimeout("CheckReadyState()", 1000);
}
function handleHelpButtonClick()
{
	ViewListMenu('Help');
}

function HandleFeatureButtonClick()
{
	var oEl = window.event.srcElement;
	var oSpan = oEl;
	while (!oSpan.className || oSpan.className && oSpan.className!='button_cell_feature')
		oSpan = oSpan.parentElement;
	switch (oSpan.innerText)
	{
		case 'Favorites':
		ShowFloater('FeatureCodeFavorites');
		return;

		case 'Feature Codes':
		ShowFloater('FeatureCodeFavorites');
		return;
		
		case config('SPEED_DIAL'):
		ShowFloater('SpeedDial');
		return;
		
		case 'Log Off':
		CloseOut(true);
		return;
		
		case 'Help':
		ViewListMenu('Help');
		return;
	}
}
/*
function SaveXML()
{
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	
	oActNode.save("C:\test.xml");
}

function CreateFile()
{
	var fso, tf, i=0;
	fso = new ActiveXObject("Scripting.FileSystemObject");
	xTmp.loadXML("<ACCOUNTS></ACCOUNTS>");
	var oDevices = xTmp.firstChild;
	while (i < 1000)
	{
		var node = xTmp.createElement("A")
		node.setAttribute("u", i);
		node.setAttribute("f", "firstname"+i);
		node.setAttribute("l", "lastname"+i);
		oDevices.appendChild(node);
		i++;
	}
	tf = fso.CreateTextFile("c:\\accounts.xml", true);
	tf.WriteLine(xTmp.xml);
	tf.Close();
	alert("done");
}*/

xWin = 0;
yWin = 0;
var sNum = 500;
function shakeBrowser()
{
	moveBrowser();
	sNum--;
	if (sNum > 0)
		setTimeout('shakeBrowser()',10);
	else
		sNum = 500;
}

function moveBrowser()
{
	var xMod = 0 + ((getRandNum(1) > 4) ? (-getRandNum(1)) : getRandNum(1));
	var yMod = 0 + ((getRandNum(1) > 4) ? (-getRandNum(1)) : getRandNum(1));
	window.moveBy(xMod,xMod);
}

function getRandNum(length)
{
	return parseInt(Math.random() * Math.pow(10,length));
}

// ****************************************************
// ****************  FALCON CLIENT  *******************
// ****************************************************

var nCEIntervalID;
var nCEIntervalLength = 100;

// from Commands.h
var CLIENT_TYPE_WEB = new Number(0x00000001);
var CLIENT_TYPE_FALCON_WEB = new Number(0x00000100);

function CheckForActiveXControlUpdates()
{
	CallControlMethod('CheckForJavaScriptCalls');
}

function Resize(size)
{
	//var oIcon = getObj('cc_call_control_toggle_icon');
	switch (size)
	{
		// 0 – Toolbar
		case 0:
			Hide('CC');
			SetToolbarDisplay('none', true);
			//oIcon.src = 'img/iExpPlus.gif';
			break;
			
		// 1 – Toolbar plus type-ahead/call list
		case 1:
			Show('CC');
			SetToolbarDisplay('none', true);
			//oIcon.src = 'img/iExpMinus.gif';
			break;
		
		// 2 – Full Size
		case 2:
			SetToolbarDisplay('');
			break;
		
	}
}

// Whenever the web client resizes, you need to call the following method on the ActiveX control:
var LOGGED_IN_CLIENT_TYPE_FALCON_WEB = new Number(0x00000100);
function NotifyResized(size)
{
	if ((bt_ACCOUNT_STATUS & LOGGED_IN_CLIENT_TYPE_FALCON_WEB) && (sPlatform=='WinCE'))
	{
		CallControlMethod('NotifyResized', size+'');
	}
}

// ****************************************************
// *******************  PROGRESS BARS  ****************
// ****************************************************

function FakeProgress()
{
	MakeProgressBars('fake');
}

function MakeProgressBars(process)
{
	var msg, title, style = 'width:200px;background-color:#369;border:1px solid #333;text-align:left;';
	switch (process)
	{
		case 'CSIM':
			title = text('PB/'+process);
			AddBar('ImportContacts', text('SYNC/CSV'), style);
			break;
		
		case 'SYEV':
			title = text('PB/'+process);
			AddBar('Init Synch 1', text('SYNC/INIT1'), style);
			AddBar('Init Synch 2', text('SYNC/INIT2'), style);
			AddBar('Init Synch 3', text('SYNC/INIT3'), style);
			break;
		
		case 'SYCS':	
			title = text('PB/'+process);
			var opers = ParseDelimitedList(oCurSynchNode.getAttribute('operations'));
			var evals = ParseDelimitedList(oCurSynchNode.getAttribute('eval'));

			// remote delete
			if (eval(opers[3]) && parseFloat(evals[3]) > 0)
				AddBar('Remote Deletes', text('SYNC/STEP1A'), style);

			// if the user doesn't permit remote deletes we must unlink the remote contacts
			if (!eval(opers[3]) && parseFloat(evals[3]) > 0)
				AddBar('Cancel Remote Deletes', text('SYNC/STEP1B'), style);
			
			// local delete
			if (eval(opers[2]) && parseFloat(evals[2]) > 0)
				AddBar('Local Deletes', text('SYNC/STEP2'), style);

			// local adds
			if (eval(opers[0]) && parseFloat(evals[0]) > 0)
				AddBar('Local Adds', text('SYNC/STEP3'), style);
				
			//remote adds
			if (eval(opers[1]) && parseFloat(evals[1]) > 0)
				AddBar('Remote Adds', text('SYNC/STEP4'), style);
				
			// remote updates
			if (eval(opers[5]) && parseFloat(evals[5]) > 0)
				AddBar('Remote Updates', text('SYNC/STEP5'), style);
				
			// local updates
			if (eval(opers[4]) && parseFloat(evals[4]) > 0)
				AddBar('Local Updates', text('SYNC/STEP6'), style);
				
			break;
				
			/*
			
			 // First, we delete all the entries from the Remote DBs
		      if (m_bContinueSynchOperation && bAllowDeleteRemote)     CompleteRemoteDeletes(pController);
		      if (m_bContinueSynchOperation && !bAllowDeleteRemote)    CancelRemoteDeletes(pController);
		      // Then delete the entries from the UCServer DB (LDAP).
		      if (m_bContinueSynchOperation && bAllowDeleteUCServer)   CompleteUCServerDeletes(pController);
		      // Then do all the additions:
		      if (m_bContinueSynchOperation && bAllowAddUCServer)      CompleteUCServerAdds(pController);
		      // Next, add all the new entries to the Remote DBs, and update the existing one
		      if (m_bContinueSynchOperation && bAllowAddRemote)        CompleteRemoteAdds(pController);
		      // Then, update the existing UCServer (LDAP) DB
		      if (m_bContinueSynchOperation)                           CompleteRemoteUpdates(pController, !bAllowUpdateRemote);
		      // Finally, we update the UCServer changes
		      if (m_bContinueSynchOperation && bAllowUpdateUCServer)   CompleteUCServerUpdates(pController);
			
			// evaluation
			"sy_source_AllowLocalAdd",     aEvalNums[0]
			"sy_source_AllowRemoteAdd",    aEvalNums[1]
			"sy_source_AllowLocalDelete",  aEvalNums[2]
			"sy_source_AllowRemoteDelete", aEvalNums[3]
			"sy_source_AllowLocalUpdate",  aEvalNums[4]
			"sy_source_AllowRemoteUpdate", aEvalNums[5]
			x+= "<div class=\""+GetEvalClass(aEvalNums[7]
			
			// operations 
			0 'sy_source_AllowLocalAdd'
			1 'sy_source_AllowRemoteAdd'
			2 'sy_source_AllowLocalDelete'
			3 'sy_source_AllowRemoteDelete'
			4 'sy_source_AllowLocalUpdate'
			5 'sy_source_AllowRemoteUpdate'
			
			*/
			
	}
	BuildProgressBars(process, title);
	CheckProgress();
}

function AddBar(method, msg, style)
{
	// prevent spaces
	var re = new RegExp(' ', 'g')
	var oBar = oSys.createElement('BAR');
	oBar.setAttribute('style', style);
	oBar.setAttribute('id', method.replace(re, "_"));
	oBar.text = msg;
	oBarsNode.appendChild(oBar.cloneNode(true));
}

function BuildProgressBars(process, title)
{
	var html, source;
	switch (process)
	{
		case 'CSIM':
			source="iAdd"; break;
		case 'SYEV':
			source="iView"; break;
		case 'SYCS':
			source="iSynch"; break;
	}
	switch (process)
	{
		case 'CSIM':
		case 'SYEV':
		case 'SYCS':
			html = CreateHTML('PB',1,oBarsNode);
			getObj('ABEX').innerHTML = html;
			getObj('pb_title').innerHTML = (title) ? ("<img src='img/"+source+".gif' class=\"icon\" style=\"margin:3px 5px;\">") : '';
			getObj('pb_title').innerHTML += (title) ? ((oCurSynchNode) ? Insert(oCurSynchNode.text, title) : title) : '';
			Hide('ABSY');
			isSYNCDIVdisplayed=6;
			Show('ABEX');
			SetButtons('SYPB');
			
	}
}

var oCurBar;
var percent=0;
var check_completion_timer=0

function CheckProgress()
{
	UpdateProgressBar();
	check_completion_timer = window.setInterval('UpdateProgressBar()',200);
}

function UpdateProgressBar()
{
	if (oCurBar)
	{
		if (percent == 100)
		{
			percent=0;
			if (oCurBar.nextSibling)
				oCurBar = oCurBar.nextSibling;
			else
				ClearProgressBars();
		}
		else
		{
			var re1 = new RegExp('_', 'g');
			var status = CallControlMethod('GetCompletionStatus', oCurBar.getAttribute('id').replace(re1, ' '));
			var s_vals = ParseDelimitedList(status);
			if (s_vals[0] == 'Not Started' && oCurBar.previousSibling)
			{
				percent = 0;
				oCurBar=oCurBar.previousSibling;
				UpdateProgressBar();
			}
			else if (s_vals[0] == 'Complete' || (s_vals[1] != '0' && (s_vals[1]==s_vals[2])))
				percent = 100;
			else if (s_vals[1] != '0' && (s_vals[1]!=s_vals[2]))
				percent = parseInt(parseFloat(s_vals[1])/parseFloat(s_vals[2])*100);
/*			if (s_vals[0] == 'Complete' || (s_vals[1] != '0' && (s_vals[1]==s_vals[2])))
				percent = 100;
			else if (s_vals[0] != 'Not Started')
				percent = parseInt(parseFloat(s_vals[1])/parseFloat(s_vals[2])*100);*/
			if (check_completion_timer)
				UpdateBar(oCurBar, percent);
		}
	}
	else if (oBarsNode.hasChildNodes())
	{
		oCurBar = oBarsNode.firstChild;
		UpdateProgressBar();
	}
}

function MaxOutProgressBars()
{
	while (oCurBar)
	{
		UpdateBar(oCurBar, 100);
		oCurBar = oCurBar.nextSibling;
	}
}

function UpdateBar(node, percent)
{
	var bar = getObj('pb_'+ node.getAttribute('id'));
	if (bar && bar.style && !isNaN(percent))
	{
		bar.style.width = percent+'%';
		// sometimes the previous bar won't get maxed, make sure it's at 100%
		var prev_node = node.previousSibling;
		if (prev_node)
		{
			var prev_bar = getObj('pb_'+ prev_node.getAttribute('id'));
			if (prev_bar)
				prev_bar.style.width = '100%';
		}
	}
}

function ClearProgressBars()
{
	window.clearTimeout(check_completion_timer);
	check_completion_timer = null;
	RemoveChildNodes(oBarsNode);
	oCurBar=null;
	percent=0;
}

/*function GoToPostProgressStep(type, str)
{
	switch (type)
	{
		case 'SYEV':
			//Hide('ABEX');
			//Show('ABSY');
			//SetButtons('SYCS');
			break;
	}
}*/



