﻿/*////////////////////////////////////////////////////////////////////////
//                                                                      //
//  Copyright NetWitness Corporation 2006-2010                          //
//                                                                      //
//  Unpublished - All rights reserved under the copyright laws of the   //
//  United States.  No copy of this document may be made without        //
//  expressed permission of NetWitness Corporation.                     //
//                                                                      //
//  NetWitness Corporation                NetWitness                    //
//  500 Grove Street, Suite 300           www.netwitness.com            //
//  Herndon, VA  20170                                                  //
//                                                                      //
////////////////////////////////////////////////////////////////////////*/

// keycode numbers
var CODE_TAB    = 9;
var CODE_ENTER  = 13;
var CODE_SHIFT  = 16;
var CODE_CTRL   = 17;
var CODE_ALT    = 18;
var CODE_ESC    = 27;
var CODE_PAGEUP = 33;
var CODE_PAGEUP = 34;
var CODE_END    = 35;
var CODE_HOME   = 36;
var CODE_LEFT   = 37;
var CODE_UP     = 38;
var CODE_RIGHT  = 39;
var CODE_DOWN   = 40;
var CODE_INSERT = 45;
var CODE_DEL    = 46;

var CODE_0      = 48;
var CODE_1      = 49;
var CODE_2      = 50;
var CODE_3      = 51;
var CODE_4      = 52;
var CODE_5      = 53;
var CODE_6      = 54;
var CODE_7      = 55;
var CODE_8      = 56;
var CODE_9      = 57;

var CODE_A      = 65;
var CODE_B      = 66;
var CODE_C      = 67;
var CODE_D      = 68;
var CODE_E      = 69;
var CODE_F      = 70;
var CODE_G      = 71;
var CODE_H      = 72;
var CODE_I      = 73;
var CODE_J      = 74;
var CODE_K      = 75;
var CODE_L      = 76;
var CODE_M      = 77;
var CODE_N      = 78;
var CODE_O      = 79;
var CODE_P      = 80;
var CODE_Q      = 81;
var CODE_R      = 82;
var CODE_S      = 83;
var CODE_T      = 84;
var CODE_U      = 85;
var CODE_V      = 86;
var CODE_W      = 87;
var CODE_X      = 88;
var CODE_Y      = 89;
var CODE_Z      = 90;

// invalid FILENAME characters

var INVALID_FILENAME_CHARS  = new Array("\\", "/", ":", "*", "?", "\"", "<", ">", "|");
var MONTH_ABR               = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

// Various JavaScript Utils

function XML()
{
    // constructor
}

/**
*   Create a new Document object.  If no args specified,
*   document will be empty.  If a root tag is specified, the
*   document will contain that single root tag.  If the root tag has a 
*   namespace prefix, the second argument must specify the URL that
*   identifies the namespace.
*/

XML.newDocument = function(rootTagName, namespaceURL) 
{
    if (!rootTagName) rootTagName = "";
    if (!namespaceURL) namespaceURL = "";
    
    if (document.implementation && document.implementation.createDocument)
    {
        return document.implementation.createDocument(namespaceURL,
                                                      rootTagName,
                                                      null);
    } else { // IE
        var doc = new ActiveXObject("MSXML2.DOMDocument");
        
        if (rootTagName) 
        {
            var prefix = "";
            var tagname = rootTagName;
            var p = rootTagName.indexOf(':');
            if (p != -1)
            {
                prefix = rootTagName.substring(0,p);
                tagname = rootTagName.substring(p+1);
            }
            
            if (namespaceURL) 
            {
                if (!prefix) prefix = "a0";
            } else {
                prefix = "";
            }
            
            var text = "<" + (prefix?(prefix+":"):"") + tagname +
                (namespaceURL
                    ?(" xmlns:"+prefix+'="'+namespaceURL+'"')
                    :"") +
                "/>";
            doc.loadXML(text);
        }
        return doc;
    }
};

/*
*   This function takes a URL to an XML document and returns 
*   an object containing the document.
*/
XML.loadAsync = function(url, callback)
{
    var xmlDoc = XML.newDocument() ;
    
	if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc.onload = function() { callback(xmlDoc); };
	}
	else if (window.ActiveXObject)
	{
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4) callback(xmlDoc);
		};
 	}
	else
	{
		alert('Your browser can\'t handle this script');
		return;
	}	
	xmlDoc.load(url);		
}

/**
*   String Utils
*/

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

String.prototype.trimHTML = function() {
    return this.replace(/^\u0026nbsp\u003b+/,"");
}

String.prototype.escHtml = function() {    
    var i, e = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }, t = this;
    for (i in e) {
        t = t.replace(new RegExp(i, 'g'), e[i]);
        return t;
    }
}

