/* ------------------------------------------------------------------------ *
 * SAS Institute, Inc.                                                      *
 *                                                                          *
 * Copyright (c) 2002 SAS Institute, Inc.  All rights reserved.             *
 *                                                                          *
 * Contains general functions used throughout the Citation Web application  *
 *                                                                          *
 * Dependencies: citation_events.js, citation_dialogUtils                   *
 *                                                                          *
 * @author Rick Evans (rievan) - no longer at SAS                           *
 * @author Harry Maxwell (sashjm)                                           *
 * ------------------------------------------------------------------------ */
// globals
var g_wrsVersion          = 3.1;
var g_console             = null;
var g_showDebugMsgs       = false;
var g_showEventDebugMsgs  = false;
var g_closeWindowOnError  = false;

var g_helpDocDialog       = null;
var g_step4CheckAll       = false;
var g_pageLoaded          = false;
var g_openTOC             = 'open';
// indicates the wizard step page number if in wizard
var g_wizardStep          = null;

// constants
var IMAGE_DIR = 'images/';
var TABLE_IMAGE_DIR = IMAGE_DIR + 'table/';
var MENU_END_SPACER_WIDTH = 15;

function findDOM(objectID) 
{
    if (objectID == null
        || objectID.match(/^$/)) 
    {
        return null;
    }
    return (document.getElementById(objectID));
}
function findDOMStyle(id) 
{
    var style = null;
    var obj = findDOM(id);
    if (obj != null)
    {
        style = obj.style;
    }
    return style;
}

