// Creates the set of tabs the first time the page is loaded
function initTabs(tabsetName)
{
	var defaultTab = $F("visibleTab__" + tabsetName);
	
	// cookie overrides the default above
	if (cookieJar.get("visibleTab__" + tabsetName) != null) {
		defaultTab = cookieJar.get("visibleTab__" + tabsetName);
		if ($("tab__" + tabsetName + "__" + defaultTab) == null)
			defaultTab = "";
	}

	// if not set, then let's just pick the first tab
	if (defaultTab == "") {
		var tabTitles = $$(".tabTitle__" + tabsetName);
		defaultTab = tabTitles[0].value;
	}
	createTabsetTabs(tabsetName, defaultTab)
}


// Outputs a list of tabs for a tabset.  This is called every time the user clicks on a new tab.
function createTabsetTabs(tabsetName, selectedTab)
{
	var tabset = $("tabsetTabs__" + tabsetName);
	tabset.innerHTML = "";

	// set the cookie
	cookieJar.put("visibleTab__" + tabsetName, selectedTab);
	
	// output the tabs
	var tabs = $$(".tabTitle__" + tabsetName);
	for (var i=0; i < tabs.length; i++) {
		var tabClass = "";
		if (i == 0)
			tabClass += ' firstTab';
		else if (i == tabs.length-1)
			tabClass += ' lastTab';
		if (tabs[i].value == selectedTab)
			tabClass += " selected";
		tabset.innerHTML += "<li "
						  + (tabClass == "" ? "" : "class='" + tabClass + "' ")
						  + "onclick=\"createTabsetTabs('" + tabsetName + "', '" + tabs[i].value + "')\">" + tabs[i].name + "</li>";
	}
	
	// make the appropriate tab contents hidden/visible
	currentlyVisible = $("tab__" + tabsetName + "__" + $F("visibleTab__" + tabsetName));
	if (currentlyVisible != null)
		Element.hide(currentlyVisible);
	newlyVisible = Element.show($("tab__" + tabsetName + "__" + selectedTab));
	$("visibleTab__" + tabsetName).value = selectedTab;
}


/**
 * At the end of the page, this function is called so that we can apply some UI
 * stuff to the tables that are of class "list".
 * 
 * It loops through each table with the class name 'list' on this page.  For
 * each table it applies 'oddRow' to odd numbered rows and 'evenRow' to even
 * numbered rows.
 * 
 * Then it checks to see if the table is empty and inserts a 'There are no...'
 * row into the table if it is.
 */
function tableListUI() {
	
	$$('table.list').each(function(table) {
		var rows = table.select('tr');
		
		// highlight rows
		var i = 0;
		rows.each(function(row) {
			row.removeClassName("oddRow");
			row.removeClassName("evenRow");
			if (i%2 == 1) {
				row.addClassName("oddRow");
			} else {
				row.addClassName("evenRow");
			}
			i++;
		});

		// Is the table empty?
		if (rows.length < 2) {
			var cols = rows[0].childElements().length;
			table.insert("<tbody class='noItemsRow'><tr><td colspan='" + cols + "'>There are no items to display in this list.</td></tr></tbody>");
		}
	});
}

function turnOnOffVM() {
	if ($("activateVoiceMail").checked)
		Effect.SlideDown("vmSettings", {duration:0.25});
	else
		Effect.SlideUp("vmSettings", {duration:0.25});
}


function turnOnOffFindMe()
{
	if ($("findMeOrderOff").checked) {
		if ($("findMeEntries").visible())
			Effect.SlideUp("findMeEntries", {duration:0.25});
	}
	else if (! $("findMeEntries").visible())
		Effect.SlideDown("findMeEntries", {duration:0.25});
}

function updateFindMeDurations(selectElement)
{
	if ($("findMeOrderAll").checked) {
		var selectBoxes = $$("select[name='findMeDuration']");
		if (selectElement == null)
			selectElement = selectBoxes[0];

		for (var i=0; i < selectBoxes.length; i++) {
			if (selectBoxes[i].previous().value != "")
				selectBoxes[i].selectedIndex = selectElement.selectedIndex;
		}
	}
}


/**
 * Look for dual-select boxes and highlight everything in the righthand select box.
 */
function formPreSubmit(form)
{
	var selects = $$("select.selectAllOnSubmit");
	for (var i=0; i<selects.length; i++) {
		for (var j=0; j<selects[i].length; j++) {
			selects[i].options[j].selected = true;
		}
	}
}


// Used by the Dual-Select Boxes
function findInSelect(valueID, selectID, findNext)
{
	var element = $(selectID);
	var valueElement = $(valueID);
	if (! element || ! valueElement)
		window.alert('Error. Could not find needed elements.');
	var value = valueElement.value;
	if (! value || value == '')
		return false;
	
	if (element.options.length>0) {
		var beginIndex = 0;
		if (findNext == true) {
			if (element.selectedIndex)
				beginIndex = element.selectedIndex+1;
		}
		for (var i = beginIndex; i < element.options.length; i++) {
			if (element.options[i].text.toUpperCase().indexOf(value.toUpperCase()) != -1) {
				element.selectedIndex = i;
				break;
			}
		}
	}
}
 
 
// Used by the Dual-Select Boxes
function moveItem(from, to)
{
	var f, SI; /* selected Index */
	if (from.options.length>0) {
		for (i=0;i<from.length;i++) {
			if (from.options[i].selected) {
				SI = from.selectedIndex;
				f = from.options[SI].index;
				to.options[to.length] = new Option(from.options[SI].text,from.options[SI].value);
				from.options[f] = null;
				i--; 
			}
		}
	}
}