String.prototype.htmlspecialchars = function() {
    var str = this.replace(/&/g, '&amp;');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/"/g, '&quot;');
    str = str.replace(/\\n/g, '<br/>');
    return str;
};

String.prototype.startsWith = function(str) {
    return !this.indexOf(str);
}

Array.prototype.trimAll = function() {    
    for (var i = 0; i < this.length; i++)
    {
        this[i] = this[i].trim();        
    }
    return this;
}

Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

function blank()
{
    return false;
}

function clone(obj){

    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = {};
    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}

function createSpaceStr(sArray)
{
    if (sArray) {
        var str     = new Array();

        var emptyImgHTML    = "<img src='res/img/empty.gif' align='absmiddle'/>";
        var lineImgHTML     = "<img src='res/img/line.gif' align='absmiddle'/>";             
                
        for (s=0;s<sArray.length;s++)
        {
            if (sArray[s]){
               str.push(emptyImgHTML); 
            } else {
               str.push(lineImgHTML); 
            }
        }    
        return str.join("");
    } 
    return "";
}

function isRightClick()
{
    if (document.all) {
        if (event.button == 2) {
            return true;
        }
    }   
    if (document.layers) {
        if (e.which == 3) {               
            return true;
        }
    }   
    return false;
}

function createDOMNode(loadXml)
{
    if (isIE)
    {
        return createIEDOM(loadXml);
    } else {
        return createMozDOM(loadXml);
    }    
}

function loadDOMNode(node, str)
{
    if (isIE)
    {
        node.loadXML(str) ;        
    } else {
        var oParser = new DOMParser();
        node = oParser.parseFromString(str, 'text/xml');    
    }
}

function createIEDOM(loadXml)
{
    var arrSignatures = ["MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument",
                         "Microsoft.XmlDom"];
    for (var domIdx = 0; domIdx < arrSignatures.length; domIdx++)
    {
        try{
            var oXmlDom = new ActiveXObject(arrSignatures[domIdx]);
            oXmlDom.loadXML(loadXml) ;
            return oXmlDom;
        } catch (oError) {
            //ignore
        }
    }
    
    throw new Error("MSXML is not installed on your system.");
}

function createMozDOM(loadXml)
{
    var oParser = new DOMParser();
    var oXmlDom = oParser.parseFromString(loadXml, 'text/xml');
    return oXmlDom;
}

function getDOMNode(xmlDoc, xpath)
{    
    //alert(xpath);
    if (isIE) //IE XPath
    {            
        var theNode ;
        
        try
        {
            theNode = xmlDoc.documentElement.selectSingleNode(xpath);
        }
        catch (oError)
        {
            theNode = xmlDoc.selectSingleNode(xpath);
        }
        
        return theNode;        
    } 
    else if (isMoz || isSafari) // Firefox XPath or Chrome/Safari
    {
        var oEvaluator = new XPathEvaluator();
        var oResult = oEvaluator.evaluate(  xpath, 
                                            xmlDoc, 
                                            null,
                                            XPathResult.FIRST_ORDERED_NODE_TYPE,
                                            null );        
        if (oResult != null) {
            return oResult.singleNodeValue;
        } else {
            return null;
        }                                                
    }    
}

function getDOMNodeList(xmlDoc, xpath)
{
    if (isIE) //IE XPath
    {
        var theNodeList ;
        
        try
        {
            theNodeList = xmlDoc.documentElement.selectNodes(xpath);
        }
        catch (oError)
        {
            theNodeList = xmlDoc.selectNodes(xpath);
        }
        
        return theNodeList;
            
    }
    else if (isMoz || isSafari) // Firefox XPath or Chrome/Safari
    {
        var oEvaluator = new XPathEvaluator();
        var oResult = oEvaluator.evaluate(  xpath, 
                                            xmlDoc, 
                                            null,
                                            XPathResult.ORDERED_NODE_ITERATOR_TYPE,
                                            null );
        var aNodes = new Array();
                                                            
        if (oResult != null) {
            var oElement = oResult.iterateNext();
            while (oElement) {
                aNodes.push(oElement);
                oElement = oResult.iterateNext();
            }
            return aNodes;            
        } else {
            return null;
        }                                                
    }
}

function getRulegroupById(xmlDoc, id)
{        
    return getDOMNode(xmlDoc, "//rulegroup[@id='"+id+"']");
}

function getRepDefGroups(xmlDoc)
{
    return getDOMNodeList(xmlDoc, "//rdgroup");
}

function getRepDefById(xmlDoc, id)
{
    return getDOMNode(xmlDoc, "//reportdef[@id='"+id+"']");
}

