/* *******************************************************************
   File:          cacFunctions.js
   Written by:    CAC, Nov 03
   Last revision:
   
   Notes:         i discovered satyam's function file after i'd  
                  already written a number of functions for the same 
                  purposes. Since their code is flawed (using loop 
                  vars outside loop, work with form fields not str 
                  vars, ...) i created this file.

  ********************************************************************/

/* COOKIE FUNCTIONS
   ******************************************************************document.write ("cookies= " + document.cookie + "<br />");
	check if cookie exists for Org                                  
   *****************************************************************/

function getCookie(sOrgAbbrev)
{
   var result = null;
	var sCookie = ' ' + document.cookie + ';' ;	
	var startOfCookie = sCookie.indexOf(' CTSNET_USER_ID=') ;
	var endOfCookie ;
	
	if (startOfCookie != -1)
	{
	   startOfCookie += 16 ;
		endOfCookie = sCookie.indexOf(';', startOfCookie) ;
		result = unescape(sCookie.substring(startOfCookie, endOfCookie)) ;
		return result;
	}
	else
	   return false;
}


/* ******************************************************************
   Opens a new window the height and width specified.
   ******************************************************************/
var newWindow_obj = null; // global variable

function sizedNewWindow(windowname_str, url_str, winheight, winwidth) 
{
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */
  if( newWindow_obj == null || newWindow_obj.closed )
  {
//      xlocation = (screen.availWidth - winwidth) / 2;
//      ylocation = (screen.availHeight - winheight) / 2;
//      xlocation = screen.availWidth - winwidth ;
      xlocation = screen.availWidth - winwidth - 10 ;
      ylocation = 1  ;  
      winfunctions_str = "height=" + winheight + ",width=" + winwidth + ",screenX=" + xlocation + ",left=" + xlocation + ",screenY=" + ylocation + ",top=" + ylocation + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=1,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=1";
      newWindow_obj = open( url_str, windowname_str,  winfunctions_str );
  }
  else
  {
    newWindow_obj = open( url_str, windowname_str );
    newWindow_obj.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
	}
}


/* ==================================================================
   STRING FUNCTIONS
   ==================================================================/
	
/* ******************************************************************
   Trims trailing and preceding spaces
   RETURNS trimmed string          
   ******************************************************************/
function trimStr(trim_str)
{
   var firstChar = 0 ;
   var lastChar = trim_str.length - 1 ;

   // get first character position, skipping spaces
   for ( var j = 0; j < trim_str.length ; j++ )
   {
      if (trim_str.charAt(j) != ' ' && trim_str.charAt(j) != '\t')
      {
         firstChar = j ;
         break ;
      }
   }

   // if string contains more than one char, get last character position   
   if ( firstChar <  lastChar )
      for ( var k = lastChar ;  k >= 0 ; k-- )
         if ( (trim_str.charAt(k) != ' ') && trim_str.charAt(k) != '\t')
         {
            lastChar = k ;
            break ;
         }         
   
   trim_str = trim_str.substring(firstChar, (lastChar + 1) ) ; 
   return trim_str;
}


/* ******************************************************************
   tests for empty string
   RETURNS true for empty string          
   ******************************************************************/
function isEmpty (test_str)
{   
   test_str = trimStr(test_str) ;
	
	if (test_str.length == 0 ) 
      return true ;   // string is empty
   
   for (var i=0; i < test_str.length; ++i)
      if (test_str.charAt(i) != ' ' && test_str.charAt(i) != '\t')
         return false ;

   return true ;   // string isn't empty but contains no valid chars
}


/* ******************************************************************
   tests the string for spaces, replacing internal spaces with 
   underscore and trimming preceding and trailing spaces.  multiple
   spaces are replaced with a single underscore.
   NOTE: Code should check if the string is empty BEFORE calling this
   function
   RETURNS: the string trimmed and with '_' replacing internal spaces 
   ******************************************************************/
