/*==================================================================
	File:		VSScripts.js
	
	Contains:	External JavaScripts used in pages generated 
				by vscgi.exe.
				
	Copyright:	2002 Microsoft Corporation
==================================================================*/

var menu_backgroundHiliteClass			= "menu_item_text_hover";
var menu_backgroundNotHiliteClass		= "menu_item_text";
var menu_background2HiliteClass			= "menu_submenu_icon_hover";
var menu_background2NotHiliteClass		= "menu_submenu_icon";
var menu_borderHiliteClass				= "menu_border_hilite";
var menu_borderNotHiliteClass			= "menu_border";

var onWindowsIE = (navigator.appVersion.indexOf("MSIE") != -1 &&
				navigator.appVersion.indexOf("Windows") != -1);

// Virtual Machine Remote Control scripts
function VSClientControl_OnSwitchedDisplay(id)
{
	var VMName = "";
	if (document.getElementById("vm") != null)
		VMName = document.getElementById("vm").value;
	// the activex control returns Virtual Server as the display
	// name when in adminstrator mode.  We expect an empty vm name
	if (VSClientControl.AdministratorMode == true && id == "Virtual Server")
			id = "";
	// check that we aren't switching to the same vm 
	if (VMName != id)
	{
		var currentLocation = window.location.href;
		var	queryStart = currentLocation.indexOf('?');
		if (queryStart != -1)
		{
			// get the host and path information
			var	newLocation = currentLocation.substring(0, queryStart);
			// get the view part of the url without hardcoding it
			var currentSearch = window.location.search;
			var searchStart = currentSearch.indexOf('&');
			if (searchStart != -1)
			{
				newLocation += currentSearch.substring(0, searchStart);
			}
			else
				newLocation += currentSearch;
			// append the new vm name if applicable
			if (id != "")
			{
				newLocation += '&vm=' + escape(id);
			}	
			window.location.href = newLocation;
		}
	}
	return true;
}

function VSClientControl_Load(style, id, codebase, classID, serverIP, port, vmName, administratorMode, reducedColors)
{
	var objectHtml = "<object class=\"" + style + "\" ID=\"" + id + "\" codebase=\"" + codebase + "\" classID=\"" + classID + "\">\r\n";
	objectHtml	+= "\t<PARAM NAME=\"ServerAddress\" VALUE=\"" + serverIP + "\">\r\n";
	objectHtml	+= "\t<PARAM NAME=\"ServerPort\" VALUE=\"" + port + "\">\r\n";
	objectHtml	+= "\t<PARAM NAME=\"ServerDisplayName\" VALUE=\"" + vmName + "\">\r\n";
	objectHtml	+= "\t<PARAM NAME=\"AdministratorMode\" VALUE=\"" + administratorMode + "\">\r\n";
	objectHtml	+= "\t<PARAM NAME=\"ReducedColorsMode\" VALUE=\"" + reducedColors + "\">\r\n";

	// Setup the appearance properties
	var ourRules = document.styleSheets[0].rules;
	var styleFound = false;
	var styleIndex = 0;

	for (i = 0; i < ourRules.length; ++i)
	{
		if ((ourRules[i].selectorText == style) || ourRules[i].selectorText == ("." + style))
		{
			styleFound = true;
			styleIndex = i;
			break;
		}
	}
	
	if (styleFound)
	{
		var controlStyle = ourRules[styleIndex].style;

		if (controlStyle.backgroundColor != "")
			objectHtml	+= "\t<PARAM NAME=\"MenuBackColor\" VALUE=\"" + controlStyle.backgroundColor + "\">\r\n";

		if (controlStyle.color != "")
			objectHtml	+= "\t<PARAM NAME=\"MenuFontColor\" VALUE=\"" + controlStyle.color + "\">\r\n";

		if (controlStyle.fontFamily != "")
			objectHtml	+= "\t<PARAM NAME=\"MenuFontFace\" VALUE=\"" + controlStyle.fontFamily + "\">\r\n";
	
		// remove non-numeric characters, so that '12pt' becomes '12'
		var fontSize = controlStyle.fontSize;
		fontSize = fontSize.replace(/\D*/g,"");

		if (fontSize != "")
			objectHtml	+= "\t<PARAM NAME=\"MenuFontSize\" VALUE=\"" + fontSize + "\">\r\n";
	}

	objectHtml	+= "</object>";

	document.write(objectHtml);
}

// Menu scripts
var visibleSubMenu 		= null;
var subMenuToShow		= null;
var subMenuToHide		= null;
var reenterMenuCount	= 0;
var submenu_shadows 	= new Array

function menuFindParentCell(el)
{
	var curEl = el;
	while (curEl != null && curEl.className != "menu_item")
		curEl = curEl.parentElement;
	return curEl;
}

function setTableCellClass(tbl, row, col, cssClass)
{
	cell = tbl.tBodies[0].rows[row].cells[col];
	if (cell != null)
		cell.className = cssClass;
}

function menu_onfocus(el)
{
	menu_onmouseover(el);
}

function menu_onblur(el)
{
	menu_onmouseout(el);
}

function menu_onmouseover(el)
{
	var menuCell = menuFindParentCell(el);
	if (menuCell == null)
		return;
	
	setTableCellClass(menuCell, 0, 0, menu_borderHiliteClass);
	setTableCellClass(menuCell, 1, 0, menu_borderHiliteClass);
	setTableCellClass(menuCell, 1, 3, menu_borderHiliteClass);
	setTableCellClass(menuCell, 2, 0, menu_borderHiliteClass);

	setTableCellClass(menuCell, 1, 1, menu_backgroundHiliteClass);
	setTableCellClass(menuCell, 1, 2, menu_background2HiliteClass);
}