// Used by the Dual-Select Boxes
function moveItemUp(to)
{
	try {
		var SI = to.selectedIndex;
		if (SI <= 0)
			return;
		var toMove = to.options[SI];
		var fromMove = to.options[SI-1];
		to.options[SI] = new Option(fromMove.text,fromMove.value);
		to.options[SI-1] = new Option(toMove.text,toMove.value, true);
	}
	catch (Exception) {}
}

function moveItemDown(to)
{
	try {
	var SI = to.selectedIndex;
	if (SI >= to.length-1)
		return;
	var toMove = to.options[SI];
	var fromMove = to.options[SI+1];
	to.options[SI] = new Option(fromMove.text,fromMove.value);
	to.options[SI+1] = new Option(toMove.text,toMove.value, true);
	}
	catch (Exception) {}
 }

function positionMenu(parent, menuID)
{
	var parent = $(parent);
	var menu = $("menu__"+menuID);
	menu.style.left = parent.cumulativeOffset()[0] + "px";
	menu.style.top = parent.cumulativeOffset()[1] + parent.getHeight() -1 +"px";
	menu.style.zIndex=100;
}
function positionSubmenu(parent, submenuID)
{
	var parent = $(parent);
	var submenu = $("submenu__"+submenuID);
	submenu.style.left = parent.getWidth() + "px";
	submenu.style.top = parent.positionedOffset()[1] -5 + "px";
}



function setSelectedOption(selectElem, value)
{
	for (var i=0; i<selectElem.options.length; i++) {
		if (selectElem.options[i].value == value)
			selectElem.selectedIndex = i;
	}
}

//Left-pads the variable num up to a length of length
//i.e., zeroPad(34, 3) = 034 and zeroPad(34, 1) = 34
function zeroPad(num, length)
{
	numStr = num.toString();
	while (numStr.length < length)
		numStr = "0" + numStr;
	
	return numStr;
}



function getDayOfWeek(dateObj)
{
	dayName = dateObj.toString().substring(0, 3);
	if (dayName == 'Sun')		return 0;
	else if (dayName == 'Mon')	return 1;
	else if (dayName == 'Tue')	return 2;
	else if (dayName == 'Wed')	return 3;
	else if (dayName == 'Thu')	return 4;
	else if (dayName == 'Fri')	return 5;
	else if (dayName == 'Sat')	return 6;
	else return 0;
}

function getDaysInMonth(dateObj) {
    return 32 - (new Date(dateObj.getYear(), dateObj.getMonth(), 32)).getDate();
}

function drawDateTool(fieldName)
{
	var year = $F('dateTool_year');
	var month = $F('dateTool_month');
	var dateObj = new Date();
	if ((year != '') && (month != ''))
		dateObj = new Date(year, month-1, 1);
	dayOfWeek = getDayOfWeek(dateObj);
	
	// clear all the buttons before the start of the first day of the month
	var calBoxes = $$("table#dateSelector td");
	for (i=0; i<calBoxes.length; i++) {
		if ((i < dayOfWeek) || ((i-dayOfWeek+1) > getDaysInMonth(dateObj)))
			calBoxes[i].childElements()[0].innerHTML = "&nbsp;";
		else
			calBoxes[i].childElements()[0].innerHTML = zeroPad(i-dayOfWeek+1, 2);
	}
	
	// should we make the last two rows invisible?
	var calRows = $$("table#dateSelector tr");
	if (calRows[calRows.length-2].childElements()[0].childElements()[0].innerHTML == '&nbsp;')
		calRows[calRows.length-2].hide();
	else
		calRows[calRows.length-2].show();
	if (calRows[calRows.length-1].childElements()[0].childElements()[0].innerHTML == '&nbsp;')
		calRows[calRows.length-1].hide();
	else
		calRows[calRows.length-1].show();
	
	return false;
}

function showDateTool(fieldName, showDate, showTime) {
	var showTool = false;
	var field = $('dateTool_fieldName');
	var dateTool = $('dateTool');
	if ((! $('dateTool').visible()) || ($F('dateTool_fieldName') != fieldName))
		showTool = true;
	
	dateTool.style.left = $(fieldName).cumulativeOffset()[0] + "px";
	dateTool.style.top = $(fieldName).cumulativeOffset()[1] + $(fieldName).getHeight() + "px";
	field.value = fieldName;
	
	// parse the default value from the field
	var dateTime = $F(fieldName);
	if (dateTime.indexOf("-") != -1) {
		setSelectedOption($('dateTool_year'), dateTime.substring(0, 4));
		setSelectedOption($('dateTool_month'), dateTime.substring(5, 7));
		$('dateTool_day').value = dateTime.substring(8, 10);
	}
	if (dateTime.indexOf(":") != -1) {
		var colonIndex = dateTime.indexOf(":");
		setSelectedOption($('dateTool_hour'), dateTime.substring(colonIndex-2, colonIndex));
		setSelectedOption($('dateTool_minute'), dateTime.substring(colonIndex+1, colonIndex+3));
	}
	drawDateTool(fieldName);
	highlightDate();
	
	// make the datetool appear
	$('dateTool_dateSelector').hide();
	$('dateTool_timeSelector').hide();
	if (showDate)
		$('dateTool_dateSelector').show();
	if (showTime)
		$('dateTool_timeSelector').show();
	if (showTool)
		dateTool.show();
	else
		dateTool.hide();
}