function replaceSpaces (spaceTest_str)
{ 
   spaceTest_str = trimStr( spaceTest_str ) ;
   // search trimmed string for spaces and replace with underscore
   for (var n = 0 ; n <= spaceTest_str.length ; n++ )
   {
      currentChar = spaceTest_str.charAt(n) ;
      if ( currentChar == ' ' )
      {
         if ( n > 0 )  // if preceding char is already an underscore skip to next char
         {
            if ( spaceTest_str.charAt(n - 1) != '_' )
               spaceTest_str =  spaceTest_str.replace(spaceTest_str.charAt(n), "_");
            else
            {
               spaceTest_str = spaceTest_str.substr( 0, n ) + 
                                spaceTest_str.substr( (n + 1), (spaceTest_str.length - (n + 1) ) );
               n = n - 1 ;                          
            }
         }
         else     // first char, throw away
         {
            spaceTest_str =  spaceTest_str.substr( 1 , spaceTest_str.length - 1 );
            n = n =1 ;
         }        
         
      }
   }

   return spaceTest_str ;   
}


/* ******************************************************************
   tests the string for spaces or special characters.  both are
	removed and preceding and trailing spaces are trimmed
   NOTE: Code should check if the string is empty BEFORE calling this
   function
   RETURNS: the string trimmed and with no spaces or spec chars 
   ******************************************************************/
function removeSpaces (spaceTest_str)
{ 
   spaceTest_str = trimStr( spaceTest_str ) ;
   // search trimmed string for spaces and replace with underscore
   for (var n = 0 ; n <= spaceTest_str.length ; n++ )
   {
      currentChar = spaceTest_str.charAt(n) ;
      if ( currentChar == ' ' )
      {
			spaceTest_str = spaceTest_str.substr( 0, n ) + 
           		          spaceTest_str.substr( (n + 1), (spaceTest_str.length - (n + 1) ) );
         n = n - 1 ;          
      }
   }

	// search trimmed, spaceless string for spaces or non alpha chars in 
   // middle and remove
   for (var m = 0 ; m < spaceTest_str.length ; m++ )
   {
      currentCharCode = spaceTest_str.charCodeAt(m) ;
      
      // 46 = '.' ; 45 = '-' ; 48 = '0' ; 122 = 'z' ; 57 = '9' ; 
      // 65 = 'A' ; 90 = 'Z' ; 97 = 'a'      
      if ( ( ( currentCharCode < 48 ) && ( currentCharCode != 45 ) && 
             ( currentCharCode != 46 )  ) || 
           ( currentCharCode > 122 ) ||
           ( ( currentCharCode > 57 ) && ( currentCharCode < 65 ) ) ||
           ( ( currentCharCode > 90 ) && ( currentCharCode < 97 ) ) 
          )
      {  
         if ( m > 0 )  
         {
         	spaceTest_str = spaceTest_str.substr( 0, m ) + 
            spaceTest_str.substr( (m + 1), (spaceTest_str.length - (m + 1) ) );
            m = m - 1 ;            
         }
         else     // first char 
         {
            spaceTest_str =  spaceTest_str.substr( 1, spaceTest_str.length - 1 );
            m = m - 1 ;
         }        
      }
   }

   return spaceTest_str ;   
}


/* ******************************************************************
   tests the string for non-numeric characters.
   NOTE: Code should check if the string is empty BEFORE calling this
   function
   RETURNS: true if all numeric, else false
   ******************************************************************/
function isnumeric(numTest_str)
{
   for (var i = 0; i < numTest_str.length; i++ )
   {  
      if (numTest_str.charAt(i) < "0" || numTest_str.charAt(i) > "9")
         return false;
    }     
   return true;
}


/* ******************************************************************
   tests the string for non-numeric characters other than '.'
	if numeric but no decimal point, the decimal point is added and a
	confirmation message displayed allowing the user to submit the form 
	with the revised value or cancel and return to the form to edit the 
	value.
   NOTE: Code should check if the string is empty BEFORE calling this
   function
   RETURNS: true if all numeric, else false
   ******************************************************************/
