// $Source: /opt/cvs/cvsroot/devel/common_js/utils.js,v $
// $Revision: 1.25 $
// $Date: 2004/04/07 18:14:47 $

// check to see if given field is blank
function isblank(s) {

        var blank = true;

        for (var i = 0; i < s.length; i++) {
                var c = s.charAt(i);
                if ((c != ' ') && (c != '\n') && (c != '\t')) {
                        blank =  false;
                        break;
                }
        }
        return blank;
}

function isValidDate(dateStr, dateLabel, warnBeforeToday)
{
	var firstSlash = dateStr.indexOf("/");
	var secondSlash = dateStr.indexOf("/", firstSlash + 1);
	var validDate = true;
	

	if ((firstSlash == -1) || (secondSlash == -1)) {
		alert("Please enter " + dateLabel + " in the format: MM/DD/YYYY");
		validDate = false;
	}
	else {
		var monthStr = dateStr.substring(0,firstSlash);
		var dayStr = dateStr.substring(firstSlash + 1, secondSlash);
		var yearStr = dateStr.substring(secondSlash + 1);

		if (yearStr.length < 4) {
			alert("Please enter " + dateLabel + " in the format: MM/DD/YYYY");
			validDate = false;
		}
		
		else if ((monthStr < 1) || (monthStr > 12)) {
			alert(dateLabel + ": Please enter a valid month");
			validDate = false;
		}
		else if ((yearStr < 1990) || (yearStr > 2999)) {
			alert(dateLabel + ": Please enter a valid year");
			validDate = false;
		}
		else if ((dayStr < 1) || (dayStr > 31)) {
			alert(dateLabel + ": Please enter a valid day of month");
			validDate = false;
		}
		else if (((monthStr == 4) || (monthStr == 6) || (monthStr == 9) || (monthStr == 11))
				&& (dayStr > 30)) {
			alert(dateLabel + ": Please enter a valid day of month");
			validDate = false;
		}
		else if ((monthStr == 2) && (dayStr > 29)) {
			alert(dateLabel + ": Please enter a valid day of month");
			validDate = false;
		}
		else if (warnBeforeToday) {

			var travelDate = new Date(dateStr + " 23:59:00");
			var todayDate = new Date();
			
			if (travelDate < todayDate) {
				if (confirm(dateLabel + " is earlierddd than today, are you sure you want to continue?"))
					return true;
				else
					return false;
			}
		}
	}

	return validDate;
}

function isValidEuroDate(dateStr, dateLabel, warnBeforeToday)
{
	var firstSlash = dateStr.indexOf("/");
	var secondSlash = dateStr.indexOf("/", firstSlash + 1);
	var validDate = true;
	

	if ((firstSlash == -1) || (secondSlash == -1)) {
		alert("Please enter " + dateLabel + " in the format: DD/MM/YYYY");
		validDate = false;
	}
	else {
		var dayStr = dateStr.substring(0,firstSlash);
		var monthStr = dateStr.substring(firstSlash + 1, secondSlash);
		var yearStr = dateStr.substring(secondSlash + 1);

		if (yearStr.length < 4) {
			alert("Please enter " + dateLabel + " in the format: DD/MM/YYYY");
			validDate = false;
		}
		
		else if ((monthStr < 1) || (monthStr > 12)) {
			alert(dateLabel + ": Please enter a valid month");
			validDate = false;
		}
		else if ((yearStr < 1990) || (yearStr > 2999)) {
			alert(dateLabel + ": Please enter a valid year");
			validDate = false;
		}
		else if ((dayStr < 1) || (dayStr > 31)) {
			alert(dateLabel + ": Please enter a valid day of month");
			validDate = false;
		}
		else if (((monthStr == 4) || (monthStr == 6) || (monthStr == 9) || (monthStr == 11))
				&& (dayStr > 30)) {
			alert(dateLabel + ": Please enter a valid day of month");
			validDate = false;
		}
		else if ((monthStr == 2) && (dayStr > 29)) {
			alert(dateLabel + ": Please enter a valid day of month");
			validDate = false;
		}
	//	else if (warnBeforeToday) {
	//		
	//		var dateStr = formatDate(dateStr,"DD/MM/YYYY");
	//		alert("date is" + dateStr);
	//		
	//		var travelDate = new Date(dateStr + " 23:59:00");
	//		var todayDate = new Date();
	//		
	//		if (travelDate < todayDate) {
	//			if (confirm(dateLabel + dateStr + " isggg earlier than today, are you sure you want to continue?"))
	//				return true;
	//			else
	//				return false;
	//		}
	//	}
	}

	return validDate;
}

