//**************************************************************************
//		Copyright  Sybase, Inc. 1998-2000
//						 All Rights reserved.
//
//	Sybase, Inc. ("Sybase") claims copyright in this
//	program and documentation as an unpublished work, versions of
//	which were first licensed on the date indicated in the foregoing
//	notice.  Claim of copyright does not imply waiver of Sybase's
//	other rights.
//
//	 This code is generated by the PowerBuilder HTML DataWindow generator.
//	 It is provided subject to the terms of the Sybase License Agreement
//	 for use as is, without alteration or modification.  
//	 Sybase shall have no obligation to provide support or error correction 
//	 services with respect to any altered or modified versions of this code.  
//
//       ***********************************************************
//       **     DO NOT MODIFY OR ALTER THIS CODE IN ANY WAY       **
//       ***********************************************************
//
//       ***************************************************************
//       ** IMPLEMENTATION DETAILS SUBJECT TO CHANGE WITHOUT NOTICE.  **
//       **            DO NOT RELY ON IMPLEMENTATION!!!!		      **
//       ***************************************************************
//
// Use the public interface only.
//**************************************************************************

// these arrays will be filled with internationalized strings based on the server
var DW_shortDayNames = new Array("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat");
var DW_longDayNames = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var DW_shortMonthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec");
var DW_longMonthNames = new Array("January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

// these three are dependent on localization settings
//var DW_PARSEDT_monseq = 0;
//var DW_PARSEDT_dayseq = 1;
//var DW_PARSEDT_yearseq = 2;

//  Solução para o problema de formatação de data
//  Agrinei Jorge	24/01/2001
var DW_PARSEDT_dayseq = 0;
var DW_PARSEDT_monseq = 1;
var DW_PARSEDT_yearseq = 2;


// Added to determine if dates are being processed in client side JavaScript.
var bDateTimeProcessingEnabled = false;

var gMask = "";

// DWItemStatus
var DW_ITEMSTATUS_NOCHANGE = 0;
var DW_ITEMSTATUS_MODIFIED = 1;

// common utility functions



// By Andreas Bruckner, using decimal characters as dot. (BEGIN)

function convert2dot_string (strDecimalString) {
	var strDotString;
 	
 	if (DW_decimalChar == ",") {
 		// Replace all "," with "." to make the string to a valid number
 		strDotString = strDecimalString.replace (",", ".");
 	} else {
 		// Do nohting, because the decimalCharacter should not be "," (German-Format).
 		strDotString = strDecimalString;
 	}
 	
 	return strDotString;
 }

// By Andreas Bruckner, using decimal characters as dot. (END)



function escapeString( inString )
{
    var index;
    var outString = "";
    var tempChar;

    // force to string type or charAt will fail!
    if (typeof inString != "string")
    	inString = inString.toString();

    var strLength = inString.length;
    for ( index=0; index < strLength; index++ )
        {
        tempChar = inString.charAt( index );
        if (tempChar == "\"" || tempChar == "'") 
            outString += "~" + tempChar;
        else if (tempChar == "\r")
            outString += "~r";
        else if (tempChar == "\n")
            outString += "~n";
        else if (tempChar == "~")
            outString += tempChar + "~";
        else
            outString += tempChar;
        }
    return outString;
}

// default event returns to 0
function _evtDefault (value)
{
    if (value + "" == "undefined")
        return 0;
    return value;
}

//This is assuming that the browser supports ***Java Script 40***
//If it does not delete this code and use the commented out code

function DW_parseIsSpace(theChar)
{
    return /^\s$/.test(theChar);

//For Browsers not supporting ***Java Script 40***
//    return theChar == " " || theChar == "\t";
}

function DW_parseIsDigit(theChar)
{
    return /^\d$/.test(theChar);

//For Browsers not supporting ***Java Script 40***
//    return theChar >= "0" && theChar <= "9"
}

function DW_parseIsAlpha(theChar)
{
    return /^\w$/.test(theChar) && ! /^\d$/.test(theChar);

//For Browsers not supporting ***Java Script 40***
//   return (theChar >= "a" && theChar <= "z") || (theChar >= "A" && theChar <= "Z");
}

// auto binding of events expect <controlName>_<eventName>
function HTDW_eventImplemented(sEventName)
{
    // check if we already have one scripted
    if (this[sEventName] == null)
        {
        // check for function with default name
        var testName = this.name + '_' + sEventName;
        if (eval ('typeof ' + testName) == 'function')
            this[sEventName] = eval(testName);
        }

    return this[sEventName] != null;
}

// utility functions
function allowInString (inString, refString)
{
    var index, tempChar;
    var strLength = inString.length;
    for (index=0; index < strLength; index++)
        {
        tempChar= inString.charAt (index);
        if (refString.indexOf (tempChar)==-1)  
            return false;
        }
    return true;
}

function DW_Trim(inString)
{
    var indexStart, indexEnd, tempChar, outString;
    var strLength = inString.length;
    // skip leading blanks
    for (indexStart=0; indexStart < strLength; indexStart++)
        {
        tempChar= inString.charAt (indexStart);
        if (tempChar != " ")
            break;
        }
    if (indexStart != strLength)
        {
        // skip trailing blanks
        for (indexEnd=strLength-1; indexEnd > 0; indexEnd--)
            {
            tempChar= inString.charAt (indexEnd);
            if (tempChar != " ")
                break;
            }
        // get all chars in between
        outString = inString.substring(indexStart, indexEnd+1);
        }
    else
        outString = "";
    return outString;
}

function DW_Round(num, decPlaces)
{
	var powTen = Math.pow(10.0,decPlaces);
	num *= powTen;
	if (num >= 0)
	    num = Math.floor(num + 0.5);
	else
	    num = Math.ceil(num - 0.5);

    return num / powTen;
}

function DW_IsNonNegativeNumber(inString, bNilIsNull)
{
if (arguments.length < 2)
        bNilIsNull = false;
    if (inString == "")
        return bNilIsNull;
    else
    {
        var newString = DW_Trim(inString);		
        if (newString == "")								
            return false; 										
        else														
        {														
			var result = new DW_NumberClass();	
			if(DW_parseNumberStringAgainstMask(inString, result, false)) 	
			{													
				if (result >= 0) 							
					return true; 								
			}													
			
			return false; 									
		}														
    }
}

function DW_IsValidDisplayOrDataValue(inString, bNilIsNull)
{
    if (arguments.length < 2)
        bNilIsNull = false;
    if (inString == "")
        return bNilIsNull;
    else
        {
        var i;
        for(i = 0; i < this.displayValue.length; i++)
            {
            if (inString == this.displayValue[i])
                return true;		    
            if (inString == this.dataValue[i])
                return true;		    
            }
        return false;
        }
}

function DW_IsNumber(inString, bNilIsNull)
{
if (arguments.length < 2)
        bNilIsNull = false;
    if (inString == "")
        return bNilIsNull;
    else
    {
        var newString = DW_Trim(inString);		
        if (newString == "")		
            return false;		
        else			
			return DW_parseNumberStringAgainstMask(inString, null, true);		
    }
}

// exprContext class
function HTDW_exprContextClass(dataWindow)
{
    this.dw = dataWindow;
    this.row = -1;
    this.currentText = "";
}

// Col0 class
function HTDW_Col0Class(rowId)
{
    this.colModified = new Array();
    this.rowId = rowId;
    this.modified = false;
}

// Row class
function HTDW_RowClass(rowId)
{
    var col;

    // column 0 holds special data
    this[0] = new HTDW_Col0Class(rowId);
    
    // get data values
    for (col = 1; col < arguments.length ; col++)
        {
        this[0].colModified[col] = false;
        this[col] = arguments[col];
        }

    this.numCols = arguments.length;
}

function HTDW_Row_generateChange (rowNum, rowObj)
{
    var col;
    var result;

    if (rowObj[0].modified)
        {
        result = "(ModifyRow " + rowNum + " " + rowObj[0].rowId + " (";
        for (col = 1; col < rowObj.numCols; col++)
            {
            if (rowObj[0].colModified[col])
                {
                if (rowObj[col] == null)
                    result += "(" + col + " 1)";
                else
                    result += "(" + col + " 0 '" + escapeString(rowObj[col]) + "')";
                }
            }
        result += "))";
        }
    else
        result = "";

    return result;
}

function HTDW_Row_dumpRow (rowNum, rowObj)
{
    var col;
    var result;

    result = "Row " + rowNum + "\n" + 
             "Modified:" + rowObj[0].modified + "\n" +
             "RowId:" + rowObj[0].rowId + "\n" + 
             "NumCols:" + (rowObj.numCols - 1) + "\n";
             
    for (col = 1; col < rowObj.numCols; col++)
        {
        result += "   Col " + col + " modified:" + rowObj[0].colModified[col] + " '" + rowObj[col] + "'\n";
        }

    // alert (result);
    
    return result;
}

// set up class functions
HTDW_RowClass.generateChange = HTDW_Row_generateChange;
HTDW_RowClass.dumpRow = HTDW_Row_dumpRow;

function HTDW_ColumnGob(name, colNum, rowInDetail, region, bRequired, bNilIsNull, bFocusRect, formatFunc, getDisplayFormatFunc, getEditFormatFunc, column)
{
    this.name = name;
    this.colNum = colNum;
    this.rowInDetail = rowInDetail;
    this.region = region;
    this.bRequired = bRequired;
    this.bNilIsNull = bNilIsNull;
    this.bFocusRect = bFocusRect;

    this.getDisplayFormat = getDisplayFormatFunc;
    this.getEditFormat = getEditFormatFunc;
    this.format = formatFunc;
    this.column = column;
}

function HTDW_ComputeGob(name, region, computeFunc, formatFunc, getDisplayFormatFunc)
{
    this.name = name;
    this.region = region;

    this.compute = computeFunc;
    this.getDisplayFormat = getDisplayFormatFunc;
    this.format = formatFunc;
}

// Depend classes common function
// DependCompute class
function HTDW_DependComputeUpdate(htmlDw, row, bSkipCurrent)
{
    var gob = this.gob;
    var control = htmlDw.findControl(gob.name, row, gob.region == 0);

    if (control != null && typeof gob.compute == "function")
        {
        // body
        if (gob.region == 0)
            row = row;
        // header
        else if (gob.region == 1)
            row = htmlDw.firstRow;
        // footer or summary
        else if (gob.region == 2 || gob.region == 3)
            row = htmlDw.lastRow;

        var exprCtx = htmlDw.exprCtx;
        exprCtx.row = row;
        exprCtx.currentText = "";

        var value = gob.compute(exprCtx);

        if (control.type == "hidden" || control.type == "password" || 
            control.type == "text" || control.type == "textarea")
            {
            var displayValue;
            if (gob.format != null && gob.getDisplayFormat != null)
                {
                var formatString;
                if (typeof gob.getDisplayFormat == "string")
                    formatString = gob.getDisplayFormat;
                else
                    formatString = gob.getDisplayFormat (exprCtx);
                displayValue = gob.format (formatString, value);
                }
            else if (value != null)
                displayValue = value.toString();
            else
                displayValue = "";
            control.value = displayValue;
            }
        }
}

function HTDW_DependCompute(gob)
{
    this.gob = gob;
    
    this.update = HTDW_DependComputeUpdate;
}

// DependColumn class
function HTDW_DependColumnUpdate(htmlDw, row, bSkipCurrent)
{
    var gob = this.gob;
    var control = htmlDw.findControl(gob.name, row, gob.region == 0);

    // don't mess with the current control if asked not to
    if (control != null && 
            ! (bSkipCurrent && control == htmlDw.currentControl))
        {
        // body
        if (gob.region == 0)
            row = row + gob.rowInDetail;
        // header
        else if (gob.region == 1)
            row = htmlDw.firstRow;
        // footer or summary
        else if (gob.region == 2 || gob.region == 3)
            row = htmlDw.lastRow;

        var value = htmlDw.rows[row][gob.colNum];

        if (control.type == "hidden" || control.type == "password" || 
            control.type == "text" || control.type == "textarea" ||
            control.type == "select-one")
            {
            var displayValue;
            if (gob.format != null && gob.getDisplayFormat != null)
                {
                var exprCtx = htmlDw.exprCtx;
                exprCtx.row = row;
                exprCtx.currentText = "";
                if (typeof gob.getDisplayFormat == "string")
                    formatString = gob.getDisplayFormat;
                else
                    formatString = gob.getDisplayFormat (exprCtx);
                displayValue = gob.format (formatString, value);
                }
            else if (value != null)
                displayValue = value.toString();
            else
                displayValue = "";
            control.value = displayValue;
            }
        }
}

function HTDW_DependColumn(gob)
{
    this.gob = gob;

    this.update = HTDW_DependColumnUpdate;
}

// Column class
function HTDW_Column_addDepend(depend)
{
    if (this.dependents == null)
        this.dependents = new Array();

    this.dependents[this.dependents.length] = depend;
}

function HTDW_Column_updateDependents(htmlDw, row, bSkipCurrent)
{
    if (this.dependents != null)
        {
        for (var i=0; i < this.dependents.length; ++i)
            this.dependents[i].update (htmlDw, row, bSkipCurrent);
        }
}

function HTDW_ColumnClass(colId, name, convertFromStringFunc, typeValidationFunc, itemValidateFunc, validationMessageFunc, computeFunc, displayGobName)
{
    this.colId = colId;
    this.name = name;
    this.dependents = null;
    
    this.convertFromString = convertFromStringFunc;
    this.validateByType = typeValidationFunc;
    this.validateItem = itemValidateFunc;
    this.validationError = validationMessageFunc;
    this.compute = computeFunc;
    this.displayGobName = displayGobName;
    
    // interface functions
    this.addDepend = HTDW_Column_addDepend;
    this.updateDependents = HTDW_Column_updateDependents;

    this.displayValue = new Array();
    this.dataValue = new Array()
}

// DataWindow class
function HTDW_findControl(gobName, row, bInBody)
{
    var control;
    var controlExists;
    var controlName = gobName;
    var controlObject;

    if (bInBody)
        controlName += "_" + row;

    if (this.dataForm + "" != "undefined")
        {
        controlObject = 'this.dataForm.' + controlName;
        controlExists = eval('typeof ' + controlObject);
        if (controlExists == "object")
            control = eval(controlObject);
        }
    else if (this.navLayerForms[0] + "" != "undefined") // try array of Netscape layered forms
        {
        var rowObj = this.rows[row];
        var index = 0;
        if (bInBody)
            index = row * (rowObj.numCols - 1); // skip over for search
        for( ; index < this.navLayerForms.length; index++)
             {
             if (this.navLayerForms[index].elements[0].name == controlName)
                 {
                 control = this.navLayerForms[index].elements[0];
                 break;
                 }
             }
        }
    else
        control = null;
        
    return control;
}

function HTDW_itemGainFocus(newRow,newCol,control,gob)
{
    var bRowChanged = false;
    
    // default arguments
    control.row = newRow;
    control.col = newCol;
    control.gob = gob;
    
    // if in the middle of trying to force focus back
    // to a control, ignore all other focus stuff
	if (this.forcingBackFocusTo != null)
	    {
	    // check if we have made it back yet
	    if (this.forcingBackFocusTo == control)
	    {
    		this.forcingBackFocusTo = null;
    		this.currentControl = control;
	    }
    	// don't do any other focus related stuff
    	return;
    	}

    // bail if we think that the current control already has focus
    // (Could happen if a button is pressed)
    if (this.currentControl == control)
        return;
        
    if (newRow != -1)
        {
        if (newRow != this.currRow)
            {
            bRowChanged = true;

            // row focus changing event
            if (this.eventImplemented("RowFocusChanging"))
                {
                var result = _evtDefault(this.RowFocusChanging (this.currRow+1, newRow+1));
                // if 1 returned, don't allow focus to change (leave focus in last control to have gained focus
                if (result == 1)
                    {
                    this.restoreFocus();
                    // bail out early
                    return;
                    }
                }
            }
            
        this.currRow = newRow;
        }
    if (newCol != -1)
        this.currCol = newCol;

    this.currentControl = control;

    // update the displayed value to be in editible form
    if (newRow != -1 && newCol != -1 && 
	    (this.currentControl.type == "hidden" || this.currentControl.type == "password" ||
		 this.currentControl.type == "text" ||this.currentControl.type == "textarea"))
        {
        var value = this.rows[newRow][newCol];
        if (gob.format != null)
            {
            var displayValue;

            if (gob.getEditFormat != null)
                {
                var formatString;
                if (typeof gob.getEditFormat == "string")
                    formatString = gob.getEditFormat;
                else
                    {
                    var exprCtx = this.exprCtx;
                    exprCtx.row = control.row;
                    exprCtx.currentText = "";
                    formatString = gob.getEditFormat (exprCtx);
                    }
                displayValue = gob.format (formatString, value);
                }
            else if (value != null)
                displayValue = value.toString();
            else
                displayValue = "";
            this.currentControl.value = displayValue;
            }
        else if ( value != null )
            {
            // Do not compare against Date/Time if no date fields have been defined
            if (!bDateTimeProcessingEnabled ||
               (value.toString != DW_DatetimeToString &&
                value.toString != DW_DateToString &&
                value.toString != DW_TimeToString))
                this.currentControl.value = value.toString( );
            }
        else
            this.currentControl.value = "";
        }
    
    // can only programatically change border on IE4
    if (control.gob.bFocusRect && HTDW_DataWindowClass.isIE4)
        {
        this.currentControlBorder = control.style.borderStyle;
        control.style.borderStyle = "dotted";
        }
        
    // row focus changed event
    if (bRowChanged && this.eventImplemented("RowFocusChanged"))
        this.RowFocusChanged (newRow+1)
        
    // item focus changed event
    if (newCol != -1 && this.eventImplemented("ItemFocusChanged"))
        this.ItemFocusChanged (newRow+1, this.cols[newCol].name)
}

function HTDW_itemLoseFocus(control)
{
    // restore border
    // can only programatically change border on IE4
    if (control.gob.bFocusRect && HTDW_DataWindowClass.isIE4 && this.currentControl == control)
        control.style.borderStyle = this.currentControlBorder;

    // don't do validation if in the middle of forcing focus
    // due to validation error (endless loop could happen)
    if (this.forcingBackFocusTo != null)
        return 2;

    if (this.currentControl != control)
        {
           //---------------------------------------------------------------------------
           // O alert foi comentado pois é totalmente dispensável. O foco é passado
           // para o controle correto .... ninguem precisa ficar recebendo a mensagem!
           //---------------------------------------------------------------------------

           // alert("Problema de foco. O controle que perdeu o foco não é o controle atual!");

	   // fake it out
	   this.currentControl = control;
        }

	var gob = control.gob;
	if (gob.getEditFormat != null)
	{
		if (typeof gob.getEditFormat == "string")
		gMask = gob.getEditFormat;
		else
		{
			var exprCtx = this.exprCtx;
			exprCtx.row = control.row;
			exprCtx.currentText = "";
			gMask = gob.getEditFormat (exprCtx);
		}
	}

    if (!control.bChanged)  // check if Change misfired (losing focus beyond frame?)
        {
        var newValue;
        var row = control.row;
        var col = control.col;
        var rowObj = this.rows[row];
        var colObj = this.cols[col];

        if (control.type == "select-one")
            newValue = control.options[control.selectedIndex].value;
        else
            newValue = control.value;

        if (newValue == "")
            {
            if (control.gob.bNilIsNull)
				{
				if (rowObj[col] != null)
					control.bChanged = true;
				}
			else if (rowObj[col] != null && rowObj[col] != "")  // for inserts
				control.bChanged = true;
            }
        else if (colObj.convertFromString != null)
            {
            var convertedValue;
			if (colObj.convertFromString == parseInt)
			{
				var reg = /,/g;
				var noComma = newValue.replace(reg, "");
				convertedValue = colObj.convertFromString (noComma, 10);
			}
			else
				convertedValue = colObj.convertFromString (newValue);

            if (rowObj[col] != convertedValue)
                control.bChanged = true;
            }
        else
            {
            if (rowObj[col] != newValue)
                control.bChanged = true;
            }
        }

    var result = this.AcceptText();

	gMask = "";

    if (result == 1)
        {
        // reformat the data
        var gob = control.gob;
        var value = this.rows[control.row][gob.colNum];
		
        if (control.type == "hidden" || control.type == "password" || 
            control.type == "text" || control.type == "textarea")
            {
            if (gob.format != null)
                {
                var displayValue;

                if (gob.getDisplayFormat != null)
                    {
                    var formatString;
                    if (typeof gob.getDisplayFormat == "string")
                        formatString = gob.getDisplayFormat;
                    else
                        {
                        var exprCtx = this.exprCtx;
                        exprCtx.row = control.row;
                        exprCtx.currentText = "";
                        formatString = gob.getDisplayFormat (exprCtx);
                        }
                    displayValue = gob.format (formatString, value);
                    }
                else if (value != null)
                    displayValue = value.toString();
                else
                    displayValue = "";
                this.currentControl.value = displayValue;
                }
            else if ( value != null )
                {
                // Do not compare against Date/Time if no date fields have been defined
                if (!bDateTimeProcessingEnabled ||
                    (value.toString != DW_DatetimeToString &&
                     value.toString != DW_DateToString &&
                     value.toString != DW_TimeToString))
                     this.currentControl.value = value.toString( );
                }
            else
                this.currentControl.value = "";
            }
        }
        
    return result;
}


function HTDW_getChanges()
{
    var changes = "";
    var index, rowObj;
    for (index=0; index < this.rows.length; ++index)
        {
        rowObj = this.rows[index];
        if (rowObj != null)
            {
            HTDW_RowClass.dumpRow (index, rowObj);
            changes += HTDW_RowClass.generateChange (index, rowObj);
            }
        }
    return changes;
}

function HTDW_itemError(row, col, exprCtx, bIsRequired)
{
    var colObj = this.cols[col];
    var result = 0;

    // item error event
    if (this.eventImplemented("ItemError"))
        result = _evtDefault(this.ItemError (row+1, colObj.name, exprCtx.currentText))

    // map unknown results to 0
    if (result != 1 && result != 2 && result != 3)
        result = 0;
        
    if (result == 0)
        {
        //// Tradução das mensagens
        var sMessage;
        if (colObj.validationError != null)
            sMessage = colObj.validationError (exprCtx);
        else if (bIsRequired)
            sMessage = "É necessário especificar um valor para '" + colObj.name + "'.";
        else
            sMessage = "O item '" + exprCtx.currentText + "' não passou no teste de validação.";

        alert (sMessage);
        }

    return result;
}

function HTDW_restoreFocus()
{
    if (this.currentControl != null)
        {
        this.forcingBackFocusTo = this.currentControl;
        this.currentControl.focus();
        }
}



function HTDW_setCheckboxValue(control, chkValue, unchkValue)
{
    if (control.checked)
        control.value = chkValue;
    else
        control.value = unchkValue;
}

function HTDW_acceptText()
{
    // nothing to do if no current control
    if (this.currentControl == null)
        return 1;
        
    var control = this.currentControl;
    var row = control.row;
    var col = control.col;
    var bRequired = control.gob.bRequired;
    var colObj = this.cols[col];
    var bIsValid = true;
    var exprCtx = this.exprCtx;
    var validAction = 2;  // default to accept
    var newValue;
    if (control.type == "select-one")
        newValue = control.options[control.selectedIndex].value;
	else
	{
        newValue = control.value;

        // By Andreas Bruckner, using decimal characters as dot. (BEGIN)
 		if (colObj.validateByType == DW_IsNumber) {
 			// Current Item is of type number
 			// Change the may-existing comma (",") with dots (".").
 			control.value = convert2dot_string (control.value);
 			newValue = control.value;
 		}
        // By Andreas Bruckner, using decimal characters as dot. (END)

	}

    exprCtx.row = row;
    exprCtx.currentText = newValue;

    // check if value required
    if (bRequired && ! control.bChanged)
        {
        if (this.rows[row][col] == null)
            validAction = this.itemError (row, col, exprCtx, true);
        }
    else if (bRequired && control.gob.bNilIsNull && newValue == "")
        validAction = this.itemError (row, col, exprCtx, true);

    if (control.bChanged)
        {
        if (bIsValid && colObj.validateByType != null)
            bIsValid = colObj.validateByType(newValue, control.gob.bNilIsNull);

        if (bIsValid && colObj.validateItem != null)
            bIsValid = colObj.validateItem (exprCtx);

        // item changed event
        if (bIsValid && this.eventImplemented("ItemChanged"))
            {
            validAction = _evtDefault(this.ItemChanged (row+1, colObj.name, newValue));
            // map unknown results to 0
            if (validAction != 1 && validAction != 2)
                validAction = 0;
            // map itemChanged action codes to itemError action codes
            if (validAction == 0) // accept value
                validAction = 2;
            else
                {
                bIsValid = false;
                if (validAction == 1) // reject value, no focus change
                    validAction = 1;
                else // reject value, allow focus change
                    validAction = 3;
                }
            }

        if (! bIsValid)
            validAction = this.itemError (row, col, exprCtx, false);

        if (validAction == 2)
            {
            var rowObj = this.rows[row];
            if (control.gob.bNilIsNull && newValue == "")
                {
                if (rowObj[col] != null)
                    { 
                    rowObj[col] = null;
                    if (rowObj[0].modified != true)
                        this.modifiedCount++;
                    rowObj[0].colModified[col] = true;		    
                    rowObj[0].modified = true;
                    }
                }
            else if (colObj.convertFromString != null)
                {
				var convertedValue;
				if (colObj.convertFromString == parseInt)
					convertedValue = colObj.convertFromString (newValue, 10);
				else
					convertedValue = colObj.convertFromString (newValue);

                if (rowObj[col] != convertedValue)
                    {
                    rowObj[col] = convertedValue;
                    if (rowObj[0].modified != true)
                        this.modifiedCount++;	    
                    rowObj[0].colModified[col] = true;		    
                    rowObj[0].modified = true;
                    }
                }
            else
                {
                if (rowObj[col] != newValue)
                    {
                    rowObj[col] = newValue;
                    if (rowObj[0].modified != true)
                        this.modifiedCount++;	    
                    rowObj[0].colModified[col] = true;		    
                    rowObj[0].modified = true;
                    }
                }
            control.bChanged = false;
            // skip current control
            colObj.updateDependents(this, row, true);
            }
        }

    // force focus back if an error (focus change will happen after we return!)
    if (validAction < 2)
        {
        this.forcingBackFocusTo = control;
        control.focus();
        }

    var result = (validAction < 2) ? -1 : 1;

    return result;
}


// if false returned, don't allow focus to change or action to happen (leave focus in last control to have gained focus
function HTDW_itemClicked(row, col, objName)
{
    var evtResult = 0;

    // CR228156 - click on DDDW column fires a validation error in IE5.x - Partha
    if (this.currentControl != null)
    {
	if ( this.currentControl.type == "select-one" )
	{
	    if ( HTDW_DataWindowClass.isIE4 
		&& this.currentControl.gob.bRequired == true 
		&& this.currentControl.value == "" )
            	return false ;
	    else 
		if (this.AcceptText() != 1)
			return false;

	}
    	else if (this.currentControl.type == "checkbox" 
		|| this.currentControl.type == "radio" 
		|| this.currentControl.type == "select-multiple" )
	{
        	if (this.AcceptText() != 1)
			return false;
	}
    }
    
    if (this.eventImplemented("Clicked"))
        evtResult = _evtDefault(this.Clicked (row+1, objName));

    // prevent clicked event from bubbling up in IE4 or higher
    if (HTDW_DataWindowClass.isIE4)
        window.event.cancelBubble = true;

    this.clickedRow = row;
    this.clickedCol = col;
    
    return evtResult != 1;
}

function HTDW_performAction(action)
{
    var rc = 0;
    // OnSubmit can prevent the page from being submitted by returning 1
    if (this.eventImplemented("OnSubmit"))
        rc = _evtDefault(this.OnSubmit ());
    if (rc == 0)
    {
        // set action and context
    	this.actionField.value = action;
    	this.contextField.value = this.GetFullContext();

        var ls_context = new String(this.contextField.value);

	////// Agrinei Jorge	25/11/2003
	////// O caracter % não estava sendo interpretado corretamente por 
	////// ser especial no contexto web ( url escape )

        this.contextField.value = ls_context.replace(/[%]/gi,'%25');

	////// FIM


        this.submitForm.submit();
    }
}

function HTDW_GetFullContext()
{
    var result;

    result = this.context;
    result += "(";
    result += this.getChanges();
    if (this.currRow != -1)
        result += "(row " + this.currRow + ")";
    if (this.sortString != null)
        result += "(sortString '" + escapeString (this.sortString) + "')";
    result += ")";
    
    return result;
}

function HTDW_buttonPress(action, row, buttonName)
{
    var evtResult;

    // false from clicked will cancel processing
    if (!this.itemClicked(row, -1, buttonName))
        return;

    // button clicking event
    if (this.eventImplemented("ButtonClicking"))
        {
        evtResult = _evtDefault(this.ButtonClicking (row+1, buttonName));
        // non-zero return will cancel processing
        if (evtResult != 0)
            return;
        }

    // make sure all changes have been recorded
    if (action != "" && this.AcceptText() != 1)
        // cancel processing if AcceptText fails
        return;

    // update start event 
    if (action == "Update" && this.eventImplemented("UpdateStart"))
        {
        evtResult = _evtDefault(this.UpdateStart ());
        // a return of 1 will cancel action
        if (evtResult == 1)
            return;
        }

    if (action == "Print")
	    {
        window.print();
        return;
        }
    // an action of "" is a user defined button which doesn't cause a page reload
    if (action != "")
		this.performAction(action);
    else
        {
        // button clicked event
        if (this.eventImplemented("ButtonClicked"))
            this.ButtonClicked (row+1, buttonName)
        }
}

function HTDW_getColNum(col)
{
    if (typeof col == "string")
        {
        for (var i=1; i< this.cols.length; ++i)
            {
            var colObj = this.cols[i];
            if (colObj.name == col)
                return i;
            }
        }
    else
        return col;

    // if we get here, then we couldn't find it
    return -1;
}

function HTDW_DeletedCount()
{
	return this.deletedCount;
}

function HTDW_DeleteRow(row)
{
	if(this.AcceptText() == 1)
		{
		if (row > 0)
    		this.currRow = row-1;
		this.performAction ("DeleteRow");
		return 1;
		}
	else
		return -1;
}

function HTDW_GetClickedColumn()
{
	return this.clickedCol;
}

function HTDW_GetClickedRow()
{
	return this.clickedRow + 1;
}

function HTDW_GetColumn()
{
	return this.currCol;
}

function HTDW_GetNextModified(startRow)
{
    var nextModified = 0;
    var index, rowObj;

    if (startRow == null)
        return null;

    for (index=startRow-1; index < this.rows.length; ++index)
        {
        rowObj = this.rows[index];
        if (rowObj != null)
            {
            if (rowObj[0].modified)
                {
                nextModified = index+1;
                break;
                }
            }
        }
    return nextModified;
}

function HTDW_GetRow()
{
	return this.currRow + 1;
}

function HTDW_GetItem(row, col)
{
	var result;
	var colNum = this.getColNum(col);
    var rowObj = this.rows[row-1];

	if (colNum == -1 ||
	        (rowObj + "" == "undefined") || 
			rowObj[colNum] + "" == "undefined")
		result = -1;
	else
		result = rowObj[colNum];

	return result;
}

function HTDW_GetItemStatus(row, col)
{
    if (row == null || col == null)
        return null;

    var dwItemStatus = DW_ITEMSTATUS_NOCHANGE;
    var colNum = this.getColNum(col);
    var rowObj = this.rows[row-1];

    if (colNum == -1 ||
            (rowObj + "" == "undefined") || 
            (colNum > 0 && rowObj[colNum] + "" == "undefined"))
        dwItemStatus = -1;
    else if (colNum == 0)
        {
        if (rowObj[0].modified)
            dwItemStatus = DW_ITEMSTATUS_MODIFIED;
        }
    else
        {
        if (rowObj[0].colModified[colNum])
            dwItemStatus = DW_ITEMSTATUS_MODIFIED;
        }

	return dwItemStatus;
}

function HTDW_InsertRow(row)
{
	if(this.AcceptText() == 1)
		{
		this.currRow = row-1;
		this.performAction ("InsertRow");
		return 1;
		}
	else
		return -1;
}

function HTDW_ModifiedCount()
{
    return this.modifiedCount;
}

function HTDW_Retrieve()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("Retrieve");
		return 1;
		}
	else
		return -1;
}