function isCurrency( numTest_str, formField, fieldName )
{
   for (var i = 0; i < numTest_str.length; i++ )
   {  
      if ( (numTest_str.charAt(i) < "0" && numTest_str.charAt(i) != '.' ) || numTest_str.charAt(i) > "9"  )
			return false;
		else 
			if ( numTest_str.charAt(i) == '.'  &&  i != ( numTest_str.length - 3 ) )
				return false ;
   }     
	
	if ( numTest_str.charAt(numTest_str.length - 3) != '.' )
	{
		formField.value = numTest_str.substr( 0, numTest_str.length - 2 ) + '.' + numTest_str.substr( numTest_str.length - 2, numTest_str.length ) ;
		return confirm ( fieldName + " has been edited to include the required two decimal places. It is now " + formField.value + ". If the value is correct click OK.  If you need to change the value select cancel.");
	}
	return true;
}  


/* ******************************************************************
   tests the string for non alphanumeric characters and replaces
   them with underscore.  trims preceding and trailing spaces 
   multiple spaces are replaced with a single underscore.
   NOTE: Code should check if the string is empty BEFORE calling this
   function
   RETURNS: the string trimmed and with '_' replacing non aphanum chars 
   ******************************************************************/
function replaceSpChars (specCharTest_str)
{  // search trimmed string for spaces or non alpha chars in middle
   // and replace with underscore
   for (var m = 0 ; m < specCharTest_str.length ; m++ )
   {
      currentCharCode = specCharTest_str.charCodeAt(m) ;
      
      // 46 = '.' ; 45 = '-' ; 48 = '0' ; 122 = 'z' ; 57 = '9' ; 
      // 65 = 'A' ; 90 = 'Z' ; 97 = 'a'      
      if ( ( ( currentCharCode < 48 ) && ( currentCharCode != 45 ) && 
             ( currentCharCode != 46 )  ) || 
           ( currentCharCode > 122 ) ||
           ( ( currentCharCode > 57 ) && ( currentCharCode < 65 ) ) ||
           ( ( currentCharCode > 90 ) && ( currentCharCode < 97 ) ) 
          )
      {  
         if ( m > 0 )  // if preceding char is already an underscore skip to next char
         {
               if ( (specCharTest_str.charAt(m - 1) != '_') && 
                    (m != specCharTest_str.length - 1 ) )
                  specCharTest_str =  specCharTest_str.replace(specCharTest_str.charAt(m), "_");
               else
                  if ( ( m == specCharTest_str.length - 1 ) && 
                       ( (specCharTest_str.charAt(m - 1)) != '_' ) )
                     specCharTest_str = specCharTest_str.substr( 0, m ) ;
                  else
                     if ( ( m == specCharTest_str.length - 1 ) && 
                          ( (specCharTest_str.charAt(m - 1)) == '_' ) )
                        specCharTest_str = specCharTest_str.substr( 0, m - 1 ) ;
                     else
                     {
                        specCharTest_str = specCharTest_str.substr( 0, m ) + 
                           specCharTest_str.substr( (m + 1), (specCharTest_str.length - (m + 1) ) );
                        m = m - 1 ;                          
                     }
         }
         else     // first char 
         {
            specCharTest_str =  specCharTest_str.substr( 1, specCharTest_str.length - 1 );
            m = m - 1 ;
         }        
      }
   }
   return specCharTest_str ;   
}


/* ==================================================================
   FORM FUNCTIONS - FORM FUNCTIONS - FORM FUNCTIONS - FORM FUNCTIONS
   ==================================================================/
	
/* ******************************************************************
   Gets the value of the selected radio button.
	Pass in the radio button object, getRadioValue(this.form.radioname)
	Returns the value of the selected radio button.  If none have been 
	   selected null is returned.
   ******************************************************************/

function getRadioValue(frmRadioObj)
{	var value = null;
	for ( var i=0; i < frmRadioObj.length; i++ )
		if ( frmRadioObj[i].checked )
		{	
			value = frmRadioObj[i].value;
			break;
		}
							  
	return value ;
}