function menu_onmouseout(el)
{
	var menuCell = menuFindParentCell(el);
	if (menuCell == null)
		return;

	setTableCellClass(menuCell, 0, 0, menu_borderNotHiliteClass);
	setTableCellClass(menuCell, 1, 0, menu_borderNotHiliteClass);
	setTableCellClass(menuCell, 1, 3, menu_borderNotHiliteClass);
	setTableCellClass(menuCell, 2, 0, menu_borderNotHiliteClass);

	setTableCellClass(menuCell, 1, 1, menu_backgroundNotHiliteClass);
	setTableCellClass(menuCell, 1, 2, menu_background2NotHiliteClass);
}

function menu_onclick(el, href, openInNewWindow)
{
	var menuCell = menuFindParentCell(el);

	if (menuCell == null)
		return;

	if (href != null)
	{
		// Is the user holding down the shift key?
		if (openInNewWindow || window.event.shiftKey)
			window.open(href);
		else
			window.location = href;
	}
}

function combo_disable(menuID)
{
	var el = document.getElementById("root" + menuID);
	if (el == null)
		return;
		
	el.className = "combo_table_disabled";
}

function combo_enable(menuID)
{
	var el = document.getElementById("root" + menuID);
	if (el == null)
		return;
	
	el.className = "combo_table";
}

function combo_show(menuID)
{
	var el = document.getElementById("root" + menuID);
	if (el == null)
		return;
		
	if (el.className == "combo_table_disabled")
		return;
		
	var subMenu = document.getElementById(menuID);
	if (subMenu == null)
		return;
	
	submenu_adjustDimensions(subMenu);
		
	// Position the submenu relative to its parent menu		
	subMenu.style.top = (submenu_calcMenuTop(el, menuID) + el.offsetHeight) + "px";
	subMenu.style.left = submenu_calcMenuLeft(el) + "px";
	subMenu.style.width = el.style.width;

	subMenuToShow = subMenu;
	setTimeout("submenu_deferredDisplaySubMenu(\'" + menuID + "\')", 2);
		
	var curSelectedIndex = 0;
	curSelectedIndex = el.style.VSComboSelectedIndex;
	setTimeout("combo_set_option_focus('" + menuID + "'," + curSelectedIndex + ")", 10);

	var bodyEl = document.getElementById("body");
	if (bodyEl == null)
		return;
		
	bodyEl.onclick = combo_hide;
}

function combo_set_option_focus(menuID, optionIndex)
{
	var targetElt = document.getElementById(menuID+"_anchor_"+optionIndex);
	if (targetElt != null)
		targetElt.focus()
}

// global variable hack because you can't define arguments to the onclick function
var combo_scrolling = false;

function combo_anchorkeyuphandler(menuID)
{
	// on a up/down arrow, open up the menu
	if (window.event.keyCode == 38 || window.event.keyCode == 40)
	{
		// if it's already visible entry
		var el = document.getElementById(menuID);
		if (el != null && el != visibleSubMenu)
			combo_show(menuID);
	}
}

function combo_anchorkeydownhandler(menuID)
{
	// on a tab, close up the menu
	if (window.event.keyCode == 9)
	{
		combo_hide(menuID);
	}
}

function combo_anchorfocus(menuID)
{
	var el = document.getElementById("root" + menuID);
	if (el == null)
		return;
	if (el.className == "combo_table_disabled")
		return;
		
	document.getElementById("text" + menuID).className = "combo_option_selected";
}

function combo_anchorblur(menuID)
{
	document.getElementById("text" + menuID).className = "combo_text";
}

function combo_hide()
{
	submenu_hide();
}

function combo_optionkeyhandler(el)
{
	// identify the combo container and index
	var comboName = el.style.VSComboContainer;
	var comboIndex = parseInt(el.style.VSComboIndex, 10);
	var targetIndex;
	
	//window.alert(window.event.keyCode);
	
	if (window.event.keyCode == 38) 
	{
		targetIndex = comboIndex - 1;
	}
	if (window.event.keyCode == 40) 
	{
		targetIndex = comboIndex + 1;
	}
	
	//window.alert("looking for combo_"+comboName+"_option_"+targetIndex);	
	
	var targetElt = document.getElementById("combo_"+comboName+"_anchor_"+targetIndex);
	if (targetElt != null)
	{
		targetElt.focus();
		
		var targetOptionElt = document.getElementById("combo_"+comboName+"_option_"+targetIndex);
		combo_scrolling = true;
		targetOptionElt.onclick();
		combo_scrolling = false;
	}
}

function combo_optionkeydownhandler(menuID)
{
	// on a tab, close up the menu
	if (window.event.keyCode == 9)
	{
		combo_hide(menuID);
	}
}

function combo_option(el, formfield, val, textval)
{
	var formEl = document.getElementById(formfield);
	if (formEl == null)
		return;
		
	formEl.value = val;
	document.getElementById("textcombo_" + formfield).innerHTML = textval;
	
	if (formEl.onchange != null)
		formEl.onchange();
		
	el.className = "combo_option_selected";
	
	var rootComboEl = document.getElementById("rootcombo_" + formfield);
	if (rootComboEl != null)
		rootComboEl.style.VSComboSelectedIndex = el.style.VSComboIndex;
	
	if (!combo_scrolling) {
		combo_hide();
		document.getElementById("anchorcombo_" + formfield).focus();
	}
}

