//
//    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;

            window.setTimeout('resizeHeader("' + objName + '")',1);
      	}
      } // ResizeBrowser

      // function which resize header to the same width as browser
      // this function meed to be called with delay
      function resizeHeader( objName )    {
          var browse = document.getElementById(objName),
              header = document.getElementById(objName + "Header");
          if (browse && header)
              header.style.width = browse.clientWidth;
      }

  // Set maximum lengths according selection of fundidentifeir
  function setIdentifierLength() {
    switch(document.all.SelectLocate.value) {
      case 'SECID':
       document.all.fundText.maxLength = 10;
       break;
      case 'ISIN':
        document.all.fundText.maxLength = 12;
        break;
      case 'VALOREN':
        document.all.fundText.maxLength = 9;
        break;
      case 'VAL':
        document.all.fundText.maxLength = 9;
        break;
      case 'CUSIP':
        document.all.fundText.maxLength = 9;
        break;
      case 'SEDOL':
        document.all.fundText.maxLength = 7;
        break;
      case 'CITCO BANK':
        document.all.fundText.maxLength = 12;
        break;
      case 'CITCO':
        document.all.fundText.maxLength = 12;
        break;
      case 'CUSTOM':
        document.all.fundText.maxLength = 30;
        break;
      case 'TRADING ID':
        document.all.fundText.maxLength = 12;
        break;
      case 'TRCCS':
        document.all.fundText.maxLength = 12;
        break;
      case 'CFS':
        document.all.fundText.maxLength = 12;
        break;
      case 'NTAS':
        document.all.fundText.maxLength = 12;
        break;
    }
  } // Set FundIdentifierLength


   function checkspchars(obj)
   {
      var iCount
      var spChars = "!()&?\\\'|\"";
      var chrArray = spChars.split("");
      for (iCount in chrArray)
         {
         if (obj.value.indexOf(chrArray[iCount]) >= 0) 
            {
            alert ("Special characters [" + spChars + "] cannot be used in entered text.\nPlease re-enter your search.");
            return false;
            }
         }
      return true;
   }

  /* check for length of fundText based on selected fund type  */
  /* on leave of fundText field, before running findFund. If length */
  /* okay, run findFund in the ARM Frame. */

  function checkFund(cNRA) {
    
    /** if the fund text field has an entry **/
    if (document.all.fundText.value != '') {
      switch(document.all.SelectLocate.value) {
         case 'SECID':
          if (document.all.fundText.value.length > 10) {
            alert('CDS ID must be less than 11 characters.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
         break;

         case 'ISIN':
          if (document.all.fundText.value.length != 12) {
            alert('ISIN Numbers must be 12 characters.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          break;

      case 'VALOREN':
        // make sure that the value is an integer
        var i_Valor = parseInt(document.all.fundText.value);

        if (isNaN(i_Valor)) {
          alert('Valoren Numbers must be numeric.');
          document.all.fundText.select();
          document.all.fundText.focus();
          return false;
        }
        if (document.all.fundText.value.length < 6) {
          alert('Valoren Numbers must be at least 6 digits.');
          document.all.fundText.select();
          document.all.fundText.focus();
          return false;
        }
        if (document.all.fundText.value.length > 9) {
          alert('Valoren Numbers must not be more than 9 digits.');
          document.all.fundText.select();
          document.all.fundText.focus();
          return false;
        }
        // front fill valoren # with zeroes to make the length 9
        while (document.all.fundText.value.length < 9)
        { document.all.fundText.value = '0' + document.all.fundText.value; }
        break;

        case 'VAL':
          // make sure that the value is an integer
          var i_Valor = parseInt(document.all.fundText.value);

          if (isNaN(i_Valor)) {
            alert('Valoren Numbers must be numeric.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          if (document.all.fundText.value.length < 6) {
            alert('Valoren Numbers must be at least 6 digits.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          if (document.all.fundText.value.length > 9) {
            alert('Valoren Numbers must not be more than 9 digits.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          // front fill valoren # with zeroes to make the length 9
          while (document.all.fundText.value.length < 9)
          { document.all.fundText.value = '0' + document.all.fundText.value; }
          break;

        case 'CUSIP':
          if (document.all.fundText.value.length <= 5) {
            alert('Cusip Numbers must be between 6 and 9 characters long.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          break;

        case 'CITCO BANK':
          if (document.all.fundText.value.length < 4 || document.all.fundText.value.length > 12) {
            alert('Citco Bank Numbers must be >= 4 characters or <= 12 characters.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          var select_val = 'CITCO';
          break;

        case 'TRADING ID':
          if (document.all.fundText.value.length != 12) {
            alert('Trading Id Numbers must be 12 characters.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          var select_val = 'TRCCS';
          break;

        case 'CFS':
          if (document.all.fundText.value.length > 12) {
            alert('Citco Fund Services Numbers must be 11 characters or less.');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          break;

        case 'SEDOL':
          if (document.all.fundText.value.length <= 5) {
            alert('Sedol Numbers must be 6 or 7 characters');
            document.all.fundText.select();
            document.all.fundText.focus();
            return false;
          }
          break;
      }

     if (! checkspchars(document.all.fundText))
         return false;

     // Retrieve the fund details
      retrieveFund(cNRA);

    } //  if fundText.value != '' 

  } // end function checkfund();

  // get Idetification Code
  function refreshQueryIden()
  {
    // if the value from the identifier drop-down 
    // list is CITCO BANK then convert to CITCO   
    // list is TRADING ID then convert to TRCCS   
    if (document.all.SelectLocate.value == 'CITCO BANK')
        var cSelectVal = 'CITCO';
    else
    if (document.all.SelectLocate.value == 'TRADING ID')
        var cSelectVal = 'TRCCS';
    else
        var cSelectVal = document.all.SelectLocate.value;

    return cSelectVal;
  } // refreshQueryIden

  var xmlhttp;

  // function invokeAsyncProcedure(url, callback)
  function invokeAsyncProcedure (url, callback, status)
  {
    if (!xmlhttp) { 
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    window.status = status;
    xmlhttp.open("GET",url+"&rid=" + Math.random(),true);
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          window.status = "";		
          if (eval('typeof ' + callback)=='function') 
              window[callback](xmlhttp);
          else 
  	  {
  	    alert("Function " + callback + " is not available.");
  	    return false;
  	  }
        }
     }
    xmlhttp.send(null);
  } //invokeAsyncProcedure


  // this function reset the session
  function resetSession(reason, option)
  {
    alert("Session Expired\n\nYou have exceeded the allowed period of inactivity.\nYour session has expired and you must login again.");

    if (option == 0) 
    {
      var TgtURL = document.location.protocol + "//" + document.location.host;
    

      var startPath      ="parent";
    
      while (eval(startPath + ".frames[0].name") != eval(startPath + ".parent.frames[0].name")) 
 
      { 
    
        startPath += ".parent";
 
      } 
 
      fRef = eval("new " + startPath + ".frameRef"); 
 
      fRef.location = startPath + "."; 
    
      if (!fRef.x3616) 
      { 
    
  	if (top.TitleFrame.SetUserNameLabel) 
top.TitleFrame.SetUserNameLabel(""); 
  
        if (top.BrowseFrame) top.BrowseFrame.location.href= document.location.protocol + "//" + document.location.host + "/static/disclaimer.HTML?Bkr=wscfn"; 
  
	if (top.ViewFrame) top.ViewFrame.location.href=document.location.protocol + "//" + document.location.host + "/static/GFNiF4a.html"; 
  
        if (top.HiddenFrame) top.HiddenFrame.location.href=document.location.protocol + "//" + document.location.host + "/static/HiddenFrame.html"; 
     
        if (top.NavFrame) top.NavFrame.location.href=document.location.protocol + "//" + document.location.host + "/static/GFNiF2.html"; 
     
      }
    
  else  
    
	  top.location = TgtURL;

    }
  } //resetSession