function getRepDefGroupById(xmlDoc, id)
{    
    return getDOMNode(xmlDoc, "//rdgroup[@id='"+id+"']");
}

function getChartDefGroups(xmlDoc)
{
    return getDOMNodeList(xmlDoc, "//cdgroup");
}

function getChartDefById(xmlDoc, id)
{
    return getDOMNode(xmlDoc, "//chart[@id='"+id+"']");
}

function getChartDefGroupById(xmlDoc, id)
{
    return getDOMNode(xmlDoc, "//cdgroup[@id='"+id+"']");
}

function getRulegroups(xmlDoc)
{
    return getDOMNodeList(xmlDoc, "//rulegroup");
}

function getListgroups(xmlDoc)
{
    return getDOMNodeList(xmlDoc, "//listgroup");
}

function getMetaValues(xmlDoc)
{
    return getDOMNodeList(xmlDoc, "//metaGroup");
}

function getToolboxValues(xmlDoc)
{
    return getDOMNodeList(xmlDoc, "//toolboxGroup");
}

function getRuleById(xmlDoc, id)
{        
    //writeDebugMessage(XMLtoString(xmlDoc) + " "+id);
    var sXPath      = "//rule[@id='"+id+"']";
    return getDOMNode(xmlDoc, sXPath);
}

function getFolderById(xmlDoc, folderTagName, id)
{
    var sXPath      = "//"+folderTagName+"[@id='"+id+"']";
    return getDOMNode(xmlDoc, sXPath);
}


function XMLtoString(xmlDoc) {
    
    if (isIE) //IE XPath
    {        
        return xmlDoc.xml;
    }
    //else if (isMoz) // Firefox XPath
    else
    {
        var oSerializer = new XMLSerializer();
        var sXml        = oSerializer.serializeToString(xmlDoc, "text/xml");   
        return sXml;
    }
}    

function isChartDef(str)
{
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('cd') != -1)       { return true; }
    else                                { return false; }    
}

function isRepDef(str)
{
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('rd') != -1)       { return true; }
    else                                { return false; }    
}

function isRule(str)
{    
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('rl') != -1)       { return true; }
    else                                { return false; }    
}

function isChain(str)
{    
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('ch') != -1)       { return true; }
    else                                { return false; }    
}

function isChainFolder(str)
{    
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('chg') != -1)      { return true; }
    else                                { return false; }    
}


function isList(str)
{
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('ls') != -1)       { return true; }
    else                                { return false; }    
}

function isRuleFolder(str)
{
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('rg') != -1)       { return true; }
    else                                { return false; }    
}

function isListFolder(str)
{
    var typeArray   = str.split("-");    
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('lg') != -1)       { return true; }
    else                                { return false; }    
}

function isFolder(str)
{
    var typeArray   = str.split("-");
    var type        = typeArray[typeArray.length-1];
    if      (type.indexOf('rg') != -1)  { return true; }
    else if (type.indexOf('lg') != -1)  { return true; }
    else if (type.indexOf('dg') != -1)  { return true; }
    else if (type.indexOf('cg') != -1)  { return true; }
    else                                { return false; }    
}

function isPlaceholder(id)
{    
    var typeArray   = id.split("-");        
    var type        = typeArray[typeArray.length-1];    
    
    if (type.indexOf('tbv') != -1)      { return true; }
    else                                { return false; }   
}

function isReportDef(id)
{
    var typeArray   = id.split("-");    
    var type        = typeArray[typeArray.length-1];
    
    if (type.indexOf('rd') != -1)       { return true; }
    else                                { return false; }   
}

function isReportDefFolder(str)
{    
    var typeArray   = str.split("-");
    var type        = typeArray[typeArray.length-1];
    if (type.indexOf('dg') != -1)       { return true; }
    else                                { return false; }    
}

function isDragChart(str)
{    
    if (str.indexOf('dragChart') != -1) { return true; }
    else                                { return false; }    
}

function isEditablePlaceholder(id)
{
    if      ( id == 'tb1-tbv0' )        { return true; }
    else if ( id == 'tb1-tbv1' )        { return true; }
    else if ( id == 'tb1-tbv2' )        { return true; }    
    else                                { return false; }   
}

function isReportCtr(id)
{
    if (id == "reportbldr-ctr")         { return true; }
}

function isMinTblDrop(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('minTbl') != -1) && (type.indexOf('drop') != -1))  { return true; }
    else                                                                { return false; }  
}

function isMinTblDrag(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('minTbl') != -1) && (type.indexOf('drag') != -1))  { return true; }
    else                                                                { return false; }      
}

function isHourlyTblDrop(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('hTbl') != -1) && (type.indexOf('drop') != -1))  { return true; }
    else                                                              { return false; }  
}

