//
//    Program:    static/corefns.js
//
//    Purpose:    Centrally define the set of "core" java script functions that
//                must be made available at the frameset level for the Trading
//                and Balances module to work.
//
//    Notes:      JavaScripts taken directly from the previous frame set 
//                definitions, unchanged.
//
//

      // ************************************
      // !! Core Frame Reference Functions !!
      // ************************************

      function checkDate(inYear,inMonth,inDay)
      {

        var lLeap  = false;
        var cMonths;
        var iYear  = parseInt(inYear);

        var cMonth = inMonth;
        var cDay   = inDay;

        // ParseInt blows, if begins with a zero (e.g. month is entered as '09') parseInt returns 0 so have to deal with it.
        if (cMonth.substr(0,1) == '0')
          cMonth = cMonth.substr(1,1);

        if (cDay.substr(0,1) == '0')
          cDay = cDay.substr(1,1);

        var iMonth = parseInt(cMonth);
        var iDay   = parseInt(cDay);

        // Must enter a four digit year
        if (!checkDigit(inYear) || iYear < 1000)
        {
          alert('The year must be four digits');
          return false;
        }

        if (iYear < 1)
        {
          alert('You must enter a year.');
          return false;
        }


        // Month has to be 1 to 12
        if (!checkDigit(inMonth) || (iMonth < 1 || iMonth > 12))
        {
          alert('The month must be two digits from 1 to 12');
          return false;
        }

        /* Check for Leap Years */
        // Is it a century?
        if (parseInt(iYear / 100) == iYear / 100)
        {
          // Is it evenly divisible by 400?
          if (parseInt(iYear / 400) == iYear / 400)
          {
            // It's a leap year!
            lLeap = true;
          }
        }
        else
        {
          // It's just a 'regular' year, check if it's evenly divisible by 4 it's a leap year
          if (parseInt(iYear / 4) == iYear / 4)
            lLeap = true;
        }

        if (lLeap)
        {
          cMonths = "31,29,31,30,31,30,31,31,30,31,30,31";
        }
        else
        {
          cMonths = "31,28,31,30,31,30,31,31,30,31,30,31";
        }

        // Parse the offset to the starting position in cMonths
        iOffset = ( ( (iMonth - 1) * 3 ) );
        iValidDays = parseInt(cMonths.substr(iOffset,2));

        if (iDay > iValidDays)
        {
          cMessage = "Month " + cMonth + " only has " + iValidDays.toString() + " days in it.";
          alert(cMessage);
          return false;
        }

        if (!checkDigit(inDay) || iDay < 1)
        {
          alert('Day must be two digits and greater than 0.');
          return false;
        }

        return true;
      }

      // Form/Element exists?
      function formElemExists (pathName,formName,elemName)
      {
        // Addition to check that frame/form/element is actually valid
        var cDocForm;
        var lFormInDoc = false;
        var cDocElem;
        var lElemInForm = false;


        // Get number of forms in doc
        var iFrmLen = parseInt(eval(pathName + ".document.forms.length"));

        if (iFrmLen == 0)
          return false;

        //alert('iFrmLen:' + iFrmLen.toString());

        for (var iCnt = 0; iCnt <= iFrmLen; i++)
        {
          cDocForm = eval(pathName + ".document.forms[" + iCnt.toString() + "].name");
          //alert('cDocForm:' + cDocForm);
          if (formName == cDocForm)
          {
            lFormInDoc = true;
            break;
          }
        }

        // If not lFormInDoc then return false
        if (!lFormInDoc) return false;

        // Get number of elements in form
        var iElmLen = parseInt(eval(pathName + ".document." + formName + ".elements.length"));

        //alert('iElmLen:' + iElmLen);

        if (iElmLen == 0)
          return false;

        for (iCnt = 0; iCnt < iElmLen; iCnt++)
        {
          cDocElem = eval(pathName + ".document." + formName + ".elements[" + iCnt.toString() + "].name");

          if (elemName == cDocElem)
          {
           lElemInForm = true;
           break;
          }
        }

        if (!lElemInForm)
          return false;
          
        return true;
      }


      // Get value
      function getVal(frameName,formName,elemName)
      {
        pathName = findPath(frameName);
        if (pathName != null)
        {

          if (!formElemExists(pathName,formName,elemName))
            return null;

          pathName += ".document." + formName + "." + elemName + ".value";
          return eval(pathName);
        }
        else return null;
      }

      // Set value
      function setVal(frameName,formName,elemName,valName)
      {
        pathName = findPath(frameName);

        if (pathName != null)
        {

          if (!formElemExists(pathName,formName,elemName))
            return null;

          pathName += ".document." + formName + "." + elemName + ".value = " + "'" +
                      valName + "';";
          eval(pathName);
          return 'ok';
        }
        else return null;
      }

      // Run a function
      function runFunc(frameName,funcName,retVal)
      {
        pathName = findPath(frameName);
        if (pathName !=  null)
        {
          pathName += '.' + funcName + '()';
          if (retVal.charAt(0).toLowerCase() == 'y')
          {
            retVal = eval(pathName);
            return retVal;
          }

          eval(pathName);
          return 'ok';

        }
        else return null;
      }

      // Set element focus 
      function setFocus(frameName,formName,elemName)
      {
        pathName = findPath(frameName);
        if (pathName != null)
        {
          pathName += '.' + formName + '.' + elemName + '.focus()';
         eval(pathName);
         return 'ok';
        }
        else return null;
      }

      // Set document.location
      function setLoc(frameName,newLocation)
      {
        pathName = findPath(frameName);

        if (pathName != null)
        {
          if (newLocation.charAt(0) != "'")
            pathName += (".document.location = " + "'" + newLocation + "'");
          else
            pathName += (".document.location = " + newLocation);

          eval(pathName);
          return 'ok';
        }
        else return null;

      }

      var startPath = "";     // specific to findPath
      var lastFrameName = ""; // specific to findPath

      // Main find frame function
      function findPath(frameName)
      {
        // Find top of frame hierarchy.

        // if we've already asked to find the path then return the same answer... No need to go through it again.
        if (startPath != "" && lastFrameName == frameName && eval(startPath)) {
          return startPath;
        }
        lastFrameName = frameName;

        startPath = "parent.frames[0]";
        var comparePath = "parent.parent.frames[0]";

        while( eval(startPath + ".name") != eval(comparePath + ".name") )
        {
          startPath = "parent." + startPath;
          comparePath = "parent." + comparePath;
        }

        // Set reference object
        if (eval(startPath + ".name") == frameName) return startPath;

        while (eval(startPath + ".name") != frameName)
        {
          // Check next frame
          startPath = startPath + ".frames[0]";

          // if last object then fall back up the obj tree till there is somewhere else to check.
          // if nothing else in the obj tree then return false.
          if (eval(startPath) == null)
          {
            startPath = self.fallTree(startPath);
            if (startPath == null) return null;
          }
        }

        return startPath;

      }

      // Tree search find next valid frame ref routine.
      function fallTree(startPath)
      {
        // When indexOf and lastIndexOf are the same, cannot chop off anymore 'frames[x]'
        if (startPath.indexOf("frames") == startPath.lastIndexOf("frames"))
          lIndex    = startPath.lastIndexOf("[");
        else
        {
          startPath = startPath.substring(0, (startPath.lastIndexOf("frames") - 1));
          lIndex    = startPath.lastIndexOf("[");
        }
        // Add one to last frames index.
        startPath = startPath.substring(0,lIndex + 1) + (parseInt(startPath.charAt(lIndex + 1)) + 1) +
                    startPath.substring(lIndex + 2,startPath.length);

        // If new increment is an invalid frame
        if (eval(startPath) == null)
        {
          // and if we are at the highest level then no more frames to search.
          if (startPath.indexOf("frames") == startPath.lastIndexOf("frames"))
            return null;

          // otherwise try agin
          startPath = self.fallTree(startPath);
          return startPath;
        }
        // Else we got a good one so pass it back.
        else return startPath;
      }

  function frameRef()
  {
    this.findPath = findPath;
    this.runFunc  = runFunc;
    this.setLoc   = setLoc;
    this.getVal   = getVal;
    this.setVal   = setVal;
    this.checkDate = checkDate;
  }

  function setContextVal(stringVal)
  {
    // Context Id 
    frameRef.prototype.x3616 = stringVal;
  }

  function checkDigit(inString)
  {
     var iNum = 0.

     if (inString.length < 1) {
        return false;
     }

     while(iNum <= inString.length - 1)
     {
        if ( !(inString.substr(iNum,1) == parseInt(inString.substr(iNum,1))))
        {
           return false;
        }
        iNum++;
     }
     return true;
  }

  function remZeroes(trimAcc)
  {
    var acct1st = trimAcc.substr(0,1);

    while (acct1st == '0' && trimAcc.length > 6)
    { 
      trimAcc = trimAcc.substr(1,trimAcc.length - 1) ;
      acct1st = trimAcc.substr(0,1) ;
    }

    return trimAcc;
  }

  function StatusBar(str) 
   {
     window.status = str;
     return true;
   }

  function refreshQueryNRA(cFormName, cAccount, cSelectedNRA, cNewNRA, cNRAList, cTopPos, cLeftPos1, cLeftPos2)
  {

    if(eval('document.' + cFormName + '.SelectAcctNo'))
    {
      DSelectAcctNo.innerHTML = "";
      DSelectAcctNo.outerHTML = "";
    }

    if(eval('document.' + cFormName + '.AcctNo'))
    {
      DAcctNo.innerHTML = "";
      DAcctNo.outerHTML = "";
    }

    var cAccountS = remZeroes(cAccount);
    var cNRAArray = cNRAList.split(",");

    if (cNewNRA == 'yes')
    {
      /** build up HTML string to send into insertAdjacentHTML **/
      var cHTML = '<DIV STYLE="position:absolute; TOP:' + cTopPos + 'px; LEFT:' + cLeftPos1 + 'px" ID="DSelectAcctNo">' +
        '<LABEL FOR="SelectAcctNo" TITLE="Choose an Account Number"' +
        ' onMouseOver="return StatusBar(\'Account Number\')"' +
        ' onMouseOut="return StatusBar(\'\')">' +
        ' </LABEL>' +
            '<SELECT NAME="SelectAcctNo" id="SelectAcctNo">' +
            '<OPTION VALUE=All' + cAccountS + '>All Accounts</OPTION>' +
            '<OPTION ';

         if (cAccount == cSelectedNRA)
           cHTML = cHTML + ' SELECTED ';

         cHTML = cHTML +  ' VALUE=' + cAccount + '>' + cAccountS + '</OPTION>';

          /** build up the entries on the SelectAcctNo drop-down list based on SelectNRA hidden drop-down **/
          /** check if one was previously selected **/
          for (var j = 1; j < (cNRAArray.length + 1); j++)
          {

            if (cAccount + cNRAArray[j-1] == cSelectedNRA)
              cHTML = cHTML + '<OPTION SELECTED VALUE=';
            else
              cHTML = cHTML + '<OPTION VALUE=';

            cHTML = cHTML + cAccount + cNRAArray[j-1] +
                            '>' + cAccountS + cNRAArray[j-1] +
                            '</OPTION>' ;
          }

          /** end the drop-down list and end the DIV **/
          cHTML = cHTML + '</SELECT></DIV>' ;
        }

        else
        {
          /** build up HTML string to send into insertAdjacentHTML **/
          var cHTML =  
            '<DIV STYLE="position:absolute; TOP:' + cTopPos + 'px; LEFT:' + cLeftPos2 + 'px" ID="DAcctNo">' +
            '<LABEL FOR="AcctNo" TITLE="Account Number"' +
            ' onMouseOver="return StatusBar(\'Account Number\')"' +
            ' onMouseOut="return StatusBar(\'\')">' +
            ' </LABEL>' +
            '<INPUT type=text name=AcctNo value="' + cAccount + '" id=AcctNo size=12 readonly></DIV>' ;
        }

        /** run the dynamic creation of the HTML **/
        eval('document.' + cFormName + '.insertAdjacentHTML("BeforeEnd", cHTML )');
      }  /** end refreshQueryNRA () **/

      function genInputDisabler() {
         var curObj;
         for (var i = 0; i < document.all.length; i++) {
            curObj = document.all[i];
            if (curObj.type && (curObj.type == "text" || curObj.type == "select-one" || curObj.type == "select-multiple" || curObj.type == "radio" || curObj.type == "checkbox" || curObj.type == "textarea")) {
               curObj.disabled = true;
            }
         }
      }

      // function that allow a dynamic resize of the main browser of the screen, 
      // Parameters are the id of the Main Browser, minimum size allowed for the browser and number of pixels used by other elements in the screen (on top or below of the browser)
      // This function needs to be called as part of the onLoad and onResize window functions
      function resizeBrowser( objName, minSize, otherElement) {
          if (objName == "" || !objName) return false;
      	var browse = document.getElementById(objName);
      	if (browse) {
      		if (document.body.offsetHeight - otherElement > minSize)
      			browse.style.height = document.body.offsetHeight - otherElement;
      		else
      			browse.style.height = minSize;
      	}
      } // ResizeBrowser