function HTDW_RowCount()
{
	return this.rowCount;
}

function HTDW_ScrollFirstPage()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("PageFirst");
		return 1;
		}
	else
		return -1;
}

function HTDW_ScrollLastPage()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("PageLast");
		return 1;
		}
	else
		return -1;
}

function HTDW_ScrollNextPage()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("PageNext");
		return 1;
		}
	else
		return -1;
}

function HTDW_ScrollPriorPage()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("PagePrior");
		return 1;
		}
	else
		return -1;
}

function HTDW_SetItem(row,col,value)
{
	var result;
	var colNum = this.getColNum(col);
    var rowObj = this.rows[row-1];

	if (colNum == -1 ||
	        (rowObj + "" == "undefined") || 
			rowObj[colNum] + "" == "undefined")
		result = -1;
	else
		{
        if (rowObj[colNum] != value)
			{
			rowObj[colNum] = value;
			if (rowObj[0].modified != true)
				this.modifiedCount++;	    
			rowObj[0].colModified[colNum] = true;
			rowObj[0].modified = true;
			}

		// update them all
		this.cols[colNum].updateDependents(this, row-1, false);
		result = 1;
		}

	return result;
}

function HTDW_SetColumn(col)
{
    var result = -1;
	var colNum = this.getColNum(col);

    if (colNum != -1)
        {
        var colObj = this.cols[colNum];
        if (typeof colObj != "undefined" && colObj.displayGobName != null)
            {
            var control = this.findControl(colObj.displayGobName, this.currRow, true);
            // if we can't find a control, then we can't set the column
            if (control != null)
                {
                // force focus onto the found control
                // the onFocus event will change the currency variables
                control.focus();
                result = 1;
                }
            }
        }
	return result;
}