function isHourlyTblDrag(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('hTbl') != -1) && (type.indexOf('drag') != -1))  { return true; }
    else                                                              { return false; }    
}

function isDailyTblDrop(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('dTbl') != -1) && (type.indexOf('drop') != -1))  { return true; }
    else                                                              { return false; }  
}

function isDailyTblDrag(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];    
    if ((tbl.indexOf('dTbl') != -1) && (type.indexOf('drag') != -1))  { return true; }
    else                                                              { return false; }    
}

function isAdhocTblDrop(str) 
{
    var typeArray   = str.split("-");    
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('aTbl') != -1) && (type.indexOf('drop') != -1))  { return true; }
    else                                                              { return false; }  
}

function isAdhocTblDrag(str) 
{
    var typeArray   = str.split("-");
    var tbl         = typeArray[0];
    var type        = typeArray[typeArray.length-1];
    
    if ((tbl.indexOf('aTbl') != -1) && (type.indexOf('drag') != -1))  { return true; }
    else                                                              { return false; }  
}

function insertAtCursor( textArea, insertText ) 
{
    if (isIE) 
    {
        textArea.focus();
        sel = document.selection.createRange();
        sel.text = insertText;        
    } 
    else
    {
        var startPos = textArea.selectionStart;
        var endPos = textArea.selectionEnd;
        textArea.value = textArea.value.substring(0, startPos)
            + insertText
            + textArea.value.substring(endPos, textArea.value.length);
    } 
}

function getRuleXPath(xmlNode, nodeid)
{    
    return '//rule[@nodeid="'+nodeid+'"]';
}

function getRuleTreeXPath(xmlNode, id)
{
    return '//rule[@id="' + id + '"]';
}

function getRuleName(xmlNode, id)
{
    var ruleNode = getDOMNode(xmlNode, '//rule[@id="'+id+'"]');
    return ruleNode.getAttribute('name');
}

function sortNumber(a,b)
{
    return a - b
}

/*******************************/
/* Control Section              */
/*******************************/

function hoverImgBtn(iObj)
{
    /*if (iObj.className != 'imgLinkDown')
    {
        if (iObj.className == 'imgLink')
        {
            iObj.className = 'imgLinkHover';
        } else {
            iObj.className = 'imgLink';
        }
    }*/
}

function isEnter(evt)
{
    evt=evt||window.event;
    var el=this;
    if((evt.keyCode||evt.which)==13) {
        return true;
    }     
    return false;
}

eeIsDown = false;
eeTotal = 106;
eeCntr  = 0;

function eeUpdate(bool)
{
    if (eeIsDown) {
        document.getElementById('header-img').src = 'res/img/egg.jpg';
        eeIsDown = false;        
    } else {
        document.getElementById('header-img').src = 'res/img/header.png';        
    }
    eeCntr = 0;
}

function eeAdd(e) {
    if (document.getElementById) {
        eeCntr += parseInt(e.which);        
        if (eeCntr == eeTotal) {
            eeIsDown = true;
        }
        
    }    
    
}

function eeSub(e) {
    if (document.getElementById) {
        eeCntr -= parseInt(e.which);        
    }
    
    eeIsDown = false;  
}

function eeCheck(e)
{
    
	var myKeyCode=0;
	var myShiftKey=false;
	var myMsg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

	// Internet Explorer 4+
	if ( document.all ) {
		myKeyCode=e.keyCode;
		myShiftKey=e.shiftKey;

	// Netscape 4
	} else if ( document.layers ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

	// Netscape 6
	} else if ( document.getElementById ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;
        alert(e.which); 
	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
		alert( myMsg );

	// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	} else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
		alert( myMsg );

	}
}

function inUse(uname, action)
{
    alert(uname + ' is currently ' + action);
}

function encodeHTML(str)
{
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/>/g, "&gt;");
    str = str.replace(/</g, "&lt;");    
    return str;
}

function decodeHTML(str)
{
    str = str.replace(/&amp;/g, "&");
    str = str.replace(/&gt;/g, ">");
    str = str.replace(/&lt;/g, "<");    
    return str;
}

var isForcedRefresh = false;
var promptOnNavigate = false;

window.onbeforeunload = exit;