function chooseDateTime(finishAndHide)
{
	// put together the date-time that was selected
	var year = $F('dateTool_year');
	var month = zeroPad($F('dateTool_month'), 2);
	var day = zeroPad($F('dateTool_day'), 2);
	var hour = zeroPad($F('dateTool_hour'), 2);
	var minute = zeroPad($F('dateTool_minute'), 2);
	var second = "00";
	if (minute == "59")
		second = "59";
	var dateTime = '';
	if ($('dateTool_dateSelector').visible())
		dateTime = (day == '&nbsp;' ? '' : year + '-' + month + '-' + day);
	if ($('dateTool_timeSelector').visible())
		dateTime += (dateTime == '' ? '' : ' ') + hour + ":" + minute + ":" + second;
	if ($($F('dateTool_fieldName')).maxLength > 0)
		dateTime = dateTime.substring(0, $($F('dateTool_fieldName')).maxLength);
	highlightDate();
	
	// if we're done, update the field and hide the tool
	if (! finishAndHide)
		finishAndHide = (($('dateTool_dateSelector').visible()) && (! $('dateTool_timeSelector').visible()));
	if (finishAndHide) {
		$($F('dateTool_fieldName')).value = dateTime;
		$('dateTool').hide();
	}
	return false;
}

function highlightDate() {
	var calBoxes = $$("table#dateSelector td");
	for (var i=0; i<calBoxes.length; i++) {
		if (calBoxes[i].childElements()[0].innerHTML == '&nbsp;')
			calBoxes[i].childElements()[0].removeClassName('selected');
		else if (calBoxes[i].childElements()[0].innerHTML == $F('dateTool_day'))
			calBoxes[i].childElements()[0].addClassName('selected');
		else
			calBoxes[i].childElements()[0].removeClassName('selected');
	}
	
	return false;
}


function actionSelect_changeSelection(field) {
	
	field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	actionSelect = $('id'+id);// This is the hidden input field.
	var actionOptions = $("actionSelectOptions__"+id);
	var select1Val = $F(field);
	
	var visibleOptions = 0;
	var options = actionOptions.descendants();
	for (var i=0; i<options.length; i++) {
		if (options[i].id.endsWith('__'+id)) {
			if ((select1Val != '') && (options[i].id.startsWith(select1Val))) {
				$(options[i]).show();
				visibleOptions++;
			} else {
				options[i].hide();
			}
		}
	}
	
	// update the value of the actionSelect
	if (select1Val.indexOf('IvrScript') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>file</Name><Value></Value></Element><Element><Name>args</Name><Value></Value></Element><Element><Name>variable</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrUserInput') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>variable</Name><Value></Value></Element><Element><Name>audioFile</Name><Value></Value></Element><Element><Name>maxDigits</Name><Value></Value></Element><Element><Name>timeout</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrVariableRoute') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>variable</Name><Value></Value></Element><Element><Name>operator</Name><Value>=</Value></Element><Element><Name>value</Name><Value></Value></Element><Element><Name>trueAction</Name><Value></Value></Element><Element><Name>falseAction</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrMessage') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>filename</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrTodRoute') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>timeRange</Name><Value></Value></Element><Element><Name>weekDays</Name><Value></Value></Element><Element><Name>daysOfMonth</Name><Value></Value></Element><Element><Name>months</Name><Value></Value></Element><Element><Name>action</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrChangeCID') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>number</Name><Value></Value></Element><Element><Name>name</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrRedirect') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>action</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrMySqlVariable') != -1) {
		actionSelect.value = '<IvrAction><Type>' + select1Val + '</Type><Element><Name>mode</Name><Value>load</Value></Element><Element><Name>variable</Name><Value></Value></Element><Element><Name>value</Name><Value></Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrAction>';
	} else if (select1Val.indexOf('IvrSayNumber') != -1) {
		actionSelect.value = '<IvrSayNumber><Type>' + select1Val + '</Type><Element><Name>variable</Name><Value></Value></Element><Element><Name>sayAs</Name><Value>Digits</Value></Element><Element><Name>comment</Name><Value></Value></Element></IvrSayNumber>';
	} else {
		actionSelect.value = '';
	}
}