/* ******************************************************************
   Gets the index of the selected radio button.
	Pass in the radio button object, getSelectedRadio(this.form.radioname)
	Returns the index of the selected radio button.  If none have been 
	   selected null is returned.
   ******************************************************************/

function getSelectedRadio(frmRadioObj)
{	var value = null;
	for ( var i=0; i < frmRadioObj.length; i++ )
		if ( frmRadioObj[i].checked )
		{	
			value = i;
			break;
		}
							  
	return value ;
}

/* ******************************************************************
   CHECKBOX functions
	1. is one of the checkboxes selected/checked -- Returns true or 
		false
	2. check all of the checkboxes -- nothing returned
	3. clear all of the checkboxes -- nothing returned	
   ******************************************************************/

function isChecked(frmFieldObj)
{
	for ( i = 0; i < frmFieldObj.length; i++ )
   	if (frmFieldObj[i].checked == true)
			return true;

	// to handle when only one checkbox
	if (frmFieldObj.checked == true)
		return true;
	
	return false;
}	
	
function checkAll(frmFieldObj)
{
	for (i = 0; i < frmFieldObj.length; i++)
		frmFieldObj[i].checked = true ;
		
	frmFieldObj.checked = true;
}

function uncheckAll(frmFieldObj)
{
	for (i = 0; i < frmFieldObj.length; i++)
		frmFieldObj[i].checked = false ;

	frmFieldObj.checked = false;
}

/* ******************************************************************
   handler for form textarea or text field.
   called ONCHANGE and ONSUBMIT 
   count the number of characters entered and trigger an alert if over
   maxChar characters.  The extra character is for the CR-LF that gets 
   inserted at the end of the text 
   Returns TRUE if within the limited number of characters, else FALSE
   ******************************************************************/

function testTxtLength (frmTextObj, maxChar, frmFieldLabel) 
{  /*Validate textarea length before submitting the form for product features*/
   if ( frmTextObj.value.length > maxChar ) 
   {  diff = frmTextObj.value.length - maxChar ;
      if ( diff > 1 )
         diff = diff + " characters" ;
      else
         diff = diff + " character" ;
      
      alert("Your " + frmFieldLabel + " is limited to " + maxChar + " characters. \nIt currently " 
             + "exceeds the maximum number of characters. Please \nreduce the text by " + diff + ".");
      frmTextObj.focus();
      frmTextObj.select();
            
      return false;
   }  /* end if */
   
   else
      return true;
}


/* ******************************************************************
   ONBLUR handler for state to auto set corresponding country. 
   To use this function the country form field must be named 
   'country' (id also). 
   ******************************************************************/
	var canadaProvinces_str = new String("MB,BC,AB,NT,NF,NB,ON,NS,PE,PQ,SK,YT");

   function getCountry(form, selectedStateProvince, sStateField, sCountryField )   
   {   
		if (typeof sStateField == "undefined") 
			sStateField = form.stateProvince ;

		if (typeof sCountryField == "undefined") 
			sCountryField = form.country ;

      if ( selectedStateProvince == "" )
               return true;   // this occurs if they select Not Applicable-do nothing            
                 
      else if ( canadaProvinces_str.indexOf( selectedStateProvince ) >= 0 )          
      {  
         sCountryField.options[0].value = "Canada" ;
         sCountryField.options[0].text = "Canada" ; 
         sCountryField.selectedIndex=0; 
         return true;
      }
      	else  if ( selectedStateProvince == "Not Applicable" )
                  {  // this is a bug if it occurs something has gone wrong.
                     // clear out value and replace with empty string
                     sStateField.options[0].value = "";            
                     sStateField.options[0].text = "Not Applicable";    
                     sStateField.selectedIndex = 0;      
                     return true;
                  }
                  
               else
                  {  
                     sCountryField.options[0].value = "United States" ;
                     sCountryField.options[0].text = "United States" ; 
                     sCountryField.selectedIndex=0; 
                     return true;
                  }         

   }   

