// *****************************************************************************
// *
// * Shane M Allred 
// * IBM Global Services
// * Version 1.2
// *
// * This file contains generic JavaScript functions that can be used for 
// * some generic types of form validation. 
// *
// * These functions include:
// * - Checking a required field
// * - Checking a list of required fields
// * - Trimming a string or field value
// * - Retrieving the selected value of a form control
// * - Setting the value or selected value of a form control
// * - Validating an email address
// * - Selecting a field
// * - Sending a referall page URI to a friend
// *
// * The following form control types are supported where applicable
// * - text
// * - textarea
// * - submit
// * - file
// * - password
// * - select-one
// * - select-multiple
// * - checkbox
// * - radio
// *
// *****************************************************************************
//Open the default e-mail editor with the referral page in the message



function emailPage(e_subject, e_body) {
  var mail_str = "mailto:?subject=" + 
    escape(e_subject) + "&body=" + escape(e_body) + " " + escape(location.href);

  location.href = mail_str;
}

// Checks the validity of an email address
function checkEmail(email) {
  var at="@";
  var dot=".";
  var lat=email.indexOf(at);
  var lstr=email.length;
  var ldot=email.indexOf(dot);
  var l1dot=email.lastIndexOf(dot);

  if (email.indexOf(at)==-1&&ldot==l1dot){
    return false;
  }
  if ((email.indexOf(at)==-1&&ldot==l1dot)|| email.indexOf(at)==0 || email.indexOf(at)==lstr){
   return false;
  }
  if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr){
    return false;
  }
  if (email.indexOf(at,(lat+1))!=-1){
    return false;
  }
  if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot){
    return false;
  }
  if (email.indexOf(dot,(lat+2))==-1){
    return false;
  }
  if (email.indexOf(" ")!=-1 || email.indexOf("\\")!=-1 || email.indexOf(":")!=-1  || email.indexOf(";")!=-1 || email.indexOf("\"")!=-1){
    return false;
  }
  if (email.indexOf(",")!=-1 || email.indexOf("<")!=-1 || email.indexOf(">")!=-1  || email.indexOf("(")!=-1 || email.indexOf(")")!=-1 || email.indexOf("*")!=-1){
    return false;
  }
  return true;			
}

// Creates a popup window
function popupWindow(mypage, myname, w, h, scroll) {
  var winl = (screen.width - w) / 2;
  var wint = (screen.height - h) / 2;
  var winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable,status';
  var win = window.open(mypage, myname, winprops);
  win.focus();
}

// Checks the size of a field value against a user defined value
function checkLength(form, fieldName, size) {
  var value = getSelectedValue(form, fieldName);

  if (value.length > size) {
    return false;
  }

  return true;
}

// Checks an array of required fields
function checkRequiredFields(form, fieldNames, labels, message) {
  var isValid = true;

  for (var i = 0; i < fieldNames.length; i++) {
    var fieldName = fieldNames[i];
    var fieldLabel = labels[i];
  
    if (!checkRequiredField(form, fieldName)) {
      isValid = false;
      message += "\n" + fieldLabel;
    }
  }

  if (!isValid) {
    alert(message);
  }

  return isValid;
}

// Checks a single required field
function checkRequiredField(form, fieldName) {
  var hasValue = false;

  if (getSelectedValue(form, fieldName) != "") {
    hasValue = true;
  }

  return hasValue;
}

// Prepopulates form elements based on type
function prepopulateForm(form, fields, values) {
  for (var i = 0; i < fields.length; i++) {
    var fieldName = fields[i];
    var fieldValue = values[i];

    setSelectedValue(form, fieldName, fieldValue);      
  }
}

// Trims the leading and trailing spaces from a text input field
function trimField(form, fieldName) { 
  var field = form.elements[fieldName];
		
  field.value = trimValue(field.value);
}

// Trims the leading and trailing spaces from a string
function trimValue(value) {
  var reg1 = /^(\s*)(.*[^\s])(\s*)$/;
  var reg2 = /^(\s*)$/;

  if (reg1.test(value)) {  
    return value.replace(reg1, "$2");
  }
  else if (reg2.test(value)) {
    return "";
  }
  else {
    return value;
  }
}

