/*------------------------------------------------------------------------------
Name:
    std_js.js
Purpose:
    Provides standard functions used by all pages
History:                                Person:
    01 Sep 1999: created                    Rob Sinow
    19 Nov 1999: added cookie functions     Rob Sinow
    22 Nov 1999: modified cookie funtions   Rob Sinow
        to expire cookie at current date
        instead of 01-Jan-70
    22 Nov 1999: removed onunload function  Rob Sinow
    16 Feb 2000: added to PremCalc app      Rob Sinow
    09 Aug 2000: added popUp scripts        Rob Sinow
    09 Aug 2000: added onunload function    Rob Sinow
------------------------------------------------------------------------------*/

var page_ok = false;
var helpOver = false;
var popUpReady = false;
var textAreaMaxLength = 250;
var isOpera = window.opera;
var isIE = navigator.userAgent.indexOf("MSIE") >= 0 && !isOpera;
var isGecko = navigator.userAgent.indexOf("Gecko") >= 0 && navigator.userAgent.indexOf("KHTML") < 0;
var isMozilla = navigator.userAgent.indexOf("Mozilla") >= 0 && !isIE;
var offset = 0;
var charCount = 4

if ( isOpera )
{
    offset = navigator.userAgent.indexOf("Opera") + 6;
}
else if ( isIE )
{
    offset = navigator.userAgent.indexOf("MSIE") + 5;
}
else if ( isGecko )
{
    offset = navigator.userAgent.indexOf("Gecko") + 6;
    charCount = 8;
}
else if ( isMozilla )
{
    offset = navigator.userAgent.indexOf("Mozilla") + 8;
}

var browserVersion = parseFloat(navigator.userAgent.substring(offset, offset + charCount),10);

//
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}
//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid. If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//  Function to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function DeleteCookie (name,path,domain) {
  var gmtDate = new Date();
  
  if (GetCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=" + gmtDate.toGMTString();
  }
}

function execOnload()
{
    popUpReady = true;
    
    if ( typeof window.onloadFuncts != "undefined" )
    {
        for ( m=0;m<window.onloadFuncts.length;m++ )
        {
            window.onloadFuncts[m]();
        }
        fromList = false;
        
        thisLocation = new String(window.location);
        
        startPos = thisLocation.indexOf("start=");
        if ( startPos > 0 )
        {
            /*startPos = startPos + 6;
            endPos = thisLocation.indexOf("&", startPos);
            if ( endPos <= 0 )
            {
                endPos = thisLocation.length;
            }
            startNumber = parseInt(thisLocation.substring(startPos, endPos), 10);
            if ( startNumber >= 1 )
            {*/
                fromList = true;
            //}
        }
    
        /*if ( window.name != "updateFrame" && window.name != "menuFrame" && window.name != "reportList" || fromList )
        {
            //waitBar("off");
        }*/
    }
}

function execOnunload()
{
    if ( typeof window.helpWindow != "undefined" && window.helpWindow != "" && !window.helpWindow.closed )
    {
        window.helpWindow.close();
    }
}

/*function eventHandler()
{
    if ( isIE )
    {
        if ( isDOM )
        {
            document.body.oncontextmenu = noMenu;
        }
        else
        {
            document.body.onmousedown = handleIEClick;
        }
    }
}

if ( window.onloadFuncts )
{
    window.onloadFuncts[window.onloadFuncts.length] = eventHandler;
}
else
{
    window.onloadFuncts = new Array();
    window.onloadFuncts[0] = eventHandler;
}*/

function handleIEClick()
{
    /*if ( !top.rightClick )
    {
        if ( ( window.event.button == 2 || window.event.button == 3)// || window.event.button == 4 
            && window.event.srcElement.type != "text" && window.event.srcElement.type != "textarea"
            && window.event.srcElement.type != "select-one" && window.event.srcElement.type != "radio"
            && window.event.srcElement.type != "checkbox" && window.event.srcElement.type != "password" )
        {
            alert("The right mouse button has been disabled");
            window.event.cancelBubble = true;
        }
        window.screenX = window.event.screenX;
        window.screenY = window.event.screenY;
    }*/
}
        
function mouseTracker(e)
{
    e = e || window.Event || window.event;
    window.pageX = e.pageX || e.clientX;
    window.pageY = e.pageY || e.clientY;
}

function noMenu()
{
    /*if ( !top.rightClick )
    {
        if ( window.event.srcElement.type != "text" && window.event.srcElement.type != "textarea"
            && window.event.srcElement.type != "select-one" && window.event.srcElement.type != "radio"
            && window.event.srcElement.type != "checkbox" && window.event.srcElement.type != "password" )
        {
            window.event.returnValue = false;
        }
    }*/
}

// Returns the absolute left of any positional element passed to it
// IE and DOM specfifc
function getX(posElement)
{
    var newLeft = posElement.offsetLeft;
    var newPosElement = posElement;
    
    while ( newPosElement.offsetParent )
    {
        newLeft += newPosElement.offsetParent.offsetLeft;
        newPosElement = newPosElement.offsetParent;
    }

    if ( isIE && navigator.userAgent.indexOf("Mac_PowerPC") >= 0 )
    {
        newLeft += 10;
    }
    return newLeft;
}