function combo_mouseover(el)
{
	if (el == null) return;
	var elId = el.id;
	var a = elId.lastIndexOf("_");
	var i;
	for (i = 0; i >= 0; i++)
	{
		var elt = document.getElementById(elId.substring(0, a+1) + i);
		if (elt != null) {
			elt.className = "combo_option";
		} else {
			i = -2;
		}
	}
	
	el.className = "combo_option_hovered";
}

function combo_mouseout(el)
{
	if (el.className == "combo_option_hovered")
		el.className = "combo_option";
}

function submenu_calcMenuTop(subMenu, menuID)
{
	var curEl = subMenu;
	var topVal = 0;
	while (curEl != null)
	{
		topVal += curEl.offsetTop;
		curEl = curEl.offsetParent;
	}
	
	var newMenu = document.getElementById(menuID);
	if (newMenu != null)
	{
		var docTop = 0;
		var screenHeight = 0;
		// ie
		if (document.all != null)
		{
			if (document.documentElement.clientHeight != null)
			{
				docTop = document.documentElement.scrollTop;
				screenHeight = document.documentElement.clientHeight;
			}
			else
			{
				docTop = document.body.scrollTop;
				screenHeight = document.body.clientHeight;
			}
		}
		// netscape or mozilla
		else
		{
			docTop = window.pageYOffset;
				screenHeight = window.innerHeight;
		}
			
		if (topVal - docTop + newMenu.offsetHeight > screenHeight)
			topVal -= newMenu.offsetHeight - 21;

		if (topVal < docTop)
			topVal = docTop - 2;
	}
	
	return topVal;
}

function submenu_calcMenuLeft(subMenu)
{
	var curEl = subMenu;
	var leftVal = 0;
	while (curEl != null)
	{
		leftVal += curEl.offsetLeft;
		curEl = curEl.offsetParent;
	}

	return leftVal;
}

function submenu_keypressopen(el, menuID)
{
	// if the key is left arrow, open the menu
	if (window.event.keyCode == 39)
	{
		var containingTable = el.offsetParent.offsetParent;
		if (containingTable != null)
		{
			submenu_onmouseover(containingTable, menuID);
			containingTable.focus;
		}
	}
}

function submenu_tabfocusin(el, menuID)
{
	menu_onmouseover(el);
}

function submenu_tabfocusout(el, menuID)
{
	var focusEl = document.activeElement;
	
	var menuCell = menuFindParentCell(focusEl);
	if (menuCell != null)
	{
		var activeMenuID = menuCell.style.VSMenuContainer;
		if (activeMenuID == menuID)
			return false;
	}
		
	var containingTable = el.offsetParent.offsetParent;
	if (containingTable != null)
		submenu_onmouseout(containingTable, menuID);
}

function submenu_adjustDimensions(subMenu)
{
	maxHeight = parseInt(subMenu.style.customHeight);
	maxWidth  = parseInt(subMenu.style.customWidth);
	bHorScroll  = (subMenu.style.customScroll == "XScroll" || subMenu.style.customScroll == "XYScroll") ? true : false;
	bVerScroll  = (subMenu.style.customScroll == "YScroll" || subMenu.style.customScroll == "XYScroll") ? true : false;

	hScrollAdded = false;

	if (maxWidth > 0)
	{
		if (bHorScroll)
		{
			// see if we need to validate the maximum width requirements
			if (maxWidth > 0)
			{
				if (subMenu.offsetWidth > maxWidth)
				{
					subMenu.style.width = maxWidth + "px";
					subMenu.style.overflowX = "auto";
	
					// adjust maxWidth with the new value of offsetWidth
					// This is required, so that we don't enter this function
					// as offsetWidth will always be a bit higher than maxWidth
					subMenu.style.customWidth = subMenu.offsetWidth;
	
					// add the scroll bar height to current size, because
					// otherwise in extreme case, when there is only one VM
					// and it has very long name, the horizontal scroll bar
					// will hide its name.
					subMenu.style.height = subMenu.offsetHeight + 16; // 16 is approximate height of scroll bar
	
					// So that we know we added a horizontal scroll bar
					hScrollAdded = true;
				}
			}
		}
		else
		{
            subMenu.style.width = (maxWidth + "px");
			subMenu.style.overflowX = "hidden";
		}
	}

	if (maxHeight > 0)		
	{
		if (bVerScroll)
		{
			// Now verify that we haven't exceeded maximum height
			if (subMenu.offsetHeight > maxHeight)
			{
				subMenu.style.height = maxHeight  + "px";
				subMenu.style.overflowY = "auto";
				
				// adjust the height so that we don't enter this path again
				// unless the page is refreshed
				subMenu.style.customHeight = subMenu.offsetHeight;

				// if we didn't add a horizontal scroll bar, that there may be
				// a case when all the VM are only one letter name, and in that
				// case, the scroll bar will hide their names, so we need to increase
				// the width
				if (hScrollAdded == false)
				{
					subMenu.style.width = subMenu.offsetWidth + 16; // 16 is approximate width of scroll bar
				}
			}
		}
		else
		{
		    subMenu.style.height = (maxHeight + "px");
			subMenu.style.overflowY = "hidden";
		}
	}
}

