/*============================================================================
== Licensed Materials - Property of IBM                                     ==
==                                                                          ==
== 5697-D24                                                                 ==
==                                                                          ==
== (C) Copyright IBM Corp. 1995, 1998.    All Rights Reserved.              ==
==                                                                          ==
== US Government Users Restricted Rights - Use, duplication or disclosure   ==
== restricted by GSA ADP Schedule Contract with IBM Corp.                   ==
============================================================================*/

var cmdFormDoc = "/ncacom/s_cmd.htm"
var blankFN    = "/butnbars/s_blank.htm"

var doSaveFlag = false
var uniqueMagicCookie = 0
var badParameter="!@#$%"
var db2DecimalDelimiter = "."
var decimalDelimiter = "."

var cmdFrameNum = 2
var cmdFrameName = "results"
var cmdFrameURL = ""

var maxPerSearch  = 15
var searchMoreURL = ""

var origValue = ""
// @11246
var origValuePrev = ""
var origField


//==========================================================
// Getting version and types of browsers
//==========================================================
var iVer = parseFloat(navigator.appVersion);
var sName = navigator.appName;


//============================================================================
// Maximum lengths of text fields/text areas and URLs                       ==
//============================================================================

var kMaxLengthShopperGroupText = 1000
var kMaxLengthCategoryTemplateDescription = 4000
var kMaxLengthProductLongDescription = 4000
var kMaxLengthProductTemplateDescription = 4000
var kMaxLengthStoreDescription = 1000

//==========================================================
// Other constants
//==========================================================

var kMaximumDecimalPlacesInPrice = 2;
var kAccessControlError = "/ncerror/auth.html";

//==========================================================
// Utility functions
//==========================================================

// --- Adrian Changes : Added a extra parameter to determine which FORM was passed ------
// --- Most important Function as it affects the Product and Price page!!!!!
// Returns the last form or the 2nd last page depending on the form_flag in a window
// If the flag is True, it will return the last form
// If flag is False, it will return the 2nd last form (needed Only by the Product,Price Page


function gGetLastForm( aWindow ,form_flag)
{
 	// Show how many forms are there
	//alert ("Currently there is " + aWindow.document.forms.length + "forms.");

   if( aWindow == null )  {
		alert( "Parameter 'aWindow' missing in call to gGetLastForm()" )
	 }
	else if (!form_flag) {
		// the the forms to 0 because it is the Product_information form
		return( aWindow.document.forms[aWindow.document.forms.length - 2])

	}
	else if (form_flag) {
	 //alert("Return the Original Form");
	 return( aWindow.document.forms[aWindow.document.forms.length - 1] );
	}

	alert("Can't get Forms")
	return ("");

}

function dumpObject( obj )
{
    var text = "Object:\n";
    for( var i in obj ) {
	    text += obj[i] + "\n";
	}
	alert( text );
}


//==============================
// NCSelectOption object
//==============================

// Used for generating <OPTION> tags dynamically
function NCSelectOption( value, text )
{
    // Properties
    this.value = value;
    this.text = text;

    // Methods
    this.addToTable = NCSelectOption_addToTable;
    this.getTag = NCSelectOption_getTag;
}

function NCSelectOption_addToTable( table )
{
    table[table.length] = this;
}

// Tags cannot be generated unless they are first in line?!
function NCSelectOption_getTag()
{
    return( "<OPTION VALUE=\"" + this.value + "\">" + this.text + "</OPTION>" );
}

function generateOptionTags( aWindow, table )
{
    for( var i = 0; i < table.length; i++ ) {
         aWindow.document.writeln( table[i].getTag() );
    }
}


function getOrigValue(field) {
    // @11246
    origValuePrev = origValue
    origValue = field.value
    origField = field
}

function nochange(field) {
    // @11246
    var backValue = ( !origField || field == origField ) ? origValue : origValuePrev
    if (field.value != backValue){
        alert(msgNoChange)
        field.value = backValue
        if(backValue == origValue)
            origValue = ""
    }
}

function MakeArray(n) {
    this.length = n
    return this
}

function isBlank(str) {
    if ((str != null) && (str != "")) {
        for (var i=0; i < str.length; i++) {
            var ch = str.charAt(i)
            if ((ch != ' ') && (ch != '\r') && (ch != '\n') && (ch != '\t')) {
                return false
            }
        }
    }

    return true
}

function reprompt(field, message) {
    window.status = "";
    alert(message);
    field.focus();
    field.select();
	top.enableSubTask=true;
}

function repromptFieldTooLong( field, nBytes ) {
    var msgSend = msgFieldTooLong + " Maximum length is " + nBytes + " characters."
    reprompt( field, msgSend )
}

function checkSelectData(str) {
    if (isBlank(str)) return ""
    else return str
}

