var oldcn = "";
var oldbg = "";
var oldf = "";
var curobj = null;
var errmsg = "Please correct the following errors:\n";
var SELECT_COLOR = "#316AC5";
var WHITE = "#FFFFFF";

//*****************************************************************************
// changeBg and changeBgBack may have some issues in Firefox.
// Be sure to test in both IE and Firefox. Use the following to
// prevent the call if the browser is Firefox.
//
//    onmouseover="if (document.all) changeBg(this,'#EEEEEE');"
//
// NOTE: Any HTML color code can be used in place of #EEEEEE.
//*****************************************************************************
function changeBg(obj, color)
{
    curobj = obj;
    curobj.oldbg = obj.style.backgroundColor;
    curobj.style.backgroundColor = color;
    curobj.onmouseout = changeBgBack;
}

function changeBgBack()
{
    curobj.style.backgroundColor = curobj.oldbg;
    curobj.oldbg = "";
}
//*****************************************************************************

function setDisplay(elid, disp)
{
    var el = document.getElementById(elid);
    if (el)
        el.style.display = disp;
}

function hoverOver(obj, bgcolor, fcolor)
{
    if (oldbg == "")
        oldbg = obj.style.backgroundColor;

    if (oldf == "")
        oldf = obj.style.color;

    curobj = obj;

    if(bgcolor != "")
        curobj.style.backgroundColor = bgcolor;

    if(fcolor != "")
        curobj.style.color = fcolor;

    curobj.onmouseout = hoverOut;

}

function hoverOut()
{
    curobj.style.backgroundColor = oldbg;
    curobj.style.color = oldf;
    oldbg = "";
    oldf = "";
}



function getField(id)
{
    var elem = document.getElementById(id);
    if (elem)
        return elem;
    else
        return false;
}

function getElem(id)
{
    var elem = document.getElementById(id);
    if (elem)
        return elem;
    else
        return false;
}


function getValue(id)
{
    var elem = document.getElementById(id);
    var val = "";

    if (elem)
        val = elem.value;

    return val;
}

function getRadioValue(items)
{
        var item = null;
        j=items.length; //alert(j)
	    for (i=0; i<j; i++){
            item = items[i];
		    if(item.checked) return item.value;
        }
        return null;
}

function setValue(id, val)
{
    var elem = document.getElementById(id);

    if (elem)
        elem.value = val;
}

function parmExists(obj)
{
    if (typeof(obj) == "undefined")
        return false;
    else
        return true;
}

function getOpenerValue(id)
{
    var elem = window.opener.document.getElementById(id);
    var val = "";

    if (elem)
        val = elem.value;

    return val;

}

function setOpenerValue(id, val)
{
    var elem = window.opener.document.getElementById(id);

    if (elem)
        elem.value = val;
}

function submitForm(frm)
{
    if (typeof(frm) == "undefined")
        frm = document.forms[0];

    frm.submit();
}

function openerSubmit()
{
    window.opener.document.forms[0].submit();
}


function gobutton(xxx) {
    window.document.forms[0].request.value=xxx;
    window.document.forms[0].submit();
    return true;
}

function selcust(cust) {
    document.form1.customer.value = cust;
    sendrequest('chgcust',cust);
}

function savePrevReq(){
    setValue('prevrequest',getValue('request'));
}

function placeFocus() {
    if (document.forms.length > 0) {
        for (i = 0; i < window.document.form1.length; i++) {
            if (window.document.form1.elements[i].type == "text") {
                window.document.form1.elements[i].focus();
                break;
             }
        }
    }
}

function openWin1(html) {
    MyWin=window.open(html,'','width=600,height=500,scrollbars=1,resizable,nostatus,nomenubar');
    MyWin.focus();
    return;
}

function changeRowBg(row)
{

    if(row.className == "selectedTableItem"){
        row.className = oldcn;
    }
    else{
        oldcn = row.className;
        row.className = "selectedTableItem";
    }
}

function sendrequest(reqname, reqparms){
    document.form1.request.value = reqname;
    document.form1.parameters.value = reqparms;
    document.form1.submit();
}

function showurl(url){
    parent.location = url;
}

function changeMainFrame(url){
    parent.main.location=url;
}

function UserWindow(w, h, x, y)
{
    this.width = w;
    this.height = h;
    this.left = x;
    this.top = y;
}