function submenu_onmouseover(el, menuID)
{
	menu_onmouseover(el);

	var subMenu = document.getElementById(menuID);
	if (subMenu == null)
		return;

	submenu_adjustDimensions(subMenu);

	// See if we should cancel a previous attempt to hide this menu.
	if (subMenu == visibleSubMenu)
	{
		reenterMenuCount++;
	}
	else
	{
		// Position the submenu relative to its parent menu		
		subMenu.style.top = submenu_calcMenuTop(el, menuID) + "px";
		subMenu.style.left = (submenu_calcMenuLeft(el) + el.offsetWidth) + "px";

		subMenuToShow = subMenu;
		setTimeout("submenu_deferredDisplaySubMenu(\'" + menuID + "\')", 100);
	}
}

function submenu_deferredDisplaySubMenu(menuID)
{
	var subMenu = document.getElementById(menuID);
	if (subMenu == null)
		return;

	if (subMenu == subMenuToShow)
	{
		if (visibleSubMenu != subMenuToShow)
		{
			submenu_hide();
			visibleSubMenu = subMenu;
			subMenuToShow = null;
			subMenu.style.visibility = "visible";

			if (onWindowsIE)
			{
				// Look for the submenu container.
				var container = subMenu;
				while (container != null && container.className != "submenu_container")
					container = container.parentElement;
				if (container == null)
					return;
				
				container.style.zIndex = 5;
				submenu_makeDropShadow(container);
			}
		}
	}
}

function submenu_onmouseout(el, menuID)
{
	menu_onmouseout(el);

	var subMenu = document.getElementById(menuID);
	if (subMenu == null)
		return;

	if (subMenu == visibleSubMenu)
	{
		subMenuToHide = subMenu;
		
		// Schedule the submenu to go away if we don't re-enter the
		// submenu before the timer fires.
		setTimeout("submenu_deferredHideSubMenu(\'" + menuID + "\', " + reenterMenuCount + ")", 100);
	}
	else if (subMenu == subMenuToShow)
	{
		subMenuToShow = null;
	}
}

function submenu_deferredHideSubMenu(menuID, outCount)
{
	var subMenu = document.getElementById(menuID);
	if (subMenu == null)
		return;

	if (visibleSubMenu == subMenuToHide && 
		subMenu == subMenuToHide && 
		outCount == reenterMenuCount)
	{
		submenu_hide();
	}
}

function submenu_hide()
{
	if (visibleSubMenu != null)
	{
		if (onWindowsIE)
			submenu_destroyDropShadow();

		visibleSubMenu.style.visibility = "hidden";
		visibleSubMenu = null;
		subMenuToHide = null;
	}
}

function submenu_makeDropShadow(subMenu)
{
	var rectIndex;
	
	for (rectIndex = 4; rectIndex > 0; rectIndex--)
	{
		var rect = document.createElement('div');
		var rectStyle = rect.style
		rectStyle.position = "absolute";
		rectStyle.left = (subMenu.style.posLeft + rectIndex) + 'px';
		rectStyle.top = (subMenu.style.posTop + rectIndex) + 'px';
		rectStyle.width = subMenu.offsetWidth + 'px';
		rectStyle.height = subMenu.offsetHeight + 'px';
		rectStyle.zIndex = subMenu.style.zIndex - rectIndex;
		rectStyle.backgroundColor = '#888888';
		var opacity = 1 - rectIndex / (rectIndex + 1);
		rectStyle.filter = "alpha(opacity = " + (100 * opacity) + ")";
		subMenu.insertAdjacentElement("afterEnd", rect);
		
		// Track the rects so we can destroy them later
		submenu_shadows[submenu_shadows.length] = rect;
	}
}

function submenu_destroyDropShadow()
{
	if (submenu_shadows != null)
	{
		var rectIndex;
		for (rectIndex = 0; rectIndex < submenu_shadows.length; rectIndex++)
			submenu_shadows[rectIndex].removeNode(true);
		submenu_shadows = new Array();
	}
}

// open help in new window (in "kiosk" mode)

function OpenHelp(helpFile)
{
	window.open(helpFile, '_blank', 'toolbar=0,status=0,menubar=0,scrollbars=1,resizable=1,width=260,height=' + Math.round(window.screen.availHeight*3/4));
	return false;
}

// listbox selection script

function listselect_setDirectoryPath(listID, textBoxID, checkRequireInput)
{
	var textBox = document.getElementById(textBoxID.id);
	var textBoxValue = textBox.value;
	var listBoxValue = document.getElementById(listID.id).value;

	// append a backslash if needed 
	if (listBoxValue.length > 0)
	{	
		if (listBoxValue.charAt(listBoxValue.length - 1) != '\\')
			listBoxValue = listBoxValue + "\\";
	}
	
	if (textBoxValue == "")
	{
		document.getElementById(textBoxID.id).value = listBoxValue;
	}
	else
	{
		var newTextBoxValue = "";
		// find up to the last backslash
		newTextBoxValue = textBoxValue.substring (textBoxValue.lastIndexOf ("\\") + 1, textBoxValue.length); 
		
		// append the listbox value with that value and replace
		newTextBoxValue = listBoxValue + newTextBoxValue;
		
		document.getElementById(textBoxID.id).value = newTextBoxValue;
	}
	
	if (checkRequireInput)
	{
		eval("RequireInput_" + textBoxID.id + " (false)");
	}
	
	// Set the selection to the end of the text box so the user can fill
	// in the rest of the path.
	textBox.focus();
	var selectRange = textBox.createTextRange();
	selectRange.move("character", textBox.value.length);
	selectRange.select();
	
	return true;
}


