// @(#)library.js %W%
// Author: Keith Thompson
// Description: Misc Java Scripts
// Created: 09/20/2009
//
// Directory of scripts:
//
// navChanged - Set the NayKey & NavType fields
//      Use: onClick="navChanged('NavType','NavKey');submit();"
//
// doConfirm - Confirm an action
//      Use: <A href="javascript:if (doConfirm('Confirm Delete')) { navChanged('Delete','
//            NavKey
//           ');main.submit() } else alert(''Delete Cancelled'');">Delete</A>
//
// checkEmailValidation - Check for a valid e-mail format
//       Use: if ((tempobj.value=="") || !checkEmailValidation(tempobj))
//             
//
// setCombo - 
// Use: 
//
// validate - Validate alpha/numeric
//      Use: onBlur="validate(this)"
//
// validatedigit - Validate numeric only
//      Use: onBlur="validatedigit(this)"
//
// validatealpha - Validate alpha only
//      Use: onBlur="validatealpha(this)"
//
// checkrequired - Validate Requtred fields are entered
//      Use: <FORM onSubmit="return checkrequired(this)">
//           Name fields to begin with required. IE: requiredCusip
//
// colSort - Sort columns in a table (object, row)
//
// FormatDate - auto format and validation of date fields
//      Use: onFocus="javascript:vDateType='1'"
//           onKeyUp="DateFormat(this,this.value,event,false,'1')"
//           onBlur="DateFormat(this,this.value,event,true,'1')"
//
//
var submitcount=0;

function getBrowserHeight()
{
	if (window.innerHeight)
	   {return window.innerHeight;}
	else if (document.documentElement && document.documentElement.clientHeight != 0)
	   {return document.documentElement.clientHeight;}
	else if (document.body)
	   {return document.body.clientHeight;}
	return 0;
};

function getBrowserWidth()
{
	if (window.innerWidth)
	   {return window.innerWidth;}
	else if (document.documentElement && document.documentElement.clientWidth != 0)
	   {return document.documentElement.clientWidth;}
	else if (document.body)
	   {return document.body.clientWidth;}
	return 0;
};

function doConfirm(confirmText)
{
  if (confirmText.length > 0)
    return confirm(confirmText);
    else return confirm('Are you Sure?');
}

function checkform()
{
   // * * Required fields  * *
   iscomplete=true;
   msgArea = document.getElementById("RequiredMsg");
   if (!checkReq())
      {
         msgArea.innerHTML = "<span class='errorRequired'>*</span>&nbsp;Indicates a required field";
         iscomplete=false;
      }
   else
      msgArea.innerHTML = "<span class='errorRequired'>&nbsp;</span>";
   acceptButton = document.getElementById("btnAccept");
   if (iscomplete==false)
   {
      acceptButton.disabled="disabled";
      acceptButton.className="BoxButtonDisable";
   }
   else
   {
      acceptButton.disabled="";
      acceptButton.className="BoxButton";
   }
	var timer= setTimeout("checkform()",500);
};

function passwordStrength(password)
{
   var desc = new Array();
   desc[0] = "Very Weak";
   desc[1] = "Weak";
   desc[2] = "Better";
   desc[3] = "Medium";
   desc[4] = "Strong";
   desc[5] = "Strongest";
   var score   = 0;
   //if password bigger than 6 give 1 point
   if (password.length > 6) score++;
   //if password has both lower and uppercase characters give 1 point      
   if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;
   //if password has at least one number give 1 point
   if (password.match(/\d+/)) score++;
   //if password has at least one special caracther give 1 point
   if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;
   //if password bigger than 12 give another 1 point
   if (password.length > 12) score++;
   document.getElementById("passwordDescription").innerHTML = desc[score];
   document.getElementById("passwordStrength").className = "strength" + score;
}

function checkEmailValidation(formInput) {
   var message;
   if (stringEmpty(formInput.value)) 
      message = "Error! There is no input value entered.";
   else if (noAtSign( formInput.value ))
      message = "Error! The address \"" + formInput.value + "\" does not contain an '@' character.";
   else if (nothingBeforeAt(formInput.value)) 
   {
      message = "Error! The address \"" + formInput.value;
      message += "\" must contain at least one character before the '@' character";
   } 
   else if (noLeftBracket(formInput.value)) 
   {
      message = "Error! The address \"" + formInput.value;
      message += "\" contains a right square bracket ']',\nbut no corresponding left square bracket '['.";
   } 
   else if (noRightBracket(formInput.value)) 
   {
      message = "Error! The address \"" + formInput.value;
      message += "\" contains a left square bracket '[',\nbut no corresponding right square bracket ']'.";
   } 
   else if (noValidPeriod(formInput.value))
      message = "Error! The address \"" + formInput.value + "\" must contain a period ('.') character.";
   else if (noValidSuffix(formInput.value)) 
   {
      message = "Error! The address \"" + formInput.value;
      message += "\" must contain a two, three or four character suffix.";
   } 
   else 
      return (true);
   return (false);
}