function OpenWindow(url, w, h, x, y){
    window.open(url,"mywindow","width=" + w + ",height=" + h + ";status=no,resizable=yes,toolbar=no,location=no,menubar=no,scrollbars=yes,screenX=" + x + ",screenY=" + y + ",left=" + x + ",top=" + y);
}

function OpenFixedWindow(url, w, h, x, y){
    window.open(url,"mywindow","width=" + w + ",height=" + h + ";status=no,resizable=no,toolbar=no,location=no,menubar=no,scrollbars=yes,screenX=" + x + ",screenY=" + y + ",left=" + x + ",top=" + y);
}

function openCgiWindow(win, request, pgm, addParms)
{
    w = win.width;
    h = win.height;
    x = win.top;
    y = win.left;

    sessid = getValue("session");
    corpid = getValue("corpid");
    userclt = getValue("userclt");

    url = "/dmicgip/" + pgm + ".pgm?session=" + sessid + "&request=" + request + "&corpid=" + corpid + "&userclt=" + userclt;
    if(typeof(addParms)!="undefined")
        url += "&" + addParms;

    OpenFixedWindow(url, w, h, x, y);
}

function CreateWindow(title, content, w, h, x, y) {
    top.consoleRef=window.open('','newwindow',
    'width=' + w + ',height=' + h
    +',menubar=0'
    +',toolbar=0'
    +',status=0'
    +',scrollbars=1'
    +',resizable=1'
    +',left=' + x
    +',top=' + y)
    top.consoleRef.document.writeln(
    '<html><head><title>' + title + '</title></head>'
    +'<body bgcolor=white onLoad="self.focus()">'
    +content
    +'</body></html>'
 )
 top.consoleRef.document.close()
}

function CreateFixedWindow(title, content, w, h, x, y) {
    top.consoleRef=window.open('','newwindow',
    'width=' + w + ',height=' + h
    +',menubar=0'
    +',toolbar=0'
    +',status=0'
    +',scrollbars=1'
    +',resizable=0'
    +',left=' + x
    +',top=' + y)
    top.consoleRef.document.writeln(
    '<html><head><title>' + title + '</title></head>'
    +'<body topmargin="0" leftmargin="0" bgcolor=white onLoad="self.focus()">'
    +content
    +'</body></html>'
 )
 top.consoleRef.document.close()
}

function setfocus(obj){
    f = document.getElementById(obj);
    if(f)
        f.focus();
}

function errorAlert(errs)
{
    if (errs != "")
    {
        alert(errmsg + errs);
    }

}
//*******************************************************************
// Javascript routines for data validation
//*******************************************************************/

/********************************************************************
* isValid - Verifies that string contains only valid characters.
*    Parameters:
*        strString         String to be checked
*        strValidChars    List of characters that are valid.
*    Returns:
*        False if strings contains invalid character.
********************************************************************/
function isValid(strString, strValidChars)
//  check if field contains valid characters
{
   //var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

/********************************************************************
* isNumeric - Verifies that string contains only numeric characters.
*    Parameters:
*        strString         String to be checked
*    Returns:
*        False if strings contains invalid character.
********************************************************************/
function isNumeric(strString)
//  check for valid numeric strings
{
   var chrs = "0123456789.,-";
   return isValid(strString, chrs);
}

/********************************************************************
* isDate - Verifies that string is a valid date.
*    Parameters:
*        dateStr         String to be checked
*        showAlert        Boolean flag indicating whether alert should
*                        shown if date is invalid.
*    Returns:
*        False if string is not a valid date
********************************************************************/
function isDate(dateStr, showAlert){
    var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if(typeof(showAlert)=="undefined")
        showAlert = true;

    if (dateStr != ""){
        if (matchArray == null) {
            if (showAlert) alert("Please enter date as either mm/dd/yyyy.");
            return false;
        }


        month = matchArray[1]; // parse date into variables
        day = matchArray[3];
        year = matchArray[5];

        if (month < 1 || month > 12) { // check month range
            if (showAlert) alert("Month must be between 1 and 12.");
            return false;
        }

        if (day < 1 || day > 31) {
            if (showAlert) alert("Day must be between 1 and 31.");
            return false;
        }

        if ((month==4 || month==6 || month==9 || month==11) && day==31) {
            if (showAlert) alert("Month "+month+" doesn't have 31 days!")
            return false;
        }

        if (month == 2) { // check for february 29th
            var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day > 29 || (day==29 && !isleap)) {
                if (showAlert) alert("February " + year + " doesn't have " + day + " days!");
                return false;
            }
        }
    }

    return true; // date is valid
}