function listselect_setFilePath(listID, textBoxID, checkRequireInput)
{
	var listBoxValue = listID.value;
	
	document.getElementById(textBoxID.id).value = listBoxValue;
	
	if (checkRequireInput)
	{
		eval("RequireInput_" + textBoxID.id + " (false)");
	}

	return true;
}


// numeric only input box scripts

function checkClipboardCode(objEvent, strKey) 
{
	var reClipboardChars = /[cvxz]/i;

	if (!onWindowsIE)
		return objEvent.ctrlKey && reClipboardChars.test(strKey);
	else
		return false;
}

function isValid(strValue, allow) 
{
	if (allow == 2)
	{
		var reValidFloatString = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
		return reValidFloatString.test(strValue) || 
			strValue.length == 0;
	}
	else if (allow == 1)
	{
		var reValidIPString = /^[0123456789ABCDEFabcdef:-]+$/;
		return reValidIPString.test(strValue) || 
			strValue.length == 0;
	}
	else
	{
		var reValidString = /^\d*$/;
		return reValidString.test(strValue) || 
    		strValue.length == 0;
    }
}

function input_maskKeyPressSize(objEvent) 
{
	var selectionList = document.forms["form1"].vhdSizeScale;

	if (selectionList.value == "MB")
	{
		return input_maskKeyPress(objEvent);
	}
	else
	{
		return input_maskKeyPressFloat(objEvent);
	}
}

function input_maskChangeSize(objEvent) 
{
	var selectionList = document.forms["form1"].vhdSizeScale;

	if (selectionList.value == "MB")
	{
		return input_maskChange(objEvent);
	}
	else
	{
		return input_maskChangeFloat(objEvent);
	}
}


function input_maskPasteSize(objEvent) 
{
	var selectionList = document.forms["form1"].vhdSizeScale;

	if (selectionList.value == "MB")
	{
		return input_maskPaste(objEvent);
	}
	else
	{
		return input_maskPasteFloat(objEvent);
	}
}

var reKeyboardChars = /[\x00\x08\x0D]/;      
var reValidChars = /^\d/;
var reValidFloatChars = /^[0123456789.]/;
var reValidIPChars = /^[0123456789ABCDEFabcdef:-]/;

function input_maskKeyPressIP(objEvent) 
{
	
	var iKeyCode, strKey, objInput;  
	       
	if (onWindowsIE) 
	{
		iKeyCode = objEvent.keyCode;
		objInput = objEvent.srcElement;
	} else {
		iKeyCode = objEvent.which;
		objInput = objEvent.target;
	}
	       
	strKey = String.fromCharCode(iKeyCode);

	if (isValid(objInput.value, 1)) 
	{
		objInput.validValue = objInput.value;

		if (!reValidIPChars.test(strKey) &&
	 		!reKeyboardChars.test(strKey) && 
	  		!checkClipboardCode(objEvent, strKey)) 
	  	{
			return false;
		}
	} 
	else 
	{
		return false;
	}
	
	return true;
}

function input_maskChangeIP(objEvent) 
{
	var objInput;
	    
	// if ie
	if (onWindowsIE)
		objInput = objEvent.srcElement; 
	else
		objInput = objEvent.target;
	     
	if (!isValid(objInput.value, 1)) 
	{
		objInput.value = objInput.validValue || "";
		objInput.focus();
		objInput.select(); 
	}
	else 
	{
		objInput.validValue = objInput.value;
	}
}


function input_maskPasteIP(objEvent) 
{
	var strPasteData = window.clipboardData.getData("Text");
	var objInput = objEvent.srcElement;
	
	if (!isValid(strPasteData, 1)) 
	{
		objInput.focus();
		return false;
	}
}

function input_maskKeyPressFloat(objEvent) 
{
	
	var iKeyCode, strKey, objInput;  
	       
	if (onWindowsIE) 
	{
		iKeyCode = objEvent.keyCode;
		objInput = objEvent.srcElement;
	} else {
		iKeyCode = objEvent.which;
		objInput = objEvent.target;
	}
	       
	strKey = String.fromCharCode(iKeyCode);

	if (isValid(objInput.value, 2)) 
	{
		objInput.validValue = objInput.value;

		if (!reValidFloatChars.test(strKey) &&
	 		!reKeyboardChars.test(strKey) && 
	  		!checkClipboardCode(objEvent, strKey)) 
	  	{
			return false;
		}
	} 
	else 
	{
		return false;
	}
	
	return true;
}

function input_maskChangeFloat(objEvent) 
{
	var objInput;
	    
	// if ie
	if (onWindowsIE)
		objInput = objEvent.srcElement; 
	else
		objInput = objEvent.target;
	     
	if (!isValid(objInput.value, 2)) 
	{
		objInput.value = objInput.validValue || "";
		objInput.focus();
		objInput.select(); 
	}
	else 
	{
		objInput.validValue = objInput.value;
	}
}


function input_maskPasteFloat(objEvent) 
{
	var strPasteData = window.clipboardData.getData("Text");
	var objInput = objEvent.srcElement;
	
	if (!isValid(strPasteData, 2)) 
	{
		objInput.focus();
		return false;
	}
}

function input_maskKeyPress(objEvent) 
{
	var iKeyCode, strKey, objInput;  
	       
	if (onWindowsIE) 
	{
		iKeyCode = objEvent.keyCode;
		objInput = objEvent.srcElement;
	} else {
		iKeyCode = objEvent.which;
		objInput = objEvent.target;
	}
	       
	strKey = String.fromCharCode(iKeyCode);

	if (isValid(objInput.value, 3)) 
	{
		objInput.validValue = objInput.value;

		if (!reValidChars.test(strKey) &&
	 		!reKeyboardChars.test(strKey) && 
	  		!checkClipboardCode(objEvent, strKey)) 
	  	{
			return false;
		}
	} 
	else 
	{
		return false;
	}
	
	return true;
}

