

// Vignette Generated Content Marker - DO NOT REMOVE


// Checks form for required elements
// Fields to be validated must be supplied in a hidden field: txtRequiredInputs
// Additional validation options can be supplied via the field name: (fieldName-option)
// field names cannot contain dashes. Also, have a * as the end of the field name will validate all similarly named fields.
//
// text, textarea, password:
//   0 - blank
//   1 - numeric
//   2 - valid email address
//   3 - valid phone number
//   4 - valid zip code
// select (single): checks to see if the first element isn't selected
// select (multiple): checks for at least one selected item
// radio/checkbox: checks to see if object is selected.
//   NOTE: radios/checkboxes will turn into arrays if more than one object of a name is detected.
//         Therefore, if a type is determined to be undefined, it is assumed to be a multi-element object.
//         Dynamically added nodes enter the dom tree, but somehow don't make it fully into javascript, so
//         new objects are added as additional array elements to the cloned nodes, rather than fully accessible
//         objects of their own.
//
// @param thisForm Form object to be tested
// @return true/false
function validateForm(thisForm) {
    // Test if required inputs field exists
    if (!thisForm.txtRequiredInputs) {
        alert("DEVELOPER ERROR: Missing required inputs field.");
        return false;
    }

    if (trimSpace(thisForm.txtRequiredInputs.value) == "") {
        alert("DEVELOPER ERROR: Required inputs field is empty.");
        return false;
    }

    var requiredInputs = thisForm.txtRequiredInputs.value.split(" ");

    for (var i = 0; i < requiredInputs.length; i++) { 
        var formElementList = requiredInputs[i].split("-");
        var formItem = formElementList[0];
        var validationOption = formElementList[1];
        if (!validationOption) { validationOption = 0; }

        var validateList = new Array;   // sublist of form fields to validate
        if (formItem.indexOf("*") > 0) {
            formItem = formItem.replace(/\*/,"1");  // dynamic node array is based on first element name
            var curObject = eval("thisForm." + formItem);
            // object will not have a name if it is an array (possible if only 1 element in multi)
            if (!curObject.name) {
                for (var j = 0; j < curObject.length; j++) { validateList[formItem + "[" + j + "]"] = 1; }
            } else {
                validateList[formItem] = 1;
            }
        } else {
            validateList[formItem] = 1;
        }

        for (formElement in validateList) {
            curObject = eval("thisForm." + formElement);
            if (!curObject) {
                alert("DEVELOPER ERROR: " + formElement + " is an non-existant form element.");
                return false;
            }

            // check text and textareas
            if (curObject.type == "text" || curObject.type == "textarea" || curObject.type == "password") {
                var tempValue = trimSpace(curObject.value);
                if (!tempValue) {
                    alert("There is missing data in a required field.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 1 && isNaN(tempValue) && !isValidPhone(tempValue)) {
                    alert("The value entered is not a number.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 2 && !isValidEmail(tempValue)) {
                    alert("The email address entered is not in the correct format.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 3 && !isValidPhone(tempValue)) {
                    alert("The value entered is not a valid phone number.");
                    curObject.focus(); curObject.select();
                    return false;
                } else if (validationOption == 4 && !isValidZip(tempValue)) {
                    alert("The value entered is not a valid zip code.");
                    curObject.focus(); curObject.select();
                    return false;
                }
            } else if ((curObject.type == "select-one" && curObject.selectedIndex == 0) ||
                curObject.type == "select-multiple" && curObject.selectedIndex == -1) {
                if (curObject.selectedIndex == -1 || curObject.selectedIndex == 0) {
                    alert("Please make a selection from the list.");
                    curObject.focus();
                    return false;
                }
            } else if (curObject.type == "radio" || curObject.type == "checkbox") {
                if (!curObject.checked) { 
                    alert("There is missing data in a required field.");
                    curObject.focus();
                    return false;
                }
            } else if (!curObject.type) {
                var passedFlag = false;

                for (var j = 0; j < curObject.length; j++) {
                    if (curObject[j].checked) { passedFlag = true; }
                }

                if (!passedFlag) {
                    alert("There is missing data in a required field.");
                    curObject[0].focus();
                    return false;
                }
            }
        }
    }

    return true;
}


// @param thisForm Form object to be tested
// @param popUp checks for popUp window
// @return true/false

function processSageWs(theForm,popUp) {
    theForm.ip.value = document.location.href;
	ip = document.location.href;
	if (popUp == 'y') {
	    cimsWindow = window.open(newsLetter+'&ip='+ip,'newsLetter',"WIDTH=770,HEIGHT=600,scrollbars=yes,toolbar=yes,resizable=yes,location=yes,menubar=yes,statusbar=yes"); 
    	theForm.target = 'cimsWindow';
    	return false;
  	} else {
    	return true;
  	}

}

// ===== Date validation functions ====
function daysInFebruary (year){
// A year is a leap year if it is divisible by 4 but not by 100.  
// Exceptionally, a year that's divisible by 400 is a leap year.
	var numDays= 28;
	if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
	  numDays = 29;
	}
    return numDays;
}
function DaysArray(n) {
    tempDays = new Array(n);
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {tempDays[i] = 30}
		if (i==2) {tempDays[i] = 29}
   } 
   return tempDays
}

function isValidDate(argDay, argMonth, argYear) {
	var daysInMonth = DaysArray(12)
	var strMonth=argMonth;
	var strDay=argDay;
	var strYr=argYear;
    // Declaring valid date character, minimum year and maximum year
    var minYear=1900;
    var maxYear=2100;

	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYr.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid year")
		return false
	}
	
return true
}