/*********************************************************************
* checkDate - Verifies that string is a valid date.
**********************************************************************
* Same as isDate()
*
* Added because of conflict with function in date.js which is needed
* for popup calendar to function.  Make sure date.js is copied in
* AFTER main.js so that correct isDate function is  called by popup
* calendar code.
*
*    Parameters:
*        dateStr         String to be checked
*        showAlert        Boolean flag indicating whether alert should
*                        shown if date is invalid.
*    Returns:
*        False if string is not a valid date
********************************************************************/
function checkDate(datefld, showAlert){

    var dateStr = datefld.value;
    var datePat = /^(\d{1,2})(\/|\-|\.)?(\d{1,2})(\/|\-|\.)?(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    var valid = true;

    if(typeof(showAlert)=="undefined")
        showAlert = true;

    if (dateStr != ""){
        if (matchArray == null) {
            if (showAlert) alert("Please enter date as mmddyyyy, mm/dd/yyyy, mm-dd-yyyy, or mm.dd.yyyy.");
            valid = false;
        }
        else{
            month = matchArray[1]; // parse date into variables
            day = matchArray[3];
            year = matchArray[5];

            //alert("month=" + month + "\nday=" + day + "\nyear=" + year);

            if (month < 1 || month > 12) { // check month range
                if (showAlert) alert("Month must be between 1 and 12.");
                valid = false;
            }

            if (day < 1 || day > 31) {
                if (showAlert) alert("Day must be between 1 and 31.");
                valid = false;
            }

            if ((month==4 || month==6 || month==9 || month==11) && day==31) {
                if (showAlert) alert("Month "+month+" doesn't have 31 days!")
                valid = false;
            }

            if (month == 2) { // check for february 29th
                var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
                if (day > 29 || (day==29 && !isleap)) {
                    if (showAlert) alert("February " + year + " doesn't have " + day + " days!");
                    valid = false;
                }
            }
            month = padBefore(month, 2, "0");
            day = padBefore(day, 2, "0");
        }

        if (valid){
            datefld.className = "txtbox";
            datefld.value = month + "/" + day + "/" + year;
        }
        else
            datefld.className = "txtbox_invalid";
    }
    else{
        datefld.className = "txtbox";
    }


    return valid; // date is valid
}



/********************************************************************
 * DHTML email validation script. Courtesy of SmartWebby.com
 * (http://www.smartwebby.com/dhtml/)
 *
 *  Modified by Matt Lavinder of Data Management on 7/1/2005
 *        - Added showAlert parameter.
 ********************************************************************/
function echeck(str, showAlert) {

    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)

    if(typeof(showAlert)=="undefined")
        showAlert = true;

    if (str.indexOf(at)==-1){
       if (showAlert) alert("Invalid E-mail ID");
       return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       if (showAlert) alert("Invalid E-mail ID");
       return false
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        if (showAlert) alert("Invalid E-mail ID");
        return false
    }

     if (str.indexOf(at,(lat+1))!=-1){
        if (showAlert) alert("Invalid E-mail ID");
        return false
     }

     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        if (showAlert) alert("Invalid E-mail ID");
        return false
     }

     if (str.indexOf(dot,(lat+2))==-1){
        if (showAlert) alert("Invalid E-mail ID");
        return false
     }

     if (str.indexOf(" ")!=-1){
        if (showAlert) alert("Invalid E-mail ID");
        return false
     }

     return true
}

//*******************************************************************
// Javascript routines for string manipulation
//*******************************************************************/

function trim(TRIM_VALUE){
    if(TRIM_VALUE.length < 1){
        return"";
    }
    TRIM_VALUE = rtrim(TRIM_VALUE);
    TRIM_VALUE = ltrim(TRIM_VALUE);
    if(TRIM_VALUE==""){
        return "";
    }
    else{
        return TRIM_VALUE;
    }
} //End Function