// taken from O'Reilly JavaScript 4th Edition, pg 234
function showDebugMsgs(where,msg) {
    if (! g_showDebugMsgs) {
        return;
    }
    // open new window, first time this function is called
    if ((g_console == null) || (g_console.closed)) 
    {
        // no default URL supplied
        g_console = window.open('', 'DebugConsole',
            'width=750,height=350,left=10px,top=10px,resizable,scrollbars=yes', true);
        if (g_console.document.readyState == "complete")
        {    
            g_console.document.open('text/plain');
        }
    }
    /* - cannot be used with pop-up menus as it forces hidePopup to be called
    g_console.focus();
    */
    var text = null;
    if (msg) {
        text = where + ': ' + msg;
    } else {
        text = 'DEBUG: ' + where;
    }
    g_console.document.writeln(text);
    // always scroll to end so last line is visible
    g_console.scrollTo(0,1000000);
    status = text;
    // do not call close but leave window open
}
function getEventSource(where, event) {
    var eventSource = null;
    if (event) {
        var msg = '';
        // Netscape events
        if (event.target) {
            msg = 'NS-EVENT';
            event.stopPropagation();
            eventSource = event.currentTarget;
            if (event.currentTarget) {
                msg += ' target='+event.currentTarget.id
                    +', currentTarget='+event.currentTarget.id
                    +',';
            }
            msg += ' phase='+event.eventPhase;
        // IE events
        } else if (event.srcElement) {
            msg = 'IE-EVENT';
            event.cancelBubble = true;
            eventSource = event.srcElement;
            if (event.srcElement) {
                msg += ' source='+event.srcElement.id;
            }
            if (event.fromElement) {
                msg += ' from='+event.fromElement.id;
            }
            if (event.toElement) {
                msg += ' to='+event.toElement.id;
            }
        }
        if (g_showEventDebugMsgs
            && eventSource != null) {
            showDebugMsgs(where, msg);
        }
    }
    return eventSource;
}
function unload() {
    // do nothing for now
}
function onPageLoad() {
    // set variable that indicates the page has been fully loaded
    g_pageLoaded = true;
    
    registerActionTriggerIndicatorForReportLinks();
}
function initialize() {
    // nothing more to do as all other functions moved into mainPageLayout
    // to prevent nasty re-drawing due to jsp:includes being used with
    // struts template:get statements
}
function dialogInitialize() {
    var div = findDOM('pageContentsDiv');
    if (div != null) {
        try {
            //this works for IE
            div.style.height = document.body.clientHeight - 10;
        } catch (e) {
            try {
                //this works for Netscape
                div.style.height = window.innerHeight - 10;
            } catch (e) {
                div.style.height = "100%";
            }
        }
    }
    var preview = findDOM('previewData');
    if (preview != null) {
        try {
            //this works for IE
            preview.style.height = document.body.clientHeight - 115;
        } catch (e) {
            try {
                //this works for Netscape
                preview.style.height = window.innerHeight - 115;
            } catch (e) {
                preview.style.height = "100%";
            }
        }
    }
}
function showErrors(msgs) {
    if (msgs != null) {
        alert(msgs);
    }
}
function setSelectionCursor(doc) {
    if (doc != null && doc.style != null && doc.style.cursor != null)
    {
        if (navigator.appName.indexOf('Netscape') != -1) {
            // Netscape cursor
            doc.style.cursor = 'pointer';
        } else {
            // IE cursor
            doc.style.cursor = 'hand';
        }
    }
}
function setDefaultCursor(doc) {
    if (doc != null && doc.style != null && doc.style.cursor != null)
    {
        doc.style.cursor = 'auto';
    }
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Convenience method that sets the style of the cursor for current document's
// body to the given style. Calling this method is equivalent to calling
// setElementCursortStyle(document.body, style);
// @param style - cursort style to set for document
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function setDocumentCursorStyle(style) {
    setElementCursorStyle(document.body, style);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Sets the style of the elements cursor to the given style
// @param element - element whose cursor style is to be set
// @param style - cursort style to set for document
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function setElementCursorStyle(element, style) {
    element.style.cursor = style;
}
function handleKeyPress(event,dialog) 
{
    var keyCode = ( event.which != null ) ? event.which : event.keyCode;
    var stopProcessing = false;
    // escape key was pressed
    if (keyCode == 27) 
    {
        stopProcessing = true;
        // IE has different mechanism to cancel event processing
        if (navigator.appName.indexOf('Netscape') == -1) 
        {
            event.returnValue = false;
        }
        // always stop progress if progress exists
        var foundProgress = false;
        var progress = findDOM('progressIndicatorDialog');
        if (progress != null) 
        {
            if (progress.style.visibility == 'visible') 
            {
                foundProgress = true;
            }
        } 
        else 
        {
            progress = findDOM('progressIndicator');
            if (progress != null) 
            {
                if (progress.style.visibility == 'visible') 
                {
                    foundProgress = true;
                }
            }
        }
        // only call cancel progress when progress is visible
        // because it has the side affect of closing the dialog
        // or in main window going back to previous URLs
        if (foundProgress && cancelProgress != null) 
        {
            cancelProgress(dialog);
        } 
        else if (dialog) 
        {
            self.close();
        } 
        else 
        {
            // if current page is errors page then close it
            if (window.closeErrorsWindow != null) 
            {
                closeErrorsWindow();
            }
            // always make sure all popup menus are closed
            if (window.hideAllPopups != null) 
            {
                hideAllPopups(event);
            }
        }
    }
    return stopProcessing;
}

function allowNumericOnly(event) {
    var keyCode = ( event.which != null ) ? event.which : event.keyCode;
    var stopProcessing = false;
    if (! String.fromCharCode(keyCode).match(/[0-9]/)) {
        stopProcessing = true;
        // IE has different mechanism to cancel event processing
        if (navigator.appName.indexOf('Netscape') == -1) {
            event.returnValue = false;
        }
    }
    return stopProcessing;
}
function allowNoQuotes(event) {
    var keyCode = ( event.which != null ) ? event.which : event.keyCode;
    var stopProcessing = false;
    if (String.fromCharCode(keyCode) == "'"
        || String.fromCharCode(keyCode) == '"') {
        stopProcessing = true;
        // IE has different mechanism to cancel event processing
        if (navigator.appName.indexOf('Netscape') == -1) {
            event.returnValue = false;
        }
    }
    return stopProcessing;
}
function allowNoBlanks(event) {
    var keyCode = ( event.which != null ) ? event.which : event.keyCode;
    var stopProcessing = false;
    if (String.fromCharCode(keyCode) == " ") {
        stopProcessing = true;
        // IE has different mechanism to cancel event processing
        if (navigator.appName.indexOf('Netscape') == -1) {
            event.returnValue = false;
        }
    }
    return stopProcessing;
}
function changeImageInactive(id, baseName) {
    var doc = findDOM(id);
    if (doc != null) {
        doc.src = IMAGE_DIR + baseName + '_inactive.gif';
        doc.style.cursor = 'text';
    }
}
function changeImageActive(id, baseName) {
    var doc = findDOM(id);
    if (doc != null) {
        doc.src = IMAGE_DIR + baseName + '_default.gif';
        showDebugMsgs("changeImageActive", id + " = " + doc.src);
        doc.style.cursor = 'text';
    }
}
function changeImageRollover(id, baseName) {
    var doc = findDOM(id);
    if (doc != null) {
        doc.src = IMAGE_DIR + baseName + '_rollover.gif';
        showDebugMsgs("rollover", id + " = " + doc.src);
        setSelectionCursor(doc);
    }
}
// added by rkw to support application branding
// This functions changes the applied image to one in a static location instead 
// of the standard image directories
function changeImageStatic(id, imagePath) {
    var doc = findDOM(id);
    if (doc != null) {
        doc.src = imagePath;
        setSelectionCursor(doc);
    }
}
function changeTableImageActive(id, baseName) {
    var doc = findDOM(id);
    if (doc != null) {
        doc.src = TABLE_IMAGE_DIR + baseName + '-default.gif';
        doc.style.cursor = 'text';
    }
}
function changeTableImageRollover(id, baseName) {
    var doc = findDOM(id);
    if (doc != null) {
        doc.src = TABLE_IMAGE_DIR + baseName + '-rollover.gif';
        setSelectionCursor(doc);
    }
}

isGUICancelInProgress = false;
cancelButtonWasSuppressed = false;

function progressIndicatorStart() 
{
    var foundDialog = false;
    var progress = findDOM('progressIndicatorDialog');
    if (progress != null) {
        foundDialog = true;
    } else {
        progress = findDOM('progressIndicator');
        if (progress == null) {
            return;
        }
    }
    var progressIframe = findDOM('progressIndicatorIframe');
    if(progressIframe)
    {
        progressIframe.style.left = parseInt(progress.offsetLeft) + 1;
		progressIframe.style.top = parseInt(progress.offsetTop) + 1;
 		progressIframe.style.width = parseInt(progress.offsetWidth) - 1;
		progressIframe.style.height = parseInt(progress.offsetHeight) - 1;
		progressIframe.style.display = 'inline';  
    }
    
    var yOrigin = 0;
    if (! foundDialog) {
        yOrigin = 65;       // primary menu is 65px high
    }
    progress.style.top = yOrigin;
    progress.style.visibility = 'visible';
    if (foundDialog) {
        return;
    }

    content = findDOM('applicationLevelMenu');
    if (content != null) {
        content.style.visibility = 'hidden';
    }
    content = findDOM('applicationTabs');
    if (content != null) {
        content.style.visibility = 'hidden';
    }
    content = findDOM('reportLevelMenu');
    if (content != null) {
        content.style.visibility = 'hidden';
    }
    content = findDOM('welcome');
    if (content != null) {
        content.style.visibility = 'hidden';
    }
    
    window.scrollTo(0, 0);
    
    showDebugMsgs("progressIndicatorStart", "isGUICancelInProgress: " + isGUICancelInProgress);
    if(isGUICancelInProgress == true)
    {
        suppressCancelButtonAndChangeText(); 
        isGUICancelInProgress = false; 
        cancelButtonWasSuppressed = true;
    }
    else
    {
	    showDebugMsgs("progressIndicatorStart", "cancelButtonWasSuppressed: " + cancelButtonWasSuppressed);
	    if(cancelButtonWasSuppressed == true)
	    {
	        enableCancelButtonAndChangeText();
	        cancelButtonWasSuppressed = false;
	    }
	}
}
function progressIndicatorStop() {
    window.status = '';
    var progress = findDOM('progressIndicatorDialog');
    if (progress != null) {
        progress.style.visibility = 'hidden';
        progressIframe = findDOM('progressIndicatorIframe');
        if (progressIframe != null) {
            progressIframe.style.display = 'none';
        }
        return;
    }
    progress = findDOM('progressIndicator');
    if (progress != null) {
        progress.style.visibility = 'hidden';
    }
    progressIframe = findDOM('progressIndicatorIframe');
    if (progressIframe != null) {
        progressIframe.style.display = 'none';
    }    
    var content = findDOM('applicationLevelMenu');
    if (content != null) {
        content.style.visibility = 'visible';
    }
    content = findDOM('applicationTabs');
    if (content != null) {
        content.style.visibility = 'visible';
    }
    content = findDOM('reportLevelMenu');
    if (content != null) {
        content.style.visibility = 'visible';
    }
    content = findDOM('welcome');
    if (content != null) {
        content.style.visibility = 'visible';
    }  
}
function changeLabel(labelID, text) {
    var doc = findDOM(labelID);
    if (doc != null) {
        var kids = doc.childNodes;
        var numKids = kids.length;
        if (numKids > 0) {
            var kids2 = kids[0].childNodes;
            if (kids2 != null) {
                var numKids2 = kids2.length;
                if (numKids2 > 0) {
                    kids2[0].data = text;
                } else {
                    kids[0].data = text;
                }
            } else {
                kids[0].data = text;
            }
        }
    }
}
function getLabel(labelID) {
    var label = '';
    var doc = findDOM(labelID);
    if (doc != null) {
        var kids = doc.childNodes;
        var numKids = kids.length;
        if (numKids > 0) {
            label = kids[0].data;
        }
    }
    return label;
}
function changeTableImage(imageID, simpleRBID, crossRBID) {
    var imageDoc = findDOM(imageID);
    var simpleRB = findDOM(simpleRBID);
    var crossRB = findDOM(crossRBID);
    if (imageDoc != null
        && simpleRB != null
        && crossRB != null) {
        if (simpleRB.checked) {
            imageDoc.src = IMAGE_DIR + 'thumb_table_columns.gif';
        } else if (crossRB.checked) {
            imageDoc.src = IMAGE_DIR + 'thumb_table_crosstab.gif';
        }
    }
}
// IMPORTANT: This function should be called in response to a keyup event in a text field.
// If you call this in response to a keydown event then a newly typed character will not
// have been appended to the the text fields value yet when the onkeydown handler is
// invoked. I assume it could also be called in response to a keypress event but
// unfortunately IE 5+ doesn't recognize the backspace character correctly.
function checkLogon(usernameID, minUsernameLen, passwordID, minPasswordLen, logonButtonID) {
    if (findDOM(usernameID) != null
        && findDOM(passwordID) != null
        && findDOM(logonButtonID) != null) {

        var username  = findDOM(usernameID).value;
        var password  = findDOM(passwordID).value;

        //alert( 'username.length = ' + username.length + ',\npassword.length = ' + password.length );
        if (username.length >= minUsernameLen
            && password.length >= minPasswordLen) {
            // enable the button by changing the default images
            //  and allowing onClick, onMouseOver, and onMOuseOut
            findDOM(logonButtonID).disabled = false;
        } else {
            findDOM(logonButtonID).disabled = true;
        }
    }
}
// Activates the target element when the spacebar is pressed.
// The target element is activated by dispatching a click event
// to all of the target's onclick listeners.
function spaceBarActivateListener(event) {
    //alert('ENTERING spaceBarActivateListener');
    var keyCode = ( event.which != null ) ? event.which : event.keyCode;
    if( String.fromCharCode(keyCode) == ' ' ) {
        //space bar pressed while event target has focus
        var evtTrg = ( event.target != null ) ? event.target : event.srcElement;

        //dispatch a click event to the event target's click handlers
        eventNotify ( evtTrg, 'click', true );
    }
    //alert('EXITING spaceBarActivateListener');
}
//==============================================================================
// Functions to open and manage specific dialogs within the app
//==============================================================================
//
// requires citation_dialogUtils.js
function openRankFilterDialog(actionUrl)
{
    cwDialogManager.openDialog(
                        actionUrl, //dlgUrl
                        'cwBuilderRankFilter', //dlgName
                        cwDialogManager.RANK_FILTER, //dlgFeatures
                        true, //bReplaceUrl
                        true, //modal
                        false //bReplaceIfOpen
                    );
}
function openSaveDialog( link, onDlgClosing, onDlgClosed) 
{
    var saveDlg = cwDialogManager.openDialog(
                        link, //dlgUrl
                        cwDialogManager.SAVE_OPTIONS, //dlgName
                        cwDialogManager.SAVE_OPTIONS, //dlgFeatures
                        true, //bReplaceUrl
                        true, //bModal
                        false //bReplaceIfOpen
                    );

    if( onDlgClosing != null ) {
      registerEventHandler ( saveDlg, "WINDOW_CLOSING", onDlgClosing, false );
    }

    if( onDlgClosed != null ) {
      registerEventHandler ( saveDlg, "WINDOW_CLOSED", onDlgClosed, false );
    }
}
function closeHelpDocDialog() 
{
    if (g_helpDocDialog != null) {
        if (!g_helpDocDialog.closed) {
            g_helpDocDialog.close();
        }
        g_helpDocDialog = null;
    }
}
function openHelpDocDialog(event, helpPath) 
{
    var windowName = null;
    // nav.jsp is used for Table Of Contents and Index
    if ( helpPath.indexOf( "nav.jsp" ) != -1 ) {
        windowName = "SASHelpNavV";
    } else {
        windowName = "SASHelpV";
    }
    g_helpDocDialog = window.open(helpPath,
        windowName,
        'width=600px,height=475px,left=20px,top=20px,resizable=yes');
    g_helpDocDialog.focus();
}

function openGenericDialog(name,page) 
{
    cwDialogManager.openDialog(
                        page, //dlgUrl
                        name, //dlgName
                        cwDialogManager.STD_DLG_FEATURES, //dlgFeatures
                        true, //bReplaceUrl
                        false, //modal
                        false //bReplaceIfOpen
                    );
}
function openHelpWebPageDialog(name,page) 
{
    cwDialogManager.openDialog(
                        page, //dlgUrl
                        name, //dlgName
                        cwDialogManager.HELP_DLG, //dlgFeatures
                        true, //bReplaceUrl
                        false, //modal
                        false //bReplaceIfOpen
                    );
}
function cwPrintReport(reportUrl) 
{ 
	var dlgUrl = "openViewReportPrintOptions.do?dialogCommand=openDialog";
	if (reportUrl != null) {
		dlgUrl = "openViewReportPrintOptions.do?REPORT_ID=" + encodeURIComponent(reportUrl) + "&dialogCommand=openDialog";
	}
    openPrintDialog(dlgUrl); 
}     
function openPrintDialog(dlgUrl) 
{
    cwDialogManager.openDialog(
                        dlgUrl,  //dlgUrl
                        cwDialogManager.PRINT_OPTIONS,   //dlgName
                        cwDialogManager.PRINT_OPTIONS,   //dlgFeatures
                        true, //bReplaceUrl
                        true, //bModal
                        false //bReplaceIfOpen
                    );
} 
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CLASS BREAK XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
//------------------------------------------------------------------------------
// CLASS: RemoveInvalidSecurityChars
//
// Restricts input in an html "textarea" element to maximum of N characters.
//
// @param textInputField - the "textarea" element whose input is to be restricted
// the "textarea"
//------------------------------------------------------------------------------
function RemoveInvalidSecurityChars(textInputField)
{
    this.textField = textInputField;
}

//------------------------------------------------------------------------------
// For any events that would normally cause the value of the associated
// "textarea" to change this method responds by blocking any additonal
// input characters that would cause the maximum number of characters to be
// exceeded .
//------------------------------------------------------------------------------
RemoveInvalidSecurityChars.prototype.handleEvent = function(event)
{
    event = event != null ? event : window.event;
    if( event != null )
    {
        if( isPasteEvent != null && isPasteEvent(event)  )
        {
            var strPasteData = _removeBadCharacters(window.clipboardData.getData('Text'));

            var currentCharacterCount = strPasteData.length;
            if( currentCharacterCount > 0 )
            {
                // => insert paste chars at caret position
                // => use document's selection object to obtain insertion point
                if( document.selection != null )
                {
                    var insertionRange = document.selection.createRange();
                    insertionRange.text = strPasteData;
                    //automatically unselect text so subsequent input adds
                    insertionRange.collapse(false);
                    insertionRange.select();
                } else {
                    this.textField.value = this.textField.value + strPasteData;
                }
            }
        } else if( event.type == "keypress") {
            var keyCode = ( event.which != null ) ? event.which : event.keyCode;
            var keyData = _removeBadCharacters(String.fromCharCode(keyCode));
            if( document.selection != null )
            {
                var insertionRange = document.selection.createRange();
                insertionRange.text = keyData;
                //automatically unselect text so subsequent input adds
                insertionRange.collapse(false);
                insertionRange.select();
            } else {
                this.textField.value = this.textField.value + keyData;
            }
        }
        //simply block the default paste and keypress behavior
        return _terminateEventProcessing(event);
    }//if( event != null )
    else
    {
        alert("event == null");
        return false;
    }
}

//------------------------------------------------------------------------------
// Initializes the object by registering itself as a listener for the relevant
// events fired by the associated "textarea" object. Events listened for include
// paste and keypress events.
//
// NOTE: Users of this class must call this method for the class to have any effect.
//------------------------------------------------------------------------------
RemoveInvalidSecurityChars.prototype.initialize = function ()
{
    registerEventHandler( this.textField, 'keypress', this, false );
    registerEventHandler( this.textField, 'paste', this, false );
}
//------------------------------------------------------------------------------
// Private method that removes all security violation characters.
//
// Character    HTML        HexCode
// ---------    ----        -------
// <            &lt;        &#60;
// >            &gt;        &#62;
// (                        &#40;
// )                        &#41;
// #                        &#35;
// &            &amp;       &#38;
// \                        &#92;
//
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
//------------------------------------------------------------------------------
function _removeBadCharacters(value)
{
    var returnValue = value;
    returnValue = returnValue.replace(/\</g,"");
    returnValue = returnValue.replace(/\>/g,"");
    returnValue = returnValue.replace(/\(/g,"");
    returnValue = returnValue.replace(/\)/g,"");
    returnValue = returnValue.replace(/\&/g,"");
    returnValue = returnValue.replace(/\#/g,"");
    returnValue = returnValue.replace(/\\/g,"");
    return returnValue;
}
//------------------------------------------------------------------------------
// Private method that prevents the event being processed from being propagated
// up the document heirarchy. Also prevents the default behavior for the event
// being processed from occurring.
//------------------------------------------------------------------------------
function _terminateEventProcessing(eventObj)
{
    if( eventObj.preventDefault != null ) {
        //alert("preventDef");
        eventObj.preventDefault();
    }

    eventObj.returnValue = false;
    //eventObj.cancelBubble = true;

    if( eventObj.stopPropagation != null ) {
        //alert("stopPropagation");
        eventObj.stopPropagation();
    }

    return false;
}
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CLASS BREAK XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
//------------------------------------------------------------------------------
// CLASS: RemoveInvalidFilterChars
//
// Restricts input in an html "textarea" element to maximum of N characters for filters and prompts
//
// @param textInputField - the "textarea" element whose input is to be restricted
// the "textarea"
//------------------------------------------------------------------------------
function RemoveInvalidFilterChars(textInputField)
{
    this.textField = textInputField;
}

//------------------------------------------------------------------------------
// For any events that would normally cause the value of the associated
// "textarea" to change this method responds by blocking any additonal
// input characters that would cause the maximum number of characters to be
// exceeded .
//------------------------------------------------------------------------------
RemoveInvalidFilterChars.prototype.handleEvent = function(event)
{
    event = event != null ? event : window.event;
    if( event != null )
    {
        if( isPasteEvent != null && isPasteEvent(event)  )
        {
            var strPasteData = _removeBadCharacters(window.clipboardData.getData('Text'));

            var currentCharacterCount = strPasteData.length;
            if( currentCharacterCount > 0 )
            {
                // => insert paste chars at caret position
                // => use document's selection object to obtain insertion point
                if( document.selection != null )
                {
                    var insertionRange = document.selection.createRange();
                    insertionRange.text = strPasteData;
                    //automatically unselect text so subsequent input adds
                    insertionRange.collapse(false);
                    insertionRange.select();
                } else {
                    this.textField.value = this.textField.value + strPasteData;
                }
            }
        } else if( event.type == "keypress") {
            var keyCode = ( event.which != null ) ? event.which : event.keyCode;
            var keyData = _removeBadFilterCharacters(String.fromCharCode(keyCode));
            if( document.selection != null )
            {
                var insertionRange = document.selection.createRange();
                insertionRange.text = keyData;
                //automatically unselect text so subsequent input adds
                insertionRange.collapse(false);
                insertionRange.select();
            } else {
                this.textField.value = this.textField.value + keyData;
            }
        }
        //simply block the default paste and keypress behavior
        return _terminateFilterEventProcessing(event);
    }//if( event != null )
    else
    {
        alert("event == null");
        return false;
    }
}

//------------------------------------------------------------------------------
// Initializes the object by registering itself as a listener for the relevant
// events fired by the associated "textarea" object. Events listened for include
// paste and keypress events.
//
// NOTE: Users of this class must call this method for the class to have any effect.
//------------------------------------------------------------------------------
RemoveInvalidFilterChars.prototype.initialize = function ()
{
    registerEventHandler( this.textField, 'keypress', this, false );
    registerEventHandler( this.textField, 'paste', this, false );
}
//------------------------------------------------------------------------------
// Private method that removes all security violation characters.
//
// Character    HTML        HexCode
// ---------    ----        -------
// <            &lt;        &#60;
// >            &gt;        &#62;
// (                        &#40;
// )                        &#41;
// \                        &#92;
//
// Allows & and # to be used
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
//------------------------------------------------------------------------------
function _removeBadFilterCharacters(value)
{
    var returnValue = value;
    returnValue = returnValue.replace(/\</g,"");
    returnValue = returnValue.replace(/\>/g,"");
    returnValue = returnValue.replace(/\(/g,"");
    returnValue = returnValue.replace(/\)/g,"");
    returnValue = returnValue.replace(/\\/g,"");
    return returnValue;
}
//------------------------------------------------------------------------------
// Private method that prevents the event being processed from being propagated
// up the document heirarchy. Also prevents the default behavior for the event
// being processed from occurring.
//------------------------------------------------------------------------------
function _terminateFilterEventProcessing(eventObj)
{
    if( eventObj.preventDefault != null ) {
        //alert("preventDef");
        eventObj.preventDefault();
    }

    eventObj.returnValue = false;
    //eventObj.cancelBubble = true;

    if( eventObj.stopPropagation != null ) {
        //alert("stopPropagation");
        eventObj.stopPropagation();
    }

    return false;
}
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX END OF CLASS BREAK XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/

function redrawReportName(reportName) {
    var reportNameLabel = findDOM('reportName');
    if (reportNameLabel != null) {
        changeLabel('reportName', reportName);
    }
    reportNameLabel = findDOM('bantitle2');
    if (reportNameLabel != null) {
        changeLabel('bantitle2', reportName);
        if (findDOM('banbullet') != null) {
            if (reportName != null && ! reportName.match(/^$/)) {
                findDOM('banbullet').style.visibility = 'visible';
            } else {
                findDOM('banbullet').style.visibility = 'hidden';
            }
        }
    }
}
function closeErrorsWindow() 
{
    var rootAppWindow = cwDialogManager._getRootApplicationWindow(window);
    // Special override:
    // To the dialog manager, print window appears to be a main window.
    // the global variable override allows an unusual window, such as the
    // print output window, which acts like a top-level window but is not a dialog,
    // to designate behavior when it's close button is pressed after an 
    // error in printing.
    // showDebugMsgs("closeErrorsWindow" , window.name + " rootAppWin: " + rootAppWindow.name);
    if (g_closeWindowOnError) 
    {
        window.close();
    }
    // Root window
    //
    // Third case: from portal, not viewer (WRS), not a secondary window
    // start up WRS app from portal, no requested report, go to manage/open and 
    // try to render a report that fails.  Currently this is closing the window
    // even though it should revert to portal.  Usually the above would catch
    // a WRS main page situation because g_closeWindowOnError is set specially 
    // to true ONLY when it's the print preview window.
    else if (window == rootAppWindow)
    {
        // showDebugMsgs("closeErrorsWindow", "window is root with no opener");
        window.location.href = 'recoveryTransaction.do';
        return;
    }
    else 
    {    
	    // anything else other than the root window mandates that we shut the window
	    // that would go for any dialog window, or any auxiliary window, such as the
	    // print preview results.
	    window.close();
    }
}

var linksToExclude = new Array();

function addLinkToExclude( elementToExclude )
{
    linksToExclude[linksToExclude.length] = elementToExclude;
}

function excludeLink( elementToLookFor )
{
    for( var index = 0; index < linksToExclude.length; index++ )
    {
        if( linksToExclude[index] == elementToLookFor )
        {
            return true;
        }
    }
    return false;
}

var wrsMapLayer;
var wrsZoomLayer;

function registerActionTriggerIndicatorForReportLinks()
{
    for( index = 0; index < document.links.length; index++ ) 
    {
        var linkElement = document.links[index];
        if( linkElement.href != null && linkElement.href.indexOf('javascript') == -1
            && linkElement.target != '_blank' && excludeLink(linkElement) == false)  
        {
            if( registerEventHandler != null ) 
            {
                registerEventHandler( linkElement, 'click', onLeavePage, false );
            }
        }
    }
    
    // see if there is an ESRI map zoom layer available
    showDebugMsgs('registerActionTriggerIndicatorForReportLinks', 'WRS zoom layer: ' + wrsZoomLayer);
    if(wrsZoomLayer)
    {   // register click events on the zoom layer catches zoom in/out
        registerEventHandler( wrsZoomLayer, 'mouseup', onLeavePage, false );
        showDebugMsgs('registerActionTriggerIndicatorForReportLinks', 'Registered event handler for ESRI map zoom layer.');
    }          
}

function onLeavePage()
{
    progressIndicatorStart();
    if(typeof g_msgPleaseWait != "undefined")
        window.status = g_msgPleaseWait;
    var progressIndicatorElement = findDOM('progressIndicator');
    if(progressIndicatorElement != null)
    {
        findDOM('progressIndicator').style.height = document.body.scrollHeight;
    }
    
    reloadAnimatedImage('progressIndicatorImage');
}

// After the progress indicator has been hidden if it is made visible the animated spinning coin image no longer spun.
// Found this trick on the Net to reload the image simply by finding it in the DOM, saving the name, 
// setting it to an empty string and then restoring the same name. This reloads the image and gets it spinning again.

function reloadAnimatedImage(imageId)
{
    var imageString = '';
    var imageElement = findDOM(imageId);
    if( imageElement != null )
    {
        showDebugMsgs('reloadAnimatedImage', 'Found the target image to reload');
        imageString = imageElement.src;
        imageElement.src = '';
        imageElement.src = imageString;
    }
}

// var originalMapOnClick = window.sas_mapOnClick;
// var wrsMapOnClick = function(esriMapObjId)
// {
//     debugger;
//     wrsMapOnClick.originalMapOnClick(esriMapObjId);
//     var esriMapObject = eval(esriMapObjId);
//     if(esriMapObject != undefined)
//     {
//         if(esriMapObject.mode != 6) // if esri map and the identify action has been selected skip wait
//         {
//             onLeavePage();
//         }
//     }    
// }
// wrsMapOnClick.originalMapOnClick = originalMapOnClick; //add
// window.sas_mapOnClick = wrsMapOnClick;