function HTDW_SetRow(row)
{
    var result = -1;
    row -= 1;
	var colNum = this.currCol;

    if (colNum != -1)
        {
        var colObj = this.cols[colNum];
        if (typeof colObj != "undefined" && colObj.displayGobName != null)
            {
            var control = this.findControl(colObj.displayGobName, row, true);
            // if we can't find a control, then we can't set the row
            if (control != null)
                {
                // force focus onto the found control, 
                // the onFocus event will change the currency variables
                control.focus();
                result = 1;
                }
            }
        }
	return result;
}

function HTDW_SetSort(sortString)
{
	this.sortString = sortString;
	return 1;
}

function HTDW_Sort()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("Sort");
		return 1;
		}
	else
		return -1;
}

function HTDW_Update()
{
	if(this.AcceptText() == 1)
		{
		this.performAction ("Update");
		return 1;
		}
	else
		return -1;
}


////----------------------------------------------------------------------------
//
// Função:  		HTDW_TFCValidate()
//
// Acesso:  		Public 
//
// Argumentos:		Nenhum
//
// Retorno:  		O mesmo do AcceptText
//
// Descrição:  	Esta função foi criada para modificar o comportamento de 
//              validação html. A validação era efetuada a cada vez que o
//              controle perdia o foco, e apenas se o controle perdesse o
//              foco. Essa função percorre todas as linhas e colunas da
//              datawindow e verifica se o dado respeita a expressão de
//              validação. Caso não respeite é mostrada a mensagem de validação
//              e o foco é passado para o controle.
//
// ----------------------------------------------------------------------------
// Histórico		
//
// Agrinei Jorge		14/08/2001		1.00.00	Versão inicial
// ----------------------------------------------------------------------------
// TecnoTRENDS
////----------------------------------------------------------------------------