// Returns the absolute top of any positional element passed to it
// IE and DOM specfifc
function getY(posElement)
{
    var newTop = posElement.offsetTop;
    var newPosElement = posElement;

    while ( newPosElement.offsetParent )
    {
        newTop += newPosElement.offsetParent.offsetTop;
        newPosElement = newPosElement.offsetParent;
    }

    if ( isIE && navigator.userAgent.indexOf("Mac_PowerPC") >= 0 )
    {
        newTop += 16;
    }
    return newTop;
}

currentImageRef = "";

function hidePopUp(divName)
{
    if ( popUpReady )
    {
        document.getElementById(divName).style.visibility = "hidden";
    }
    status = "";
    return true;
}

function showPopUp(popUpValue,popUpClass,imageObject,divName,direction,popUpWidth,popUpType)
{
    // This function requires five arguments:
    //     popUpValue  = The text desired in the popup
    //     popUpClass   = The class of popup ( only needed for Netscape )
    //     imageObject = The image used for the location of the popup
    //     divName = The name of the positioned element to show
    //     direction = The direction of the text relative to the image
    if ( popUpReady )
    {
        if ( isIE )
        {
            xOffset = document.body.scrollLeft;
            yOffset = document.body.scrollTop;
            docWidth = document.body.clientWidth;
            docHeight = document.body.clientHeight;
        }
        else
        {
            xOffset = pageXOffset - 18;
            yOffset = pageYOffset - 18;
            docWidth = innerWidth;
            docHeight = innerHeight;
        }
        
        currentRight = docWidth + xOffset;
        currentBottom = docHeight + yOffset;
        
        window.pageX = getX(imageObject) + 20;
        window.pageY = getY(imageObject) + 20;

        popUp = document.getElementById(divName);
        
        popUp.innerHTML = "";
        
        if ( typeof popUpValue != "undefined")
        {
            if ( popUpType == "context" )
            {
                newContent = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td class=\"serifFont\"";
                
                if ( popUpWidth != "" )
                {
                     popUp.style.width = popUpWidth + "px";
                     newContent = newContent + " width=\"" + popUpWidth + "\"";
                }
                
                newContent = newContent + "><span class=\"contextHelp\">" + popUpValue + "</span></td></tr></table>";
            }
            else
            {
                newContent = popUpValue;
            }

            popUp.innerHTML = newContent;
        }
        
        if ( window.pageX + popUp.offsetWidth > currentRight )
        {
            popUpRight = window.pageX + popUp.offsetWidth;
            popUpDifference = popUpRight - currentRight;
            window.pageX = window.pageX - popUpDifference;
        }
        
        if ( window.pageY + popUp.offsetHeight > currentBottom )
        {
            popUpBottom = window.pageY + popUp.offsetHeight;
            popUpDifference = popUpBottom - currentBottom;
            window.pageY = window.pageY - 50;
        }
        
        if ( direction == "right" )
        {
            popUp.style.left = window.pageX + "px";
            popUp.style.top = window.pageY;
        }
        else if ( direction == "left" )
        {
            popUp.style.left = window.pageX - popUp.offsetWidth - 25 + "px";
            popUp.style.top = window.pageY + "px";
        }
        
        popUp.style.visibility = "visible";
    }
    status = popUpValue;
    return true;
}