function rtrim(VALUE){
    var w_space = String.fromCharCode(32);
    var v_length = VALUE.length;
    var strTemp = "";
    if(v_length < 0){
        return"";
    }


    var iTemp = v_length -1;

    while(iTemp > -1){
        if(VALUE.charAt(iTemp) == w_space){}
        else{
            strTemp = VALUE.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;

    } //End While
    return strTemp;

} //End Function

function ltrim(VALUE){
    var w_space = String.fromCharCode(32);
    if(v_length < 1){
        return"";
    }
    var v_length = VALUE.length;
    var strTemp = "";

    var iTemp = 0;

    while(iTemp < v_length){
        if(VALUE.charAt(iTemp) == w_space){}
        else{
            strTemp = VALUE.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    } //End While
    return strTemp;
} //End Function

function padBefore(str, len, chr)
{

    if(typeof(chr)=="undefined")
        chr = " ";

    str = str + ""; //<< convert to string trick
    slen = str.length;
    if(slen < len){
        for (i=slen;i<len;i++)
        {
            str = chr + str;
        }
    }
    return str;
}

function padAfter(str, len, chr)
{

    if(typeof(chr)=="undefined")
        chr = " ";

    str = str + ""; //<< convert to string trick
    slen = str.length;
    if(slen< len){
        for (i=slen;i<len;i++)
        {
            str = str + chr;
        }
    }
    return str;
}

function round(expr, dec)
{
   var str = "" + Math.round(expr * Math.pow(10,dec));
   while (str.length <= dec) { str = "0" + str; }
   var decpoint = str.length - dec;
   return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

function decimalPlaces(num)
{
    var str    = num.toString();
    var len = str.length;
    var pos = str.indexOf(".");
    var dif = 0;

    if (pos > 0)
    {
        dif = len - pos - 1;
        return dif;
    }
    else
    {
        return 0;
    }
}

function checkLevel(xxx)
{
	document.form1.dtllvl.value = xxx;
}

/******************************************************************************
 * Preload images so they are in browser cache.
 *   Parameters:
 *     paths - Array containing paths of images to be loaded.
 ******************************************************************************/
function preloadImages(paths)
{
    if (!document.images)
        return false;

    var img = new Image();
    for (var i=0; i<paths.length; i++)
    {
        img.src = paths[i];
    }
}

/*************************************************************************************************************
* checkEmail - Verifies that email address if valid.
**************************************************************************************************************
*    Parameters:
*       fldEmail    Reference to field containing email address or email address string.
*       showAlert   True if alert box should be shown. False otherwise.
*    Returns:
*        False if field does not contain a valid email address.
*
*    Notes:     As seen above, either reference to textbox or string may be passed to function.
*               - Field class will be changed to "txtbox_invalid" if field is invalid.
*               - Field class will be changed to "txtbox" if field is valid.
*************************************************************************************************************/
function checkEmail(fldEmail, showAlert) {
/********************************************************************
 * DHTML email validation script. Courtesy of SmartWebby.com
 * (http://www.smartwebby.com/dhtml/)
 *
 *  Modified by Matt Lavinder of Data Management on 7/1/2005
 *        - Added showAlert parameter.
 *  Modified by Matt Lavinder of Data Management on 3/14/2006
 *        - Changed name from echeck to checkEmail.
 *        - Added echeck function to call checkEmail for backwards
 *          compatibility
 *        - Changed first parameter to object (field) and added
 *          check to see if parameter is string or object.
 *        - Added code to change color of field if parameter is object
 *          and email address is invalid.
 ********************************************************************/
    var isObj = false;
    var isValid = true;

    if (typeof(fldEmail) == "string")
        str = fldEmail;
    else{
        str = fldEmail.value;
        isObj = true;
    }

    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
   
    if(!parmExists(showAlert))
        showAlert = true;

    if (str.indexOf(at)==-1){
       if (showAlert) alert(ERRMSG_EMAIL);
       isValid = false
    }

    if ((str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) && isValid == true){
       if (showAlert) alert(ERRMSG_EMAIL);
       isValid =  false
    }

    if ((str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) && isValid == true){
        if (showAlert) alert(ERRMSG_EMAIL);
        isValid =  false
    }

     if ((str.indexOf(at,(lat+1))!=-1) && isValid == true){
        if (showAlert) alert(ERRMSG_EMAIL);
        isValid =  false
     }

     if ((str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) && isValid == true){
        if (showAlert) alert(ERRMSG_EMAIL);
        isValid =  false
     }

     if ((str.indexOf(dot,(lat+2))==-1) && isValid == true){
        if (showAlert) alert(ERRMSG_EMAIL);
        isValid =  false
     }

     if ((str.indexOf(" ")!=-1) && isValid == true){
        if (showAlert) alert(ERRMSG_EMAIL);
        isValid =  false
     }

    if (isObj)
    {
        if (isValid)
            setTextBoxStatus(fldEmail, true);
        else
            setTextBoxStatus(fldEmail, false);
    }

     return isValid;
}

