/*
* $Id$
*
* Copyright (c) 2001-2013 Avocent Corporation. All rights reserved.
*
* @file dataFunctions.js
* The file defines functions for generating request URI from HTML elements,
* sending POST request, getting response and saving the response value back to
* HTML elements.
*/
var AJAXDebug = 0;
var VAL_TRUE = "1";
var VAL_FALSE = "0";
var TOP_YES = "Yes"; // Yes
var TOP_NO = "No"; // no
var TOP_TRUE = "true"; // true
var TOP_FALSE = "false"; // false
var TOP_NONE = "None"; // none
var TOP_ENA = "Enabled"; // enabled
var TOP_DIS = "Disabled"; // disabled
var TOP_USR = "User"; // user
var TOP_OPR = "Operator"; // operator
var TOP_ADM = "Administrator"; // admin
var plsWaitMsg = "Please Wait"; // Please wait
var unknowExcMsg = "Unknown exception occurred during this operation."; // Unknown exception occurred during this operation.
var excMsg = "Unable to retrieve data. Please try again later."; // Unable to retrieve data. Please try again later.
var securityExcMsg = "Security exception occurred during this operation."; // Security exception occurred during this operation.
var badReqExcMsg = "Bad request format exception occurred during this operation."; // Bad request format exception occurred during this operation.
var requestCtxt = new Object();
requestCtxt.m_fieldMapping = null;
requestCtxt.updateComplete = null;
var FieldMapping;
FieldMapping.TYPE_HTML = 0; // Indicates the filed ia a HTML element other than the following.
FieldMapping.TYPE_TEXT = 1; // Indicates the filed is a HTML input element of text type.
FieldMapping.TYPE_TEXT_NUMERIC = 2; // Indicates the filed is a HTML input element of text type, whose content is numeric.
FieldMapping.TYPE_CHECKBOX = 3; // Indicates the filed is a HTML input element of checkbox type.
FieldMapping.TYPE_SELECT = 4; // Indicates the filed ia a HTML select element.
FieldMapping.TYPE_RADIO = 5; // Indicates the filed is a HTML input element of radio type.
FieldMapping.TYPE_CALLBACK = 6; // Indicates the filed content is updated by the function dataCallback() in each page.
var xmlRequestObject;
var Cell;
Cell.ICON = 0;
Cell.CONTENT = 1;
Cell.BLANK = 2;
Cell.HIDDEN = 3;
// For displaying local time.
var TIME_TITLE = 0; // Time string format for title bar.
var TIME_SESSION_LOG = 1; // time string format for session logs.
var TIME_SYSTEM_LOG = 2; // time string format for system event logs.
var TIME_SECURITY = 3; // time string format for certificate.
var TIME_POWER_GRAPH = 4; // time string format for power graph.
var TIME_CONSUMPTION = 5; // time string format for power consumption start date.
// BTS 71865: Flag indicating whether to show UTC time or local time.
var G_bIsToShowLocalTime = false;
var arrMonthName = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var MSG_TYPE_INFO = 0; // Indicates an info message
var MSG_TYPE_ERROR = 1; // Indicates an error message
/**
* Defines a class named Cell which performs as an HTML table cell.
*
* @param type - the content type of the table cell.
* @param value - the content of the table cell.
* @param align - the alignment type of the content of the table cell.
*/
function Cell(type, value, align)
{
this.m_type = type;
this.m_value = value;
this.m_align = align;
}
/**
* Defines a class named FieldMapping.
* Each field has a fieldName and a dataName.
*
* @param n - the field name.
* @param d - the field data.
* @param type - the type of the field.
* @param encoder - a pointer to the function which can encode the filed data.
* @param decoder - a pointer to the function which can decode the filed data.
* @note If there is no field name then the field is only accessed on edits.
* In this way a page can iterate through all values returned by
* the server to populate data for the page, but still skip element that
* have no display value that would otherwise cause a "field xxxx not found"
* message to be displayed.
*/
function FieldMapping( n, d, type, encoder, decoder )
{
// m_fieldName is used for displaying data.
this.m_fieldName = n;
// m_fieldOriginalValue is used for saving value of HTML element when page is loaded.
this.m_fieldOriginalValue = "";
// m_dataName is used for updating data.
if ( d == null )
{
this.m_dataName = n;
}
else
{
this.m_dataName = d;
}
if ( type == null )
{
this.m_type = FieldMapping.TYPE_HTML;
}
else
{
this.m_type = type;
}
if ( encoder == null )
{
this.m_encoder = encodeText;
}
else
{
this.m_encoder = encoder;
}
if ( decoder == null )
{
this.m_decoder = decodeText;
}
else
{
this.m_decoder = decoder;
}
}
/**
* Gets the FiledMapping object whose m_fieldName matches the specified field name.
*
* @param strFieldName - The specified field name.
* @return The FiledMapping object whose m_fieldName matches the specified field name.
* null if no FieldMapping objects matches the specified field name
*/
function getFieldMapByName(strFieldName)
{
if (strFieldName == null)
{
return (null);
}
for (var idx = 0; idx < fieldList.length; ++idx)
{
if (strFieldName == fieldList[idx].m_fieldName)
{
return (fieldList[idx]);
}
}
return (null);
}
/**
* Gets the value of a visible HTML element according to its element type.
*
* @param fieldMap - A pointer to the FieldMapping object.
* @return The value of the visible HTML element. null if the visible HTML element is not found.
* @note This function has dependency on validate.js because it uses some functions defined in validate.js.
* Please include validate.js in the html page when this function is used.
*/
function getHTMLFieldValue(fieldMap)
{
if (fieldMap == null)
{
return (null);
}
var objVisibleElement = null;
var iFieldType = fieldMap.m_type;
if (iFieldType == FieldMapping.TYPE_RADIO)
{
objVisibleElement = document.getElementsByName(fieldMap.m_fieldName);
if (objVisibleElement == null)
{
return (null);
}
for (var i = 0; i < objVisibleElement.length; i++)
{
if (objVisibleElement[i].checked == true)
{
return (objVisibleElement[i].value);
}
}
}
else
{
objVisibleElement = document.getElementById(fieldMap.m_fieldName);
if (objVisibleElement == null)
{
return (null);
}
if (iFieldType == FieldMapping.TYPE_HTML)
{
return (objVisibleElement.innerHTML);
}
else if (iFieldType == FieldMapping.TYPE_TEXT)
{
return (objVisibleElement.value);
}
else if (iFieldType == FieldMapping.TYPE_TEXT_NUMERIC)
{
if (isAHexValue(objVisibleElement.value))
{
return (convertHexToDec(objVisibleElement.value));
}
return (objVisibleElement.value);
}
else if (iFieldType == FieldMapping.TYPE_CHECKBOX)
{
return (objVisibleElement.checked);
}
else if (iFieldType == FieldMapping.TYPE_SELECT)
{
if (objVisibleElement.options == null)
{
return (null);
}
for (var i = 0; i < objVisibleElement.options.length; i++)
{
if (objVisibleElement.options[i].selected == true)
{
return (objVisibleElement.options[i].value);
}
}
}
}
return (null);
}
/**
* Sets original values of visible HTML elements.
*
* @note It seems to be more properly to save original values inside setFieldListFromXML().
* However in some pages such as Network Interface configuration, Services, some HTML elements are modified after
* calling setFieldListFromXML() therefore this function is isolated from setFieldListFromXML() so that we can
* make sure the settings saved are those displayed in WebGUI.
* In addition, this function has dependency on validate.js because it calls getHTMLFieldValue().
* Please include validate.js in the html page when this function is used.
*/
function setOriginalSettinigs()
{
for (var i = 0; i < fieldList.length; i++)
{
fieldList[i].m_fieldOriginalValue = getHTMLFieldValue(fieldList[i]);
}
}
/**
* Gets original value of the specified visible HTML element.
*
* @param strFieldName - The id attribute of the visible HTML element,
* or name attribute if its type is FieldMapping.TYPE_RADIO.
*
* @return Original value of the HTML element.
* null if any error occurs.
*/
function getOriginalSetting(strFieldName)
{
if (("" == strFieldName) || (strFieldName == null) || (strFieldName == undefined))
{
return (null);
}
for (var i = 0; i < fieldList.length; i++)
{
if (strFieldName == fieldList[i].m_fieldName)
{
return (fieldList[i].m_fieldOriginalValue);
}
}
return (null);
}
/**
* Checks if the values of visible HTML elements are changed.
*
* @param bIsToCompareDisabled - Indicate if to compare when the visible HTML element is disabled.
* @return true - Changed.
* @return false - Not changed.
* @note This function has dependency on validate.js because it calls isVisibleFieldChanged().
* Please include validate.js in the html page when this function is used.
*/
function isVisibleFieldListChanged(bIsToCompareDisabled)
{
for (var i = 0; i < fieldList.length; i++)
{
if (isVisibleFieldChanged(fieldList[i].m_fieldName, bIsToCompareDisabled))
{
return (true);
}
}
return (false);
}
/**
* Checks if the value of a visible HTML element is changed.
*
* @param strFieldName - The id of the visible HTML element to be checked.
* @param bIsToCompareDisabled - Indicate if to compare when the visible HTML element is disabled.
* @return true - The value is changed.
* @return false - The value is not changed, or the parameters are null,
* or the visible HTML element with id 'strFieldName' cannot be found.
* @note This function has dependency on validate.js because it may call getHTMLFieldValue().
* Please include validate.js in the html page when this function is used.
*/
function isVisibleFieldChanged(strFieldName, bIsToCompareDisabled)
{
if ((strFieldName == null) || (bIsToCompareDisabled == null))
{
return (false);
}
var objFiledMap = getFieldMapByName(strFieldName);
if (objFiledMap == null)
{
return (false);
}
var objVisibleElement = null;
var objVisibleValue = null;
if (objFiledMap.m_type == FieldMapping.TYPE_RADIO)
{
objVisibleElement = document.getElementsByName(objFiledMap.m_fieldName)[0];
}
else
{
objVisibleElement = document.getElementById(objFiledMap.m_fieldName);
}
if ((objVisibleElement.disabled) && (!bIsToCompareDisabled))
{
return (false);
}
objVisibleValue = getHTMLFieldValue(objFiledMap);
if (objFiledMap.m_fieldOriginalValue == objVisibleValue)
{
return (false);
}
return (true);
}
/**
* Creates and returns an object of FieldMapping with specific checkbox behaviors pre-defined.
*
* @param n - the field name.
* @param d - the field data.
* @return An object of FieldMapping with type of checkbox.
* @note Convenience object that "extends" FieldMapping with specific checkbox behaviors pre-defined.
*/
function CheckboxMapping( n, d )
{
return new FieldMapping(n, d, FieldMapping.TYPE_CHECKBOX, encodeCheckbox, decodeBoolean);
}
/**
* Creates and returns an object of FieldMapping with specific radio behaviors pre-defined.
*
* @param n - the field name.
* @param d - the field data.
* @return An object of FieldMapping with type of radio.
* @note Convenience object that "extends" FieldMapping with specific radio behaviors pre-defined.
*/
function RadioMapping( n, d )
{
return new FieldMapping(n, d, FieldMapping.TYPE_RADIO, encodeRadio, decodeRadio);
}
/**
* Encodes a text to URL format.
*
* @param text - the specified text string to be encoded.
* @return a string after URI encoded - the function succeeds.
* an empty string - any error occurs.
*/
function encodeSetValue( text )
{
if ( text == null )
{
return "";
}
else
{
var newUrl = text.replace(/\\/g, "\\\\" );
newUrl = newUrl.replace(/:/g, "\\:" );
/* ConnectionHandler's tokenizer uses: (),=&? */
newUrl = newUrl.replace(/,/g, "\\," );
newUrl = newUrl.replace(/\(/g, "\\(" );
newUrl = newUrl.replace(/\)/g, "\\)" );
newUrl = newUrl.replace(/\=/g, "\\=" );
newUrl = newUrl.replace(/&/g, "\\&" );
newUrl = newUrl.replace(/\?/g, "\\?" );
return (encodeURIComponent(newUrl));
}
}
/**
* Encodes the data of a text field.
*
* @param formElement - the field to be encoded.
* @return a string after URI encoded - the function succeeds.
* an empty string - any error occurs.
*/
function encodeText( formElement )
{
return (encodeSetValue( formElement.value ));
}
/**
* Encodes the data of a checkbox field.
*
* @param formElement - the field to be encoded.
* @return "1" (as true) - the checkbox is checked.
* "0" (as false) - the checkbox is unchecked.
*/
function encodeCheckbox( formElement )
{
if (formElement.checked)
{
return ("1");
}
else
{
return ("0");
}
}
/**
* Encodes the data of a select field.
*
* @param formElement - the field to be encoded.
* @return the value according to the index, or an empty string.
*/
function encodeSelect( formElement )
{
if ( formElement.selectedIndex >= 0 )
{
//alert("call to encodeSelect: " + formElement.options[ formElement.selectedIndex ].value);
return (formElement.options[ formElement.selectedIndex ].value);
}
else
{
return ('');
}
}
/**
* Encodes the data of a radio field.
*
* @param formElement - the field to be encoded.
* @return the value of the checked radio item, or an empty string.
*/
function encodeRadio( formElement )
{
for ( var i = 0 ; i < formElement.length ; ++i )
{
if ( formElement[i].checked )
{
return (formElement[i].value);
}
}
return ('');
//return formElement.options[ formElement.selectedIndex ].value;
}
/**
* Decodes the data of a select field.
*
* @param fieldMapping - the select field.
* @param value - the value to indicates the selected index.
*/
function decodeSelect( fieldMapping, value )
{
var selectedIndex = -1;
var elem = document.getElementById( fieldMapping.m_fieldName );
if ( (elem != null) && (elem.options != null) )
{
for ( var i = 0; i < elem.options.length; ++i )
{
if ( elem.options[i].value == value )
{
selectedIndex = i;
break;
}
}
elem.options.selectedIndex = selectedIndex;
}
}
/**
* Decodes the data of a text/html/select field.
*
* @param fieldMapping - the text/html/select field.
* @param value - the value to be saved to the field.
* @note The default decoder.
*/
function decodeText( fieldMapping, value )
{
var myVal = value;
if (value == null)
{
myVal = "";
}
if (( fieldMapping.m_type == FieldMapping.TYPE_TEXT ) ||
( fieldMapping.m_type == FieldMapping.TYPE_TEXT_NUMERIC))
{
setTextField( fieldMapping.m_fieldName, myVal );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_HTML )
{
setDiv( fieldMapping.m_fieldName, myVal );
//appendChild( fieldMapping.m_fieldName, myVal );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_SELECT )
{
setSelectedOption( fieldMapping.m_fieldName, myVal );
}
}
/**
* Decodes Encryption string values.
*
* @param fieldMapping - the text/html/checkbox field.
* @param value - the value to be saved to the field.
*/
function decodeEncryption( fieldMapping, value )
{
var myVal = value;
if (value == null)
{
myVal = "";
}
if (( fieldMapping.m_type == FieldMapping.TYPE_TEXT ) ||
( fieldMapping.m_type == FieldMapping.TYPE_TEXT_NUMERIC ))
{
setTextField( fieldMapping.m_fieldName, myVal );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_HTML )
{
setDiv( fieldMapping.m_fieldName, myVal );
}
else if( fieldMapping.m_type == FieldMapping.TYPE_CHECKBOX )
{
var bVal = "1"; // true
if ( (myVal == "NONE") || (myVal == "0") || (myVal == "") )
{
bVal = "0"; // false
}
setCheckbox( fieldMapping.m_fieldName, bVal );
}
}
/**
* Decodes boolean type value to either Yes or None.
*
* @param fieldMapping - the text/html/checkbox field.
* @param value - the value to be decoded and saved to the field.
* @note The default decoder.
*/
function decodeBooleanNoneYes( fieldMapping, value )
{
//alert("Decode bool yes/no: " + value );
var strYesNone = "";
if ( value == true )
{
strYesNone = TOP_YES;
}
else
{
strYesNone = TOP_NONE;
}
if (( fieldMapping.m_type == FieldMapping.TYPE_TEXT ) ||
( fieldMapping.m_type == FieldMapping.TYPE_TEXT_NUMERIC ))
{
setTextField( fieldMapping.m_fieldName, strYesNone );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_HTML )
{
setDiv( fieldMapping.m_fieldName, strYesNone );
//appendChild( fieldMapping.m_fieldName, value == true ? "Yes" : "None" );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_CHECKBOX )
{
setCheckbox( fieldMapping.m_fieldName, value );
}
}
/**
* Decodes boolean type value to either Yes or No.
*
* @param fieldMapping - the text/html/checkbox field.
* @param value - the value to be decoded and saved to the field.
*/
function decodeBoolean( fieldMapping, value )
{
//alert("Decode bool yes/no: " + value );
var strYesNo = "";
if ( value == true )
{
strYesNo = TOP_YES;
}
else
{
strYesNo = TOP_NO;
}
if (( fieldMapping.m_type == FieldMapping.TYPE_TEXT ) ||
( fieldMapping.m_type == FieldMapping.TYPE_TEXT_NUMERIC ))
{
setTextField( fieldMapping.m_fieldName, strYesNo );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_HTML )
{
setDiv( fieldMapping.m_fieldName, strYesNo );
//appendChild( fieldMapping.m_fieldName, strYesNo );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_CHECKBOX )
{
setCheckbox( fieldMapping.m_fieldName, value );
}
}
/**
* Decodes boolean type value to either true or false.
*
* @param fieldMapping - the text/html/checkbox field.
* @param value - the value to be decoded and saved to the field.
*/
function decodeBooleanTrueFalse( fieldMapping, value )
{
var strTrueFalse = "";
if ( value == true )
{
strTrueFalse = TOP_TRUE;
}
else
{
strTrueFalse = TOP_FALSE;
}
if (( fieldMapping.m_type == FieldMapping.TYPE_TEXT ) ||
( fieldMapping.m_type == FieldMapping.TYPE_TEXT_NUMERIC ))
{
setTextField( fieldMapping.m_fieldName, strTrueFalse );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_HTML )
{
setDiv( fieldMapping.m_fieldName, strTrueFalse );
//appendChild( fieldMapping.m_fieldName, strTrueFalse );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_CHECKBOX )
{
setCheckbox( fieldMapping.m_fieldName, value );
}
}
/**
* Decodes boolean type value to either Enabled or Disabled.
*
* @param fieldMapping - the text/html/checkbox field.
* @param value - the value to be decoded and saved to the field.
*/
function decodeBooleanEnabledDisabled( fieldMapping, value )
{
var strEnabledDisabled = "";
if ( value == true )
{
strEnabledDisabled = TOP_ENA;
}
else
{
strEnabledDisabled = TOP_DIS;
}
if (( fieldMapping.m_type == FieldMapping.TYPE_TEXT ) ||
( fieldMapping.m_type == FieldMapping.TYPE_TEXT_NUMERIC ))
{
setTextField( fieldMapping.m_fieldName, strEnabledDisabled );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_HTML )
{
setDiv( fieldMapping.m_fieldName, strEnabledDisabled );
//appendChild( fieldMapping.m_fieldName, strEnabledDisabled );
}
else if ( fieldMapping.m_type == FieldMapping.TYPE_CHECKBOX )
{
setCheckbox( fieldMapping.m_fieldName, value );
}
}
/**
* Decodes radio field value.
*
* @param fieldMapping - the radio field.
* @param value - the value to be decoded and saved to the field.
*/
function decodeRadio( fieldMapping, value )
{
if ( value == null )
{
return;
}
var elemList = document.getElementsByName( fieldMapping.m_fieldName );
if ( elemList == null )
{
return;
}
for ( var i = 0; i < elemList.length; ++i )
{
if ( elemList[i].value == value )
{
elemList[i].checked = true;
break;
}
}
}
/**
* Saves the XML element value to the relating field.
*
* @param xmlDoc - a pointer to the XML Document object.
* @note TODO: this can be refactored into waitWithCallback.
*/
function setFieldListFromXML(xmlDoc)
{
if (xmlDoc == null)
{
/*
* Request failed
* TODO: disable screen?
*/
}
else
{
// Set the fields.
for ( var i = 0; i < fieldList.length; ++i )
{
var dataName = fieldList[i].m_dataName;
var paramValue = getXMLValue( xmlDoc, dataName );
if ( fieldList[i].m_type == FieldMapping.TYPE_CALLBACK )
{
dataCallback( fieldList[i], paramValue, xmlDoc );
}
else
{
fieldList[i].m_decoder( fieldList[i], paramValue );
}
}
}
hideElement( 'progressScreen' );
showInlineElement( 'contentArea' );
}
/**
* Formats and displays progress panel.
*/
function formatProgressPanel()
{
var txt = '
'
+ '| ' + plsWaitMsg + '... |
'
+ ' '
+ '
|
';
document.write( txt );
}
/**
* Formats message panel.
*/
function formatMsgPanel()
{
var strMsgHeader = "Message";
var strMsgFooterHide = "Hide Message";
var strHTMLMsgPanel = ''
+ ''
+ ''
+ '';
document.write(strHTMLMsgPanel);
}
/**
* Displays progress image in place of the content panel.
*/
function showProgressPanel()
{
disableAllButtons();
hideElement( 'contentArea' );
showProgressBlockElement('progressScreen');
}
/**
* Displays progress element even if form already loaded.
*
* @param elemName - the element name.
*/
function showProgressBlockElement( elemName )
{
var elem = document.getElementById( elemName );
if ( (elem == null) || (elem['style'] == null) )
{
//alert('Missing element ' + elemName );
}
else
{
var txt = '
'
+ '| '+plsWaitMsg+'... |
'
+ ' '
+ '
|
';
}
elem.innerHTML = txt;
elem.style.display = 'block';
}
/**
* Displays the content panel in place of the progress panel.
*/
function showContentPanel()
{
hideElement( 'progressScreen' );
showInlineElement( 'contentArea' );
enableAllButtons();
hideElement( 'msgPanel' );
}
/**
* Sends POST GET request got from the fields pre-defined.
*
* @param renderPageCallback - a pointer to the callback function.
*/
function loadData( renderPageCallback )
{
var reqUrl = 'data?get=';
for ( var i = 0; i < fieldList.length; ++i )
{
reqUrl += fieldList[i].m_dataName + ',';
}
loadDataURL( reqUrl, renderPageCallback );
}
/**
* Sends POST request.
*
* @param reqUrl - the request URL.
* @param postData - the properties to request.
* @param renderPageCallback - a pointer to the callback function.
*/
function sendPost( reqUrl, postData, renderPageCallback )
{
if ( renderPageCallback != null )
{
document.chainedCallback = renderPageCallback;
}
else
{
document.chainedCallback = setFieldListFromXML;
}
loadXMLDocument( reqUrl, waitWithCallback, postData );
}
/**
* Sends POST request.
*
* @param reqUrl - the request URL.
* @param renderPageCallback - a pointer to the callback function.
*/
function loadDataURL( reqUrl, renderPageCallback )
{
if ( renderPageCallback != null )
{
document.chainedCallback = renderPageCallback;
}
else
{
document.chainedCallback = setFieldListFromXML;
}
loadXMLDocument( reqUrl, waitWithCallback );
}
/**
* Formats the POST SET request according to the pre-defined fields.
*
* @param formElement - the name-value set for the SET request.
* @return A string representing the request URI.
*/
function formatPostRequest( formElement )
{
var req = "";
if ( formElement.elements.length > 1 )
{
var elem = formElement.elements[0];
req = elem.name + ":" + encodeSetValue( elem.value );
for ( var i = 1; i < formElement.elements.length; ++i )
{
elem = formElement.elements[i];
req += ',' + elem.name + ":" + encodeSetValue( elem.value );
}
}
return (req);
}
/**
* Formats the POST SET request according to the pre-defined fields.
*
* @param formElement - the name-value set for the SET request.
* @param fieldList - the fields.
* @param bIsToAddDisabled - indicates whether to add disabled HTML elements to the SET request.
* If bIsToAddDisabled is false and an HTML element is disabled,
* its value won't be added to the SET request string.
*
* @return A string representing the request URI.
*/
function formatPostRequestForFields( formElement, fieldList, bIsToAddDisabled )
{
var req = "";
var count = 0;
for ( var i = 0; i < fieldList.length; ++i )
{
if ( fieldList[i] == null )
{
continue;
}
var field = fieldList[i];
var encoder = fieldList[i].m_encoder;
var formElem = formElement[field.m_fieldName];
if ( (formElem != null) && (encoder != null) )
{
if ((false == bIsToAddDisabled) && (formElem.disabled))
{
continue;
}
if ( count != 0 )
{
req += ",";
}
count ++;
req += field.m_dataName + ":" + encoder( formElem );
}
}
return (req);
}
/**
* Returns an XML node value.
*
* @param xmlDoc - a pointer to the XML Document object.
* @param elementName - the node name.
* @return A string representing the node value of a text node, or a non-text node.
* null when the XML node is an empty element. (ex: )
* An empty string when any error occurs.
*/
function getXMLValue( xmlDoc, elementName )
{
//alert("getXMLValue( xmlDoc, " + elementName + ");");
var rtn = "";
var i = 0;
if ( (xmlDoc == null) || (xmlDoc.childNodes.length == 0) )
{
//alert("Received bad XML document.");
return (rtn);
}
var elements = xmlDoc.getElementsByTagName( elementName );
if( (elements != null) && (elements.length > 0) && (elements[0].childNodes != null) )
{
if ( elements[0].childNodes.length == 0 )
{
return (null);
}
if ( elements[0].childNodes[0].nodeType == 3)
{
var j = elements[0].childNodes.length;
for (i = 0; i < j; i++)
{
rtn = rtn + elements[0].childNodes[i].nodeValue;
}
// Fix for FireFox. Long returns are broken up into 4096 byte child nodes. IE is all in one.
//alert("rtn len=" + rtn.length + "ChildNode count=" + j + "\n" );
}
else
{
rtn = elements[0];
}
}
return (rtn);
}
/**
* Requests the XML document.
*
* @param url - the request URL.
* @param callback - a pointer to the callback function.
* @param postData - the data used to POST.
* @note Lets load the WebPage defined by url ( output should be xml )
* If we are using IE then we will use microsoft ActiveX Object, there are
* two microsoft objects we can try. If the first fails, move to second one.
* if not IE then we will use the defined JS object XMLHttpRequest().
*/
function loadXMLDocument( url, callback, postData )
{
loadXMLDocument__( url, callback, postData, true );
}
/**
* Requests the XML document synchronously.
*
* @param strURL - the request URL.
* @param fCallback - a pointer to the callback function.
* @param strPostData - the data used to POST.
*/
function loadXMLDocumentSynchronous(strURL, fCallback, strPostData)
{
if (strPostData == undefined)
{
strPostData = null;
}
if (fCallback == null)
{
loadXMLDocument__(strURL, function (){}, strPostData, false);
}
else
{
loadXMLDocument__(strURL, fCallback, strPostData, false);
}
}
/**
* Requests the XML document.
*
* @param url - the request URL.
* @param callback - a pointer to the callback function.
* @param postData - the data used to POST.
* @param asynchronous - indicates whether synchronous or asynchronous.
*/
function loadXMLDocument__( url, callback, postData, asynchronous )
{
if( window.XMLHttpRequest )
{
xmlRequestObject = new XMLHttpRequest();
}
else if ( window.ActiveXObject )
{
try
{
xmlRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
// alert("XMLHttpRequest is executed");
}
catch ( e )
{
try
{
xmlRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch ( E )
{
}
}
}
if ( xmlRequestObject )
{
xmlRequestObject.onreadystatechange = callback;
xmlRequestObject.open("POST", url, asynchronous );
if ( postData == null )
{
postData = '';
}
addCSRFTokenToRequestHeader(url);
xmlRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded" );
xmlRequestObject.send( postData );
}
}
/**
* Gets an XML node by the node name.
*
* @param xmlDoc - a pointer to the XML Document object.
* @param name - the node name.
* @return an XML node - the function succeeds.
* null - any error occurs.
*/
function getXMLTagByName( xmlDoc, name )
{
var tagList = xmlDoc.getElementsByTagName( name );
var rtn = null;
if ( tagList.length > 0 )
{
rtn = tagList[0];
}
return (rtn);
}
/**
* Saves the value to the text filed.
*
* @param fieldId - indicates the field's id.
* @param value - the value to save.
*/
function setTextField( fieldId, value )
{
var elem = document.getElementById( fieldId );
if ( (elem != null) && (elem.value != undefined) )
{
if (value == null)
{
elem.value = '';
}
else
{
elem.value = value;
}
}
}
/**
* Saves the value to the HTML div element.
*
* @param fieldId - indicates the element's id.
* @param value - the value to save.
*/
function setDiv( fieldId, value )
{
var elem = document.getElementById(fieldId);
// This is the element in the HTML page.
if (elem != null)
{
if ("innerText" in elem && "outerHTML" in elem)
{
elem.innerText = value;
elem.textContent = value;
}
else
{
elem.innerHTML = value;
}
}
}
/**
* Saves the value to the HTML checkbox element.
*
* @param fieldId - indicates the element's id.
* @param value - the value to save.
*/
function setCheckbox( fieldId, value )
{
var val = false;
if ( value != undefined )
{
if (my_trim(value) == "0")
{
val = false;
}
else
{
val = true;
}
}
var elem = document.getElementById( fieldId );
if ( (elem != null) && (elem.checked != undefined) )
{
elem.checked = val;
}
}
/**
* Removes the side blank characters from the string.
* @param str - the string.
* @return The trimmed string.
*/
function my_trim(str)
{
if ( (str == null) || (str == undefined) )
{
return ("");
}
str = str.replace(/^\s*/gi, "");
str = str.replace(/\s*$/gi, "");
return (str);
}
/**
* Saves the value to the HTML radio element.
*
* @param formElement - the HTML radio element.
* @param fieldName - the field name.
* @param value - the value.
*/
function setRadio( formElement, fieldName, value )
{
if ( value != null )
{
for ( var i = 0; i < formElement.elements.length; ++i )
{
var elem = formElement.elements[i];
if ( (elem.name == fieldName) && (elem.value == value) )
{
elem.checked = true;
break;
}
}
}
}
/**
* Saves the value to the HTML select element.
*
* @param name - the HTML select element's id.
* @param value - the value.
*/
function setSelectedOption( name, value )
{
var selElement = document.getElementById( name );
if ( (selElement != null) && (selElement.options) )
{
for ( var i = 0; i < selElement.options.length; ++i )
{
if ( selElement.options[i].value == value )
{
selElement.options[i].selected = true;
break;
}
}
}
}
/**
* Gets the selected item of the HTML select element.
*
* @param formElement - the HTML select element.
* @param fieldName - the field name.
* @return the selected item - the function succeeds.
* null - any error occurs.
*/
function getSelectedRadio( formElement, fieldName )
{
for ( var i = 0; i < formElement.elements.length; ++i )
{
var elem = formElement.elements[i];
if ( elem.name == fieldName && elem.checked )
{
return (elem);
}
}
return (null);
}
/**
* Shows a prompted window with error message.
*
* @param msg - the error message.
*/
function showErrorMessage( msg )
{
alert(" Error: " + msg );
}
/**
* Sets the innterHtml of a message element and displays it.
*
* @param elementName - the name of the message element.
* @param msg - the error message.
* @note Set the style display to block.
*/
function showBlockMessage( elementName, msg )
{
var elem = document.getElementById( elementName );
if ( elem != null )
{
elem.innerHTML = msg;
elem.style.display = 'block';
}
else
{
alert('Cannot find element: ' + elementName );
}
}
/**
* Sets the innterHtml of a message element and displays it.
*
* @param elementName - the name of the message element.
* @param msg - the error message.
* @note Set the style display to inline.
*/
function showInlineMessage( elementName, msg )
{
var elem = document.getElementById( elementName );
if ( elem != null )
{
elem.innerHTML = msg;
elem.style.display = 'inline';
}
else
{
alert('Cannot find element: ' + elementName );
}
}
/**
* Hides an HTML element (such as error message).
*
* @param elemName - the name of the element.
*/
function hideElement( elemName )
{
setDisplayStyle(elemName, 'none');
}
/**
* Shows an HTML element.
*
* @param elemName - the name of the element.
* @note Set the style display to block.
*/
function showBlockElement( elemName )
{
setDisplayStyle(elemName, 'block');
}
/**
* Shows an HTML element.
*
* @param elemName - the name of the element.
* @note Set the style display to inline.
*/
function showInlineElement( elemName )
{
setDisplayStyle(elemName, 'inline');
}
/**
* Shows an HTML element.
*
* @param strElementName - the name of the element.
* @note Set the style display to ''.
*/
function showElement( strElementName )
{
setDisplayStyle(strElementName, '');
}
/**
* Shows or hides an HTML element.
*
* @param strElementName - the name of the element.
* @param strStyle - the display style.
*/
function setDisplayStyle( strElementName, strStyle )
{
var objElement = document.getElementById( strElementName );
if ( (strStyle == null) || (objElement == null) || (objElement['style'] == null) )
{
//alert('Missing element ' + strElementName );
}
else
{
objElement.style.display = strStyle;
}
}
/**
* Checks whether the element is hidden or not found.
*
* @param objElement - the element object.
* @retval true - the element is hidden or not found.
* @retval false - the element is not hidden.
*/
function isElementHiddenOrNotFound(objElement)
{
if ((objElement == null) || (typeof objElement != "object") || (objElement["style"] == null))
{
return (true);
}
// Check style attribute.
try
{
if (objElement.style.display == "none")
{
return (true);
}
else
{
return (false);
}
}
catch (err)
{
}
return (true);
}
/**
* Converts the privilege level to a string.
*
* @param type - the privilege level.
* @return The privilege name.
*/
function ipmiPrivToName( type )
{
var name = "Unknown";
if ( type == 15 )
{
name = TOP_NONE; // None.
}
else if ( type == 2 )
{
name = TOP_USR; // User.
}
else if ( type == 3 )
{
name = TOP_OPR; // Operator.
}
else if ( type == 4 )
{
name = TOP_ADM; // Administrator.
}
return (name);
}
/**
* Displays the update area in place of the content panel and progress panel.
*/
function showUpdateArea()
{
hideElement( 'contentArea' );
hideElement('progressScreen');
showInlineElement('updateArea');
}
/**
* Used as a callback function of loadXMLDocument.
*
* @note 1. This function will be called each time the xmlRequestObject's
* readyState changes.
* When the readyState is 4, indicating that processing is
* complete, the status is checked. If the status is ok then
* the method document.chainedCallback will be called. document.chainedCallback
* should be defined at the page level prior to calling loadXMLDocument.
* 2. Rarely that header.html (represented by top.frames.3) is not loaded completely
* while this function is in use. A try-catch statement is used to prevent the error of
* top.frames[3].hideErrorPanel being undefined from occurring.
*/
function waitWithCallback()
{
// Only execute for state "loaded", all other states have no processing.
if (xmlRequestObject.readyState == 4)
{
// only if "OK"
if (xmlRequestObject.status == 200 )
{
var xmlDoc = xmlRequestObject.responseXML;
var reqStatus = getXMLValue( xmlDoc, 'status' );
if ( reqStatus != 'ok' )
{
if (xmlDoc != null)
{
var message = getXMLValue( xmlDoc, 'status' );
// alert(" Request failed: " + message );
errorHandler(message);
/*
* If we fail perform the callback with a null doc
* to signal the chainedCallback that the server'
* did not recognize the request.
*/
document.chainedCallback(null);
}
}
else
{
/*
* It might be wise at somepoint to implement
* chainedCallback as a stack to avoid accidentally
* stepping on a callback by overwriting it with
* a value that hasn't been called back yet. This
* would introduce substantial complexity though...
*/
if (top.frames.length >= 3)
{
/*
* A successful login on WebGUI will redirect the browser to index.html and then load
* index.html's six frames.
* Rarely top.frames.3 (header.html) has not been loaded completely when top.frames.4
* (which has been loaded completely of course) receives a POST response, as a result,
* top.frames.hideErrorPanel is undefined.
* A try-catch statement is used to prevent the error from occurring.
*/
try
{
top.frames[3].hideErrorPanel();
}
catch (err)
{
//alert("top.frames[3].hideErrorPanel = " + top.frames[3].hideErrorPanel);
}
}
document.chainedCallback(xmlDoc);
if ( requestCtxt.updateComplete != null)
{
requestCtxt.updateComplete( requestCtxt, xmlDoc );
}
}
}
else if ( xmlRequestObject.status == 401 )
{
document.location = "/login.html";
}
else
{
// showErrorMessage(" Could not retrieve data from server ( status=" +
// xmlRequestObject.status + ", " + xmlRequestObject.statusText + ")" );
showContentPanel();
}
}
} //end of waitWithCallback
/**
* Displays error message panel.
*
* @param errorMsg - the error message.
* @note Rarely that header.html (represented by top.frames.3) is not loaded completely
* while this function is in use. A try-catch statement is used to prevent the error of
* top.frames[3].showErrorPanel being undefined from occurring.
*/
function errorHandler(errorMsg)
{
var displayErrorMsg = unknowExcMsg;
if (errorMsg != null)
{
if ( (errorMsg == "ProcessingError") || (errorMsg == "GeneralError") )
{
displayErrorMsg = excMsg;
}
else if (errorMsg == "SecurityException")
{
displayErrorMsg = securityExcMsg;
}
else if (errorMsg == "RequestFormatException")
{
displayErrorMsg = badReqExcMsg;
}
else if (errorMsg == "ExceptionUnknown")
{
displayErrorMsg = unknowExcMsg;
}
// Print the message directly.
else
{
displayErrorMsg = errorMsg;
}
}
if (top.frames.length >= 3)
{
/*
* A successful login on WebGUI will redirect the browser to index.html and then load
* index.html's six frames.
* Rarely top.frames.3 (header.html) has not been loaded completely when top.frames.4
* (which has been loaded completely of course) receives a POST response, as a result,
* top.frames.showErrorPanel is undefined.
*/
try
{
top.frames[3].showErrorPanel(displayErrorMsg);
}
catch (err)
{
}
}
}
/**
* Changes the style based on the row index.
*
* @param tableRowIndex - the row index.
* @return the style according to the row index.
*/
function getStyleForRow(tableRowIndex)
{
// The first row is header, so even index leads to data-area-canvas-odd
if ((tableRowIndex % 2) == 0)
{
return ('data-area-canvas-odd');
}
else
{
return ('data-area-canvas');
}
}
/**
* Inserts a blank cell to the row.
*
* @param tr - the table row.
* @return cellIndex - the index of the cell to insert.
*/
function insertBlankCell(tr, cellIndex)
{
var cell = tr.insertCell(cellIndex);
cell.className = getStyleForRow(tr.rowIndex);
cell.innerHTML = '
';
}
/**
* Displays a table cell.
*
* @param cell - the table cell.
* @param tableRowIndex - the table row index.
* @param innerHTML - the content of the cell.
* @param align - the style of alignment.
* @param cellType - the type of the cell.
*/
function populateCell(cell, tableRowIndex, innerHTML, align, cellType)
{
cell.className = getStyleForRow(tableRowIndex);
cell.vAlign = 'middle';
if (align != null)
{
cell.align = align;
}
if (cellType == null)
{
// Don't interpret no type as unknown, default to content.
cellType = Cell.CONTENT;
}
switch (cellType)
{
case Cell.ICON:
cell.innerHTML="
";
break;
case Cell.CONTENT:
if ( innerHTML == ' ' )
{
cell.innerHTML = '[N/A]';
}
else
{
cell.innerHTML = innerHTML;
}
break;
case Cell.BLANK :
cell.innerHTML='
';
break;
case Cell.HIDDEN :
cell.innerHTML='' + innerHTML + '';
break;
default:
showErrorMessage("Unknown type for cell, cell - " + celltype);
break;
}
}
/**
* Submits a request for data to the server and call refreshDataCallback when the response arrives.
*
* @param data - the request data.
*/
function refreshData(data)
{
document.chainedCallback = refreshDataCallback;
loadXMLDocument('data?get=' + data, waitWithCallback);
}
/**
* Appends the table row to the table.
*
* @param table - the table's id.
* @param row - the table row.
*/
function appendTableRow(table, row)
{
var aTable = document.getElementById(table);
if (null == aTable)
{
return;
}
var newRowIndex = aTable.rows.length;
/*
* doesn't seem to be a way to set style="height: 1px;" for blank.gif rows...
* but it also doesn't seem to affect table layout.
*/
var tr = aTable.insertRow(newRowIndex);
for (i = 0; i < row.length; i++)
{
cell = tr.insertCell(i);
populateCell(cell, newRowIndex, row[i].m_value, row[i].m_align, row[i].m_type);
}
}
/**
* Removes the table rows from the table.
*
* @param tableName - the table's id.
* @param startRow - the start index of the row to be removed.
* @param endRow - the end index of the row to be removed.
*/
function clearTableRows(tableName, startRow, endRow)
{
aTable = document.getElementById(tableName);
if ( (aTable == null) || (aTable.rows.length == 0) )
{
// Nothing to do.
return;
}
if (startRow == null)
{
startRow = 0;
}
if ( (endRow == null) || (endRow > aTable.rows.length) )
{
endRow = aTable.rows.length;
}
// Delete at the starting point until the number of rows between start and end are gone.
for (var x = startRow; x < endRow; x++)
{
aTable.deleteRow(startRow);
}
}
/**
* Adds the strings seperated by the delimiters as options to the given select control.
*
* @param selectControl - the select control.
* @param value - the delimited string.
* @param delim - the delimiter.
*/
function delimValueToOptions(selectControl, value, delim)
{
// Clear any existing options
while (selectControl.options.length > 0)
{
selectControl.remove(0);
}
if (value == null)
{
return;
}
var valueArray = value.split(delim);
for (var optionIndex = 0; optionIndex < valueArray.length; optionIndex++)
{
var oneOption = new Option();
oneOption.text = valueArray[optionIndex];
try
{
selectControl.add(oneOption, null);
}
catch (ex)
{
// IE only
selectControl.add(oneOption);
}
}
}
/**
* Convert the given select control's options to a delimited string.
*
* @param selectControl - the select control.
* @param delim - the delimiter.
* @return A delimited string.
*/
function optionsToDelimValue(selectControl, delim)
{
var options = selectControl.options;
var delimString = "";
if (options == null)
{
return "";
}
for (var optionIndex = 0; optionIndex < options.length; optionIndex++)
{
delimString = delimString + options[optionIndex].text + delim;
}
// Drop the last delimiter
delimString = delimString.substring(0, (delimString.length - 1));
return (delimString);
}
/**
* Returns the month of a given Date object according to universal time.
*
* @param objDate - the Date object.
* @return A string holding the month (Jan~Dec).
* An empty string if objDate is null.
*/
function getMonthUTC(objDate)
{
var strMonth = "";
if (objDate == null)
{
return (strMonth);
}
switch (objDate.getUTCMonth())
{
case 0:
strMonth = "Jan";
break;
case 1:
strMonth = "Feb";
break;
case 2:
strMonth = "Mar";
break;
case 3:
strMonth = "Apr";
break;
case 4:
strMonth = "May";
break;
case 5:
strMonth = "Jun";
break;
case 6:
strMonth = "Jul";
break;
case 7:
strMonth = "Aug";
break;
case 8:
strMonth = "Sep";
break;
case 9:
strMonth = "Oct";
break;
case 10:
strMonth = "Nov";
break;
case 11:
strMonth = "Dec";
break;
default:
strMonth = "";
break;
}
return (strMonth);
}
/**
* Returns the time of a given Data object according to universal time.
*
* @param objDate - the Date object.
* @return A string holding the time (hh:mm:ss).
* An empty string if objDate is null.
*/
function getTimeUTC(objDate)
{
var strTime = "";
var iHour = 0;
var iMin = 0;
var iSec = 0;
if (objDate == null)
{
return (strTime);
}
iHour = objDate.getUTCHours();
iMin = objDate.getUTCMinutes();
iSec = objDate.getUTCSeconds();
if (iHour < 10)
{
strTime += "0" + iHour.toString();
}
else
{
strTime += iHour.toString();
}
if (iMin < 10)
{
strTime += ":" + "0" + iMin.toString();
}
else
{
strTime += ":" + iMin.toString();
}
if (iSec < 10)
{
strTime += ":" + "0" + iSec.toString();
}
else
{
strTime += ":" + iSec.toString();
}
return (strTime);
}
/**
* Pauses the program according to the given time value.
*
* @param s - The time value in seconds.
*/
function SleepInSeconds(s)
{
s = s * 1000;
var a = true;
var n = new Date();
var w = null;
var sMS = n.getTime();
while (a)
{
w = new Date();
wMS = w.getTime();
if ((wMS - sMS) > s)
{
a = false;
}
}
}
/**
* Makes the tooltips displayed on FireFox.
*
* @note FireFox doesn't support the alt attribute in img tags,
* need to use title attribute. This function help to convert
* tooltips from alt attribute to title attribute.
*/
function ShowTooltipsOnFireFox()
{
for (var i = 0; i < document.images.length; i++)
{
if (document.images[i].title == "")
{
document.images[i].title = document.images[i].alt;
}
}
}
/**
* Checks whether the input string is a valid date time string according to the given type.
*
* @param strDateTime - a time string.
* @param iType - represents the format of time string.
*
* @retval true - strDateTime is a valid string.
* @retval false - strDateTime is not a valid string.
* @note the time string should match the specified time type.
* TIME_TITLE : Wed Oct 31 00:00:00 2012
* TIME_SESSION_LOG : 2012-10-31 00:00:00
* TIME_SYSTEM_LOG : 2012-10-31 00:00:00
* TIME_SECURITY : Oct 31 00:00:00 2012 GMT
* TIME_POWER_GRAPH : 1351612800000 (milliseconds)
* TIME_CONSUMPTION : 1351612800000 (milliseconds)
*/
function isValidTimeString(strDateTime, iType)
{
var pattern;
switch (iType)
{
case TIME_TITLE:
pattern = /^([A-Za-z]{3}) [A-Za-z]{3} [0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} [0-9]{4}$/;
if (false == pattern.test(strDateTime))
{
return (false);
}
break;
case TIME_SESSION_LOG:
//break;
case TIME_SYSTEM_LOG:
pattern = /^[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$/;
if (false == pattern.test(strDateTime))
{
return (false);
}
break;
case TIME_SECURITY:
pattern = /^([A-Za-z]{3}) [0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} [0-9]{4} (GMT)$/;
if (false == pattern.test(strDateTime))
{
return (false);
}
break;
case TIME_POWER_GRAPH:
//break;
case TIME_CONSUMPTION:
pattern = /^[0-9]*.[0-9]*$/;
if (false == pattern.test(strDateTime))
{
return (false);
}
break;
default:
return (false);
//break;
}
return (true);
}
/**
* Creates a Date object based on the given time string and type.
*
* @param strDateTime - a time string.
* @param iType - represents the format of time string.
*
* @retval a Date object.
*/
function createDateObject(strDateTime, iType)
{
var objDateTime = null;
switch (iType)
{
case TIME_TITLE:
objDateTime = new Date(strDateTime);
break;
case TIME_SESSION_LOG:
//break;
case TIME_SYSTEM_LOG:
var arrTmpBuff = strDateTime.split(" ");
var arrDateBuff = arrTmpBuff[0].split("-");
var arrTimeBuff = arrTmpBuff[1].split(":");
objDateTime = new Date(arrDateBuff[0], arrDateBuff[1] - 1, arrDateBuff[2],
arrTimeBuff[0], arrTimeBuff[1], arrTimeBuff[2]);
break;
case TIME_SECURITY:
// objDateTime will be wrong if strDateTime includes "GMT".
var strTime = strDateTime.substr(0, (strDateTime.length - 4));
objDateTime = new Date(strTime);
break;
case TIME_POWER_GRAPH:
//break;
case TIME_CONSUMPTION:
var dateConverter = new Date(parseInt(strDateTime));
objDateTime = new Date(dateConverter.getUTCFullYear(), dateConverter.getUTCMonth(), dateConverter.getUTCDate(),
dateConverter.getUTCHours(), dateConverter.getUTCMinutes(), dateConverter.getUTCSeconds());
break;
default:
break;
}
return (objDateTime);
}
/**
* Converts UTC time sting to local time date object.
*
* @param strUtcDateTime - a time string which describes a UTC time.
* @param iType - represents the format of time string.
* @param dateBuffer - a date object storing the local time converted from strUtcDateTime.
*
* @retval true - convert time successfully.
* @retval false - convert time failed.
*/
function convertUtcTimeToLocalTime(strUtcDateTime, iType, dateBuffer)
{
var dateUtcDateTime = null;
if (isValidTimeString(strUtcDateTime, iType))
{
dateUtcDateTime = createDateObject(strUtcDateTime, iType);
}
else
{
return (false);
}
return (convertToLocalTime(dateUtcDateTime, dateBuffer));
}
/**
* Converts UTC time to local time.
*
* @param dateUTC - a date object representing the UTC time.
* @param dateBuffer - a date object storing the local time converted from UTC time.
*
* @retval true - convert time successfully.
* @retval false - convert time failed.
*/
function convertToLocalTime(dateUTC, dateBuffer)
{
if ((Object.prototype.toString.call(dateUTC) != '[object Date]') ||
(Object.prototype.toString.call(dateBuffer) != '[object Date]'))
{
return (false);
}
var dateCurrentTime = new Date();
var localOffset = dateCurrentTime.getTimezoneOffset() * 60000;
var LocalTime = dateUTC - localOffset;
var dateLocalTime = new Date(LocalTime);
dateBuffer.setTime(dateLocalTime.getTime());
return (true);
}
/**
* Converts date and time to a format time string.
*
* @param date - a date object.
* @param iType - represents the format of time string.
*
* @retval return an empty string if convert time failed, otherwise return a time string.
* @note the time format for the specified time type.
* TIME_SESSION_LOG : 2012-10-31 00:00:00
* TIME_SYSTEM_LOG : 2012-10-31 00:00:00
* TIME_SECURITY : 31 Oct 2012, 00:00:00
* TIME_POWER_GRAPH : 31 Oct 2012, 00:00:00
* TIME_CONSUMPTION : 31 Oct 2012, 00:00:00
*/
function getTimeFormatString(date, iType)
{
if (Object.prototype.toString.call(date) != '[object Date]')
{
return ("");
}
var strFormatTime = "";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
if (month < 10)
{
month = "0" + month;
}
if (day < 10)
{
day = "0" + day;
}
if (hour < 10)
{
hour = "0" + hour;
}
if (minute < 10)
{
minute = "0" + minute;
}
if (second < 10)
{
second = "0" + second;
}
switch (iType)
{
case TIME_SESSION_LOG:
//break;
case TIME_SYSTEM_LOG:
strFormatTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
break;
case TIME_SECURITY:
//break;
case TIME_POWER_GRAPH:
//break;
case TIME_CONSUMPTION:
month = arrMonthName[date.getMonth()];
strFormatTime = day + " " + month + " " + year + ", " + hour + ":" + minute + ":" + second;
break;
default:
break;
}
return (strFormatTime);
}
/**
* Gets timezone string.
*
* @param date - a date object.
*
* @retval return an empty string if get timezone failed, otherwise return a timezone string.
*/
function getTimezone(date)
{
if (Object.prototype.toString.call(date) != '[object Date]')
{
return ("");
}
var iTimezone = (-1) * date.getTimezoneOffset() / 60;
var strSign = "";
if (iTimezone >= 0)
{
strSign = "+";
}
var strTimezone = " (UTC" + strSign + iTimezone + ")";
return (strTimezone);
}
/**
* Returns a formatted UTC time sting or a formatted local time string.
*
* @param strValue - a time string which describes a UTC time.
* @param iType - represents the format of the time string.
*
* @retval A formatted time string..
*/
function getDateTimeString(strValue, iType)
{
var objDate = new Date();
var strDateTime = "";
if (G_bIsToShowLocalTime == true)
{
if (convertUtcTimeToLocalTime(strValue, iType, objDate))
{
strDateTime = getTimeFormatString(objDate, iType) + getTimezone(objDate);
}
else
{
strDateTime = strValue;
}
}
else
{
if (isValidTimeString(strValue, iType))
{
objDate = createDateObject(strValue, iType);
strDateTime = getTimeFormatString(objDate, iType);
}
else
{
strDateTime = strValue;
}
}
return (strDateTime);
}
/**
* Encodes special symbols '\','@','(',')',',',':','?','=','&'.
*
* @param username - A string which needs to be checked and encoded the special symbol.
* @return A string has encoded.
*/
function escapeUserName(username)
{
var tmp = new Array();
var i = 0;
var escstr = "";
var dec = "";
username = username.replace(/\\/g, "\\\\");
tmp = username.split("");
for (i = 0; i < tmp.length; i++)
{
switch(tmp[i])
{
case '@':
case '(':
case ')':
case ',':
case ':':
case '?':
case '=':
case '&':
dec = (tmp[i]+'').charCodeAt(0);
escstr+= "@0"+ dec.toString(16);
break;
default:
escstr+=tmp[i];
}
}
return (escstr);
}
/**
* Disables the HTML elements with specific HTML tag under specific HTML element.
*
* @param objElem - the target HTML element object.
* @param strTagName - HTML tag name to be disabled.
* @retrun true - successfully.
* false - objElem is null or is not object type.
* strTagName is null or empty string, or the tag is not found in the HTML document.
*/
function disableHTMLElementsByTagName(objElem, strTagName)
{
if ((objElem == null) || typeof(objElem) != "object")
{
return (false);
}
if ((strTagName == null) || (strTagName == ""))
{
return (false);
}
var objArray = objElem.getElementsByTagName(strTagName);
var i = 0;
if ((objArray == null) || (objArray.length == 0))
{
return (false);
}
for (i = 0; i< objArray.length; i++)
{
objArray[i].disabled = true;
}
return (true);
}
/**
* Converts a version string to ODM-specified format.
*
* @param strVersion - A version string.
* @return Formatted version string.
*/
function convertToODMFwVerFormat(strVersion)
{
/*
* BTS 69939: change firmware format from major.minor(.release) to major.minor,
* where major should be a value between 0~127, and minor should be
* a value between 0~99. The restraint is imposed because for this
* ODM customization, major and minor values should be in accordance
* with the revision values obtained from the IPMI Get Device ID command.
*/
var strODMFwVer = "";
var aFwVersion = strVersion.split(".");
if ((aFwVersion.length < 2) || (aFwVersion.length > 3))
{
strODMFwVer = "Error. Invalid firmware version format.";
}
else
{
var strMajor = aFwVersion[0];
var strMinor = aFwVersion[1];
var iMajor = parseInt(strMajor);
var iMinor = parseInt(strMinor);
if ((iMajor == NaN) || (iMajor < 0) || (iMajor > 127))
{
// major is out of range
strODMFwVer = "Error. Firmware major version is invalid. Expected range: [0-127].";
}
else if ((iMinor == NaN) || (iMinor < 0) || (iMinor > 99))
{
// minor is out of range
strODMFwVer = "Error. Firmware minor version is invalid. Expected range: [0-99].";
}
else if (strMinor.length == 1)
{
// minor: "1" -> "01"
strMinor = "0" + strMinor;
strODMFwVer = strMajor + "." + strMinor;
}
else
{
strODMFwVer = strMajor + "." + strMinor;
}
}
return (strODMFwVer);
}
/**
* Resets table row style.
*
* @param strTableID - The id attribute of the HTML table element.
* @note The function rearranges the background color of visible table rows.
* Even-index visible rows, the className attribute is "data-area-canvas-odd" to set background color to blue.
* Odd-indexed visible rows, the className attribute is "data-area-canvas" to set background color to gray.
* The row index is 0-based.
*/
function resetTableRowStyle(strTableID)
{
if ((strTableID == null) || (strTableID == ""))
{
return;
}
var objRows = document.getElementById(strTableID).rows;
var objCells = null;
var iVisibleRowIndex = 0;
for (var iRowIndex = 0; iRowIndex < objRows.length; iRowIndex++)
{
if (isElementHiddenOrNotFound(objRows[iRowIndex]))
{
continue;
}
objCells = objRows[iRowIndex].cells;
// Set background color.
for (var iCellIndex = 0; iCellIndex < objCells.length; iCellIndex++)
{
objCells[iCellIndex].className = getStyleForRow(iVisibleRowIndex);
}
iVisibleRowIndex++;
}
}
/**
* Passes a given sequence of arguments preceding any provided when the new function was called.
*
* @param obj - A generic object that will become 'this' of the function whose function.bind() is called.
* @note Creates a new function that, when called, itself calls this
* function in the context of the provided this value, with a given
* sequence of arguments preceding any provided when the new function was called.
*/
Function.prototype.bind = function(obj)
{
var objMethod = this, objFunction = function()
{
return objMethod.apply(obj, arguments);
};
return (objFunction);
}
/**
* Checks the result of changing network settings.
*
* @param xmlDoc - A pointer to the XML document.
*
* @return true - changing network settings is successful.
* @return false - changing network settings is falied.
*/
function isRequestSubmittedOK(xmlDoc)
{
// status != ok, an inline message is displayed on header frame.
if (xmlDoc == null)
{
return (false);
}
// OSINET return code.
var STATUS_OK = 0; // OK
var STATUS_DUPLICATE_IPV6_IP = 327725; // Duplicate IPv6 IP addresses.
var STATUS_INVALID_IPV6_IP = 327716; // Invalid IPv6 address.
var astrErrMsg = new Array();
astrErrMsg[STATUS_DUPLICATE_IPV6_IP] = "IPv6 IP Address 1 and IP Address 2 are duplicate.";
astrErrMsg[STATUS_INVALID_IPV6_IP] = "Invalid IPv6 address.";
var strSetNetworkFailed = "Changing Network settings failed.";
var strSeeOnlineHelp = "Please see the online help for more information.";
var iResult = parseInt(getXMLValue(xmlDoc, "statusCode"));
// OK.
if ((isNaN(iResult)) || (STATUS_OK == iResult))
{
return (true);
}
// Failed.
var strMsg = astrErrMsg[iResult];
if (strMsg == undefined)
{
errorHandler(strSetNetworkFailed + "
" + strSeeOnlineHelp);
}
else
{
errorHandler(strMsg + "
" + strSeeOnlineHelp);
}
return (false);
}
/**
* Terminiates all sessions.
* It's the callback function called when changes to network settings are updated.
*
* @xmlDoc A pointer to the XML document.
*
* @note The function closes the other sessions and force the user to log out.
*/
function terminateAllSessions(xmlDoc)
{
if (!isRequestSubmittedOK(xmlDoc))
{
showContentPanel();
return;
}
document.chainedCallback = function ()
{
// Force the user to log out.
top.document.location.replace("/data/logout");
};
// Kill all other sessions.
loadXMLDocument("data?set=killOtherSessions("+this.strSessionId+")", waitWithCallback);
}
/**
* Updates the content of message panel and displays it.
*
* @param strMsg - The message to be displayed.
* @param iMsgType - Indicates the message is an info or an error.
*
* @note None.
*/
function updateMessage(strMsg, iMsgType)
{
if ((strMsg == null) || (iMsgType == null))
{
return;
}
// Roll back message panel and use the original alert() function.
alert(strMsg);
return;
var objMsgIcon = document.getElementById("msgIcon");
if (objMsgIcon == null)
{
return;
}
if (iMsgType == MSG_TYPE_INFO)
{
objMsgIcon.src = "images/information.gif";
}
else if (iMsgType == MSG_TYPE_ERROR)
{
objMsgIcon.src = "images/error.gif";
}
var strHtmlMsg = strMsg.replace(/\n/g, "
");
showInlineMessage("msgContent", strHtmlMsg);
showBlockElement("msgPanel");
resizeMessagePanel();
}
/**
* Resizes the message panel to fit window size, and displays it in the center of the window.
*/
function resizeMessagePanel()
{
var objMsgContent = document.getElementById("msgContent");
var objMsgPanel = document.getElementById("msgPanel");
if ((objMsgContent == null) || (objMsgPanel == null))
{
return;
}
// There's no need to resize message panel if it is not visible.
if ((objMsgPanel.style.display == null) ||
(objMsgPanel.style.display == undefined) ||
(objMsgPanel.style.display != "block"))
{
return;
}
/**
* Reset the inline style of message content and message panel
.
* This does not affect the style settings from CSS file.
*/
objMsgContent.removeAttribute("style");
objMsgPanel.setAttribute("style", "display: block");
// Get width and height of current frame (i.e., width and height of dataPage).
var iWindowWidth = getWindowWidth(window);
var iWindowHeight = getWindowHeight(window);
// Define max width for message content
.
var iMaxContentWidth = (iWindowWidth * 0.5);
// Get width of current message content
.
var objMsgContentRect = objMsgContent.getBoundingClientRect();
var iMsgContentWidth = (objMsgContentRect.right - objMsgContentRect.left);
// Define variable for final width.
var iContentWidthToSet = iMsgContentWidth;
if (iMsgContentWidth > iMaxContentWidth)
{
iContentWidthToSet = iMaxContentWidth;
objMsgContent.setAttribute("style", "width: " + iContentWidthToSet + "px;");
}
// Define max height for message panel.
var iMaxPanelHeight = (iWindowHeight * 0.6);
// Get width/height of current message panel element.
var objMsgPanelRect = objMsgPanel.getBoundingClientRect();
var iMsgPanelWidth = (objMsgPanelRect.right - objMsgPanelRect.left);
var iMsgPanelHeight = (objMsgPanelRect.bottom - objMsgPanelRect.top);
// Define variables for final width/height.
var iPanelWidthToSet = iMsgPanelWidth;
var iPanelHeightToSet = iMsgPanelHeight;
if (iMsgPanelHeight > iMaxPanelHeight)
{
iPanelHeightToSet = iMaxPanelHeight;
// Panel width ~= content width + icon width (16px) + margin and padding (50px) + vertical scroll bar (30px)
iPanelWidthToSet = iContentWidthToSet + 100;
objMsgPanel.setAttribute("style", "display: block; overflow: auto;" +
"height: " + iPanelHeightToSet + "px;" +
"width: " + iPanelWidthToSet + "px;");
}
// Get position of current frame relative to the entire browser window.
var iWindowX = getWindowWidth(parent.bmcTree);
var iWindowY = getWindowHeight(parent.globalnav) + getWindowHeight(parent.Title) + getWindowHeight(parent.headerFrame);
/**
* The position of message panel is relative to the current frame, not browser window.
* Shift the message panel so that it looks in the center of browser window.
*/
var iMsgPanelLeft = ((iWindowX + iWindowWidth - iPanelWidthToSet) / 2) - iWindowX;
var iMsgPanelTop = ((iWindowY + iWindowHeight - iPanelHeightToSet) / 2) - iWindowY;
if (iMsgPanelLeft < 0)
{
iMsgPanelLeft = 0;
}
if (iMsgPanelTop < 0)
{
iMsgPanelTop = 0;
}
objMsgPanel.style.left = iMsgPanelLeft + "px";
objMsgPanel.style.top = iMsgPanelTop + "px";
}
/**
* Gets the width of window.
*
* @param objWindow - The window object whose width will be got.
*
* @return - The width of the input window. 0 if the input object is null.
*/
function getWindowWidth(objWindow)
{
if (objWindow == null)
{
return (0);
}
/**
* Different browsers use different properties to get the width of the browser window.
* Internet Explorer, Chrome, Firefox, Opera, and Safari uses 'objWindow.innerWidth'.
* Internet Explorer 8, 7, 6, 5 use 'objWindow.document.documentElement.clientWidth' or 'objWindow.document.body.clientWidth'.
*/
return (objWindow.innerWidth ||
objWindow.document.documentElement.clientWidth ||
objWindow.document.body.clientWidth);
}
/**
* Gets the height of window.
*
* @param objWindow - The window object whose height will be got.
*
* @return - The height of the input window. 0 if the input object is null.
*/
function getWindowHeight(objWindow)
{
if (objWindow == null)
{
return (0);
}
/**
* Different browsers use different properties to get the height of the browser window.
* Internet Explorer, Chrome, Firefox, Opera, and Safari uses 'objWindow.innerHeight'.
* Internet Explorer 8, 7, 6, 5 use 'objWindow.document.documentElement.clientHeight' or 'objWindow.document.body.clientHeight'.
*/
return (objWindow.innerHeight ||
objWindow.document.documentElement.clientHeight ||
objWindow.document.body.clientHeight);
}
/**
* Appends CSRF token into request string.
*
* @param strRequest - a request string.
*
* @return the request string appended CSRF token.
* @note If '?' doesn't exist in the request URI, then append "?[TOKEN 1 NAME]=[TOKEN 1 VALUE]".
* If the last character of the request URI is '?' or '&', then append
* "[TOKEN 1 NAME]=[TOKEN 1 VALUE]". If the last character of the request URI is ',',
* remove ',' and then append "&[TOKEN 1 NAME]=[TOKEN 1 VALUE]".
*/
function appendCSRFTokenToRequestURI(strRequest)
{
if (false == top.G_bIsCSRFPreventionEnabled)
{
return (strRequest);
}
var strAppendedTokenRequest = strRequest;
// If '?' doesn't exist. example: "http://webgui ip/fwupload/fwupload.esp"
if (-1 == strAppendedTokenRequest.indexOf('?'))
{
return (strAppendedTokenRequest + '?' + top.CSRF_TOKEN_1);
}
var strLastChar = strAppendedTokenRequest.charAt(strAppendedTokenRequest.length - 1);
/*
* If '?' or '&' is the last character.
* example:
* http://webgui ip/fwupload/fwupload.esp?
* http://webgui ip/fwupload/fwupload.esp?fwType:1&
*/
if (('?' == strLastChar) || ('&' == strLastChar))
{
return (strAppendedTokenRequest + top.CSRF_TOKEN_1);
}
if (',' == strLastChar)
{
// Remove character ',' from the end character of the string.
strAppendedTokenRequest = strAppendedTokenRequest.substring(0, (strAppendedTokenRequest.length - 1));
}
return (strAppendedTokenRequest + '&' + top.CSRF_TOKEN_1);
}
/**
* Adds CSRF token to request header.
*
* @param strRequest - a request string.
*/
function addCSRFTokenToRequestHeader(strRequest)
{
if ((false == top.G_bIsCSRFPreventionEnabled) || (-1 != strRequest.search("data/login")))
{
return;
}
if ( xmlRequestObject )
{
xmlRequestObject.setRequestHeader(top.CSRF_TOKEN_2_NAME, top.CSRF_TOKEN_2_VALUE);
}
}
// End of code