function confirmExit()
{
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

function setPromptOnNavigate(prompt)
{
    promptOnNavigate = prompt;
}

function exit()
{
    if (isForcedRefresh) 
    {
        loginRedirect();
    } else {
        var lastSlash   = window.location.href.lastIndexOf('/');
        var pageName    = window.location.href.substring(lastSlash+1);
        if (promptOnNavigate)
        {         
            return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
        }
    }
}

var _destroyingView = false;

function forceRefresh()
{
    isForcedRefresh = true;    
    exit();
}

function loginRedirect()
{
    // forcibly refresh the page
    var sURL = unescape(window.location.pathname);
    window.location.href = 'LoginPage.aspx';
}

/* AJAX Error Handle Calls */
function errorHandle(arg) {

    endLoading();
    
    if (!_destroyingView) {        
        error(arg._message);        
    }
}

// use this function to handle ajax handles that happen in the background,
// we don't want annoying error dialogs
function errorHandleSilent(arg) {

    endLoading();
    
}

function timeoutHandle() {
    
    endLoading();
    warning('Informer request has timed out');
    
}

function error(txt)
{
    var append = (openModalId == 'errorModal'); 
    
    $find('errorModal').show();
    openModalId = 'errorModal';

    if (append) {
        document.getElementById('errorText').innerHTML += '<br/>' + txt;
    } else {        
        document.getElementById('errorText').innerHTML = '';
        document.getElementById('errorText').innerHTML = txt;
    }
    
    setTimeout('errorFocus()',200);
    
    if (txt == "Authentication failed.") 
    {
        location.href = "LoginPage.aspx?timeout=yes";
    }    
}

function errorFocus()
{
    document.getElementById('errorOK').focus();
}

function clearError(txt) 
{
    openModalId = '';
    document.getElementById('errorText').innerHTML = '';        
}

function warning(txt)
{
    if ($find('warningModal'))
    {
        $find('warningModal').show();
        openModalId = 'warningModal';
        document.getElementById('warningText').innerHTML = txt;    
        setTimeout('warningFocus()',200);        
    }
}

function warningFocus()
{
    document.getElementById('warningOK').focus();
}

function clearWarning()
{
    document.getElementById('warningText').innerHTML = '';    
}

var warningOKScript ;
var warningOKScriptParams ; 

function runWarningOkScript()
{    
    if (warningOKScriptParams)
    {    
        warningOKScript(warningOKScriptParams);
    } else if (warningOKScript) {
        warningOKScript();
    } 
}

function runWarningCancelScript()
{
    warningOKScript = null ;
    $find('warningModal').hide();
}

var successOKScript ;
var successOKScriptParams ;

function success(txt)
{
    if (document.getElementById('successPanel').style.display == 'none')
    {        
        $find('successModal').show();
        openModalId = 'successModal';    
        setTimeout('successFocus()',200);        
    }
    document.getElementById('successText').innerHTML += txt + '<br/>';
}

function runSuccessOkScript()
{    
    if (successOKScriptParams)
    {    
        successOKScript(successOKScriptParams);
        successOKScript = null;
    } else if (successOKScript) {
        successOKScript();
        successOKScript = null;
    } 
}

function successFocus()
{
    document.getElementById('successOK').focus();
}

function clearSuccess()
{
    document.getElementById('successText').innerHTML = '';    
}

function beginLoadingDiv(txt, id)
{

}

var g_LOADDELAY = 1000; 
var g_isLoading = false;
var g_checkLoadingMonitorID;

function beginLoading(txt)
{
    if (!g_isLoading) {

        g_isLoading = true;
        
        if (txt != "") {
            document.getElementById('loadingText').innerHTML += txt + '<br/>';
        } else {
            document.getElementById('loadingText').innerHTML = "Loading ... ";
        }

        if ($find('loadingModal')) {
            $find('loadingModal').show();
            openModalId = 'loadingModal';
        }

        g_checkLoadingMonitorID = setInterval('checkLoading()', g_LOADDELAY);
        return false;
    }
}

function checkLoading() {
    
    if (!g_isLoading) {

        clearInterval(g_checkLoadingMonitorID);
        document.getElementById('loadingText').innerHTML = '';
        if ($find('loadingModal')) {
            $find('loadingModal').hide();
        }
    }

}

function endLoading() {

    g_isLoading = false;    
    
}

function replaceLoadingText(txt)
{
    document.getElementById('loadingText').innerHTML = txt;
}

function appendLoadingText(txt)
{
    document.getElementById('loadingText').innerHTML += txt;
}

var openModalId = '';

function showAbout()
{
    openModalId = 'aboutModal';    
    $find('aboutModal').show();    
}

function showHelp()
{
    openModalId = 'helpModal';    
    $find('helpModal').show();    
}

var inc = 10;
var scrollUpTimeoutID ;
var scrollDownTimeoutID ;

function scrollAllDown(id)
{
    var theDiv = document.getElementById(id); 
    if (theDiv) 
    { 
        // does it exist?
        theDiv.scrollTop += 10000; 
        //scrollDownTimeoutID = setTimeout("scrollDown('" + id +"')", 20); 
    }
}

function scrollUp(id)
{        
    if (scrollUpTimeoutID)   { clearTimeout(scrollUpTimeoutID); }// make sure we do not start another timer 
    if (scrollDownTimeoutID) { clearTimeout(scrollDownTimeoutID); }// make sure we do not start another timer 
    
    var theDiv = document.getElementById(id); // get the hardcoded div
    if (theDiv) 
    {   
        // does it exist?
        theDiv.scrollTop -= inc; /* if vertical scroll increment the scrollTop to move down or up */
        //else theDiv.scrollLeft+=inc; // else increment scrollLeft to move right or left
        scrollUpTimeoutID = setTimeout("scrollUp('" + id +"')", 20); // do it again in 100 miliseconds
    }
}

function scrollDown(id)
{
    if (scrollUpTimeoutID)   { clearTimeout(scrollUpTimeoutID); }// make sure we do not start another timer 
    if (scrollDownTimeoutID) { clearTimeout(scrollDownTimeoutID); }// make sure we do not start another timer 
    
    var theDiv = document.getElementById(id); 
    if (theDiv) 
    { 
        // does it exist?
        theDiv.scrollTop += inc; 
        scrollDownTimeoutID = setTimeout("scrollDown('" + id +"')", 20); 
    }
}

function stopScroll(dir)
{    
    if (dir == 'down')
    {        
        if(scrollDownTimeoutID) { clearTimeout(scrollDownTimeoutID); }
    }
    else if (dir == 'up')
    {
        if(scrollUpTimeoutID)   { clearTimeout(scrollUpTimeoutID); }
    } 
    else if ((dir == 'all') || (dir == ''))
    {        
        if(scrollUpTimeoutID)   { clearTimeout(scrollUpTimeoutID); }
        if(scrollDownTimeoutID) { clearTimeout(scrollDownTimeoutID); }
    }
}

function updateImportName(fileObj)
{
    document.getElementById('importFileName').innerHTML = 'Import <strong>' + fileObj.value + '</strong>?';
}

var messageFadeTimerID = '';
var fade = false;
var lastCheckTime ;

function startMessageChecker()
{       
    var currentTime = new Date();
    lastCheckTime = (currentTime.getMonth() + 1) + '-' +        
        currentTime.getDate() + '-' +
        currentTime.getFullYear() + ' ' +
        currentTime.getHours() + ':' +
        currentTime.getMinutes() + ':' +
        currentTime.getSeconds() + '.' +
        currentTime.getMilliseconds();    
    setInterval('checkForUnreadMessages()', 1000);
    setTimeout('initMessageDiv()', 1000);
    //setTimeout('checkForUnreadMessages()', 1000);
}

function initMessageDiv()
{
    var messageDiv      = document.getElementById('message');    
    messageDiv.style.display = 'none';    
}

function checkForUnreadMessages()
{        
    com.netwitness.informer.MessageService.GetUnreadMessages(lastCheckTime, 
        unreadMessagesChecked,
        errorHandle, 
        timeoutHandle);
        
    var currentTime = new Date();
    
    lastCheckTime = (currentTime.getMonth() + 1) + '-' +        
        currentTime.getDate() + '-' +
        currentTime.getFullYear() + ' ' +
        currentTime.getHours() + ':' +
        currentTime.getMinutes() + ':' +
        currentTime.getSeconds() + '.' + 
        currentTime.getMilliseconds() ;    
}

function unreadMessagesChecked(result, eventArgs)
{
    alert('check');
    var unreadMessages = result.getElementsByTagName('message');
    var unreadMessageHTML = "";
    var messageDiv      = document.getElementById('message');     
    var messageDivTxt   = document.getElementById('messageTxt');  
    if (unreadMessages.length > 0)
    {
        for (var i = 0; i < unreadMessages.length ; i++)
        {
            if (unreadMessages[i].firstChild.getAttribute('link') != '')
            {
                unreadMessageHTML += 
                    '<span class="msgTimeStamp">'+unreadMessages[i].getAttribute('date')+'</span> ' + 
                    '<a href="' + unreadMessages[i].firstChild.getAttribute('link')+'">' +
                    unreadMessages[i].firstChild.firstChild.nodeValue + '</a><br/>';
            } else {
                unreadMessageHTML += 
                    '<span class="msgTimeStamp">'+unreadMessages[i].getAttribute('date')+'</span> ' +                     
                    unreadMessages[i].firstChild.firstChild.nodeValue + '<br/>';
            }
        }
        
        if (!fade)
        {
            fadeInMessage(unreadMessageHTML);
        } else {
            messageDivTxt.innerHTML = unreadMessageHTML + messageDivTxt.innerHTML;
        }
    }
}

function fadeInMessage(msg)
{
    var messageDiv      = document.getElementById('message');    
    var messageDivTxt   = document.getElementById('messageTxt');
    
    //messageDiv.style.height = '178px';
    //messageDiv.style.width  = '300px';
    messageDiv.style.display = '';
    //var left = parseInt(messageDiv.style.left.replace('px', '')) ;
    //messageDiv.style.left   = (window.outerWidth - 320) + 'px';  // width (300) + offset (20)    
    //alert(window.outerWidth - 320);
    //alert('window: '+window.outerWidth + ', left: ' + messageDiv.style.left) ;//+ ', subtracted: ' + window.outerWidth - 320);
    //messageDiv.style.top    = (window.outerHeight - 188) + 'px' ;  // height (178) + offset (10)
    messageDiv.style.left = '';
    messageDiv.style.top = '';
    messageDiv.style.right = '20px';
    messageDiv.style.bottom = '10px';
    //alert('window: ' + window.outerHeight + ', top: ' + messageDiv.style.top) ;//+ ', subtracted: ' + window.outerWidth - 320);
    fade = true;    
    AjaxControlToolkit.Animation.FadeInAnimation.play(messageDiv, .5, 20, 0, 1, false);
    messageFadeTimerID  = setTimeout("fadeOutMessage()", 7000);
    messageDiv.onmouseover = freezeMessage;
    messageDivTxt.innerHTML = msg;
}

function freezeMessage()
{
    var messageDiv = document.getElementById('message');
    messageDiv.className = 'systemMessageFreeze';   
    if (messageFadeTimerID != '')
    {        
        clearTimeout( messageFadeTimerID );
        messageDiv.onmouseout = unfreezeMessage;
    }
}

function closeMessageTray()
{
    if (messageFadeTimerID != '')
    {        
        clearTimeout( messageFadeTimerID );
        fadeOutMessage();
    }
}

function unfreezeMessage()
{
    var messageDiv       = document.getElementById('message');
    messageFadeTimerID   = setTimeout("fadeOutMessage()", 2000);
    messageDiv.className = 'systemMessage';
}

function fadeOutMessage()
{
    var messageDiv = document.getElementById('message');    
    AjaxControlToolkit.Animation.FadeOutAnimation.play(messageDiv, .5, 20, 0, 1, false);    
    setTimeout('fadeOutComplete()', 1000);
}

function fadeOutComplete()
{
    var messageDiv = document.getElementById('message');
    fade = false;
    messageDiv.onmouseout   = null;
    messageDiv.onmouseover  = null;
    messageDiv.style.display = 'none';    
    //messageDiv.style.height = '1px';
    //messageDiv.style.width  = '1px';
}

/* FOCUS HACK 
    this is to deal with the issue in Firefox versions below 3.0 where 
    the text boxes within the modal popup window lose the mouse cursor 
*/
function focusHack(id)
{    
    document.getElementById(id).focus();
}

/* Disable Text Selection
    By default, web browsers display a text selection cursor over every 
    visible text node in the HTML DOM, and users can select, 
    copy, and paste any text on a web page. This is not appropriate for 
    many Ajax applications, particularly if they involve drag-and-drop 
    functionality that interferes with the web browser's normal text 
    selection facilities. This simple function disables text selection 
    within a DOM node in all modern browsers:
    
    http://ajaxcookbook.org/disable-text-selection/
*/
function disableSelection(obj) 
{
    if (obj)
    {
        obj.onselectstart = function() {
            return false;
        };
        obj.unselectable = "on";
        obj.style.MozUserSelect = "none";
        obj.style.cursor = "default";
    }
}

function toggleCheckbox(cbObj) {

    if (cbObj.checked) {
        cbObj.checked = false;
    } else {
        cbObj.checked = true;
    } 

}

function getWindowSize() 
{
    var windowSize = new Object();
    
    if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
        windowSize.w = window.innerWidth;
        windowSize.h = window.innerHeight;
    } 
    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
    {
        //IE 6+ in 'standards compliant mode'
        windowSize.w = document.documentElement.clientWidth;
        windowSize.h = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
    {
        //IE 4 compatible
        windowSize.w = document.body.clientWidth;
        windowSize.h = document.body.clientHeight;
    }
    
    return windowSize;
}

// this function accepts an xml string as a parameter
// and diplays to the UI what the status and body of the 
// message is
function parseResponse(msgNode)
{        
    //alert(msgNode.firstChild.getAttribute('status') + ' - ' + msgNode.firstChild.firstChild.nodeValue);
    var status = msgNode.firstChild.getAttribute('status');
    if (status == 'success') 
    {
        // we are suppressing success messages for now because its annoying
        //success(msgNode.firstChild.firstChild.nodeValue);
    } 
    else if (status == 'warning')
    {
        warning(msgNode.firstChild.firstChild.nodeValue);
    }
    else if (status == 'error')
    {
        error(msgNode.firstChild.firstChild.nodeValue);
    }
}

/* DateTime Functions */
function getPastDate(day, numDays)
{
    // 1 day = 1 * 24 hours = 24 hours 
    // 24 hours = 24 * 60 min = 1440 min 
    // 1440 min = 1440 * 60 sec = 86400 sec 
    // 86400 sec = 86400 * 1000 ms = 86400000 ms 
    return new Date( day.getTime() - (numDays * 86400000) );
}

function getFutureDate(day, numDays)
{
    // 1 day = 1 * 24 hours = 24 hours 
    // 24 hours = 24 * 60 min = 1440 min 
    // 1440 min = 1440 * 60 sec = 86400 sec 
    // 86400 sec = 86400 * 1000 ms = 86400000 ms 
    return new Date( day.getTime() + (numDays * 86400000) );
}

function enableFileExport() {    

    if (document.getElementById('exportFile')) {    
        document.getElementById('exportFile').disabled = false;
    }

    if (document.getElementById('cmsUsername')) {
        document.getElementById('cmsUsername').disabled = false;
    }

    if (document.getElementById('cmsPassword')) {
        document.getElementById('cmsPassword').disabled = false;
    }
}

function disableFileExport()
{
    if (document.getElementById('exportFile')) {
        document.getElementById('exportFile').disabled = true;
    }

    if (document.getElementById('cmsUsername')) {
        document.getElementById('cmsUsername').disabled = true;
    }

    if (document.getElementById('cmsPassword')) {
        document.getElementById('cmsPassword').disabled = true;
    }
}

function setVersion()
{
    com.netwitness.informer.SecurityService.GetVersion(printVersion, 
        errorHandle,
        timeoutHandle);
}

function printVersion(result, eventArgs)
{        
    var version = result.firstChild.firstChild.nodeValue ;
    
    if (document.getElementById('version'))
    {
        document.getElementById('version').innerHTML = version;
    }
}

function createDayString()
{
    var today = new Date();
    var todayMonth  = ( today.getMonth()+1 >= 10 ) ? (today.getMonth()+1) : '0' + (today.getMonth()+1) ;
    var todayDate   = ( today.getDate() < 10) ? '0' + today.getDate() : today.getDate() ;
    
    return todayMonth + '-' + todayDate + '-' + today.getFullYear();
}

function createDayStringSlashes()
{
    var today = new Date();
    var todayMonth  = ( today.getMonth()+1 >= 10 ) ? (today.getMonth()+1) : '0' + (today.getMonth()+1) ;
    var todayDate   = ( today.getDate() < 10) ? '0' + today.getDate() : today.getDate() ;
    
    return todayMonth + '/' + todayDate + '/' + today.getFullYear();
}

function setMenu()
{
    if (isMoz)
    {
        if (getFirefoxVersion() == '3')
        {
            //alert(document.getElementById('themenu').className);
            //alert(document.getElementById('themenu').className.replace('menu','menuFirefox'));
            document.getElementById('themenu').className = document.getElementById('themenu').className.replace('menu','menuFirefox');
        }
    }
}

var previousFocusID ;
function returnFocus()
{    
    if (previousFocusID)
    {
        document.getElementById(previousFocusID).focus();
        previousFocusID = '';
    }
}

function killEvent(e)
{
    e.cancelBubble = true;
    e.returnValue = false;
    
    if (e.stopPropagation) 
    { 
        e.stopPropagation();
        e.preventDefault(); 
    }
    
    return false;    
}

// variables define what section of interface have focus
var focusCtrId;

var focusRuleTree       = 'focusRuleTree';
var focusMetaTree       = 'focusMetaTree';
var focusListTree       = 'focusListTree';
var focusReportTree     = 'focusReportTree';
var focusToolboxTree    = 'focusToolboxTree';
var focusChartTree      = 'focusChartTree';
var focusSearchBox      = 'focusSearchBox';

function setFocusCtr(id)
{
    focusCtrId = id;
}

function emptySelectObj(selectObj) {

    for (var i = 0; i < selectObj.options.length; i++) {

        selectObj.removeChild(selectObj[i]); 

    }

}

function emptySelectBox(selectBox) {

    for (var i = selectBox.options.length - 1; i >= 0; i--) {
        selectBox.remove(i);
    }
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode( str ) {
    return unescape(str.replace('+', ' '));
}
