/* MediaPlus cmo36 Version cmo36A 10/06/11 23:12:05 delta js/validate.js
** Copyright 2001 Publishing Business Systems, Inc.
** All Rights Reserved Worldwide.
*/
/* #189099 11.10.05 todd	Make sure all for loop variables are declared.
** #188842 11.09.06 todd	In previousDate and greaterDate, set time part of 
**							today to 0 to prevent invalid results for today.
** #187234 11.05.05 marks	Merge 37 WR 187236 down to version 36.
** #187236 11.04.21 todd	Use dmyDateString in greaterDate function.
** #186052 11.04.12 mickeyg Add delivery schedule to updDeliveryInfo().
** #186894 11.02.16 marks	Merge 37 WR 186183 to version 36.
** #186183 11.01.21 todd	CR #35325 Add dmyPreviousDate, use in previousDate.
** #185958 10.11.23 mickeyg Return true in valtermsconditions().
** #185495 10.10.19 mickeyg	Merge up cmo35 WR#185323.
** #185323 10.09.27 mickeyg Add hidecombo().
** #185004 10.09.17 mickeyg Add processing().
** #182814 10.03.10 mickeyg Build msg records, add formObjFocus, getLabelText, 
**                          getMessage, valreqfields, and valRadioBtn; Shorten 
**                          functions named "validate" to "val"; Remove unused 
**                          functions: validatebrwstracking, validatewebspeedlog
** #183222 10.04.26 mickeyg	Merge up cmo35 WR#180163.
** #180163 09.10.30 mickeyg	Merge up cmo34 WR#180147.
** #180147 09.05.28 todd	Add isInt() and isPosInt();
** #170822 08.02.26 mickeyg Use generic errormsg variable for reusability in 
**                          builderrtext() and remove builderrtext2().
** #172254 07.09.14 mickeyg Check for 'mainnav' in activeImg().
** #171957 07.08.21 mickeyg Add updDeliveryInfo().
** #172254 07.09.14 mickeyg Check for 'mainnav' in activeImg().
** #170969 07.06.13 mickeyg Add activeImg() (for "transactions left" layout);
**                          set x/y coordinates for showCalendar.
** #167951 07.05.23 mickeyg Add valtermsconditions().
** #170924 07.05.16 mickeyg Add maximum length account number alert.
** #170838 07.05.08 mickeyg Build pathname in showCalendar.
** #168449 07.03.16 todd	Merge CMO 3.3b WR #168448 up to 3.4.
** #168448 06.10.03 todd	Create validateAccountNumber()
** #169745 07.02.01 mickeyg CR#27467 builderrtext2()
** #168832 06.12.07 mickeyg Added params to checkpwdlength() 
** #161592 06.09.19 mickeyg Removed checkAltPhoneNumber()
** #164607 05.12.12 mickeyg Check popup value for dynwinsize() 
** #163690 05.10.04 mickeyg Don't trim email ending period; Allow "+" in local 
**                          email name and changed emailexp to {2,5}; Revised 
**                          trim code in isValidEmail; Added validEmailList()
** #163168 05.09.19 todd	CR#23882 Add isValidEmail function and update 
**                          validateEmail to call it.
** #162768 05.08.10 todd    Merge WR #162362 from 3.3 to 3.4.
** #162362 05.07.27 todd	CR#23434 Check type of DonateTo
** #160803 05.07.20 robi    Merged WR#161721 from 33 to 34
** #161979 05.07.20 robi    Merged WR#160198 from 33 to 34
** #161721 05.06.03 mickeyg CR#23038 Trim email ending period. 
** #161721 05.06.02 mickeyg CR#23021 Changed emailexp to {1,3}. 
** #161721 05.05.26 mickeyg Loosen emailexp--remove {2,}. 
** #160198 05.03.16 mickeyg Increase height padding from 55 to 75 in dynwinsize.
** #159742 05.02.08 mickeyg Added trim and checkpwdlength(). 
** #159788 05.01.17 mickeyg Merged up cmo32 WR#159298. 
** #159298 04.12.01 mickeyg Changed myURLpath to point to custservice/web.
** #157818 04.08.16 mickeyg Changed email to allow dashes. 
** #157750 04.08.09 mickeyg CR#20547 Added dynwinsize(). 
** #157570 04.07.21 mickeyg Modified showCalendar to use JS vars instead of 
**                          HostURL which may not be reliable due to server 
**                          redirects.
** #155730 04.05.13 mickeyg CR#19848 Added optional errtext param to 
**                          validateRadioButtons().
** #156027 04.03.26 mickeyg Added builderrtext();
** #154445 03.12.15 mickeyg Merge up WR #153043.
** #153043 03.12.04 mickeyg CR#18624 comment out searcharray because it is not 
**                          working; revisit later
** #153043 03.10.24 mickeyg Added searcharray and seterrorfocus.
** #139428 02.08.07 mickeyg CR#14425 Added 'padding' parameter to setwindowsize
** 		   02.07.19 todd	for 'contest', validateRadioButtons needs to return
**                          true when form has no radio buttons
** #146009 02.07.01 mickeyg CR#14351 Added URL params to showCalendar 
** 	       02.03.26 mickeyg Increase calendar window size
**   	   02.02.27 mickeyg Copied transaction specific to own js files
** js/validate.js
** iServices common and validation routines
-----------------------------------------------------------------------------*/