// ===== Support Functions =====
function LTrim(txt) {
    return txt.replace(/^[\s]+/g, "");
}

function RTrim(txt) {
    return txt.replace(/[\s]+$/g, "");
}

function trimSpace(txt) {
    var tmpTxt = LTrim(txt);
    return RTrim(tmpTxt);
}

function isValidEmail(email) {
    // See if we have any spaces.
	var space = email.indexOf(" ");
	if (space != -1) { return false; }
	
	var pos1 = email.indexOf("@",1);
    if (pos1 < 1) { return false; }
    var email = email.substr(pos1 + 1);
    var pos2 = email.indexOf(".",1);
    if (pos2 < 1 || email.substr(pos2 + 1) == "") { return false; }
    return true;
}


function isValidPhone(phone) {
   var ValidChars = "0123456789.-";
   var isValidPhone=true;
   var Char;
    for (i = 0; i < phone.length && isValidPhone == true; i++) 
      { 
      Char = phone.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         isValidPhone = false;
         }
      }
    return isValidPhone;
   
   }


function charLim (theForm,maxLen) {
	if (theForm.dilUsrOpt_Post.value == "") { 
    	alert("There is missing data in a required field."); 
    	return false; 
	}
	var outputText = '';	
	var arrVar = theForm.dilUsrOpt_Post.value.split(" ")
	for(var i = 0; i < arrVar.length; i++) {
		
		if (arrVar[i].length > maxLen) {
			var lengthVar = arrVar[i].length;
			j = Math.ceil(lengthVar / maxLen);
			startPos = 0;
			endPos = maxLen - 1;
			for(var k = 0; k < j; k++) {
				tempVar = arrVar[i].substring(startPos,endPos+1);  
				tempVar = tempVar+' ';
				startPos = endPos + 1;
				endPos = endPos + maxLen;
				outputText = outputText + tempVar;
			}
			arrVar[i] = outputText; 
		}
	}
	theForm.dilUsrOpt_Post.value = arrVar.join(' ');
	return true;
}

// Valid zip code patterns:
// 10018 or 10018-5001 or A9N 7B4
function isValidZip(zip) {
   var zipRegex = new RegExp("^([0-9]{5})$|^([0-9]{5})-([0-9]{4})$|^([a-z][0-9][a-z] [0-9][a-z][0-9])$", "i");
   return zipRegex.test(zip);
}