// Get the element type of the field or array of fields
function getElementType(field) {
  var elmType = "";

  if (field != undefined) {
    elmType = field.type;

    if (elmType == undefined && field[0]) {
      elmType = field[0].type;
    }
  }
  
  return elmType;
}

// Determines if a string value is a true array
function isArrayVal(value) {
  var objType = getType(value);

  if (objType == "Array") {
    return true;
  }
  else {
    return false;
  }
}

// Returns the object type
function getType(object) {
  if (object == null) {
    return "undefined";
  }

  var id = object.constructor.toString();

  var index1 = id.indexOf (" ");
  var index2 = id.indexOf ("(");

  return id.substring (index1 + 1, index2);
}

// Selects a form field
function selectField(form, fieldName) {
  var field = form.elements[fieldName];
  var elmType;

  if (field != undefined) {
    elmType = getElementType(field);

    if (elmType == "text" || elmType == "textarea" || elmType == "password" || elmType == "file") {
      if (field[0]) {
        field = field[0];
      }

      field.focus();
      field.select();
    }
    else if (elmType == "select-one" || elmType == "select-multiple") {
      field.focus();
    }
    else if (elmType == "radio" || elmType == "checkbox" || elmType == "submit") {
      if (field[0]) {
        field = field[0];
      }

      field.focus();
    }
  }
}


// Sets the selected value for form element this could be a single value or an array
function setSelectedValue(form, fieldName, value) {
  var field = form.elements[fieldName];
  var elmType;

  if (field != undefined) {
    elmType = getElementType(field);
   
    if (elmType == "hidden" || elmType == "text" || elmType == "textarea" || elmType == "password" || elmType == "file" || elmType == "submit") {
      setTextValue(field, value);
    }
    else if (elmType == "select-one" || elmType == "select-multiple") {
      setSelectValue(field, value);
    }
    else if (elmType == "checkbox") { 
      setCheckboxValue(field, value);	
    }
    else if (elmType == "radio") { 
      setRadioValue(field, value);	
    }
  }
}

// Sets hidden, text, textarea, password, file, submit elements
function setTextValue(field, value) {
  if (field[0]) {
    for (var i = 0; i < field.length; i++) {
      if (isArrayVal(value) && value[i]) {
        field[i].value = value[i];
      }
      else if (!isArrayVal(value)) {
        field[0].value = value;
        break;
      }
    }
  }
  else if (isArrayVal(value)) {
    field.value = value[0];
  }
  else {
    field.value = value;
  }
}

// Sets select and multi select box elements
function setSelectValue(field, value) {
  if (field[0]) {
    for (var i = 0; i < field.length; i++) {
      if (isArrayVal(value)) {
        for (var j = 0; j < value.length; j++) {
          if (field[i].value == value[j]) {
            field[i].selected = true;
          }
        }
      }
      else {
        if (field[i].value == value) {
          field[i].selected = true;
        }
      }
    }
  }
}

// Sets checkbox elements
function setCheckboxValue(field, value) { 
  if (field[0]) {
    for (var i = 0; i < field.length; i++) {
      if (isArrayVal(value)) {
        for (var j = 0; j < value.length; j++) {
          if (field[i].type == "checkbox" && field[i].value == value[j]) {
            field[i].checked = true;
          }
        }
      }
      else {
        if (field[i].type == "checkbox" && field[i].value == value) {
          field[i].checked = true;
        }
      }
    }
  }
  else {
    if (isArrayVal(value)) {
      for (var i = 0; i < value.length; i++) {
        if (field.type == "checkbox" && field.value == value[i]) {
          field.checked = true;
        }
      }
    }
    else {
      if (field.type == "checkbox" && field.value == value) {
        field.checked = true;
      }
    }
  }
}

// Sets radio button elements
function setRadioValue(field, value) {
  var isNotSelected = true;
 
  if (field[0] && !isArrayVal(value)) {
    for (var i = 0; i < field.length && isNotSelected; i++) {
      if (field[i].value == value) {
        field[i].checked = true;
        isNotSelected = false;
      }
    }
  }
  else if (!isArrayVal(value)) {
    if (field.value == value) {
      field.checked = true;
    }
  }
}