/* ******************************************************************
   ONBLUR handler for country.  if country is not US or
   Canada or if US state with Canada, or U.S. with province then 
   the state value is set to not applicable.
   To use this function the state form field must be named 
   'stateProvince' (id also). 
	
	CAC, 17-Aug-2011.  modified to add country != '' in second if
	did so that if user switched their country choice to none (value = '')
	state would not be disabled.  Need this for places like adv memb search
	so a state can be selected even if no country is selected.
   ******************************************************************/

   function checkState (form, selectedCountry, selectedState, sStateField )   
   {
		if (typeof sStateField == "undefined") 
			sStateField = form.stateProvince ;

      if ((selectedCountry != "United States") && (selectedCountry != "Canada") && (selectedCountry != "") )
         {  
            sStateField.options[0].value = "";            
            sStateField.options[0].text = "Not Applicable";    
            sStateField.selectedIndex = 0;
				sStateField.disabled = true;
         }
      else
			{
				sStateField.disabled = false;
				
				if ( ( selectedCountry == "Canada" ) && ( selectedState != "" ) )
				{
					if ( canadaProvinces_str.indexOf( selectedState ) == -1 )
						{  // country is canada but u.s. state
							sStateField.options[0].value = "";            
							sStateField.options[0].text = "--Select One--";    
							sStateField.selectedIndex = 0; 
						}
				}
						
				else
				{
					if ( ( selectedState != "" ) && ( canadaProvinces_str.indexOf( selectedState ) >= 0 ) )
						{  // country is U.S. but canadian province
							sStateField.options[0].value = "";            
							sStateField.options[0].text = "--Select One--";    
							sStateField.selectedIndex = 0;                  
							
						}
					else 
						if ( selectedState == "" )
						{	// to handle case where other country selected setting text to 
							// not applicable, then switch to canada or us--get enabled 
							// field but still says not applicable.
							sStateField.options[0].value = "";            
							sStateField.options[0].text = "--Select One--";    
							sStateField.selectedIndex = 0; 
						}

				}
			}
   }



/* ==================================================================
   EMAIL FUNCTIONS - EMAIL FUNCTIONS - EMAIL FUNCTIONS 
   ==================================================================/
	
/* ******************************************************************
   Satyam function, slightly revised.
   RETURNS: True or False 
   ******************************************************************/
function isvalidemail( frmField_obj )
{ // test is a method that tests for a match of a regular expression in a string
  // returns true if found, else false
   var emailAddr_str = frmField_obj.value; 
   var regExprsn1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; 
   var regExprsn2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; 
   
   if ( !regExprsn1.test(frmField_obj) && regExprsn2.test(frmField_obj) ) 
      return true;
   else
      return false;
}


/* ******************************************************************
   Satyam function, slightly revised.  First function is failing
   on valid email addresses.  Can't remove entirely because don't 
   know where it is being used
   RETURNS: True or False 
   ******************************************************************/
function IsEmailValid( emailAddr_str )
{
   var EmailOk  = true
   var atSymLocation = emailAddr_str.indexOf('@')
   var periodLocation = emailAddr_str.lastIndexOf('.')
   var spaceLocation = emailAddr_str.indexOf(' ')
   var emailLength   = emailAddr_str.length - 1   // Array is from 0 to length-1

//alert (emailAddr_str.value);
   if ( spaceLocation  != -1 )
            EmailOk = false
   if ( ( atSymLocation < 1 ) ||                      // '@' cannot be in first position
        ( periodLocation <= atSymLocation + 1 ) ||    // Must be atleast one valid char btwn '@' and '.'
        ( periodLocation == emailLength ) ||          // Must be atleast one valid char after '.'
        ( spaceLocation  != -1 ) )                    // No empty spaces permitted
   {  
         EmailOk = false
   }
   //alert("funtion :" + EmailOk);
   return EmailOk;
}