var iserrors = false;
var iscaution = false;
var errlist = new Array();
var caulist = new Array();

var charexp = /./;
var letterexp = /[a-z]/i;
var constitexp = /^\d{7}$/;
var phonexp = /^[ \-().0-9]{7,20}$/;
var zipexp = /^\d{5}$|^\d{5}[\-\s]?\d{4}$/;
// var emailexp = /^[a-z][a-z_0-9\.]+@[a-z_0-9\.]+\.[a-z]{2,}$/i;
var emailexp = /^[a-z_+0-9\.\-]+@[a-z_0-9\.\-]+\.[a-z]{2,5}$/i;
var intexp = /^-?\d+$/;
var posintexp = /^\d+$/;
var numexp = /^\d+$|^\d*\.\d+$/;
var numexp1 = /^[0-9]+\.?[0-9]{0,2}$/
var ccexp = /^\d{16}$|^\d{15}$/;
var dateexp = /^[01][0-9]\/[0123][0-9]\/[12][7890]\d{2}$/;
var errormsg;

function hasChar(str) {
    return charexp.test(str);
}

function isValid(pattern, str) {
    return pattern.test(str);
}

function addError(myfield,myerror) {
    iserrors = true;
    errlist[errlist.length] = myerror;
}

function showErrors() {
    alert(errlist.join("\n"));
    return false;
}

function resetErrors() {
    iserrors = false;
    iscaution = false;
    errlist = null;
    errlist = new Array();
    caulist = null;
    caulist = new Array();
}


function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

// check for white spaces
var whitespace
function isblank(s) {
	whitespace = false;
	for(var i = 0; i < s.length; i++) {
    	var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) {
		whitespace = false;
		return whitespace;
		}
    }
	whitespace = true;
	return whitespace;
}

/* i18N: does builderrtext become obsolete? */
//var errormsg;
function builderrtext(myfield, mytext) {
	// input: expects complete form field name to check for object existance
	// input: expects text to append to error text string
	// output: return error message 
    if (myfield) {
       	errormsg += mytext + " \n";
    }
	return errormsg;
}

function getLabelText(inputObj, extraChar) {
    var labelText;
    if (extraChar == null)  {
        extraChar = '';
    }
    if (!inputObj) {
        alert('getLabelText(): Input object is not defined.\n');
        return false;
    }
    if (inputObj.parentNode) {
        if (inputObj.parentNode.tagName == 'label') {
            return inputObj.parentNode;
        }
    }
    var labels = document.getElementsByTagName('label'),i;
    for(var i=0; i < labels.length; i++) {
        if (labels[i].htmlFor == inputObj.id) {
            // labels[i].className = 'errormsg';
            // strip off label separator and HTML space
            labeltext = labels[i].innerHTML.replace(':', '');
            labeltext = labeltext.replace('&nbsp;', ' ');
            return labeltext + extraChar;
        }
    }
    return 'getLabelText(): ID tag missing for input object ' + inputObj.name + '\n';
}