function HTDW_TFCValidate()
{
   var li_row, li_column;
   var control;
   var gob;


   // Percorre as linhas
   for( li_row = 0; li_row < this.rowCount; li_row++ )
   {
      // Percorre as colunas
      for( li_column = 1; li_column < this.cols.length; li_column++ )
      {
         if ( control = this.findControl( this.cols[li_column].name, li_row, true) )
         {

            this.currentControl = control;
            this.currRow = li_row;
            this.currCol = li_column;

            control.gob = this.gobs[this.cols[li_column].name];
            control.row = li_row;
            control.col = li_column;


            //--------------------------------------------------------------------------------
            // Dispara o AcceptText no controle
            //--------------------------------------------------------------------------------

            var result = this.AcceptText();


            //--------------------------------------------------------------------------------
            // Se foi realizado com sucesso reformata o dado
            //--------------------------------------------------------------------------------


            if (result == 1)
            {
               // reformat the data
               gob = control.gob;
               var value = this.rows[control.row][gob.colNum];
		
               if (control.type == "hidden" || control.type == "password" || 
                    control.type == "text" || control.type == "textarea")
               {
                  if (gob.format != null)
                     {
                        var displayValue;

			if (gob.getDisplayFormat != null)
                        {
                           var formatString;
			   if (typeof gob.getDisplayFormat == "string")
                              formatString = gob.getDisplayFormat;
                           else
                           {
                              var exprCtx = this.exprCtx;
                              exprCtx.row = control.row;
                              exprCtx.currentText = "";
                              formatString = gob.getDisplayFormat (exprCtx);
                           }
                           displayValue = gob.format (formatString, value);
                        }
                        else if (value != null)
				    displayValue = value.toString();
                             else
				    displayValue = "";

                        this.currentControl.value = displayValue;
                     }
                     else if ( value != null )
                          {
				// Do not compare against Date/Time if no date fields have been defined
				if (!bDateTimeProcessingEnabled ||
				(value.toString != DW_DatetimeToString &&
				value.toString != DW_DateToString &&
				value.toString != DW_TimeToString))
				this.currentControl.value = value.toString( );
                          }
                          else
                          this.currentControl.value = "";
               }

            }
            else
            {
              return result;
            }

         }

      }
   }

   return 1;
        
}