function input_maskChange(objEvent) 
{
	var objInput;
	    
	// if ie
	if (onWindowsIE)
		objInput = objEvent.srcElement; 
	else
		objInput = objEvent.target;
	     
	if (!isValid(objInput.value, 3)) 
	{
		objInput.value = objInput.validValue || "";
		objInput.focus();
		objInput.select(); 
	}
	else 
	{
		objInput.validValue = objInput.value;
	}
}


function input_maskPaste(objEvent) 
{
	var strPasteData = window.clipboardData.getData("Text");
	var objInput = objEvent.srcElement;
	
	if (!isValid(strPasteData, 3)) 
	{
		objInput.focus();
		return false;
	}
}

// limit the text length in a text area element
function textarea_diskpathfilterandlimittext(objEvent, maxlimit)
{
	var iKeyCode, strKey, objInput;  
	       
	if (onWindowsIE) 
	{
		iKeyCode = objEvent.keyCode;
		objInput = objEvent.srcElement;
	} else {
		iKeyCode = objEvent.which;
		objInput = objEvent.target;
	}
	
	strKey = String.fromCharCode(iKeyCode);
	
	var reKeyboardChars = /[\x0D]/; 
	
	if (reKeyboardChars.test(strKey))
		return false; 

	if (objInput.value.length >= maxlimit) 
	{
		objInput.value = objInput.value.substring(0, maxlimit);
		return false;
	}
		
	return true;
}

// confirm with user before transferring to specified URL
function confirmDialog(prompt, destinationURL)
{
	if (confirm(prompt))
		window.location = EscapeQueryURL(destinationURL);
}

// confirm a user action before setting the action input tag and
// submitting the form
function confirmAction(prompt, formID)
{	
	// display a prompt to the user to see if they want to continue
	// with the pending action
	if (confirm(prompt))
	{	
		// submit the form so that the action can be processed
		document.getElementById(formID).submit();
	}
}

// enable or disable settings depending on the disconnect idle connections checkbox
function enableDisableDisconnectIdleConnectionsSettings()
{
	var	disableFormElement = !document.getElementById("vmrcEnableIdleTimeout").checked;
	
	// enable or disable the idle timeout text input
	document.getElementById("vmrcIdleTimeout").disabled = disableFormElement;
}

// enable or disable the VMRC SSL certificate settings form elements
function enableDisableSSLCertificateSettings(hasCert)
{
	var	useSSL = document.getElementById("vmrcUseEncryption").checked;

	var keepCert = document.getElementById("vmrcSSLCertificateAction_Keep");
	var requestCert = document.getElementById("vmrcSSLCertificateAction_Request");
	var useCert = document.getElementById("vmrcSSLCertificateAction_Use");
	var deleteCert = document.getElementById("vmrcSSLCertificateAction_Delete");
	
	if (useSSL)
	{
		// We can only keep or delete, if we already have
		// certificates
		keepCert.disabled = !hasCert;
		deleteCert.disabled = !hasCert;

		// We can upload or request new certificate always
		requestCert.disabled = false;
		useCert.disabled = false;
	}
	else
	{
		keepCert.disabled = true;
		requestCert.disabled = true;
		useCert.disabled = true;
		deleteCert.disabled = true;
	}

	var isRequestCertSelected = (useSSL && requestCert.checked);

	document.getElementById("vmrcSSLCertificateCommonName").disabled 					= !isRequestCertSelected;
	document.getElementById("vmrcSSLCertificateOrganization").disabled			 		= !isRequestCertSelected;
	document.getElementById("vmrcSSLCertificateUnit").disabled 							= !isRequestCertSelected;
	document.getElementById("vmrcSSLCertificateCity").disabled 							= !isRequestCertSelected;
	document.getElementById("vmrcSSLCertificateState").disabled 						= !isRequestCertSelected;
	document.getElementById("vmrcSSLCertificateCountry").disabled 						= !isRequestCertSelected;


	if (isRequestCertSelected)
	{
		combo_enable("combo_vmrcSSLCertificateStateSelector");
		combo_enable("combo_vmrcSSLCertificateCountrySelector");
		combo_enable("combo_vmrcSSLCertificateKeyLength");
	}
	else
	{
		combo_disable("combo_vmrcSSLCertificateStateSelector");
		combo_disable("combo_vmrcSSLCertificateCountrySelector");
		combo_disable("combo_vmrcSSLCertificateKeyLength");
	}


	var isUseCertSelected = (useSSL && useCert.checked);

	document.getElementById("vmrcSSLCertificateFile").disabled 				= !isUseCertSelected;
}

// enable or disable administrator or per-VM remote control settings form elements
// depending on whether VMRC is currently enabled
function enableDisableRemoteControlSettings()
{
	var		disableFormElement = !(document.getElementById("vmrcEnabled").checked);
	var		disableIdleTimeout = !document.getElementById("vmrcEnableIdleTimeout").checked;
	
	
	document.getElementById("vmrcPortNumber").disabled = disableFormElement;
	document.getElementById("vmrcUseEncryption").disabled = disableFormElement;
	document.getElementById("vmrcEnableIdleTimeout").disabled = disableFormElement;
	document.getElementById("vmrcIdleTimeout").disabled = disableFormElement || disableIdleTimeout;
	
	if (disableFormElement)	
	{
		combo_disable("combo_vmrcIPAddress");
		combo_disable("combo_vmrcResolution");
		combo_disable("combo_vmrcAuthentication");
	} 
	else
	{
		combo_enable("combo_vmrcIPAddress");
		combo_enable("combo_vmrcResolution");
		combo_enable("combo_vmrcAuthentication");
	}
	
	enableDisableSSLCertificateSettings();
}