var msgArray = new Array();
function msgRecord (id, msgtext, msgtype) {
    this.id = id;
    this.msgtext = msgtext;
    if (msgtype != null) {
		this.msgtype = msgtype;	
	}
	else {
		this.msgtype = 'error';	
    }
    // alert ('created ' + this.msgtype + ': ' + this.msgtext + ' (' + this.id + ')');
}
function getMessage(id, paramlist) {
	var errortext = '';
	// alert('msgArray.length = ' + msgArray.length);
    for (var i = 0; i < msgArray.length; i++) {
        if (msgArray[i].id == id) {
            // alert('Found ' + msgArray[i].msgtext);
			errortext = msgArray[i].msgtext;
/* paramlist - under construction
- count how many parameters were received
- look for &N when N equals the parameter number
- replace &N with paramlist value
*/
			if (paramlist != null) {
				// alert('Param list ' + paramlist);
				// alert('Error text ' + errortext);
				if (errortext.search('&') == -1) {
					alert('getMessage() received unexpected parameters');
				}
				else {
					errortext = errortext.replace('&1', paramlist);
				}
			}
			if (msgArray[i].msgtype == 'error') {
				errortext += ' (' + msgArray[i].id + ')\n';
			}
            return errortext;
            //return msgArray[i].msgtext + ' (' + msgArray[i].id + ')\n';
        }
    }
	return ('Error message ' + id + ' not found.\n');
}

var nw;
// opens calendar.html and passes a field number and URL address components 
function showCalendar(fieldNum,HostURL,AppURL) {
	//trim(HostURL);
	trim(AppURL);

    var ix = location.pathname.indexOf(AppURL);
    var pathname = location.protocol + '//' + location.hostname;
    if (ix > 0) {
        pathname += location.pathname.substring(0, ix) + AppURL;
    }
    else {
        pathname += AppURL;
    }

	// get HostURL from JS variables instead
	myURLpath = pathname + "/custservice/web/calendar.html";	

    calendar = window.open(myURLpath + '?fieldNum=' + fieldNum,'cal','width=270,height=220,screenX=450,screenY=225,left=450,top=225');
}

function validateTextBoxes(myform) {
	with (myform) {
		for (var i = 0; i < elements.length; i++ ) {
			// checks if text boxes are blank
        	if ((elements[i].type == "text" || 
			     elements[i].type == "password") && 
				elements[i].value == "") {
				alert("Please enter a value for the empty text field(s)");
				return false;
			}
		}

		return true;
	}
}

function valtermsconditions(myform) {
	if ((myform.termsaccept) && (myform.termsaccept.checked == false)) {
   		// You must accept the terms and conditions to continue
   		alert(getMessage(2271));
    	return false;
   	}
	else {
    	return true;
	}
}

function processing() {
	// suppress submit/cancel buttons and show processing gif
    if (document.getElementById("submitbutton")) {
        document.getElementById("submitbutton").style.display = 'none';
    }
    if (document.getElementById("processing")) {
        document.getElementById("processing").style.display = 'block';
    }
}

// validate a single radio button set
function valRadioButton(btn) {
    var checked = false; 
	var labeltext = getMessage(1984, getMessage(3552));
    for (var i = 0; i <= btn.length - 1; i++) {
        if (btn[i].checked) {
			checked = true;
			break;
		}
		// build list of enabled radio buttons 	
		if (btn[i].disabled == false) {
			labeltext += getLabelText(btn[i], '\n');
		}
    }
    if (checked == false) { 
		alert(labeltext);
		return false;
	}
    else return true;
}