// Returns the selected value for form element this could be a single value or an array
function getSelectedValue(form, fieldName) {
  var field = form.elements[fieldName];
  var sValue;
  var elmType;

  if (field != undefined) {
    elmType = getElementType(field);
   
    if (elmType == "hidden" || elmType == "text" || elmType == "textarea" || elmType == "password" || elmType == "file" || elmType == "submit") {
      sValue = getTextValue(field);
    }
    else if (elmType == "select-one" || elmType == "select-multiple") {
      sValue = getSelectValue(field);
    }
    else if (elmType == "radio" || elmType == "checkbox") { 
      sValue = getRadioCheckValue(field);	
    }
  }

  if (sValue == undefined) {
    sValue = "";
  }
  else if (isArrayVal(sValue) && sValue.length == 1) {
    sValue = sValue[0];
  }
  
  return sValue;
}

// Returns the value(s) of hidden, text, textarea, password, file, and submit fields
function getTextValue(field) {
  var sValue;

  if (field[0]) {
    sValue = new Array();

    for (var i = 0; i < field.length; i++) {
      if (trimValue(field[i].value).length != 0) {
        sValue[sValue.length] = trimValue(field[i].value);
      }
    }
  }
  else {
    sValue = "";

    if (trimValue(field.value).length != 0) {
      sValue = trimValue(field.value);
    }
  }
  
  return sValue;
}

// Returns the selected select box or multiple select box value(s)
function getSelectValue(field) {
  var sValue;
   
  if (field[0]) {
    sValue = new Array();

    for (var i = 0; i < field.length; i++) {
      if (field[i].selected && trimValue(field[i].value).length != 0) {     
        sValue[sValue.length] = trimValue(field[i].value);
      }
    }
  }
  else {
    sValue = "";

    if (field.selected && trimValue(field.value).length != 0) {     
      sValue = trimValue(field.value);
    }
  }

  return sValue;  
}

// Returns the selected radio button or check box value(s)
function getRadioCheckValue(field) {
  var sValue;

  if (field[0]) {
    sValue = new Array();

    for (var i = 0; i < field.length; i++) {
      if (field[i].checked && trimValue(field[i].value).length != 0) {
        sValue[sValue.length] = trimValue(field[i].value);
      }
    }
  }
  else {
    sValue = "";

    if (field.checked && trimValue(field.value).length != 0) {
      sValue = trimValue(field.value);
    }
  }

  return sValue;
}

// Formats the US currency
function formatUSCurrency(amount, hasCents) {
  var strValue = new String(amount);
  var strDec = "";

  var numReg = /^(\d+)(\.\d{2})?$/;

  if (numReg.test(strValue)) {
    var commaReg  = /(\d+)(\d{3})/;

    strDec = strValue.replace(numReg, '$2');
    strValue = strValue.replace(numReg, '$1');
    
    while (commaReg.test(strValue)) {
      strValue = strValue.replace(commaReg, '$1,$2');
    }

    strValue = "$" + strValue;

    if (hasCents) {
      strValue += strDec;
    }
  }

  return strValue;
}

// *****************************************************************************
// *
// * Add additional custom methods below here
// *
// * These methods were not created by Shane M Allred but some were modified
// * to call the new functions created. This allows the old function names to
// * still be supported.
// *
// ***************************************************************************** 

// Checks a EMEA  customer number
function checkCustomerNumberCBT(element)
{
 var num=true;
 len=element.length;
 element.toString();
 n=Number(element);
 if(len<5) 
    num=false; 
    return num; 
 }
 
 
// Checks a Canadian customer number
function checkCustomerNumberCA(custnum) {
  var re1 = /^\d{6}$/;
  return re1.test(custnum);
}

// Checks a US customer number
function checkCustomerNumber(custnum) {
  var re1 = /^\d{7}$/;
  if(custnum=="newcust"){
  	return true;
  }
  return re1.test(custnum);
}

// Function to check education card validation
function checkEdCard(element)
{
var num=true;
 len=element.length;
 element.toString();
 n=Number(element);
 if (len > 0)
 {
 if(isNaN(n))
 num=false; 
 }
 return num; 

 }