// fill in the specified text input with the specified value
function onChangeSSLCertificateSelector(inputId,value)
{
	var inputTag = document.getElementById(inputId);
	inputTag.value = value;
}

// enable or disable DHCP settings form elements
function enableDisableDHCPSettings()
{
	var		disableFormElement = !(document.getElementById("dhcpEnabled").checked);
	
	document.getElementById("dhcpNetworkAddress").disabled = disableFormElement;
	document.getElementById("dhcpNetworkMask").disabled = disableFormElement;
	document.getElementById("dhcpStartingIP").disabled = disableFormElement;
	document.getElementById("dhcpEndingIP").disabled = disableFormElement;
	document.getElementById("dhcpVirtualDHCPServerAddress").disabled = disableFormElement;
	document.getElementById("dhcpDefaultGatewayAddress").disabled = disableFormElement;
	document.getElementById("dhcpDNSServers").disabled = disableFormElement;
	document.getElementById("dhcpWINSServers").disabled = disableFormElement;
	document.getElementById("dhcpIPAddressLeaseTime").disabled = disableFormElement;
	document.getElementById("dhcpLeaseRenewalTime").disabled = disableFormElement;
	document.getElementById("dhcpLeaseRebindingTime").disabled = disableFormElement;

	if (disableFormElement)	
	{
		combo_disable("combo_leaseTimeList");
		combo_disable("combo_leaseRenewalTimeList");
		combo_disable("combo_leaseRebindingTimeList");
	} 
	else
	{
		combo_enable("combo_leaseTimeList");
		combo_enable("combo_leaseRenewalTimeList");
		combo_enable("combo_leaseRebindingTimeList");
	}
}

// enable or disable recent event settings
function enableDisableRecentEventSettings()
{
	var		disableFormElement = !(document.getElementById("show").checked);
	
	document.getElementById("error").disabled = disableFormElement;
	document.getElementById("warning").disabled = disableFormElement;
	document.getElementById("info").disabled = disableFormElement;
	document.getElementById("eventLogPreviewFetchAmount").disabled = disableFormElement;
}

// enable or disable auto start vm settings
function enableDisableAutoStartSettings()
{
	if (document.getElementById("autoStart").value == "neverAutoStart")
		document.getElementById("autoStartDelay").disabled = true;
	else
		document.getElementById("autoStartDelay").disabled = false;
}

// calculate the size value for the disk image
// depending on the format selected
function calculateDiskImageSize()
{
	var currentSize = 0;
	if (document.forms["form1"].vhdSize.value != "")
		currentSize = parseFloat(document.forms["form1"].vhdSize.value);
	var formatList = document.forms["form1"].vhdFormat;
	var formatLabelValue = parseFloat(formatList.options[formatList.selectedIndex].label);
	var selectionList = document.forms["form1"].vhdSizeScale;

	if (selectionList.options[selectionList.selectedIndex].value == "GB")
	{
		currentSize = currentSize*1024;
	}
	
	if (currentSize > formatLabelValue)
	{	
		if (selectionList.options[selectionList.selectedIndex].value == "GB")
			formatLabelValue = formatLabelValue/1024;			
		document.forms["form1"].vhdSize.value = formatLabelValue
	}	
}


// enable or disable new folder entry box based on whether folder sharing is turned on.
function enableDisableNewFolderShare()
{
	var		disableFormElement = !(document.getElementById("folderSharingEnabled").checked);
	
	if (document.getElementById("newSharedFolder"))
		document.getElementById("newSharedFolder").disabled = disableFormElement;
}


function enableDisableAfterCredentialCheckbox()
{
	var		isDisabled = !document.getElementById("credStorEnabled").checked;
	
	document.getElementById("username").disabled = isDisabled;
	document.getElementById("password").disabled = isDisabled;
	if (isDisabled)
		combo_disable("combo_autoStart");
	else
		combo_enable("combo_autoStart");
	
	// The auto start delay is governed by both the credStorEnabled checkbox
	// and by the auto start value. Therefore, if the checkbox is clicked,
	// then the function enableDisableAutoStartSettings handles the auto
	// start value functionality.
	if (!isDisabled)
		enableDisableAutoStartSettings();
	else
		document.getElementById("autoStartDelay").disabled = isDisabled;
}
	