function hidecombo(comboname, spanname) {
    // Hide combo box when only 1 choice exists and set text for UI
    if (comboname) {
    	if (comboname.length == 1) {
        	comboname.style.display = 'none';
        	document.getElementById(spanname).innerHTML =
            	comboname.options[0].text;
    	}
		else {
        	comboname.style.display = 'block';
        	document.getElementById(spanname).innerHTML = '';
		}
    }
}

// validate all radio button sets on form
function valRadioButtons(myform,errtext) {
	with (myform) {
		var names = "";
		for (var i = 0; i < elements.length; i++ ) {
			// checks if a radiobutton is selected
			if(elements[i].type == "radio") {
				if(names.indexOf(elements[i].name) < 0) {
					names = names + elements[i].name + ",";
				}
			}
		}
		if (names.length > 0) {
			var namelist=names.split(",");
			var checklist = new Array(namelist.length - 1);
			for(var i=0;i < (namelist.length - 1); i++) {
				checklist[i]=false;
				for(var j=0;j<elements.length;j++) {
					if(elements[j].type == "radio" && 
					   elements[j].name == namelist[i] && elements[j].checked) {
						checklist[i]=true;
						// if the selected radiobutton EQ newAdd make sure an 
						// alternate address was added
						if ((elements[j].value == "newAdd") && 
							(newAddress.value == "")) {
							alert("Please enter an alternate address for delivery");
							return false;
						}
						// if the selected radiobutton EQ Donate AND the Donate To select box EQ null
						if(elements[j].value == "Donate" && 
						   DonateTo.type == 'select-one' && 
						   DonateTo.options[DonateTo.selectedIndex].value == "") {
							alert("Please enter who you would like to donate to.");
							return false;
						}
					}
				}
			}

			for(var i=0;i < (namelist.length - 1); i++) {
				if(!checklist[i]) {
					if (errtext != null) {
						alert(errtext);
					}
					else {
						alert("Make a selection from each set of radiobuttons");
					}
				 return false;
				 }
			}

			return true;
		}

		return true;
    }
}

function valreqfields(fldlist) {
	var fieldname = fldlist.split(',');
	var setfocusfld = '';
	var alertMsg = '';

	for (var i = 0; i < fieldname.length; i++) {
		if (document.getElementById(fieldname[i])) {
			if (document.getElementById(fieldname[i]).value == '') {
				if (alertMsg == '') {
					// Please enter all of the following:
					alertMsg = getMessage(1984, getMessage(6207));
				}
				alertMsg += getLabelText(document.forms[0][fieldname[i]],'\n');
				/**
				if (setfocusfld == '') {
					setfocusfld = document.getElementById(fieldname[i]).focus();
				}
				**/
			}
		}
	}
	/**
	if (setfocusfld != '') {
		setfocusfld;
	}
	**/
	return alertMsg;
}

function greaterDate(inDate, dateFormat) {
	// check to see if date is greater than today
	// Create JavaScript date object representing today.
    var today = new Date();

	// Set time elements for "today" to 0, since time of entered date will be 0.
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);

	// Create JavaScript date object representing entered date;
    var chkDate = new Date(dmyDateString(inDate, dateFormat));

	// Return result of date comparison
    return (chkDate > today);
}

function previousDate(inDate, dateFormat) {
	// check to see if date is less than today
	// Create JavaScript date object representing today.
	var today = new Date();

	// Set time elements for "today" to 0, since time of entered date will be 0.
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);

	// Create JavaScript date object representing entered date;
	var chkDate = new Date(dmyDateString(inDate, dateFormat));

	// Return result of date comparison
	return (chkDate < today);
}

function checkPhoneNumber(fld) {
	var showAlert = true;
    if (!isValid(phonexp,(fld.value))) {
        if (showAlert) {
            // Please enter a valid phone number 
			alert(getMessage(1953, getLabelText(fld)));
			//seterrorfocus(fld);
        	return false;
        }
    }
	else {
        return true;
    }
}

