
// =========================================================;
// Function to trim spacess from string values              ;
// =========================================================;
function trim( str ) {
  var resultStr = "";
  var i = len = 0;

  // Return immediately if an invalid value was passed in
  if (str+"" == "undefined" || str == null)
      return null;

  // Make sure the argument is a string
  str += "";

  if (str.length == 0) 
      resultStr = "";
  else {
      // Loop through string starting at the beginning as long as there
      // are spaces.
      // len = str.length - 1;
      len = str.length;

      while ((i <= len) && (str.charAt(i) == " "))
          i++;

      // When the loop is done, we're sitting at the first non-space char,
      // so return that char plus the remaining chars of the string.
      resultStr = str.substring(i, len);
  }

  // resets the str value
  str = resultStr;

  // Begin The trim process for the spaces to the right of the string
  i = 0;

  if (str.length == 0)
      resultStr = "";
  else {
      // Loop through string starting at the end as long as there
      // are spaces.
      i = str.length - 1;
      while ((i >= 0) && (str.charAt(i) == " "))
          i--;

      // When the loop is done, we're sitting at the last non-space char,
      // so return that char plus all previous chars of the string.
      resultStr = str.substring(0, i + 1);
  }

  alert( "\"" + resultStr + "\"" );
  	return resultStr;

}


// =========================================================;
// Strip all non-numeric characters                         ;
// =========================================================;
function StripNonNumeric( str ) {
  var 	resultStr = "";

  // Return immediately if an invalid value was passed in
  if (str+"" == "undefined" || str == null)	
      return null;

  // Make sure the argument is a string
  str += "";

  // Loop through entire string, adding each character from the original
  // string if it is a number
  for (var i=0; i < str.length; i++) {
   	  if ( (str.charAt(i) >= "0") && (str.charAt(i) <= "9") )
          resultStr = resultStr + str.charAt(i);

  } // end for loop

  return resultStr;
}


// =========================================================;
// Function to set display error for max length of Text Area;
// =========================================================;
function maxLength ( obj, maxLength ) {
  var tValue = obj.value;
  if ( tValue.length > maxLength ) {
    alert ( "Error in: " + obj.name + "\n\nNumber of characters exceeds: " + maxLength + "\nCurrent number of characters: " + tValue.length );
	obj.focus();
  }
}

// =========================================================;
// Function to Confirm prompt                               ;
// =========================================================;
function confirmPrompt ( confirmType, confirmMessage) {
  if ( !confirm( "Confirm: " + confirmType + "\n\n" + confirmMessage ) ) {
    return false;
  }
  else {
    return true;
  }
}

// =========================================================;
// Function to Clear all text fields                        ;
// =========================================================;
function clearFields ( ) {
  var numElements      = document.closedForm.elements.length;
  var errorEncountered = false;
  var elementValidate;
  if ( confirm( "Confirm: Clear Fields\n\nYou are about to clear all fields." ) ) {
    for(var i = 0; i < numElements; i++) {
      if ( document.closedForm.elements[i].type == "text" || document.closedForm.elements[i].type == "textarea" || document.closedForm.elements[i].type == "password" ) {
	    document.closedForm.elements[i].value = "";
  	  }
    }
  }
}

// =========================================================;
// Function to set focus to any previously opened windows   ;
// =========================================================;
function openWindow( pWindowToOpen, pWindowName ) {
  // openWindow( "itemdetail.html?sessId=0x000016cf&altitemno=58231&itemnum=05582310", "itemdetail" );
  var vWindowStatus;
  vWindowStatus = window.open( pWindowToOpen, pWindowName, "scrollbars=1,resizable=1,toolbar=0,status=0,menubar=0,height=500,width=700,top=10,left=10");
  vWindowStatus.focus();
}


// =========================================================;
// Validate email address format                            ;
// =========================================================;
function IsValidEmail( str ) {
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
		return true;

	var isValid = true;

	str += "";

	namestr = str.substring(0, str.indexOf("@"));  // everything before the '@'
	domainstr = str.substring(str.indexOf("@")+1, str.length); // everything after the '@'

	// Rules: namestr cannot be empty, or that would indicate no characters before the '@',
	// domainstr must contain a period that is not the first character (i.e. right after
	// the '@').  The last character must be an alpha.
   	if ( (namestr.length == 0)         ||
 	       (domainstr.indexOf(".") <= 0) ||
         (domainstr.indexOf("@") != -1)   )
		    isValid = false;

    if (!isValid ) {
        alert( "js-Error: 103\n\nInvalid Email Address." );
        document.closedForm.email.focus();
    }

   	return isValid;
}

// =========================================================;
// Validate phone format                                    ;
// =========================================================;
function IsValidPhone( str ) {
  incAreaCode = true;
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")	
		return false;

	// Set default value for incAreaCode to false, if undefined or null
	if (incAreaCode+"" == "undefined" || incAreaCode+"" == "null")
		incAreaCode = false;

	var isValid = true;

	str += "";

	// After stripping out non-numeric characters, such as dashes, the
	// phone number should contain 7 digits (no area code) or 10 digits (area code)
	str = StripNonNumeric(str+"");
	if (incAreaCode && str.length != 10)
		isValid = false;
   if (!incAreaCode && str.length != 7)
		isValid = false;

    if ( !isValid ) {
      alert( "js-Error: 104\n\nInvalid Phone Number." );
      document.closedForm.email.focus();
    }

   	return isValid;
} // end IsValidPhone



// =========================================================;
// Validate all address fields                              ;
// =========================================================;
function validateAddress ( ) {
  var RequiredFieldsAreValid = false;
  var EmailFormatIsValid     = false;
  var PhoneFormatIsValid     = false;

  var shipName    = document.closedForm.name.value;
  var shipCompany = document.closedForm.company.value;
  var shipAddress = document.closedForm.address.value;
  var shipCity    = document.closedForm.city.value;
  var shipState   = document.closedForm.state.value;
  var shipZip     = document.closedForm.zip.value;
  var shipPhone   = document.closedForm.phone.value;
  var shipEmail   = document.closedForm.email.value;

  if ( shipName    == "" || shipAddress == "" ||
       shipCity    == "" || shipState   == "" ||
       shipZip     == "" || shipPhone   == "" ) {
      alert( "js-Error: 101\n\nAll fields are requied except your company name and e-mail address." );
      RequiredFieldsAreValid = false;
  }
  else {
      RequiredFieldsAreValid = true;
  }

  EmailFormatIsValid = IsValidEmail( shipEmail );
  PhoneFormatIsValid = IsValidPhone( shipPhone );

  if ( RequiredFieldsAreValid && EmailFormatIsValid && PhoneFormatIsValid )
      return true;
  else
      return false;
}

// Heinle's function for retrieving a cookie.
function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}

// An adaptation of Dorcht's function for setting a cookie.
function setCookie(name, value, expires, path, domain, secure) {
  var today = new Date();
  today.setTime( today.getTime() );
  
  if ( expires ) {
   expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date(today.getTime() + (expires) );

  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires_date.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

// An adaptation of Dorcht's function for deleting a cookie.
function delCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