function actionSelect_update(field, actionSelectID) {
	
	var field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	if (actionSelectID != null) {
		id = actionSelectID;
	}
	var actionSelect = $('id'+id);//This is the <input> which holds the xml value.
	var value = $F(field);//This is the value of the calling form element.
	var type = field.name;
	var xml = $F('id'+id);
	if(field.tagName.toLowerCase() != "select") 
		value = sanitize(value);
	field.value = value;
	
	if (type.indexOf('IvrScript') != -1) {
		if (type.indexOf('_file') != -1) {
			actionSelect.value = setFieldValue(xml, 'file', value)
		} else if (type.indexOf('_args') != -1) {
			actionSelect.value = setFieldValue(xml, 'args', value)
		} else if (type.indexOf('_variable') != -1) {
			actionSelect.value = setFieldValue(xml, 'variable', value)
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrUserInput') != -1) {
		if (type.indexOf('_variable') != -1) {
			actionSelect.value = setFieldValue(xml, 'variable', value)
		} else if (type.indexOf('_audioFile') != -1) {
			actionSelect.value = setFieldValue(xml, 'audioFile', value)
		} else if (type.indexOf('_maxDigits') != -1) {
			actionSelect.value = setFieldValue(xml, 'maxDigits', value)
		} else if (type.indexOf('_timeout') != -1) {
			actionSelect.value = setFieldValue(xml, 'timeout', value)
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrVariableRoute') != -1) {
		if (type.indexOf('_variable') != -1) {
			actionSelect.value = setFieldValue(xml, 'variable', value)
		} else if (type.indexOf('_operator') != -1) {
			actionSelect.value = setFieldValue(xml, 'operator', value)
		} else if (type.indexOf('_value') != -1) {
			actionSelect.value = setFieldValue(xml, 'value', value)
		} else if (type.indexOf('_trueAction') != -1) {
			var contextID = field.id.substring(field.id.indexOf("__")+2);
			var contextSelect = $('id'+contextID);
			var select1Val = $F('selection__'+contextID);
			if (select1Val != '') {
				var value = '<'+select1Val+'>' + $F(field) + '</'+select1Val+'>';
				actionSelect.value = setFieldValue(xml, 'trueAction', value)
			} else {
				actionSelect.value = setFieldValue(xml, 'trueAction', '')
			}
		} else if (type.indexOf('_falseAction') != -1) {
			var contextID = field.id.substring(field.id.indexOf("__")+2);
			var contextSelect = $('id'+contextID);
			var select1Val = $F('selection__'+contextID);
			if (select1Val != '') {
				var value = '<'+select1Val+'>' + $F(field) + '</'+select1Val+'>';
				actionSelect.value = setFieldValue(xml, 'falseAction', value)
			} else  {
				actionSelect.value = setFieldValue(xml, 'falseAction', '');
			}
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrMessage') != -1) {
		if (type.indexOf('_filename') != -1) {
			actionSelect.value = setFieldValue(xml, 'filename', value)
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrTodRoute') != -1) {
		if (type.indexOf('_timeRange') != -1) {
			actionSelect.value = setFieldValue(xml, 'timeRange', value)
		} else if (type.indexOf('_weekDays') != -1) {
			actionSelect.value = setFieldValue(xml, 'weekDays', value)
		} else if (type.indexOf('_daysOfMonth') != -1) {
			actionSelect.value = setFieldValue(xml, 'daysOfMonth', value)
		} else if (type.indexOf('_months') != -1) {
			actionSelect.value = setFieldValue(xml, 'months', value)
		} else if (type.indexOf('_action') != -1) {
			var contextID = field.id.substring(field.id.indexOf("__")+2);
			var contextSelect = $('id'+contextID);
			var select1Val = $F('selection__'+contextID);
			if (select1Val != '') {
				var value = '<'+select1Val+'>' + $F(field) + '</'+select1Val+'>';
				actionSelect.value = setFieldValue(xml, 'action', value)
			} else {
				actionSelect.value = setFieldValue(xml, 'action', '')
			}
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrChangeCID') != -1) {
		if (type.indexOf('_number') != -1) {
			actionSelect.value = setFieldValue(xml, 'number', value);
		} else if (type.indexOf('_name') != -1) {
			actionSelect.value = setFieldValue(xml, 'name', value);
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrRedirect') != -1) {
		if (type.indexOf('_action') != -1) {
			var contextID = field.id.substring(field.id.indexOf("__")+2);
			var contextSelect = $('id'+contextID);
			var select1Val = $F('selection__'+contextID);
			if (select1Val != '') {
				var value = '<'+select1Val+'>' + $F(field) + '</'+select1Val+'>';
				actionSelect.value = setFieldValue(xml, 'action', value)
			} else {
				actionSelect.value = setFieldValue(xml, 'action', '')
			}
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value)
		}
	} else if (type.indexOf('IvrMySqlVariable') != -1) {
		if (type.indexOf('_mode') != -1) {
			actionSelect.value = setFieldValue(xml, 'mode', value);
		} else if (type.indexOf('_variable') != -1) {
			actionSelect.value = setFieldValue(xml, 'variable', value);
		} else if (type.indexOf('_value') != -1) {
			actionSelect.value = setFieldValue(xml, 'value', value);
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value);
		}
	} else if (type.indexOf('IvrSayNumber') != -1) {
		if (type.indexOf('_variable') != -1) {
			actionSelect.value = setFieldValue(xml, 'variable', value);
		} else if (type.indexOf('_sayAs') != -1) {
			actionSelect.value = setFieldValue(xml, 'sayAs', value);
		} else if (type.indexOf('_comment') != -1) {
			actionSelect.value = setFieldValue(xml, 'comment', value);
		}
	}
}

function sanitize(value) {
	var str = value;
	str = replaceAll(str, "'");
	str = replaceAll(str, "\"");
	str = replaceAll(str, ">");
	str = replaceAll(str, "<");
	return str;
}

function replaceAll(value, character) {
	
	var str = value;
	while (str.indexOf(character) != -1) {
		str = str.replace(character, "");
	}
	return str;
}

function setFieldValue(str, field, value) {
	
	var split = str.split('<Name>'+field+'</Name><Value>');
	return split[0]+'<Name>'+field+'</Name><Value>'+value+split[1].substring(split[1].indexOf('</Value>'));
}

function addressSelect_changeSelection(field) {
	
	field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	addressSelect = $('id'+id);
	var addresses = $("addressSelectAddresses__"+id);
	var select1Val = $F(field) + "_";
	var visibleOptions = 0;
	var options = addresses.descendants();
	for (var i=0; i<options.length; i++) {
		if (options[i].id.endsWith('__'+id)) {
			if ((select1Val != '') && (options[i].id.startsWith(select1Val))) {
				$(options[i]).show();
				visibleOptions++;
			}
			else
				options[i].hide();
		}
	}
}

function contextSelect2_changeSelection(field)
{
	field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	contextSelect = $('id'+id);
	var contextOptions = $("contextSelectOptions__"+id);
	var select1Val = $F(field);
	contextSelect.value = '';
	
	// hide all of the options except the one that should be shown
	var visibleOptions = 0;
	var options = contextOptions.descendants();
	for (var i=0; i<options.length; i++) {
		if (options[i].id.endsWith('__'+id)) {
			if ((select1Val != '') && (options[i].id.startsWith(select1Val))) {
				$(options[i]).show();
				visibleOptions++;
			}
			else
				options[i].hide();
		}
	}
	if (select1Val == '') {
		contextSelect.value = '';
		return;
	}
	
	// update the value of the contextSelect
	if (visibleOptions == 0)
		contextSelect.value = '<action>' + select1Val + '</action>';
	else {
		if (select1Val != 'sendViaSIP')
			contextSelect.value = '<'+select1Val+'>' + $F(select1Val+'__'+id) + '</'+select1Val+'>';
	}
}

function contextSelect2_update(field)
{
	field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	contextSelect = $('id'+id);
	var select1Val = $F('selection__'+id);
	contextSelect.value = '<'+select1Val+'>' + $F(field) + '</'+select1Val+'>';
}

function contextSelect2Sip_update(id)
{
	contextSelect = $('id'+id);
	contextSelect.value = '';
	var dnisVal = $F('dnis_'+id);
	var hostVal = $F('host_'+id);
	
	
	if (dnisVal == 'custom') {
		$('custom_dnis_'+id).show();
		dnisVal = $F('custom_dnis_'+id);
	}
	else
		$('custom_dnis_'+id).hide();
	
	contextSelect.value = '<sendViaSIP>' + dnisVal + '@' + hostVal + '</sendViaSIP>'; 
}

function contextSelect2Jump_add(count) {
	var csSelects = $$('.csSelectJump');
	for (var i=0; i<csSelects.length; i++) {
		for (var j = 0; j < count; j++) {
			csSelects[i].options.add(new Option(csSelects[i].length, csSelects[i].length));
		}
	}
}

function showToolTip(text, width) {
	ddrivetip(text, width);
}

function hideToolTip()
{
	hideddrivetip();
}


/**
 * A number of pages call this function when they wish to add a row (or multiple rows) to a table 
 * with form elements in the rows.  This will add a new row at the bottom just like the others 
 * and reset the form elements (e.g., textboxes, selects) to default.
 */
function addRow(table, numRows)
{
  var table = $(table);
  var lastRow = table.rows[table.rows.length-1];

  for (var i=0; i<numRows; i++) {
    table.insert("<tr>" + lastRow.innerHTML + "</tr>");
    var newRow = table.rows[table.rows.length-1];
    var newRow = $(newRow);
    var inputs = newRow.getElementsBySelector("input");
    var selects = newRow.getElementsBySelector("select");

    for (var j=0; j<inputs.length; j++)
        inputs[j].value = '';
    for (var j=0; j<selects.length; j++)
        selects[j].selectedIndex=0;
  }
  tableListUI();
  return false;
}

function deleteRow(row, askForConfirmation)
{
	if (askForConfirmation==null)
		askForConfirmation = true;
	var row = $(row);
	if ((!askForConfirmation) || (confirm("Are you sure you want to delete this row?"))) {
		Effect.Fade(row, {duration:0.5});
		row.remove();
	}
}


function initDualSelect(id)
{
	var dsLeft=$('dualSelectLeft__'+id), dsRight=$('dualSelectRight__'+id)
	var select = $(id);
	for (var i=0; i<select.options.length; i++) {
		if (select.options[i].selected)
			dsRight.insert('<div id="dualSelectValue__' + id + '__' + select.options[i].value + '">' + select.options[i].text + '</div>');
		else
			dsLeft.insert('<div id="dualSelectValue__' + id + '__' + select.options[i].value + '">' + select.options[i].text + '</div>');
	}
	
	
	Sortable.create(dsLeft, {constraint:null, tag:'div', dropOnEmpty:true, containment:[dsLeft, dsRight],
		onChange:function(elem) {return changeDualSelect(elem);}
	});
	Sortable.create(dsRight, {constraint:null, tag:'div', dropOnEmpty:true, containment:[dsLeft, dsRight],
		onChange:function(elem) {return changeDualSelect(elem);}
	});
}

function changeDualSelect(elem) {
	var id = null;
	if (elem.id.startsWith('dualSelectLeft'))
		id = elem.id.substring(16);
	else if (elem.id.startsWith('dualSelectRight'))
		id = elem.id.substring(17);
	else
		id = elem.id.substring(17, elem.id.indexOf('__', 17));
	var select = $(id), dsRight = $('dualSelectRight__'+id), dsLeft = $('dualSelectLeft__'+id);
	var children = dsRight.childElements();
	while (select.options.length>0)
		select.remove(0);
	for (var i=0; i<children.length; i++) {
		var value = children[i].id.substring(19+id.length);
		var option = new Option(children[i].innerHTML, value, false, true);
		try {
			select.add(option, null);
		} catch (ex) {
			select.add(option);
		}
	}
}

function dualSelectFilter(id)
{
	var filterValue = $F('dualSelectFilter__'+id).toLowerCase();
	var dsLeft = $('dualSelectLeft__'+id);
	for (var i=0; i<dsLeft.childElements().length; i++) {
		if (dsLeft.childElements()[i].innerHTML.toLowerCase().indexOf(filterValue) == -1)
			dsLeft.childElements()[i].hide();
		else
			dsLeft.childElements()[i].show();
	}
}


/**
 * Asks the user to enter the name of a new IVR selection.
 */
function ivrSelection(selectElement, companyID)
{
	if ($F(selectElement) == "__new__") {
		var newIvrName = prompt("Enter the name of the new Caller Menu to create.\n\nOnce you press OK, the new Caller Menu will be automatically created.");
		if (newIvrName != null)
			new Ajax.Request('/ajax.html?REQUEST=contextSelect_newIvr&htmlID='+selectElement.id+'&companyID='+companyID+'&name='+newIvrName, { method: 'get'});
	}
}

/**
 * This is called when a new IVR is created by the AJAX Servlet to populate each of the ContextSelect IVR dropdowns with the newly created IVR.
 * @param ivrID			ID of the newly created IVR
 * @param ivrName		name of the newly created IVR
 * @param csSelectID	ID of the dropdown element that the user selected 'New IVR' on
 */
function newIvrCreated(ivrID, ivrName, csSelectID)
{
	var csSelects = $$('.csSelectIvrs');
	for (var i=0; i<csSelects.length; i++)
		csSelects[i].options.add(new Option(ivrName + " (newly created)", ivrID));
	$(csSelectID).selectedIndex = $(csSelectID).options.length-1;
	$(csSelectID).onchange();
}

/**
 * Create a new autocompleter for switching company ids.
 * @param input - the id of the input field.
 * @param list - the id of the list div.
 */
function createAutocompleter(input, list, loggedInUsername) {
	new Ajax.Autocompleter(input, list, '/ajax.html', {
		paramName: 'entry',
		parameters: 'REQUEST=companySearch&loggedInUsername='+loggedInUsername,
		method: 'get',
		afterUpdateElement: function(text, li) {
			loadCompanyID(text.value);
		}
	});
}

/**
 * Load the company information into the selection window.
 * @param companyID
 * @returns {Boolean}
 */
function loadCompanyID(companyID) {
	new Ajax.Request('/ajax.html?REQUEST=loadCompany&companyID='+companyID, { method: 'get'});
	return false;
}

/**
 * Deletes several voicemail messages at once.
 * 
 * Note: this function performs a reload on completion.
 * 
 * @param username - the user's username.
 * @param onFinish - the function to call when complete.
 */
function bulkDeleteVoicemails(form) {
	
	if (confirm('Are you sure you want to delete these voicemails?')) {
		var csv = getSelectedVoicemails(form);
		var username = form;
		new Ajax.Request('/ajax.html?REQUEST=bulkDeleteVm&username='+username+'&vmIDs='+csv, {method: 'get'});
	}
}

/**
 * Move several voicemails from one folder to another.
 * @param username		the user's name.
 * @param fromFolder	Either 'INBOX' or 'Old'.
 * @param toFolder		Either 'INBOX' or 'Old'.
 * @param onFinish		the function to call when complete.
 */
function bulkMoveVoicemails(username, fromFolder, toFolder, onFinish) {
	var checkboxes = $(username).getInputs('checkbox', 'check');
	for (var i=0; i<checkboxes.length; i++) {
		if (checkboxes[i].checked) {
			moveVoicemailNoRefresh(username, fromFolder, toFolder, checkboxes[i].value);
		}
	}
	
}


/**
 * Returns a comma separated list of voicemails which are
 * selected in the specified form.
 * 
 * @param form - the id of the form to search.
 */
function getSelectedVoicemails(form) {
	var form = $(form);
	var checkboxes = form.getInputs('checkbox', 'check');
	var csv = '';
	checkboxes.each(function(e){
		if (e.checked) {
			csv += (csv.length == 0?'':',') + e.value;
		}
	});
	return csv
}

/**
 * This will uncheck all the boxes in the given form.
 * 
 * @param form - the form to clear.
 */
function clearSelectedVoicemails(form) {
	var form = $(form);
	var checkboxes = form.getInputs('checkbox');
	checkboxes.each(function(e){
		e.checked = false;
	});
	$('vm_buttons').hide();
}

/**
 * Move a single voicemail from one folder to another without reloading the page.
 * @param fromFolder - the folder it is currently in.
 * @param toFolder   - the folder to move to.
 * @param vmID       - ID of the voicemail
 */
function moveVoicemailNoRefresh(username, fromFolder, toFolder, vmID) {
	new Ajax.Request('/ajax.html?REQUEST=bulkMoveVm&username='+username+'&fromFolder='+fromFolder+'&toFolder='+toFolder+'&vmIDs='+vmID, {method: 'get'});
	var elem = $$('#'+vmID + " .voicemail")[0];
	if (toFolder=='INBOX') {
		elem.addClassName('newVM');
		var icon = "<img id='move_" + vmID + "' src='/graphics/vm_move_old.png' alt='Mark as unplayed' title='Mark as unplayed' onclick=\"moveVoicemailNoRefresh('" + username + "', 'INBOX', 'Old', '" + vmID + "');\" />";
		$('move_'+vmID).replace(icon);
	}
	else {
		elem.removeClassName('newVM');
		var icon = "<img id='move_" + vmID + "' src='/graphics/vm_move_new.png' alt='Mark as played' title='Mark as played' onclick=\"moveVoicemailNoRefresh('" + username + "', 'Old', 'INBOX', '" + vmID + "');\" />";
		$('move_'+vmID).replace(icon);
	}
}

/**
 * Delete a single voicemail without reloading the page.
 * 
 * @param username - the user's username.
 * @param vmID 	   - ID of the voicemail
 */
function deleteVoicemailNoRefresh(username, vmID) {
	if (confirm('Are you sure you want to delete this voicemail?')) {
		new Ajax.Request('/ajax.html?REQUEST=bulkDeleteVm&username='+username+'&vmIDs='+vmID, {method:'get'});
	}
}

function vmDeleted(vmID) {
	Effect.Fade(vmID, {duration:0.5});
}

document.observe("dom:loaded", function() {
	if($$('.formErrorsWrapper')[0] != null) {
		$$('.formErrorsWrapper')[0].setStyle({height:$$('.formErrors')[0].getHeight()+'px'});
		var offset = $$('.formErrors')[0].positionedOffset()[1],
			topMargin = parseFloat($$('.formErrors')[0].getStyle('marginTop').replace(/auto/, 0)),
			top = offset - topMargin;
		Event.observe(window, 'scroll', function() {
			// what the y position of the scroll is
			var y = document.viewport.getScrollOffsets()[1]
			// whether that's below the form
			if (y >= top) {
			  // if so, ad the fixed class
			  $$('.formErrors')[0].addClassName('fixedErrors');
			} else {
			  // otherwise remove it
			  $$('.formErrors')[0].removeClassName('fixedErrors');
			}
		});  
	}
});


// This function is executed when the first dropdown for a ContextSelectAjax is changed.
function contextSelectAjax_changeSelection(field, preload)
{
	field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	var contextSelect = $('id'+id);
	var selection = $F(field);

	// load the OPTIONs from the Ajax Servlet
	if (($(selection+'__'+id)!=null) && (!($(selection+'__'+id).options===undefined)) && ($(selection+'__'+id).options[0].innerHTML=='loading ...')) {
		var companyID = $F('companyID');
		new Ajax.Request('/ajax.html?REQUEST=contextSelectAjax&companyID='+companyID+'&selection='+selection+'&preload='+preload, { method: 'get'});
	}

	
	// hide all of the options except the one that should be shown
	var contextOptions = $("contextSelectOptions__"+id);
	var visibleOptions = 0;
	var options = contextOptions.descendants();
	for (var i=0; i<options.length; i++) {
		if (options[i].id.endsWith('__'+id)) {
			if ((selection != '') && (options[i].id.startsWith(selection))) {
				$(options[i]).show();
				visibleOptions++;
			}
			else
				options[i].hide();
		}
	}
	if (selection == '') {
		contextSelect.value = '';
		return;
	}
	
	// update the value of the contextSelect
	if (preload)
		contextSelect.value = $F('id_default'+id);
	else if (visibleOptions == 0)
		contextSelect.value = '<action>' + selection + '</action>';
	else {
		if (selection != 'sendViaSIP')
			contextSelect.value = '<'+selection+'>' + $F(selection+'__'+id) + '</'+selection+'>';
	}
}

// This function is executed when the second dropdown for a ContextSelectAjax is changed.
function contextSelectAjax_update(field)
{
	field = $(field);
	var id = field.id.substring(field.id.indexOf("__")+2);
	contextSelect = $('id'+id);
	var selection = $F('selection__'+id);
	contextSelect.value = '<'+selection+'>' + field.value + '</'+selection+'>';
}

function contextSelectAjaxSip_update(id)
{
	contextSelect = $('id'+id);
	contextSelect.value = '';
	var dnisVal = $F('dnis_'+id);
	var hostVal = $F('host_'+id);
	
	
	if (dnisVal == 'custom') {
		$('custom_dnis_'+id).show();
		dnisVal = $F('custom_dnis_'+id);
	}
	else
		$('custom_dnis_'+id).hide();
	
	contextSelect.value = '<sendViaSIP>' + dnisVal + '@' + hostVal + '</sendViaSIP>'; 
}

function contextSelectAjaxJump_add(count) {
	var csSelects = $$('.csSelectJump');
	for (var i=0; i<csSelects.length; i++) {
		for (var j = 0; j < count; j++) {
			csSelects[i].options.add(new Option(csSelects[i].length, csSelects[i].length));
		}
	}
}



// Preloads the OPTIONs for the default selection for a ContextSelectAjax.
var contextSelectAjax_preloaded='';
function contextSelectAjax_preload()
{
	var contextSelects = $$('.contextSelectAjax');
	for (var i=0; i<contextSelects.length; i++) {
		var id=contextSelects[i].id.substring(2);
		var selection = $F('selection__'+id);
		if (contextSelectAjax_preloaded.indexOf(selection)==-1) {
			contextSelectAjax_preloaded += ' ' + selection;
			contextSelectAjax_changeSelection($('selection__' + id), true);
		}
	}
}

// Selects correct OPTION in the second dropdown for a ContextSelectAjax.
function contextSelectAjax_preload_selectDefault(id)
{
	// set the value for the context select
	var value = $F('id_default'+id);
	var selection = $F('selection__'+id);
	if (selection=='')
		return;
	$('id'+id).value = value;
	if (value.startsWith('<'+selection+'>'))
		value = value.substring(2+selection.length, value.indexOf('</'));
	var options = $(selection+"__"+id).options;
	if (! (options===undefined)) {
		for (var i=0; i<options.length; i++)
			options[i].selected = (options[i].value==value);
	}
}

function contextSelectAjax_loadSelectValues(selection, options, preload)
{
	var contextSelects=$$('.contextSelectAjax');
	for (var i=0; i<contextSelects.length; i++) {
		var id=contextSelects[i].id.substring(2);
		$(selection+'__'+id).update(options);
		if (selection=="ivr") {
			if (($('allowRouteToSameIvr__'+id)!=undefined) && ($F('allowRouteToSameIvr__'+id)=='1')) $('ivr__'+id).insert('<option value=\"__this__\">***** This Caller Menu *****</option>');
		}
		if (preload=="true")
			contextSelectAjax_preload_selectDefault(id);
	}
}

function toggleExpandCollapse(link, div) {
	var link = $(link);
	var div = $(div);
	if (div.visible()) {
		div.hide();
		link.removeClassName('expanded');
		link.addClassName('collapsed');
		link.title = 'Expand';
	} else {
		div.show();
		link.removeClassName('collapsed');
		link.addClassName('expanded');
		link.title = 'Collapse';
	}
}

function updateLevelOfService(id, title, tooltip) {
	
	var container = $(id);
	container.update(title+' ');
	if (tooltip != null) {
		var span = Element('span', {'onmouseover': 'showToolTip("'+tooltip+'")', 'onmouseout': 'hideToolTip();'});
		var img = Element('img', {'height': '14', 'src': '/graphics/info.png'});
		container.insert({bottom: span});
		span.insert({bottom: img});
	}
}

function showScreenPop(html, height, width, opacity, duration) {
	
	var id = new Date().getTime()+'-'+Math.floor(Math.random()*10000000);
	var screenPop = Element('div', {'id': 'screenPop__'+id, 'class': 'screenPop', 'style': 'display: none;'})
		.insert(Element('div').update(html))
		.insert(Element('div', {'style': 'float: right;'})
			.insert(Element('a', {'title': 'Dismiss', 'onclick': '$("screenPop__'+id+'").remove(); return false;', 'href': '#'})
				.update(Element('img', {'src': '/graphics/deleteIcon.gif'}))));
	document.body.insert({top: screenPop});
	if (height) screenPop.style.height=height+'px';
	if (width) screenPop.style.width=width+'px';
	if (opacity) {
		screenPop.appear({duration: 2.0, from: 0.0, to: opacity});
	} else {
		screenPop.appear({duration: 2.0});
	}
	if (duration) {
		setTimeout(function() {$('screenPop__'+id).fade({duration: 3.0});}, duration*1000);
		setTimeout(function() {$('screenPop__'+id).remove();}, (duration+3.0)*1000);
	}
}

function toggleDiv(div, link) {
	var div = $(div);
	var link = $(link);
	if (div.visible()) {
		div.hide();
		link.update("show");
	} else {
		div.show();
		link.update("hide");
	}
	return false;
}

var messageHideTimer;
function displayMessage(message, duration) {
	
	var body = $(pageContent);
	var id = 'messageContainer';
	var element = $(id);
	if (element != null) {	// Update message container.
		if (element.innerHTML != message) element.update(message);
	} else {				// Create message container.
		element = Element('div', {'id' : id, 'class' : id, 'style': 'display:none;'}).update(message);
		body.insert({top: element});
	}
	
	// If the container isn't visible then make it appear.
	if (!element.visible()) element.appear({duration: 2.0});
	
	// If there is an old timer clear it.
	if (messageHideTimer != null) clearTimeout(messageHideTimer);
	
	// Create a new timer.
	duration = duration || 10;
	messageHideTimer = setTimeout("$('"+id+"').fade({duration: 2.0});", duration*1000);
}