function stringEmpty (formField) {
    // CHECK THAT THE STRING IS NOT EMPTY
    return ( formField.length < 1 );
}

function noAtSign (formField) {
    // CHECK THAT THERE IS AN '@' CHARACTER IN THE STRING
    return (formField.indexOf ('@', 0) == -1);
}

function nothingBeforeAt (formField) {
    // CHECK THERE IS AT LEAST ONE CHARACTER BEFORE THE '@' CHARACTER
    return ( formField.indexOf ( '@', 0 ) < 1 );
}

function noLeftBracket (formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR LEFT BRACKET
    return ( formField.indexOf ( '[', 0 ) == -1 && formField.charAt (formField.length - 1) == ']');
}

function noRightBracket (formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR RIGHT BRACKET
    return (formField.indexOf ( '[', 0 ) > -1 && formField.charAt (formField.length - 1) != ']');
}

function noValidPeriod (formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if (formField.indexOf ( '@', 0 ) > 1 && formField.charAt (formField.length - 1 ) == ']')
        return ( false );
    // CHECK THAT THERE IS AT LEAST ONE PERIOD IN THE STRING
    if (formField.indexOf ( '.', 0 ) == -1)
        return ( true );
    return ( false );
}

function noValidSuffix(formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if (formField.indexOf('@', 0) > 1 && formField.charAt(formField.length - 1) == ']') 
        return ( false );
    // CHECK THAT THERE IS A TWO OR THREE CHARACTER SUFFIX AFTER THE LAST PERIOD
    var len = formField.length;
    var pos = formField.lastIndexOf ( '.', len - 1 ) + 1;
    return (( len - pos ) < 2 || ( len - pos ) > 4 );
}

function passwordStrength(password)
{
   var desc = new Array();
   desc[0] = "Very Weak";
   desc[1] = "Weak";
   desc[2] = "Better";
   desc[3] = "Medium";
   desc[4] = "Strong";
   desc[5] = "Strongest";
   var score   = 0;
   //if password bigger than 6 give 1 point
   if (password.length > 6) score++;
   //if password has both lower and uppercase characters give 1 point      
   if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;
   //if password has at least one number give 1 point
   if (password.match(/\d+/)) score++;
   //if password has at least one special caracther give 1 point
   if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;
   //if password bigger than 12 give another 1 point
   if (password.length > 12) score++;
   document.getElementById("passwordDescription").innerHTML = desc[score];
   document.getElementById("passwordStrength").className = "strength" + score;
}

function addLoadListener(fn)
{
   if (typeof window.addEventListener != 'undefined')
      {window.addEventListener('load', fn, false);}
   else if (typeof document.addEventListener != 'undefined')
      {document.addEventListener('load', fn, false);}
   else if (typeof window.attachEvent != 'undefined')
      {window.attachEvent('onload', fn);}
   else
      {return false;}
   return true;
};

function attachEventListener(target, eventType, functionRef, capture)
{
    if (typeof target.addEventListener != "undefined")
      {target.addEventListener(eventType, functionRef, capture);}
    else if (typeof target.attachEvent != "undefined")
      {target.attachEvent("on" + eventType, functionRef);}
    else
      {return false;}
    return true;
};

function checkSubmit() 
{  // field validation -
   if (submitcount == 0)
   {
      submitcount++;
      return true;
   }
   else 
   {
      alert("This form has already been submitted!");
      return false;
   }
}

function setCombo(vID, vValue)
{
   vTemp = document.all.item(vID);
   for(i = 0; i < vTemp.length; i++)    
      vTemp(i).value = vValue; 
}

function validate(field) 
{
   var valid = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,-'!@#$%^&*() "
   var ok = "yes";
   var temp;
   for (var i=0; i<field.value.length; i++) 
   {
      temp = "" + field.value.substring(i, i+1);
      if (valid.indexOf(temp) == "-1") 
         ok = "no";
   }
   if (ok == "no") 
   {
      alert("Invalid entry!  Only characters and numbers are accepted!");
      field.focus();
      field.select();
   }
}

function validatedigit(field) 
{
   var valid = "0123456789.,-"
   var ok = "yes";
   var temp;
   for (var i=0; i<field.value.length; i++) 
   {
      temp = "" + field.value.substring(i, i+1);
      if (valid.indexOf(temp) == "-1") 
         ok = "no";
   }
   if (ok == "no") 
   {
      alert("Invalid entry!  Field must be a number!  Valid characters '0123456789.,-$%'");
      field.focus();
      field.select();
   }
}

function validatealpha(field) 
{
   var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
   var ok = "yes";
   var temp;
   for (var i=0; i<field.value.length; i++) 
   {
      temp = "" + field.value.substring(i, i+1);
      if (valid.indexOf(temp) == "-1") 
         ok = "no";
   }
   if (ok == "no") 
   {
      alert("Invalid entry!  Field must be Alpha (a-z) only!");
      field.focus();
      field.select();
   }
}