function checkString(field) {
    if (field.value.indexOf('"') != -1) {
        reprompt(field, msgDoubleQuoteNotAllowed)
        return false
    }

    if (field.value.indexOf("\\") != -1) {
        if (field.name == "mhthead"  || field.name == "mhtfoot"   || field.name == "mhtbase" ||
            field.name == "apidllname"  || field.name == "mafilename" || field.name == "methmb"      ||
            field.name == "metbase"     || field.name == "methead"      || field.name == "metfoot" ||
            field.name == "cgdisplay"   || field.name == "cgthmb"     || field.name == "cgfull"    ||
            field.name == "prthmb"      || field.name == "prfull"       || field.name == "prurl"    ||
            field.name == "psdisplay"   || field.name == "csdisplay" ||
            field.name == "cydebug_log" || field.name == "cynotification_log" ||
            field.name == "cyorder_log" || field.name == "mpdirname") {
            // field for specifying file names; special handling provided
        }
        else {
            // DBCS
            if (DBCSFlag) {
                var i = 0
                var j = 0
                var threeChars
                var okFlag = true
                var escVal = escape(field.value)
                var len    = escVal.length
                var slash  = escape("\\")    // "%5C"

                while (i != len && (j = escVal.indexOf(slash, i)) != -1) {
                    if (j < 3) {
                        okFlag = false
                        break
                    }

                    threeChars = escVal.substring(j-3, j)
                    if (isDBCSEsc(threeChars)) {
                        i = j + 3
                    }
                    else {
                        okFlag = false
                        break
                    }
                }

                if (okFlag) return true
            }
            // DBCS

            reprompt(field, msgBackslashNotAllowed)
            return false
        }
    }

    return true
}