function isValidImageFileName(fileStr)
{
	var validFileName = true;
	
	if (fileStr.length < 1)
		return true;

	var badchar = fileStr.indexOf("*");
	if (badchar != -1) 	
		validFileName = false;

//	badchar = fileStr.indexOf(" ");
//	if (badchar != -1) 	
//		validFileName = false;
		
	badchar = fileStr.indexOf("/");
	if (badchar != -1) 	
		validFileName = false;
		
	badchar = fileStr.indexOf("~");
	if (badchar != -1) 	
		validFileName = false;

	// Verify that the file suffix is correct
	dot = fileStr.indexOf(".");
	suffix = fileStr.slice(dot);

	if ((suffix.toUpperCase() != ".JPG") && (suffix.toUpperCase() != ".ART") && (suffix.toUpperCase() != ".GIF")) {
		return false;
	}
	
	return validFileName;
}

function isValidEMailAddress(e, emailLabel, allowInvalid)
{	
/*
regular expression syntax:
/^  start the reg. exp.  
\w+  any/repeating word character  
[\.-]?  any single dot and/or dash  
\w+  any/repeating word character  
*  repeat the preceding subexpression 0 or more times
\.  single dot  
\w{2,4}  any word character, repeated 2 to 4 times  - this goes up to 4 because of the newer
	 .info and .mail domains.  Unfortunately, this allows 'john@john.comn' to go through  
$/  end the reg. exp.  
*/

//	The below string is perfect for catcing all invalid emails and allowing all valid emails, even 
//	multiples.  And it takes six years when returns invalid, so we can't use it.
//	TestValidString=/^(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+)(\s*[,\;]\s*(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+))*$/;

//	Since the above was too slow, the current algorithm is as follows: first check for 
//	valid/invalid characters. Then test against a reg expression which basically
//	insures there's at least one completely valid email in the field.

// Since you don't always want to stop nulls from going through, if its empty, go ahead and
// allow it (check for nulls will be done in calling function if need be)
	if (e.length < 1)
		return true;

	var validEMailAddress = true;
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm'.@-QWERTYUIOPASDFGHJKLZXCVBNM;,_";
	for (i=0; i<e.length; i++) {
		if (ok.indexOf(e.charAt(i))<0) {
			validEMailAddress = false;
			break;
		}
	}
	validEmail = /\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+/;
	
	if (!validEmail.test(e))
		validEMailAddress = false;
	
	if (!validEMailAddress) {
		if (allowInvalid) {
			if (confirm(emailLabel + " is not a valid E-Mail Address, are you sure you want to continue?")) {
				validEMailAddress = true;
			}
		}
		else {
			alert(e + " is not a valid E-Mail Address. Please re-enter.");
		}
	}

	return validEMailAddress;
}

function isValidNumber(inpString) {
   return /^[-+]?\d+(\.\d+)?$/.test(inpString);
}


function FormatNumber(value)
{
	if (value >= 0.0) {
		var cents = (100*(value - Math.floor(value)))+0.5;
		if (cents > 100) {
			value += 1;
			cents = 0.00;
		}
		var result = Math.floor(value) + ".";
		result += Math.floor(cents/10);
		result += Math.floor(cents%10);
	}
	else {
		var cents = (100*(Math.ceil(value) - value))+.5;
		if (cents > 100) {
			value -= 1;
			cents = 0.00;
		}
		var result = Math.ceil(value) + ".";
		result += Math.floor(cents/10);
		result += Math.floor(cents%10);	
	}
	return result;
}

// determine the days available in the given month
function displayDays(mon, dayList)
{

	var optionz = new Option("Day", "0")
	dayList.options[0]=optionz;
	dayList.options[0].selected=true;

	for (var i=1; i < 29; i++) {
		var option0 = new Option(String(i), String(i))
		dayList.options[i]=option0;
	}

	if ((mon == 4) || (mon == 6) || (mon == 9)  || (mon == 11)) {
		for (var i=29; i < 31; i++) {
			var option0 = new Option(String(i), String(i))
			dayList.options[i]=option0;
		}
		dayList.options[31]=null;
	}
	else if (mon != 2) {
		for (var i=29; i < 32; i++) {
			var option0 = new Option(String(i), String(i))
			dayList.options[i]=option0;
		}
	}
	else {
		dayList.options[31]=null;
		dayList.options[30]=null;
	}
}

// check to ensure a radio button is selected
function check_radio_buttons(aButtons)
{
    var checked = -1;

	if (aButtons.length + "" == "undefined")
	{
		if (aButtons.checked)
		{
			checked = 0;
		}
	}
	else
	{	
	    for (var i = 0; i < aButtons.length; i++)
		{
			if (aButtons[i].checked)
			{
			    checked = i;
			}
		}
	}
	
	if (checked == -1)
	{
	   return false;	
	}

	return true;
}