function checkrequired(which) 
{
   var pass=true;
   if (document.images) 
   {
      for (i=0;i<which.length;i++) 
      {
         var tempobj=which.elements[i];
         if (tempobj.name.substring(0,8)=="required") 
         {   
            if (((tempobj.type=="text"||tempobj.type=="textarea")
               && tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"
               && tempobj.selectedIndex==0)) 
            {
               pass=false;
               break;
            }
         }
      }
   }
   if (!pass) 
   {
      shortFieldName=tempobj.name.substring(8,30).toUpperCase();
      alert("Please make sure the "+shortFieldName+" field was properly completed.");
      return false;
   }
   else
      return true;
}

function showDetails(divID)
{     
   var strShow = divID+"Show";
   var strHide = divID+"Hide";

   if (objectExists(divID))
      document.all[divID].style.display = "block";
   document.all[strShow].style.display = "none";
   document.all[strHide].style.display = "block";
}

function hideDetails(divID)
{
   var strShow = divID+"Show";
   var strHide = divID+"Hide";

   if (objectExists(divID))
      document.all[divID].style.display = "none";
   document.all[strShow].style.display = "block";
   document.all[strHide].style.display = "none";
}

function toggleHideShowObject(s)
{ 
   // Must get o (object) to check its display style.  
   // Send string to hideObject and showObject.
   if (!objectExists(s)) return false; 
   var o = eval(s);
   var oPrompt = getObject(s + "Prompt");
   // hide/show the object no matter what.  If there's an associated prompt, 
   // set it to Hide if we are Showing the object, and to Show if we are Hiding the object

   if (o.style.display == "none") 
   {
      showThisObject(s)
      if (typeof oPrompt == "object")
         {setHideShowPrompt(s, "Hide")}
   } 
   else 
   {
      hideThisObject(s)
      if (typeof oPrompt == "object")
         {setHideShowPrompt(s, "Show")}
   }
}

function setHideShowPrompt(sModuleDIVName, sPrompt)
{ 
   // Given the name of the moduleDIV, plus "Prompt", you have then name of the 
   // Label "Hide/Show" for that module.  Get the DIV  and change the inner text 
   // to be whatever is sent in as sPrompt (Hide or Show).  Written by CBT 1/5/02; 
   // made into its own  function by DLM 1/7/02.
   
   var sPromptDIV = sModuleDIVName + "Prompt"; 
   if (!objectExists(sPromptDIV) ) return false; 
   oPromptDIV = eval(sPromptDIV); 
   oPromptDIV.innerText = sPrompt; 
}

function objectExists(sName, sType)
{ 
   // Second parameter is optional and specifies that object must also be of specified type.
   if (isEmpty(sType)) 
      {return (document.all[sName] != null) ;}
   else 
      {return (document.all[sName] != null && document.all[sName].type == sType);}
}

function isEmpty(s) 
{
   return (s == null || s.length == 0 || s == "")
}

function isVisible(hField)
{
   if (hField.type != "hidden")
      return true;
}

function showThisObject(s) //duplicate name
{
   //send only object name.  not form.[whatever].  using document.all, and it only needs a name.
   if (isEmpty(s)) 
      return false;
   
   s = ("document.all['" + s + "']");
   var o = eval(s);
   
   if (isEmpty(o))
   {
      return false;
   }
   o.style.display = "";
   return true;
}

function getObject(s)
{  //wrote by dlm 10/8/2002 for ease of use  -keep forgetting how to get an object
   //send only object name.  not form.[whatever].  using document.all, and it only needs a name.
   if (isEmpty(s)) 
      return false;
   s = ("document.all['" + s + "']");
   var o = eval(s);
   if (!isEmpty(o)) 
      return o;
   else 
      return null;
}

function hideThisObject(s) //duplicate name
{
   //send only object name.  not form.[whatever].  using document.all, and it only needs a name.
   if (isEmpty(s)) 
      return false;
   s = ("document.all['" + s + "']");
   var o = eval(s);
   if (isEmpty(o))
   {
      return false;
   }
   o.style.display = "none";
}

// Check browser version
var isNav4 = false, isNav5 = false, isIE4 = false
var strSeperator = "/";
// If you are using any Java validation on the back side you will want to use the / because
// Java date validations do not recognize the dash as a valid date separator.
var vDateType = 3; // Global value for type of date format
//                1 = mm/dd/yyyy
//                2 = yyyy/dd/mm  (Unable to do date check at this time)
//                3 = dd/mm/yyyy
var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.
var err = 0; // Set the error code to a default of zero
if(navigator.appName == "Netscape") 
{
   if (navigator.appVersion < "5") 
   {
      isNav4 = true;
      isNav5 = false;
   }
   else if (navigator.appVersion > "4") 
   {
      isNav4 = false;
      isNav5 = true;
   }
}
else 
   {isIE4 = true;}