function HTDW_DataWindowClass(name, submitForm, actionField, contextField)
{
    this.name = name;
    this.submitForm = submitForm;
    this.actionField = actionField;
    this.contextField = contextField;
    this.sortString = null;

    // private functions
    this.buttonPress = HTDW_buttonPress;
	this.performAction = HTDW_performAction;

    this.eventImplemented = HTDW_eventImplemented;
    this.itemClicked = HTDW_itemClicked;

    this.currRow = -1;
    this.currCol = -1;
    this.forcingBackFocusTo = null;
    this.currentControl = null;
    this.bSingleRow = false;
    
    this.gobs = new Object();
    this.rows = new Array();
    this.cols = new Array();
    this.navLayerForms = new Array();
    this.exprCtx = new HTDW_exprContextClass(this);

    // private functions
    this.getChanges = HTDW_getChanges;
    this.itemLoseFocus = HTDW_itemLoseFocus;
    this.itemError = HTDW_itemError;
    this.itemGainFocus = HTDW_itemGainFocus;
    this.restoreFocus = HTDW_restoreFocus;
    this.findControl = HTDW_findControl;
    this.setCheckboxValue = HTDW_setCheckboxValue;

    // public functions
    this.GetFullContext = HTDW_GetFullContext;

    // private functions
    this.getColNum = HTDW_getColNum;
    
    // public functions
    this.AcceptText = HTDW_acceptText;
	this.DeletedCount = HTDW_DeletedCount;
	this.DeleteRow = HTDW_DeleteRow;
	this.GetClickedColumn = HTDW_GetClickedColumn;
	this.GetClickedRow = HTDW_GetClickedRow;
	this.GetColumn = HTDW_GetColumn;
	this.GetNextModified = HTDW_GetNextModified;
	this.GetRow = HTDW_GetRow;
	this.GetItem = HTDW_GetItem;
	this.GetItemStatus = HTDW_GetItemStatus;
	this.InsertRow = HTDW_InsertRow;
	this.ModifiedCount = HTDW_ModifiedCount;
	this.Retrieve = HTDW_Retrieve;
	this.RowCount = HTDW_RowCount;
	this.ScrollFirstPage = HTDW_ScrollFirstPage;
	this.ScrollLastPage = HTDW_ScrollLastPage;
	this.ScrollNextPage = HTDW_ScrollNextPage;
	this.ScrollPriorPage = HTDW_ScrollPriorPage;
	this.SetItem = HTDW_SetItem;
	this.SetColumn = HTDW_SetColumn;
	this.SetRow = HTDW_SetRow;
	this.SetSort = HTDW_SetSort;
	this.Sort = HTDW_Sort;
	this.Update = HTDW_Update;
	this.TFCValidate = HTDW_TFCValidate;
}