function checkAlphanumeric(field) {

    var str = rmTrailingBlank(field.value)

    var ch
    for (var i=0; i<str.length; i++) {
        ch = str.charAt(i)
        if ((ch >= "0" && ch <= "9") || (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z")) {
            // ok
        } else {
          /*  reprompt(field, msgNotAlphanumeric) */
            return false
        }
    }

    return true
}

function checkThousand(inputStr) {
    if (isBlank(inputStr)) return true

    var fail = false
    var last = inputStr.length - 1
    var k

    // The rule is: If delimiter is used, they must be entered at every thousand.
    while ((k=inputStr.lastIndexOf(thousandDelimiter, last)) != -1) {
        if ((last-k) != 3) {
            fail = true
            break
        }
        last = k - 1
    }
    if (!fail) {
        if ((last < 0) || ((last >= 3) && (last != (inputStr.length-1)))) fail = true
    }

    return !fail
}

function rmThousand(str) {
    var result = ""
    var k = 0
    var l
    while ((l=str.indexOf(thousandDelimiter, k)) != -1) {
        result += str.substring(k, l)
        k = l + 1
    }
    result += str.substring(k, str.length)

    return result
}

function addThousand(str) {
   if (isBlank(str)) return ""

    var result = ""
   var db2DecPos = str.indexOf(db2DecimalDelimiter)
   var tmp = (db2DecPos == -1) ? str :
             (str.substring(0, db2DecPos) + decimalDelimiter +
              str.substring(db2DecPos+1, str.length))

    if (displayThousandDelimiter) {
        var decPos = tmp.indexOf(decimalDelimiter)
        var end  = (decPos == -1) ? tmp.length : decPos
        var tail = (decPos == -1) ? "" : tmp.substring(decPos, tmp.length)

        for (var i=end; i>3; i-=3) {
            result = thousandDelimiter + tmp.substring(i-3, i) + result
        }
        result = tmp.substring(0, i) + result + tail
    }
    else result = tmp

    return result
}

function doCheckInteger(field, show, inputStr) {
    for(var i=0; i < inputStr.length; i++) {
        var oneChar = inputStr.substring(i, i+1)
        if ((oneChar < "0" || oneChar > "9") && (oneChar != thousandDelimiter)) {
            if (show) reprompt(field, msgNotInteger)
            return badParameter
        }
    }

    if (!checkThousand(inputStr)) {
        if (show) reprompt(field, msgThousandDelimWrongPos)
        return badParameter
    }

    var num = rmThousand(inputStr)
    if (show) {  // this mean we are dealing with an integer field, not a float
        if (num.length > 9) {
            reprompt(field, msgIntegerTooLarge)
            return badParameter
        }
    }
    return num
}

function checkInteger(field, show) {
    inputStr = rmTrailingBlank(field.value)
    return doCheckInteger(field, show, inputStr)
}

function checkPlusMinusInteger(field, show) {
    inputStr = rmTrailingBlank(field.value)
    var num

    var ch1 = inputStr.charAt(0)
    if (ch1 == "+" || ch1 == "-") {
        num = doCheckInteger(field, show, inputStr.substring(1, inputStr.length))
        if (num != badParameter && ch1 == "-") num = "-" + num
    }
    else {
        num = doCheckInteger(field, show, inputStr)
    }

    return num
}

function checkFloat(field) {
    if (isBlank(field.value))   return ""
    inputStr = rmTrailingBlank(field.value)
    // check for existence of the decimal separator "." or ","
    var first_dot_pos = inputStr.indexOf(decimalDelimiter)
    var last_dot_pos  = inputStr.lastIndexOf(decimalDelimiter)

    if (first_dot_pos == -1) {
        var result
        if ((result=checkInteger(field, false)) != badParameter) return result
    }

    // check if only a separator was typed
    if ((inputStr.length == 1) && (first_dot_pos == 0)) {
        reprompt(field, msgNotFloat)
        return badParameter
    }

    // one separator there with something else
    // now look for a second separator
    if(first_dot_pos != last_dot_pos) {
        reprompt(field, msgNotFloat)
        return badParameter
    }

    // only one separator, now check all characters
    for(var i=0; i < inputStr.length; i++) {
        var oneChar = inputStr.substring(i, i+1)
        if((oneChar < "0" || oneChar > "9") && (oneChar != decimalDelimiter) && (oneChar != thousandDelimiter)) {
            reprompt(field, msgNotFloat)
            return badParameter
        }
    }

    var end = (last_dot_pos != -1) ? last_dot_pos : inputStr.length
    if (!checkThousand(inputStr.substring(0, end))) {
        reprompt(field, msgThousandDelimWrongPos)
        return badParameter
    }

    // no thousand delimiter after decimal point
    if (inputStr.lastIndexOf(thousandDelimiter) > end) {
        reprompt(field, msgThousandDelimWrongPos)
        return badParameter
    }

    var retVal = rmThousand(inputStr)
    last_dot_pos = retVal.lastIndexOf(decimalDelimiter)  // the decimal point position may have changed after rmThousand
    return (last_dot_pos == -1) ? retVal :
             (retVal.substring(0, last_dot_pos) + db2DecimalDelimiter + retVal.substring(last_dot_pos+1, retVal.length))
}

function setFillFormStatus() {
    status = msgFillFormStatus
}

function getParamDelim(count) {
  return ((count == 0) ? "?": "&")
}

function rmTrailingBlank(str) {
    if (str == "" || str == null) return str

    var lastBlank = str.lastIndexOf(' ')
    if (lastBlank == (str.length-1)) {
        var i
        for (i=str.length-2; i>=0; i--) {  // It is blank at str.length-1
            if (str.charAt(i) != ' ')
                break
        }
        return str.substring(0, i+1)       // From 0 to ith chars are returned
    }
    else return str
}

function rmTrailingHex20(str) {
    if (str == "" || str == null) return str

    var last20 = str.lastIndexOf("20")
    if (last20 == (str.length-2)) {
        var i
        for (i=str.length-4; i>=0; i-=2) {
            if ((str.charAt(i) == "2") && (str.charAt(i+1) == "0"))
                continue
            else
                break
        }
        return str.substring(0, i+2)
    }
    else return str
}

function sendCommandURL(url)
{
    sendURLFromFrame(frames.results, url);
	 dsf

}

function sendURLFromFrame(frame, url)
{
    cmdFrameURL = url;
    // !JBR-97.7.29 Data must be sent to server using POST method
    gSubmitUsingPOST( null, url, frame );
    // !JBR Removed code
    // frame.location = cmdFormDoc
}

function sendURLFromForm(form, url) {
    form.action = url
    form.submit()
}

function getDoc(frame, url)
{
    frame.location = url
}

function postDoc(frame, url)
{
    gSubmitUsingPOST( null, url, frame );
}

function doSearch(form, doSave) {
	/* True if its called by doSave rather then doSearch */
    doSaveFlag = doSave

    var searchURL = createSearchURL(form, doSave)

    if (searchURL == badParameter) return

    if (!doSave) {
        var begin = 1
        var end = begin + maxPerSearch
        searchMoreURL = searchURL
        searchURL += getParamDelim(1) + "BeginRow=" + begin + getParamDelim(2) + "EndRow=" + end

    }

    //alert("I'm doing a General Search with the following URL : " + searchURL);

    sendCommandURL(searchURL);           // doSave is true, otherwise false
}



function getMoreSearchResults(lastEnd) {
    var begin = lastEnd
    var end   = begin + maxPerSearch
    var searchURL = searchMoreURL + getParamDelim(1) + "BeginRow=" + begin + getParamDelim(2) + "EndRow=" + end
    sendCommandURL(searchURL)
}

function getNextSearchResults(nextKey) {
    var searchURL = searchMoreURL + getParamDelim(1) + "BeginKey=" + nextKey
    sendCommandURL(searchURL)
}

function setMoreSearchStatus() {
    status = msgMoreSearchStatus
}

function doSave(form) {

  // ============= UN COMMENTED BY ERVIN ==================
    if (!checkMandatory(form)) return 
  // ======================================================


    if (getParams(form, false) == badParameter) return    // check all parameters

    doSearch(form, true)
}



function doInsert(form) {

    var insertURL = createInsertURL(form) // parameters already checked
    doSaveFlag = false    // reset the flag
    frames.results.document.close()  // close the search document in order to open the insert document
    sendCommandURL(insertURL)
}

function doUpdate(form) {
    var updateURL = createUpdateURL(form) // parameters already checked
    doSaveFlag = false    // reset the flag
    frames.results.document.close()  // close the search document in order to open the insert document
    sendCommandURL(updateURL)
}

function doDelete(form) {
    if (!checkKeyOnly(form)) return

    var deleteURL = createDeleteURL(form)
    if (deleteURL == badParameter) return

    if (!confirm(msgDeleteConfirm)) return
    sendCommandURL(deleteURL)
}

function doDeleteNoConfirm(form) {
    if (!checkKeyOnly(form)) return

    var deleteURL = createDeleteURL(form)
    if (deleteURL == badParameter) return

    sendCommandURL(deleteURL)
}

function doClear(form)
{
    clearForm(form)
    cmdFrameURL = ""

    getDoc(frames.results, blankFN)
}


/* ------------------- Adrian Changes Added New Function to Clear Forms with
both Product Info and Product Price Form ---------------- */

function doClear_new(form,form2)
{
    clearForm(form)
    clearForm(form2)  /*-------------  Adrian Changes ----- Clear the Price Form also */
    cmdFrameURL = ""

    getDoc(frames.results, blankFN)
}

function doReload(frame, form) {
    var param = getParams(form, false)
    var url = reloadCmd + param
    gSubmitUsingPOST( "reload", url, frame )
}

function createSearchURL(form, keyOnly) {
    var param = getParams(form, keyOnly)


    if (param != badParameter) {

    var url = searchCmd + param
    return url
    }
    else
    return badParameter
}

function createInsertURL(form) {
    var param = getParams(form, false)
    if (param != badParameter) {
    var url = insertCmd + param
    return url
    }
    else
    return badParameter
}

function createUpdateURL(form) {
    var param = getParams(form, false)
    if (param != badParameter) {
    var url = updateCmd + param
    return url
    }
    else
    return badParameter
}

function createDeleteURL(form) {
    var param = getParams(form, true)
    if (param != badParameter) {
    var url = deleteCmd + param
    return url
    }
    else
    return badParameter
}

function addPercent(inputStr) {
    var len = inputStr.length
    var finalStr = ""
    var opSys = navigator.userAgent

    for(var i=0; i <= len-2; i+=2) {
        var twochars = inputStr.substring(i, i+2)
        if((twochars == "0D") || (twochars == "0d")) {
            if(opSys.indexOf("Win") >= 0)
                finalStr += "%0D%0A"
            else
                finalStr += "%0A"

            continue
        }
        finalStr += "%" + twochars
    }
    return finalStr
}

function uniqueToken (delimCount) {
    return ( getParamDelim(delimCount) + "uniqueToken=" + (new Date()).getTime() )
}

function checkSelected(formElement) {
    if (formElement.selectedIndex < 1) return
    if (formElement.selectedIndex == formElement.length -1) {
        formElement.selectedIndex -= 1
    }
}

// DBCS
var b1 = unescape("%81")
var e1 = unescape("%9F")
var b2 = unescape("%E0")
var e2 = unescape("%FC")

function isDBCSEsc(threeChars) {
    if (threeChars.charAt(0) != "%") return false

    var ch = unescape(threeChars)
    if ((ch >= b1 && ch <= e1) || (ch >= b2 && ch <= e2))
        return true
    else
        return false
}
// DBCS

// returns true if c is a digit
function isDigit( c ) {
    if( c.length > 1 )
        alert( "ERROR: isDigit() must be passed a string of length one." )
    if( isNaN( parseInt( c ) ) ) return false
    else return true
}

// returns true if s is a string representing a positive number and nothing
// else (unlike parseInt() which accepts a number followed by garbage)
function isPositiveNumber( s ) {
    if( isBlank( s ) ) return false
    var sLength = s.length
    var currentPosition = 0
    while( currentPosition < sLength ) {
        if( !isDigit( s.substring( currentPosition, currentPosition + 1 ) ) ) return false
        currentPosition++
    }
    // All checks must have passed!
    return true
}

// Returns true if s is a string representing a floating number in 15.4 format
// (Maximum 15 digits left of the decimal place, maximum 4 to the right)
function isValidFloat15_4Format( s ) {
    // s is a string
    if( isBlank( s ) ) return false

    // s is not blank
    var posDecimalDelimiter = s.indexOf( decimalDelimiter )
    var strIntegerPart = s.substring( 0, posDecimalDelimiter )
    var strFractionPart = s.substring( posDecimalDelimiter + 1, s.length )

    if( strIntegerPart.length > 15 ) return false
    if( strFractionPart.length > 4 ) return false

    if( !isPositiveNumber( strIntegerPart ) ) return false
    if( !isPositiveNumber( strFractionPart ) ) return false
    // All checks must have passed!
    return true
}
function isValidFloat7_4Format( s ) {
    // s is a string
    if( isBlank( s ) ) return false

    // s is not blank
    var posDecimalDelimiter = s.indexOf( decimalDelimiter )
    var strIntegerPart = s.substring( 0, posDecimalDelimiter )
    var strFractionPart = s.substring( posDecimalDelimiter + 1, s.length )

    if( strIntegerPart.length > 7 ) return false
    if( strFractionPart.length > 4 ) return false

    if( !isPositiveNumber( strIntegerPart ) ) return false
    if( !isPositiveNumber( strFractionPart ) ) return false
    // All checks must have passed!
    return true
}

function isValidFloat9_2Format( s ) {
    // s is a string
    if( isBlank( s ) ) return false

    // s is not blank
    var posDecimalDelimiter = s.indexOf( decimalDelimiter )
    var strIntegerPart = s.substring( 0, posDecimalDelimiter )
    var strFractionPart = s.substring( posDecimalDelimiter + 1, s.length )

    if( strIntegerPart.length > 9 ) return false
    if( strFractionPart.length > 2 ) return false

    if( !isPositiveNumber( strIntegerPart ) ) return false
    if( !isPositiveNumber( strFractionPart ) ) return false
    // All checks must have passed!
    return true
}

function isValidFloat9_4Format( s ) {
    // s is a string
    if( isBlank( s ) ) return false

    // s is not blank
    var posDecimalDelimiter = s.indexOf( decimalDelimiter )
    var strIntegerPart = s.substring( 0, posDecimalDelimiter )
    var strFractionPart = s.substring( posDecimalDelimiter + 1, s.length )

    if( strIntegerPart.length > 9 ) return false
    if( strFractionPart.length > 4 ) return false

    if( !isPositiveNumber( strIntegerPart ) ) return false
    if( !isPositiveNumber( strFractionPart ) ) return false
    // All checks must have passed!
    return true
}


function containsNonNumeric( s )
{
    s = "" + s
    var result = false
    var len = s.length
    var i = 0
    while( i < len && result == false ) {
        if( !isDigit( s.charAt( i ) ) )
            result = true
        else
            i++
    }
    return result
}

function gRemoveTrailingZeros( inString )
{
    if ( inString == null || inString == "" ) return inString
    if ( inString.indexOf(decimalDelimiter) == -1 ) return inString

    var len = inString.length

    var left = 0
    var right = len
    for ( var i=len-1; i>left; i-- ) {
        if ( inString.charAt(i) != '0' ) {
            right = i+1
            break
        }
        else
            --right
    }

    if ( inString.charAt(right-1) == decimalDelimiter ) right--
    var result = inString.substring( left, right )

    return result
}

// Returns a string containing a string representation the same floating number
// as source, but without any insignificant zeroes
function dropTrailingZeroes( source ) {
    // alert( "ENTER dropTrailingZeroes(), source = " + source )
    // !JBR -- 97.5.23 handle blank string
    if( isBlank( source ) ) return ""
    // source is not blank
    var destination = ""
    // start with default value of last character in source
    var posLastSignificantDigit = source.length - 1
    while( source.substring( posLastSignificantDigit, posLastSignificantDigit + 1 ) == "0" ) {
        posLastSignificantDigit--
    }
    destination = source.substring( 0, posLastSignificantDigit + 1 )
    // alert( "RETURN destination = " + destination )
    return destination
}

function dropLeadingZeroes( source ) {
    // !JBR -- 97.5.23 Handle blank string
    if( isBlank( source ) ) return ""
    // if( isBlank( source ) ) return "Do not pass me a blank string!"
    var destination = ""
    var posFirstNonZeroDigit = 0
    while( source.substring( posFirstNonZeroDigit, posFirstNonZeroDigit + 1 ) == "0" ) {
        posFirstNonZeroDigit++
    }
    destination = source.substring( posFirstNonZeroDigit, source.length )
    return destination
}

function leadingZeroPad( source, targetLength ) {
    // !JBR -- 97.5.27 Add zeroes at front until source.length is targetLength
    source = "" + source    // force string type
    var zeroesNeeded = targetLength - source.length
    // if zeroesNeeded < 0, then ignore -- source string is already (at least) long enough
    var target = "" + source
    while( zeroesNeeded > 0 ) {
        target = "0" + target
        zeroesNeeded--
    }
    return target
}

function trailingZeroPad( source, targetLength ) {
    // !JBR -- 97.7.25 Add zeroes at end of source until its length is targetLength
    source = "" + source;    // convert to string, if not already
    var zeroesNeeded = targetLength - source.length
    var target = "" + source;
    while( zeroesNeeded > 0 ) {
        target += "0";
        zeroesNeeded--;
    }
    return target;
}

function dropLeadingAndTrailingBlanks( s ) {
    // alert( "ENTER dropLeadingAndTrailingBlanks(), s = " + s )
    if( isBlank( s ) ) return ""
    var fwd = 0
    while( isBlank( s.charAt( fwd ) ) ) {
        fwd++
    }
    var back = s.length - 1
    while( isBlank( s.charAt( back ) ) ) {
        back--
    }
    var newS = s.substring( fwd, back + 1 )
    // alert( "RETURN newS = " + newS )
    return newS
}

function trimBlanks( s )
{
    return( dropLeadingAndTrailingBlanks( s ) );
}


//=========================================================
// User settings formatting
//=========================================================

// Resulting format has exactly 'digitsRight' digits right of
// the decimal delimiter
function formatFloatForUser( x, digitsRight )
{
    if( isBlank( x ) )  return( "" );
    // Assume 'x' is a well-formed float using "." as a separator
    var parts = x.split( decimalDelimiter ); // Array of tokens separated by "."
    var userFloat = "";
    if( digitsRight == 0 ) {
         // I don't want decimal places -- cut to integer part
         userFloat = parts[0];
    }
    // Assume digitsRight > 0
    else if( parts.length == 1 ) {
         // Integer
        userFloat = parts[0] + decimalDelimiter;
        for( var i = 0; i < digitsRight; i++ ) {
              userFloat += "0";
        }
    }
    else if( parts.length == 2 ) {
         // Non-integer
        var userFloat = parts[0] + decimalDelimiter;
        if( parts[1].length > digitsRight ) {
              userFloat += parts[1].substring( 0, digitsRight );
        }
        else {
              userFloat += parts[1];
              for( var i = parts[1].length; i < digitsRight; i++ ) {
                userFloat += "0";
            }
        }
    }
    else {
         userFloat = null;      // Error -- more than one delimiter
    }
    return( userFloat );
}

// function will change the db2decimalDelimiter into the decimalDelimiter
// for a float value
function formatFloatForUser2(x)
{
    if( isBlank( x ) )  return( "" );
    if (db2DecimalDelimiter == decimalDelimiter)
        return x;
    var parts = x.split( db2DecimalDelimiter );

    if (parts.length == 1)
        return x;
    else if (parts.length == 2)
    {
        return parts[0] + decimalDelimiter + parts[1];
    }
    else
        return null // Error -- more than one delimiter

}
function formatTaxRateForUser( x )
{
    return( formatFloatForUser( x, 2 ) );
}

//
// This function returns a STRING. In order to convert to a NUMERIC
// value (INT, FLOAT), use parseFloat() or parseInt(). See the
// JavaScript reference manual for details.
//
// On error, this returns NULL.
//
function getFloatFromUserInput( x )
{
    if( isBlank( x ) )  return( "" );
    var s = trimBlanks( "" + x );    // Convert to trimmed string
    var parts = s.split( decimalDelimiter );
    // START DEBUG
    // var debug_text = "Parts:\n";
    // for( var p = 0; p < parts.length; p++ ) {
    //     debug_text += parts[p] + "\n";
    // }
    // alert( debug_text );
    // END DEBUG
    for( var i = 0; i < parts.length; i++ ) {
        if( isBlank( parts[i] ) ) {
            parts[i] = "0";
        }
        else if( !isPositiveNumber( parts[i] ) ) {
            return( null );    // Error
        }
    }
    // Assume each token is an integer
    var theFloat = 0;
    if( parts.length == 1 ) {
        // Integer
        theFloat = parts[0];
    }
    else if( parts.length == 2 ) {
        // Non-integer
        theFloat = parts[0] + db2DecimalDelimiter + parts[1];
    }
    else {
        theFloat = null;
    }
    return( theFloat );
}

function getTaxRateFromUserInput( x )
{
    return( getFloatFromUserInput( x ) );
}

//=========================================================
// Price-related functions
//=========================================================

function formatPrice( price )
{
    if( isBlank( price ) )  return "";

    // Put the correct number of decimal places in the price
    price = "" + price; // convert to string, if not already
    var endDollars = price.indexOf( decimalDelimiter );
    var dollars = "";
    var cents = "";
    if( endDollars < 0 ) {
        // No cents
        dollars = price;
        //cents = null;
    }
    else {
        dollars = price.substring( 0, endDollars );
        cents = price.substring( endDollars + 1, price.length );
    }

    var formattedPrice = "";
    if( decimalPlacesInPrice <= 0 ) {
        formattedPrice = dollars;
    }
    else {
        cents = trailingZeroPad( cents, decimalPlacesInPrice );
        formattedPrice = dollars + decimalDelimiter + cents.substring( 0, decimalPlacesInPrice );
    }
    return formattedPrice;
}


// The following code *should* be in a separate file

//==========================================================
// COMMAND.JS
//==========================================================
// Contains the objects NCNameValuePair and NCForm used
// to submit data from the GUI forms.


//============================
// Global variables
//============================
var gCurrentNCForm = null;

//============================
// Global Functions
//============================
function gGetCurrentNCForm()
{
    return( gCurrentNCForm );
}

function gSetCurrentNCForm( _ncform )
{
    if( _ncform != null ) {
         gCurrentNCForm = _ncform;
    }
}


//==========================================================
// object NCNameValuePair
//==========================================================

function NCNameValuePair( n, v )
{
    // Properties
    this.name = null;
    this.value = null;

    // Methods
    this.setWithExpression = NCNameValuePair_setWithExpression;

    this.getName = NCNameValuePair_getName;
    this.getValue = NCNameValuePair_getValue;
    this.getValueEscaped = NCNameValuePair_getValueEscaped;

    this.setName = NCNameValuePair_setName;
    this.setValue = NCNameValuePair_setValue;

    // Initialisation code
    this.name = n;
    this.value = unescape( v );
}

//***** An 'expression' is of the form <name>=<value>
function NCNameValuePair_setWithExpression( nvpexpression )
{
    var startOfName = 0;
    var endOfName = nvpexpression.indexOf( "=" );
    var startOfValue = endOfName + 1;
    var endOfValue = nvpexpression.length;
    this.setName( nvpexpression.substring( startOfName, endOfName ) );
    this.setValue( nvpexpression.substring( startOfValue, endOfValue ) );
}

//============================
// GET methods
//============================

function NCNameValuePair_getName()
{
    return ( this.name );
}

function NCNameValuePair_getValue()
{
    return ( this.value );
}

function NCNameValuePair_getValueEscaped()
{
    return ( escape( this.value ) );
}

//============================
// SET methods
//============================

function NCNameValuePair_setName( name )
{
    this.name = name;
}

function NCNameValuePair_setValue( value )
{
    this.value = unescape( value );
}

//==========================================================
// object NCForm
//==========================================================

function NCForm( name, urlGetFormat )
{
    // Properties
    this.name = null;
    this.commandURL = null;
    this.nameValuePairs = null;
    this.HTMLForm = null;

    // Methods
    this.clear = NCForm_clear;
    this.createFromURL = NCForm_createFromURL;
    this.addNameValuePair = NCForm_addNameValuePair;
    this.generateHTMLForm = NCForm_generateHTMLForm;
    this.submit = NCForm_submit;

    this.getAction = NCForm_getAction;
    this.getForm = NCForm_getForm;

    this.dumpValues = NCForm_dumpValues;
    this.dumpForm = NCForm_dumpForm;

    // Initialisation code

    this.name = name;     // 'name' may be null
    this.nameValuePairs = new Array();
    this.HTMLForm = null;
    gCurrentNCForm = this;
    if( urlGetFormat ) {
         this.createFromURL( urlGetFormat );
    }
}

//============================
// Friend functions
//============================

function getCommandStringFromURL( url )
{
    var endOfCommandString = url.indexOf( "?" );
    return ( url.substring( 0, endOfCommandString ) );
}

function getNameValuePairStringsFromURL( url )
{
    var startOfParameterList = url.indexOf( "?" ) + 1;
    var thereAreMoreParameters = true;
    var startOfThisParameter = startOfParameterList;
    var endOfThisParameter = -1;
    var thisParameter = "";
    var parameterTable = new Array();
    var nParameters = 0;
    while( thereAreMoreParameters ) {
        endOfThisParameter = url.indexOf( "&", startOfThisParameter );
        if( endOfThisParameter < 0 ) {
            // Found the last parameter
            endOfThisParameter = url.length;
            thereAreMoreParameters = false;
        }
        thisParameter = url.substring( startOfThisParameter, endOfThisParameter );
        // START DEBUG
        // alert( "Found parameter: \"" + thisParameter + "\"" );
        // END DEBUG
        // Add parameter to table
        // !JBR-97.7.29 Adding some robustness, here -- do not allow blank
        // parameter -- issue warning to programmer
        if( isBlank( thisParameter ) ) {
            var warningText = "WARNING: The query string contains a blank name-value pair.";
            warningText += " The query should still be processed correctly; however it is";
            warningText += " advised to avoid blank name-value pairs.\n";
            warningText += "URL = '" + url + "'.";
            alert( warningText );
        }
        else {
            parameterTable[nParameters] = thisParameter;
            nParameters++;
        }
        // Prepare for next iteration
        startOfThisParameter = endOfThisParameter + 1;
    }
    return parameterTable;
}


//============================
// Methods
//============================

function NCForm_dumpValues()
{
    var text = "";
    text += "Action: " + this.commandURL + "\n";
    var i = 0;
    var nElements = this.nameValuePairs.length;
    for( i = 0; i < nElements; i++ ) {
        text += this.nameValuePairs[i].getName() + "=" + this.nameValuePairs[i].getValue() + "\n";
    }
    alert( text );
}

function NCForm_dumpForm()
{
    if( this.HTMLForm == null ) {
         alert( "NCForm:\nForm has not yet been generated." );
        return;
    }
    // Assume HTMLForm is not null
    var thisForm = this.HTMLForm;
    var text = "";
    text += "Action: " + this.HTMLForm.action + "\n";
    var i = 0;
    var nElements = thisForm.elements.length;
    for( i = 0; i < nElements; i++ ) {
         text += thisForm.elements[i] + "\n";
    }
    alert( text );
}

function NCForm_clear()
{
    this.commandURL = null;
    this.nameValuePairs = new Array();
}

function NCForm_addNameValuePair( nvpair )
{
    var nItems = this.nameValuePairs.length;
    this.nameValuePairs[nItems] = nvpair;
}

function NCForm_createFromURL( url )
{
    // Split URL into its command and name-value-pair list
    var command = getCommandStringFromURL( url );
    var nameValuePairStrings = getNameValuePairStringsFromURL( url );
    var nNameValuePairStrings = nameValuePairStrings.length;

    // START DEBUG
    // alert( "There are " + nNameValuePairStrings + " name-value pairs." );
    // var nvText = "";
    // for( var k = 0; k < nNameValuePairStrings; k++ ) {
    //     nvText += nameValuePairStrings[k] + "\n";
    // }
    // alert( "Here they are:\n" + nvText );
    // END DEBUG


    // Set values
    this.clear();
    this.commandURL = command;
    var i = 0;
    for( i = 0; i < nNameValuePairStrings; i++ ) {
        var thisNameValuePair = new NCNameValuePair();
        thisNameValuePair.setWithExpression( nameValuePairStrings[i] );
        this.addNameValuePair( thisNameValuePair );
    }
}

function NCForm_generateHTMLForm( aWindow )
{
    var thisName = this.name;
    var thisCommandURL = this.commandURL;
    var doc = aWindow.document;

    var nFormsInDocuments = document.forms.length;

    var formTag = "<FORM NAME=\"" + thisName;
    formTag += "\" ACTION=\"" + thisCommandURL;
    formTag += "\" METHOD=POST>";

    var i = 0;
    var nNameValuePairs = this.nameValuePairs.length;
    var hiddenFieldTags = "";
    for( i = 0; i < nNameValuePairs; i++ ) {
        hiddenFieldTags += "    <INPUT TYPE=\"hidden\" ";
        hiddenFieldTags += "NAME=\"" + this.nameValuePairs[i].getName() + "\"\n";
        hiddenFieldTags += "VALUE=\"" + this.nameValuePairs[i].getValue() + "\">\n";
    }
    var endFormTag = "</FORM>";

    // START DEBUG
    // alert( formTag + "\n" + hiddenFieldTags + "\n" + endFormTag );
    // END DEBUG

    doc.writeln( formTag );
    doc.writeln( hiddenFieldTags );
    doc.writeln( endFormTag );

    this.HTMLForm = doc.forms[thisName];
    // START DEBUG
    // var HTMLFormElementsText = "";
    // for( var a = 0; a < this.HTMLForm.elements.length; a++ ) {
    //  HTMLFormElementsText += this.HTMLForm.elements[a] + "\n";
    // }
    // alert( HTMLFormElementsText );
    // END DEBUG
}

function NCForm_submit( aWindow )
{
    // alert( "ENTER NCForm::submit()" );
    // Strategy:
    // Load blank page
    // Generate form
    // Submit it
    aWindow.location = "/ncacom/s_cmd.htm";
}

function NCForm_getAction()
{
    return( this.HTMLForm.action );
}

function NCForm_getForm()
{
    return( this.HTMLForm );
}

//=====
// Utility functions
//=====

function gSubmitUsingPOST( formName, url, theWindow )
{
    var form = new NCForm( formName, url );
    form.submit( theWindow );
}

//Trim function
function trim(str) 
{
	return str.replace(/^\s*|\s*$/g,"");
}


//=====
// END
//=====


/*--------- Adrian Changes Added New doSave for Product page as it requires to save also the Price Form -------------- */
/*
function doSave_new(form,form2) {

     if (!checkMandatory(form)) return
     if (getParams(form, false) == badParameter) return
	 // check all parameters


     if (isBlank(form2.ppprc.value)) {
	reprompt (form2.ppprc, msgPriceField)
                return false	

	}

	if(!isValidFloat7_4Format(form2.ppprc.value)) {
	reprompt (form2.ppprc, msgPriceRange)
	return false

	} 

    doSearch(form, true);
    return true;

}
*/

function report_error(msg,url,line)
{
   var w=window.open("","error" + error_count++,"resizable,status,width=200,height=300");
   var d =w.document;

d.write('JavaScript Error <BR>');
d.write('Error Message: ' + msg + '<BR>');
d.write('Document: ' + url + '<BR>');
d.write('Line Number: ' + line +'<BR>');
d.close();
return true;
}

self.onerror = report_error;
//alert("Common.js Loaded"); 


//Added by Sydney, to force the redirection from http to https
if(document.location.protocol == "http:")
	document.location = document.location.href.replace(/\bhttp:/ig, "https:");


function unCheckAllStatus(form)
{
	count = form.statusQuery.length;
	for (i=0; i < count; i++) 
	{
		if(form.statusQuery[i].checked == true)
		{form.statusQuery[i].checked = false; }
		else {form.statusQuery[i].checked = true;}
	}
}
function unCheckAll(form)
{
	count = form.reckey.length;
	for (i=0; i < count; i++) 
	{
		if(form.reckey[i].checked == true)
		{form.reckey[i].checked = false; }
		else {form.reckey[i].checked = true;}
	}
}