function checkKeypress(e, textObject, validateType, alertFlag)
{
    //Set e to the event that fired this function.
    e = e || event;
    
    if (alertFlag == "undefined")
    {
        alertFlag = false;
    }    
    
    //Obtain the key pressed from the event object.
    // if ( isMozilla )
    //{
    keyPressed = e.charCode || e.keyCode;
    //}
    //else
    //{
    //    keyPressed = e.keyCode;
    //}

    if ( keyPressed > 0 )
    {
        //If the textObject has not been passed, obtain it from the target attribute
        //of the event object.  If no target is available, return from this function.
        if ( typeof textObject == "undefined" )
        {
            textObject = e.target || e.srcElement;
            if ( textObject.type != "text" )
            {
                return;
            }
        }
      
        //If a validateType has not been passed, attempt to obtain it from the input.
        //Otherwise, assume that it is integer
        if ( typeof validateType == "undefined" )
        {
            if ( typeof textObject.validate != "undefined" )
            {
                validateType = textObject.validate;
            }
            else
            {
                validateType = "integer";
            }
        }
                
        //If maximum has not been passed, attempt to obtain it from the input.
        //Otherwise, set the maximum to false.
        //Maximum value removed. BG 3/31/05.
        //if ( typeof maximum == "undefined" )
        //{
        //    if ( typeof textObject.maximum != "undefined" )
        //    {
        //        maximum = textObject.maximum;
        //    }
        //    else
        //    {
        //        maximum = false;
        //    }
        // }
        
        //If the key pressed is not a number and is not a backspace or delete
        if ( keyPressed > 31 && ( keyPressed < 48 || keyPressed > 57 ))
        {
            //If the validation is for decimal, allow periods.
            if ( validateType == "float" && keyPressed == 46 )
            {    
				if (e.type == "keypress")
				{
	                if ( textObject.value.indexOf(".") >= 0 )
	                {
    	                if( alertFlag )
		                {
		                    alert("The '" + String.fromCharCode(keyPressed) + "' character is not allowed in this input.");
		                }
	                    if ( isIE )
	                    {
                            e.returnValue = false;
                            e.cancelBubble = true;
	                    }
	                    else
	                    {
	                        e.preventDefault();
	                        e.stopPropagation();
	                        //Blur and refocus the field to correct a bug in Netscape 6.0 - 6.01
	                        if ( isGecko && browserVersion < 20010726 )
	                        {
	                            textObject.blur();
	                            textObject.focus();
	                        }
	                    }
	                }
				}
            }
            else
            {
				if (e.type == "keypress")
				{
	                if( alertFlag )
	                {
	                    alert("The '" + String.fromCharCode(keyPressed) + "' character is not allowed in this input.");
	                }
	                if ( isIE )
	                {
	                    e.returnValue = false;
	                    e.cancelBubble = true;
	                }
	                else
	                {
	                    e.preventDefault();
	                    e.stopPropagation();
	                    //Blur and refocus the field to correct a bug in Netscape 6.0 - 6.01
	                    if ( isGecko && browserVersion < 20010726 )
	                    {
	                        textObject.blur();
	                        textObject.focus();
	                    }
	                }
				}
            }
        }

        //maximum value removed
        //if ( maximum && keyPressed != 46 && parseFloat(textObject.value + String.fromCharCode(keyPressed),10) > maximum )
        //{
        //    if ( isIE )
        //    {
        //        e.returnValue = false;
        //    }
        //    return false;
        //}
    }

}

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

function innerText(node)
{
    // is this a text or CDATA node?
    if (node.nodeType == 3 || node.nodeType == 4) {
        return node.data;
    }
    var i;
    var returnValue = [];
    for (i = 0; i < node.childNodes.length; i++) {
        returnValue.push(innerText(node.childNodes[i]));
    }
    return returnValue.join('');
}

function verifyForm(formObject)
{
    var types = new Array("required","integer","float","range","date","time","precision");
    var fields_required = new Array();
    var fields_integer = new Array();
    var fields_float = new Array();
    var fields_range = new Array();
    var fields_date = new Array();
    var fields_time = new Array();
    var fields_precision = new Array();
    var typeCounter = 0;
    var typeIndex = 0;
    var labels = document.getElementsByTagName("label");

    for ( j=0; j<types.length; j++ )
    {   
        typeCounter = 0;
        theArray = eval("fields_" + types[j]); 
        for ( i=0; i<formObject.elements.length; i++ )
        {
            if ( typeof formObject.elements[i].name != "undefined" )
            {
                typeIndex = formObject.elements[i].name.indexOf("_" + types[j]);
                if ( typeIndex > 0 && formObject.elements[i].name.length == typeIndex + types[j].length + 1 )
                {
                    theArray[typeCounter] = eval("formObject." + formObject.elements[i].name.substring(0,typeIndex));
                    typeCounter ++;
                }
            }
        }
    }

    for ( i=0; i<fields_required.length; i++ )
    {
        if ( trim(fields_required[i].value).length == 0 )
        {
            fieldName = fields_required[i].name;
            for ( j=0; j<labels.length; j++ )
            {
                if ( labels[j].htmlFor == fields_required[i].name )
                {
                    if ( isIE )
                    {
                        fieldName = labels[j].innerText;
                    }
                    else
                    {
                        fieldName = innerText(labels[j]);
                    }
                    break;
                }
            }
            if ( fieldName.charAt(fieldName.length-1) == ":" )
            {
                fieldName = fieldName.substring(0,fieldName.length-1);
            }
            alert(fieldName + " is required.");
            fields_required[i].focus();
            return false;
        }
    }

    for ( i=0; i<fields_integer.length; i++ )
    {
        if ( trim(fields_integer[i].value).length > 0 )
        {
            fieldVal = fields_integer[i].value;
            fieldValid = false;
            
            if ( !isNaN(fieldVal) )
            {
                fieldValid = true;
                numVal = eval(fieldVal);
                
                if ( numVal != Math.floor(numVal) )
                {
                    fieldValid = false;
                }
            }
            
            if ( !fieldValid )
            {
                fieldName = fields_integer[i].name;
                for ( j=0; j<labels.length; j++ )
                {
                    if ( labels[j].htmlFor == fields_integer[i].name )
                    {
                        if ( isIE )
                        {
                            fieldName = labels[j].innerText;
                        }
                        else
                        {
                            fieldName = innerText(labels[j]);
                        }
                        break;
                    }
                }
                if ( fieldName.charAt(fieldName.length-1) == ":" )
                {
                    fieldName = fieldName.substring(0,fieldName.length-1);
                }
                alert(fieldName + " must be a whole number.");
                fields_integer[i].focus();
                return false;
            }
        }
    }
    
    return true;
}

window.onload = execOnload;
window.onunload = execOnunload;