function checkpwdlength(pwdobj, minlengthobj) {
	// pwdobj - object containing password
	// minlengthobj - object containing minimum password length
    if (pwdobj.value.length < minlengthobj.value) {
        // Please enter a password length of at least ' +
        // minlengthobj.value + '.');
        alert(getMessage(1956, minlengthobj.value));
	  	pwdobj.focus();
        return false;
    }
	else {
        return true;
	}
}

// Subscription Account Number Validation
function valAccountNumber(accountNumber) {
	var checkDigit = '';

	if (accountNumber.length > 2 &&
		accountNumber.charAt(accountNumber.length - 2) == '-') {
		checkDigit = accountNumber.substring (accountNumber.length - 1);
		accountNumber = accountNumber.substring (0, accountNumber.length - 2);
	}

	// prevent Progress from blowing up its integer variable
	if (parseInt(accountNumber) > '2147483647') {
	    // Your account number appears to be too big
	    if (!confirm(getMessage(1952))) {
	    	return false;
	    }
	    else {
	    	return true;
	    }
	}

	if (isNaN(accountNumber) ||
        (checkDigit != '' && isNaN(checkDigit))) {
    	 // Please enter only numeric values
    	 alert(getMessage(1955, 'account number'));
		 return false;
    }

	return true;
}

// generic email validation for passed in email address string
function isValidEmail (email) {
	var outString;

	outString = trim(email);

    if (hasChar(outString) && !isValid(emailexp,outString)) {
        return false;
    }
	else {
        return true;
    }
}

// email validation - single email address on form
function valEmail(errormsg) {
    showAlert = true; 
	myform = document.forms[0];
	myform.email.value = trim(myform.email.value);
    if (! isValidEmail (myform.email.value)) {
        if (showAlert) {    
            // Please enter a valid email address 
			alert(getMessage(1953, getLabelText(myform.email)));
        	myform.email.focus();
        }
		return false;
	}
	else {
		return true;
	}
}

// email validation - multiple email addresses
function valEmailList(emailcount, emailrequired) {
	// emailcount - number of email address widgets
	// emailrequired - (optional) is email address a required field? yes/no
	var emailaddrlist = "";	// comma-separated list of email addresses
	var widgetname;

    // validate email addresses and accumulate them in emailaddrlist string
    for (var i = 1; i <= emailcount; i++) {
        widgetname = "email" + i;
        emailobj = document.getElementById (widgetname);
	
		emailobj.value = trim(emailobj.value);

        // if email address is not blank then validate
        if (emailobj.value != "") {
            if (isValidEmail (emailobj.value)) {
                emailaddrlist = ((emailaddrlist == "") ? "" : emailaddrlist + 
				                ",") + emailobj.value;
            }
            else {
            	// Please enter a valid email address 
				alert(getMessage(1953, getLabelText(document.forms[0][widgetname])));
                emailobj.focus();
                return false;
            }
        }
    }

	if ((emailaddrlist == '') && (emailrequired == 'yes')) {
        // Please enter a valid email address 
		alert(getMessage(1953, getLabelText(document.forms[0].email1)));
        document.forms[0].email1.focus();
        return false;
	}

	return true;
}

// checks if entered value is an integer
function isInt(str) {
    return intexp.test(str);
}

// checks if entered value is a positive integer
function isPosInt(str) {
    return posintexp.test(str);
}

// checks if entered value is a number
function isNum(str) {
    return numexp.test(str)
}


// verify at least one digit precedes or follows decimal point
function goodDecimal(S) {
	return /^\d+\.\d+$/.test(S); 
}

// checks if entered value is a decimal.  Add 0 before decimal point if needed
function checkDecimal(str) {
	goodDecimal(str);
	if(!goodDecimal(str)) {
		str = "0" + str;	
	}
	return numexp1.test(str);
}

// back button
function setscreenvalues() {
	document.forms[0].backbutton.value = "yes";
	// possible Netscape fix
	document.forms[0].method = "post";
	document.forms[0].submit();
}