function popup_window(template, formName, fieldList, valList)
{
	window.open(template + "&formName=" + formName + "&fieldList=" + fieldList + "&valList=" + valList, "popupWindow", "width=700,height=600,dependent,scrollbars,alwaysRaised");
}
function popup_windowcreditnotes(template,creditid)
{
	window.open(template + "&bcid=" + creditid, "popupWindow", "width=300,height=500,dependent,scrollbars,alwaysRaised");
}

// Function to parse the value picked from a dropdown list, assuming it is
// pipe-delimited, and copy the individual values into fields on the screen.
// The fields to be copied into are contained in the pipe-delimited list
// parameter "fldList".
function copyDD(f, ddList, fldList)
{
	var fldArr = fldList.split("|");
	var ddValArr = ddList.value.split("|");
	
	if ((ddList.value == '') || (ddList.value == '||')) {
		for (var i = 0; i < fldArr.length; i++) {
			eval ("f." + fldArr[i] + ".value = ''");
		}
	}
	else {
		for (var i = 0; i < fldArr.length; i++) {
			eval ("f." + fldArr[i] + ".value = '" + ddValArr[i] + "'");
		}
	}
} 


// Function to update drop-down lists on the form based
// on the results of a query that are passed in
function updateDDFromQuery(queryStr, formName, ddName)
{
	window.open("/FillDDFromQuery.cfm?formName=" + formName + "&queryStr=" + queryStr + "&ddName=" + ddName, "popupWindow", "width=1,height=1");
}


////////////////////////////////////////////////////////////////////////////////
// The next few functions are part of the calendar functionality.
//
// getDaysInMonth returns the number of days in the month that was passed in
//
function getDaysInMonth(monthStr, yearStr) {

	var yearV = Number(yearStr);
	

	if (monthStr == 1 || monthStr == 3 || monthStr == 5 ||
		monthStr == 7 || monthStr == 8 || monthStr == 10 ||
		monthStr == 12) {
		return 31;
	}
	else if (monthStr == 4 || monthStr == 6 || monthStr == 9 ||
			 monthStr == 11) {
		return 30;
	}
	else {
		if ((yearV % 4 == 0) && (yearV != 2000)) {
			return 29;
		}
		else {
			return 28;
		}
	}
}

// Builds the list of days that go on the calendar for the month and year
// selected.
function setDays(f, monthStr, yearStr) {

	firstDate = new Date(monthStr + "/1/" + yearStr);
	curDay = 1;
	daysInMonth = getDaysInMonth(monthStr, yearStr);

	// blank out rows
	for (var curWeek = 4; curWeek < 6; curWeek++) {
		for (var curDate = 0; curDate < 7; curDate++) {
			eval("f.day" + curWeek + curDate + ".src = '/common_images/date00.gif'");
		}
	}

	var startDate = firstDate.getDay();

	for (var curDate = 0; curDate < 7; curDate++) {

		if (startDate <= curDate) {
			if (curDay < 10) {
				eval("f.day0" + curDate + ".src = '/common_images/date0" + curDay++ + ".gif'");
			}
			else {
				eval("f.day0" + curDate + ".src = '/common_images/date" + curDay++ + ".gif'");
			}
		}
		else {
			eval("f.day0" + curDate + ".src = '/common_images/date00.gif'");
		}
	}
	for (var curWeek = 1; curWeek < 6; curWeek++) {
	
		for (curDate = 0; curDate < 7 && curDay <= daysInMonth; curDate++) {
			if (curDay < 10) {
				eval("f.day" + curWeek + curDate + ".src = '/common_images/date0" + curDay++ + ".gif'");
			}
			else {
				eval("f.day" + curWeek + curDate + ".src = '/common_images/date" + curDay++ + ".gif'");
			}
		}
	}
}

// Decrements the month by 1
function prevMonth(f, monthVal, yearVal) {

	yearLoc = yearVal.indexOf("year");
	var yearV = Number(yearVal.substring(yearLoc + 4, yearLoc + 8));

	monthLoc = monthVal.indexOf("month");
	var monthV = Number(monthVal.substring(monthLoc + 5, monthLoc + 7));
	
	if (monthV == 01) {
		monthV = 12;
		f.monthVal.src = '/common_images/month12.gif';
		yearV -= 1;
		eval("f.yearVal.src = '/common_images/year" + yearV + ".gif'");
	}
	else {
		monthV--;
		if (monthV < 10) {
			eval("f.monthVal.src = '/common_images/month0" + monthV + ".gif'");
		} else {
			eval("f.monthVal.src = '/common_images/month" + monthV + ".gif'");
		}
	}

	setDays(f, monthV, yearV);
}