// Checks the credit card expiration
function checkCreditCardExp1(classDate, cardDate) {
  var daysInMonth = new Array("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
  var SECOND = 1000; // the number of milliseconds in a second
  var MINUTE = SECOND * 60; // the number of milliseconds in a minute
  var HOUR = MINUTE * 60; // the number of milliseconds in an hour
  var DAY = HOUR * 24; // the number of milliseconds in a day
  var WEEK = DAY * 7; // the number of milliseconds in a week

  var result, cardMonth, cardDay, cardYear;
  var re = /^0*(\d{1,2})\/(\d{2})$/;

  if (re.test(cardDate)) {
    result = re.exec(cardDate);
  
    cardMonth = parseInt(result[1]);
    cardDay = parseInt(daysInMonth[cardMonth - 1]);
    cardYear = parseInt("20" + result[2]);
  }
  else {
    alert ("You have entered an invalid date.");
  }

  if (cardYear % 400 == 0 || (cardYear % 100 != 0 && cardYear % 4 == 0)) {
    cardDay = 29;
  }

  var fullCardDate = cardMonth + "/" + cardDay + "/" + cardYear;
  
  //set start_date to current date
  var start_date = new Date();
  var end_date = new Date(fullCardDate);

  //if classDate is available, set start_date to classDate
  if(trimValue(classDate).length>0) {
    start_date = new Date(classDate);
  }

  var start_time = start_date.getTime(); 
  var end_time = end_date.getTime();
  var diff_time = end_time - start_time;

  if (Math.round(diff_time / DAY) > 60) {
    return true;
  }
  else {
    return false;
  }
}
//

function checkCreditCardExpEMEA(classDate, cardDate) {
 
  var daysInMonth = new Array("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
  var SECOND = 1000; // the number of milliseconds in a second
  var MINUTE = SECOND * 60; // the number of milliseconds in a minute
  var HOUR = MINUTE * 60; // the number of milliseconds in an hour
  var DAY = HOUR * 24; // the number of milliseconds in a day
  var WEEK = DAY * 7; // the number of milliseconds in a week
 
  var result, cardMonth, cardDay, cardYear;
  var re = /^0*(\d{1,2})\/(\d{2})$/;
  if (re.test(cardDate)) {
    result = re.exec(cardDate);
    cardMonth = parseInt(result[1]);
    cardDay = parseInt(daysInMonth[cardMonth - 1]);
    cardYear = parseInt("20" + result[2]);
 if(cardMonth < 1 || cardMonth > 12){
      alert ("You have entered an invalid date.");
      return false;
 
 }
  }
  else {
    alert ("You have entered an invalid date.");
    return false;
 
  }
 
  if ((cardYear % 400 == 0 || (cardYear % 100 != 0 && cardYear % 4 == 0)) && cardMonth == 2) {
    cardDay = 29;
  }
 
  var fullCardDate = cardMonth + "/" + cardDay + "/" + cardYear;
  //set start_date to current date
  var start_date = new Date();
  var end_date = new Date(fullCardDate);
 
  //if classDate is available, set start_date to classDate
  if(trimValue(classDate).length>0) {
    start_date = new Date(classDate);
  }
 
  var start_time = start_date.getTime(); 
  var end_time = end_date.getTime();
  var diff_time = end_time - start_time;

  if (Math.round(diff_time / DAY) > 60) {
    return true;
  }
  else {
    return false;
  }
}

function checkCreditCardLength(cardType, cardNumber){
	var cardtype = cardType;
	var cardNo = cardNumber;
	 if(cardtype == "A" && (trimValue(cardNo).length)==15){
	 return true; 
 	} 
	 else if(cardtype == "D" && (trimValue(cardNo).length)==14){ 
	 return true; 
 	}
	 else if((cardtype == "I" ||cardtype == "M") && (trimValue(cardNo).length)==16){ 
	 return true; 
	 }
	 else if(cardtype == "V" && (((trimValue(cardNo).length)==13) || ((trimValue(cardNo).length)==16))){ 
	 return true; 
 	}
	 else{
	 return false;
	 }
 }

//
// Checks the required fields (supports the old function name)
function checkAllRequired(form, fields, labels, message) {
  return checkRequiredFields(form, fields, labels, message);
}

// Checks a required field (supports the old function name)
function checkRequired(form, field, label, message) {
  if (!checkRequiredField(form, field)) {
    alert(label + " " + message);
    return false;
  }
  else {
    return true;
  }
}

// Returns the selected value for a radio button group (supports the old function name)
function getSelectedRadioValue(form, field) {
  return getSelectedValue(form, field);
}

// Returns the selected value for a select box single select (supports the old function name)
function getSelectedDropDownValue(form, field) {
  return getSelectedValue(form, field);
}

// Selects a text field (supports the old function name)
function selectTextField(form, field) {
  selectField(form, field);
}

// Returns the relative path to use with SSO and JavaScript
function getRelativePath(mypage) {
  var relPath = ""; 
  var context = "/services/learning/";
  var servletExt = ".wss";
  var paramStr = "?";
  var dir = "/";
  
  var url = window.location.href;
  
  var index1 = url.indexOf(servletExt) + servletExt.length;
  var index2 = url.indexOf(paramStr);
 
  if (index1 > servletExt.length && index2 != -1 && index1 < index2) {
    var pth = url.substr(index1, index2 - index1);
    
    var index = 0;
    
    while (index != -1) {
      index = pth.indexOf(dir, index);
       
      if (index != -1) {
        relPath += ".." + dir;  
        index++;
      }
    }
  }
  
  return relPath + mypage.replace(context, "");
}

// Creates a popup window that will work with SSO
function tsPopup(mypage, myname, w, h, scroll) {  
  popupWindow(getRelativePath(mypage), myname, w, h, scroll)
}

// Removes all spaces from a string
function deleteSpaces(string) {
	var finalString = "";
	string = '' + string;
	splitString = string.split(" ");
	for(i = 0; i < splitString.length; i++)
		finalString += splitString[i];
	return finalString;
}

//check if a string contains PO Box or Post office box in all its variations and returns true if found
function containsPO(address){
	address = deleteSpaces(address);
	var POString = new Array(6);
	POString[0] = "POBOX";
	POString[1] = "P.OBOX";
	POString[2] = "PO.BOX";
	POString[3] = "P.O.BOX";
	POString[4] = "POSTOFFICEBOX";
	POString[5] = "POST.OFFICE.BOX";
	for(i=0;i<POString.length;i++)
		if(address.toUpperCase().indexOf(POString[i]) > -1)
			return true;
	return false;
}

// to return country names for corresponding country codes
function populateCountry(cCode){
 countrylist = new Array(14);
 countrylist[0] = new Array(2);
 countrylist[1] = new Array(2);
 countrylist[2] = new Array(2);
 countrylist[3] = new Array(2);
 countrylist[4] = new Array(2);
 countrylist[5] = new Array(2);
 countrylist[5] = new Array(2);
 countrylist[6] = new Array(2);
 countrylist[7] = new Array(2);
 countrylist[8] = new Array(2);
 countrylist[9] = new Array(2);
 countrylist[10] = new Array(2);
 countrylist[11] = new Array(2);
 countrylist[12] = new Array(2);
 countrylist[13] = new Array(2);
 
 countrylist[0][0] = "618";
 countrylist[0][1] = "Austria";
 
 countrylist[1][0] = "624";
 countrylist[1][1] = "Belgium";
 
 countrylist[2][0] = "678";
 countrylist[2][1] = "Denmark";
 
 countrylist[3][0] = "702";
 countrylist[3][1] = "Finland";
 
 countrylist[4][0] = "706";
 countrylist[4][1] = "France";
 
 countrylist[5][0] = "724";
 countrylist[5][1] = "Germany";
 
 countrylist[6][0] = "754";
 countrylist[6][1] = "Ireland";
 
 countrylist[7][0] = "758";
 countrylist[7][1] = "Italy";
 
 countrylist[8][0] = "788";
 countrylist[8][1] = "Netherlands";
 
 countrylist[9][0] = "806";
 countrylist[9][1] = "Norway";
 
 countrylist[10][0] = "838";
 countrylist[10][1] = "Spain";
 
 countrylist[11][0] = "846";
 countrylist[11][1] = "Sweden";
 
 countrylist[12][0] = "848";
 countrylist[12][1] = "Switzerland";
 
 countrylist[13][0] = "866";
 countrylist[13][1] = "United Kingdom";
 
 for(i=0;i<=13;i++){
  if(countrylist[i][0] == cCode){
   return(countrylist[i][1]);
  }
 }
}


 