// determine the client browser
// this should be used only where ABSOLUTELY necessary
// Generic JavaScript should be used where ever possible
HTDW_DataWindowClass.isNav4 = false;
HTDW_DataWindowClass.isIE4 = false;
if (parseInt(navigator.appVersion) >= 4)
    {
    HTDW_DataWindowClass.isNav4 = (navigator.appName == "Netscape");
    HTDW_DataWindowClass.isIE4 = (navigator.appName.indexOf("Microsoft") != -1);
    }

function DW_ShowCodeTableDisplayValue(formatString, value)
{
    if (value == null)
        return "";
    var result = value.toString();
    var i;
    for (i = 0; i < this.column.displayValue.length; i++)
        if (value.toString() == this.column.dataValue[i])
            {
            result = this.column.displayValue[i];
            i = this.column.displayValue.length; 
            }
    
   return result;
}

// between is inclusive
function DW_Between(val, test1, test2)
{
    if (val == null || test1 == null || test2 == null)
        return false;
        
    if (test1 <= val && val <= test2)
        return true;
    else
        return false;
}

function DW_BetweenByFunc(val, test1, test2, func)
{
    return func(test1, val) >= 0 && func(val, test2) <= 0;
}

function DW_In(testValue)
{
    var bResult = false;

    for (var i=1; i < arguments.length; i++)
        {
        if (arguments[i] == testValue)
            {
            bResult = true;
            break;
            }
        }
    return bResult;
}

function DW_InByFunc(testValue, func)
{
    var bResult = false;

    for (var i=2; i < arguments.length; i++)
        {
        if (func(arguments[i],testValue) == 0)
            {
            bResult = true;
            break;
            }
        }
    return bResult;
}