// increments the month by 1
function nextMonth(f, monthVal, yearVal) {

	yearLoc = yearVal.indexOf("year");
	var yearV = Number(yearVal.substring(yearLoc + 4, yearLoc + 8));
	
	monthLoc = monthVal.indexOf("month");
	var monthV = Number(monthVal.substring(monthLoc + 5, monthLoc + 7));
	
	if (monthV == 12) {
		monthV = 1;
		f.monthVal.src = '/common_images/month01.gif';
		yearV += 1;
		eval("f.yearVal.src = '/common_images/year" + yearV + ".gif'");
	}
	else {
		monthV++;
		if (monthV < 10) {
			eval("f.monthVal.src = '/common_images/month0" + monthV + ".gif'");
		} else {
			eval("f.monthVal.src = '/common_images/month" + monthV + ".gif'");
		}
	}

	setDays(f, monthV, yearV);
}

// returns the date or performs the required functionality for whatever date was selected
function returnDate(f, dayClicked, clickAction) {

	yearLoc = f.yearVal.src.indexOf("year");
	var yearV = Number(f.yearVal.src.substring(yearLoc + 4, yearLoc + 8));
	
	monthLoc = f.monthVal.src.indexOf("month");
	var monthV = Number(f.monthVal.src.substring(monthLoc + 5, monthLoc + 7));
	
	dateLoc = dayClicked.src.indexOf("date");
	
//	alert("day clicked was " + f.monthName.value + " " + dayClicked.src.substring(dateLoc + 4, dateLoc + 6) + ", " + yearV);
	dateStr = monthV + "/" + dayClicked.src.substring(dateLoc + 4, dateLoc + 6) + "/" + yearV;
//	alert(clickAction + dateStr);
	window.location.href=clickAction + dateStr;
}

////////////////////////////////////////////////////////////////////////////////


// function to load the calendar window.
function ShowCalendar(FormName, FieldName)
{
	window.open("/DateSelectPopup.cfm?FormName=" + FormName + "&FieldName=" + FieldName, "CalendarWindow", "width=200,height=240");
}


// function to load the calendar window.
function ShowEuroCalendar(FormName, FieldName)
{
	window.open("/DateEuroSelectPopup.cfm?FormName=" + FormName + "&FieldName=" + FieldName, "CalendarWindow", "width=200,height=240");
}

////////////////////////////////////////////////////////////////////////////////

// the functions below are all for the credit card validation script
// use: validCCForm(form.creditcardtype, form.ccname, form.ccexpdate)

// Form Field Validation Functions:
//
// isValidExpDate(formField,fieldLabel,required)
//   -- checks for date in the format MM/YY or MM/YYYY against the current date
// isValidCreditCardNumber(formField,ccType,fieldLabel,required)
//   -- checks for valid credit card format using the Luhn check and known digits about various cards
//

function validRequired(formField,fieldLabel)
{
	var result = true;
	
	if (formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	
	return result;
}


function allDigits(str)
{
	return inValidCharSet(str,"0123456789X");
}

function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

function isValidExpDate(formField,fieldLabel,required)
{
	var result = true;
	var formValue = formField;

	if (required && (formField == "")) {
		alert('Please enter a valid Credit Card Year');
		result = false;
		return result;
	}
  
 	if (result && (formField.length>0))
 	{
 		var elems = formValue.split("/");
 		
 		result = (elems.length == 2); // should be two components
 		var expired = false;
 		
 		if (result)
 		{
 			var month = parseInt(elems[0],10);
 			var year = parseInt(elems[1],10);
 			
 			if (elems[1].length == 2)
 				year += 2000;
 			
 			var now = new Date();
 			
 			var nowMonth = now.getMonth() + 1;
 			var nowYear = now.getFullYear();
 			
 			expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));
 			
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
 		}
 		
  		if (!result)
 		{
 			alert('Please enter a date in the format MM/YY for the "' + fieldLabel +'" field.');
			//formField.focus();
		}
		else if (expired)
		{
 			result = false;
 			alert('The date for "' + fieldLabel +'" has expired.');
			//formField.focus();
		}
	} 
	
	return result;
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;
 
  	if (result && (formField.value.length>0))
 	{ 
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}	
		if (result)
 		{ 
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert('The credit card number entered is invalid.');
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

function LuhnCheck(str) 
{
  if (str == '12346')
  	return true;
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}



function GetRadioValue(rArray)
{
	for (var i=0;i<rArray.length;i++)
	{
		if (rArray[i].checked)
			return rArray[i].value;
	}
	
	return null;
}


function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);
	
	if (cardNum == '12346') 
		return true;	

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "AMERICAN EXPRESS":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;		
		case "MASTERCARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DINERS CLUB":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;		
	}
	
	return result;
}

function validCCForm(ccTypeField,ccNumField,ccExpField)
{
	var result = isValidCreditCardNumber(ccNumField,ccTypeField.value,"Credit Card Number",true) &&
		isValidExpDate(ccExpField,"Expiration Date",true);
	return result;
}

// End of credit card validation functions
////////////////////////////////////////////////////////////////////////////////