// escape a URL string that contains query information
function EscapeQueryURL(url)
{
	var	queryStart = url.indexOf('?');
	
	if (queryStart == -1)
	{
		// this URL has no query string appended to it
		return encodeURI(url);
	}
	
	// get base URL up to and including '?'
	var	baseURL = encodeURI(url.substring(0, queryStart+1));
	
	// get query string just past the '?'
	var query = url.substring(queryStart+1);
	
	var	keyPair, keyName, keyValue;
	var	replacePlusEscapeRegExp = new RegExp("%2B", "g");
	
	// parse out each name value pair
	while (query.indexOf('&') > -1)
	{
		// set keyPair to "name=value"
		keyPair = query.substring(0, query.indexOf('&'));
		
		// make sure this is in "name=value" format
		if (keyPair.indexOf('=') > -1)
		{
			// get name and value
			keyName = keyPair.substring(0, keyPair.indexOf('='));
			keyValue = keyPair.substring(keyPair.indexOf('=')+1);
			
			// encode name and value components separately
			// also, undo any encoding of '+' to '%2B' done by encodeURIComponent()
			baseURL += encodeURIComponent(keyName).replace(replacePlusEscapeRegExp, '+') +
				'=' + encodeURIComponent(keyValue).replace(replacePlusEscapeRegExp, '+');
		}
		
		// skip past the '&' following this name value pair
		query = query.substring((query.indexOf('&')) + 1);
		
		// if there another pair?
		if (query.indexOf('&') > -1)
		{
			// yes, separate pairs with '&'
			baseURL += '&';
		}
	}
	
	// at this point, query contains the final name value pair
	if (query.indexOf('=') > -1)
	{
		keyName = query.substring(0, query.indexOf('='));
		keyValue = query.substring(query.indexOf('=')+1);

		// encode name and value components separately
		// also, undo any encoding of '+' to '%2B' done by encodeURIComponent()
		baseURL += '&' + encodeURIComponent(keyName).replace(replacePlusEscapeRegExp, '+') + 
			'=' + encodeURIComponent(keyValue).replace(replacePlusEscapeRegExp, '+');
	}
	
	return baseURL;		
}


// Events used for COM Port Page

var g_PressedAddButton = false;

function
OnComPortPageSubmit(saveButtonName)
{
	return true;
}

function
OnComPortPageFocusAdd()
{
	g_PressedAddButton = true;
}

function
OnComPortPageFocusOutAdd()
{
	g_PressedAddButton = false;
}


/*****************************************************
 * Code to validate Named Pipes
 *
 * Validates the named pipe string
 ****************************************************/

function ValidateNamedPipeString(
	inPipeRadioID, 
	inPipeNameID,
	inErrorString )
{
	var radioButton = document.getElementById(inPipeRadioID);
	var text = document.getElementById(inPipeNameID).value;

	if (radioButton.checked)
	{
		// Correct syntax: \\<computer name>\pipe\<pipename>
		var possibleErrorString = "\"" + text + "\"\n\n" + inErrorString;
		if (text.length < 10)
		{
			alert(possibleErrorString);
			return false;
		}
		// Make sure the first two \\ exist
		else if (text.charAt(0) != '\\' || text.charAt(1) != '\\')
		{
			alert(possibleErrorString);
			return false;
		}
		else
		{
			var currentChar = 2;
			
			// Look for the computer name
			while (currentChar <= text.length)
			{
				if (text.charAt(currentChar) == '\\')
				{
					// Make sure there was a computer name
					if (currentChar == 2)
					{
						alert(possibleErrorString);
						return false;
					}
					
					break;
				}
				else if (currentChar == text.length)
				{
					alert(possibleErrorString);
					return false;
				}
				
				currentChar += 1;
			}
			
			// Look for the "pipe\"
			if (text.charAt(currentChar+1) != 'p' ||
				text.charAt(currentChar+2) != 'i' ||
				text.charAt(currentChar+3) != 'p' ||
				text.charAt(currentChar+4) != 'e' ||
				text.charAt(currentChar+5) != '\\')
			{
				alert(possibleErrorString);
				return false;
			}
			else
				currentChar += 5;
				
			// Make sure there's a pipe name
			if (currentChar >= (text.length - 1))
			{
				alert(possibleErrorString);
				return false;
			}	
		}
	}
	
	return true;
}

/* ********************************************
 * Helper routines (General Purpose)
 * *******************************************/

// Convert IP address given in 4 bytes form to Int
function StringIPToInt(b1, b2, b3, b4)
{
	return	b1 * 16777216 	+ 	// 2^24
			b2 * 65536 		+	// 2^16
			b3 * 256		+	// 2^8
			b4 * 1;				// 2^0
}




// Convert IP address from a 32 bit integer to xxx.xxx.xxx.xxx form
function IntIPToString(IP)
{
	// return ((IP & 65535) >> 8);
	
	return 	(IP >>> 24) 				+ '.' + 
			((IP & 16777215) >>> 16) + '.' + 	// 2^24 - 1 (right 23 bits all ones)
			((IP & 65535) >>> 8) 	+ '.' +		// 2^16 - 1
			(IP & 255); 						// 2^8 - 1
	
}



function GetCheckBox(
	inName,
	inIndex )
{
	var checkboxId = inName + " " + inIndex;
	return document.getElementById(checkboxId);
}


function CheckBoxIfPresent(
	inName,
	inIndex )
{
	var checkbox = GetCheckBox(inName,inIndex);
	if (checkbox != null)
		checkbox.checked = true;
}

function fullAccessClicked(
	inChecked,
	inIndex )
{
	if ( inChecked )
	{
		CheckBoxIfPresent("write",inIndex);
		CheckBoxIfPresent("read",inIndex);
		CheckBoxIfPresent("execute",inIndex);
		CheckBoxIfPresent("delete",inIndex);
		CheckBoxIfPresent("read_permissions",inIndex);
		CheckBoxIfPresent("change_permissions",inIndex);
	}
}

function uncheckFullAccess(
	inChecked,
	inIndex )
{
	if ( !inChecked )
	{
		var checkbox = GetCheckBox("full",inIndex);
		if (checkbox != null)
			checkbox.checked = false;
	}
}