// dynamically resize window to table width
function setwindowsize(padding) {
    if (padding > 0) {
        wid = wid + padding;
    }
    if (typeof sizeToContent == 'function') {
        sizeToContent();
    }
    else {
        window.resizeTo(wid,document.body.offsetHeight);
    }
}

function dynwinsize(bodydiv,winHeight,winWidth) {
	var IE = document.all && navigator.appName.toLowerCase().indexOf("opera")==-1 ? true:false;

	if ((!document.forms[0]) || (document.forms[0].popup.value == 'yes')) {
		// dynamically resize IE browser window to a div container
    	if (IE) {
        	winHeight = document.all[bodydiv].offsetHeight + 75;
        	winWidth = document.all[bodydiv].offsetWidth + 30;
			// resize window to 70% of its maximum resolution
			if (window.screen.width < winWidth) {
				winWidth = window.screen.width * .70;
			}
			if (window.screen.height < winHeight) {
				winHeight = window.screen.height * .70;
			}
        	window.resizeTo(winWidth,winHeight);
    	}
    	else {
			// resize non-IE browser window to passed in height and width params
        	window.resizeTo(winWidth,winHeight);
    	}
	}
}

// switch navigation images for "transactions left" layout
function activeImg(nav) {
    if (nav == null)  {
		nav = 'mainnav';
	}
    // swap active (subitem) image
    if ((document.forms[0].activeimgname) && 
	    (document.forms[0].activeimgsrc) &&
		(document.getElementById(nav))) {
        document.images[document.forms[0].activeimgname.value].src = document.forms[0].imgPath.value + document.forms[0].activeimgsrc.value;
    }
    // swap active (group) image
    if ((document.forms[0].activegrpname) && 
	    (document.forms[0].activegrpsrc) &&
		(document.getElementById(nav))) {
        document.images[document.forms[0].activegrpname.value].src = document.forms[0].imgPath.value + document.forms[0].activegrpsrc.value;
    }
}

function updDeliveryInfo (arrayObj, mySubscriptionID) {
    // search array for matching subscription and update delivery info 
    for (var i = 0; i < arrayObj.length;  i++) {
        if (arrayObj[i].subscriptionID == mySubscriptionID) {
            if (document.getElementById('delscheddesc')) {
            	document.getElementById('delscheddesc').innerHTML =
                	arrayObj[i].delscheddesc;
			}
            document.getElementById('delmethoddesc').innerHTML =
                arrayObj[i].delMethod;
            if (arrayObj[i].showEdition == 'yes') {
                document.getElementById('editionrow').style.visibility = 'visible';
                document.getElementById('editiondesc').innerHTML =
                    arrayObj[i].editionID;
            }
			else {
				if (document.getElementById('editiondesc')) {
                	document.getElementById('editiondesc').innerHTML = '';
                	document.getElementById('editionrow').style.visibility = 'hidden';
				}		
			}
            break;
        }
    }
}

function formObjFocus() {
	var bFound = false;
  	// for each form
  	for (var f=0; f < document.forms.length; f++) {
    	// for each element in each form
    	for(var i=0; i < document.forms[f].length; i++) {
      		// if it is not a hidden element
      		if (document.forms[f][i].type != "hidden") {
        		// and it is not disabled
        		if (document.forms[f][i].disabled != true) {
            		// set the focus to it
            		document.forms[f][i].focus();
            		var bFound = true;
        		}
      		}
      		// if found in this element, stop looking
      		if (bFound == true) {
        		break;
    		}
    	}
    	// if found in this form, stop looking
    	if (bFound == true) {
      		break;
    	}
  	}
}

function seterrorfocus(fieldname) {
    var myform = document.forms[0];

    myform[fieldname].focus();
    myform[fieldname].select();
    return false;
}

/*****
function searcharray(myarrayname, myarrayfield, mymatchvalue, mysearchfield) {
    // loop through array to find and return a value
    for (var i = 0; i < myarrayname.length;  i++) {
        if (myarrayname[i].myarrayfield == mymatchvalue) {
            return myarrayname[i].mysearchfield;
        }
    }
}
*****/

