// JAVASCRIPT / CSS TO WRITE OUT ERROR MESSAGE IN THE FORM

// ************************************************
// Writes the text into a paragraph element
function writeMessage(fld, dispmessage) {
  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
};

// ************************************************
// Displays or hides an error message, depending on errorFound parameter
function writeErrorMessage(errorFound, errorParagraphId, errorText) {
	if (errorFound) {
		writeMessage(errorParagraphId, errorText);
		document.getElementById(errorParagraphId).style.display = "block"; 
	} else {
		writeMessage(errorParagraphId, "");
		document.getElementById(errorParagraphId).style.display = "none";
	}
}

////////////////////////////////////////////////////////////////
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


// -----------------------------------------------------------------
// Function    : IsEmailValid
// Language    : JavaScript
// Description : Checks if given email address is of valid syntax
// Copyright   : (c) 1998 Shawn Dorman
// http://www.goodnet.com/~sdorman/web/IsEmailValid.html
// -----------------------------------------------------------------
// Ver    Date    Description of modification
// --- ---------- --------------------------------------------------
// 1.0 09/04/1996 Original write
// 1.1 09/30/1998 CHG: Use standard header format
// -----------------------------------------------------------------
// Source: Webmonkey Code Library
// (http://www.hotwired.com/webmonkey/javascript/code_library/)
// -----------------------------------------------------------------

function EmailValid(FormName,ElemName)
{
var EmailOk  = true
var Temp     = document.forms[FormName].elements[ElemName]
var AtSym    = Temp.value.indexOf('@')
var Period   = Temp.value.lastIndexOf('.')
var Space    = Temp.value.indexOf(' ')
var Length   = Temp.value.length - 1   // Array is from 0 to length-1

if ((AtSym < 1) ||                     // '@' cannot be in first position
    (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
    (Period == Length ) ||             // Must be atleast one valid char after '.'
    (Space  != -1))                    // No empty spaces permitted
   {  
      EmailOk = false;
   }
return EmailOk;
}


function validEmail(email) {
	// + indicates 1 or more matches (same as {1,}
	// \w indicates [a-zA-Z_0-9]
	// (\w|-)+ : Match any comination of at least 1 alphanumeric chars, hyphens, or underscores
	// @ : Make sure there's an at sign
	// (\w|-)+ : Match any comination of at least 1 alphanumeric chars, hyphens, or underscores
	// \. : Make sure there's a period
	// (\w|-)+ : Match any comination of at least 1 alphanumeric chars, hyphens, or underscores 
	expr = /(\w|-)+@(\w|-)+\.(\w|-)+/
	vEmail = expr.test(email);
	return vEmail;
}


////////////////////////////////////////////////////////////////
function checkPassword(Password, ConfirmPassword) {
	pwMsg = "";
	if (Password.length < 6) {
		pwMsg = "TooShort";

	} else if (Password.length > 20) {
		pwMsg = "TooLong";

	} else if (Password != ConfirmPassword) {
		pwMsg = "NoMatch";
	}
	return pwMsg;
}

function checkUsername(Username) {
	unMsg = "";
	if (Username.length < 6) {
		unMsg = "TooShort";
	} else if (Username.length > 50) {
		unMsg = "TooLong";
	}
	return unMsg;
}

////////////////////////////////////////////////////////////////
// Checks to make sure that a  valid DATE (mm/dd/yy) has been entered
function checkDate(fmdate){
	validDate = true;
	
 	dPart = fmdate.split('/');
 		
  	if (dPart.length==3) {
  	
  		// regular expression to match required date format 
  		re = /^\d{1,2}\/\d{1,2}\/\d{2}$/; 
  		
  		if (!fmdate.match(re)) { 
  			validDate = false;
  		} else {
  			
  			MonthNum = parseInt(dPart[0]);
  			MonthDay = parseInt(dPart[1]);
  			NumDays = 31
  			
  			// Months with 30 days
  			if (MonthNum == 4 || MonthNum == 6 || MonthNum == 9 || MonthNum == 11) {
  				NumDays = 30;
  			
  			// February
  			} else if ( MonthNum == 2 ) {
  				fmYear = parseInt(dPart[2]);
  				if (fmYear >= 0 && fmYear <= 30) {
  					fmYear = 2000 + fmYear;
  				} else {
  					fmYear = 1900 + fmYear;
  				}
  				
  				NumDays = 28;
  				if ((fmYear % 4 == 0 && fmYear % 100 != 0) || (fmYear % 400 == 0)) {
  					NumDays = 29;
  				}
  			}
  			
  			// Make sure a valid day of the month was entered
  			if (MonthDay < 0 || MonthDay > NumDays) {
  				validDate = false;
  			}
  		}
  		 
  	} else {
    	validDate = false;
  	}
  	return validDate;
}

























////////////////////////////////////////////////////////////////////////////////////////////
// Checks to make sure that a valid DATE (mm/dd/YYYY) has been entered
// *****************************************************************************************
// DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function checkDateYYYY(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	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 (pos1==-1 || pos2==-1){
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false;
	}
	return true;
}


function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function daysElapsed(date1,date2) {
    var difference =
        Date.UTC(y2k(date1.getYear()),date1.getMonth(),date1.getDate(),0,0,0)
      - Date.UTC(y2k(date2.getYear()),date2.getMonth(),date2.getDate(),0,0,0);
    return difference/1000/60/60/24;
}

////////////////////////////////////////////////////////////////////////////////////////////
// *****************************************************************************************


////////////////////////////////////////////////////////////////
// Checks to make sure that a  valid ZIP CODE has been entered
function validZip(zip) {
	
	var Expr1 = /^\d{5}$/
	var Expr2 = /^\d{5}-\d{4}$/
	vZip = Expr1.test(zip) || Expr2.test(zip);
	
	return vZip;
	
}

////////////////////////////////////////////////////////////////
// Checks to make sure that a  valid STATE ABBREV. has been entered
function validStateCode(state) {
	// Match any two (and only two) alpha chars
	var Expr = /^[a-zA-Z]{2}$/i;
	
	statebool = Expr.test(state);
	return statebool;
}


function formatPhoneNumber(phoneNumber) {

	// Strip out spaces and dashes		
	phoneNumber = phoneNumber.replace(/ /g,"");
	phoneNumber = phoneNumber.replace(/-/g,"");
	phoneNumber = phoneNumber.replace(/\(/g,"");
	phoneNumber = phoneNumber.replace(/\)/g,"");	
	phoneNumber = phoneNumber.replace(/\./g,"");
	
	strLength = phoneNumber.length;
	formattedPhone = "";
	
	
	
	if (strLength >= 3) {
		formattedPhone = phoneNumber.substring(0,3) 
	}
	
	if (strLength >= 4) {
		formattedPhone = formattedPhone + "-" + phoneNumber.substring(3,6) 
	}
	
	if (strLength >= 7) {
		formattedPhone = formattedPhone + "-" + phoneNumber.substring(6,10) 
	}
	
	
	return formattedPhone;
}


////////////////////////////////////////////////////////////////
// Checks to make sure that a  valid PHONE NUMBER has been entered
function validPhone(phoneNumber) {

	// Checks to see if phone number is like 123-123-1234
	// d{x} indicates there should be x digits in a row
	var Expr = /^\d{3}-\d{3}-\d{4}$/;

	phbool = Expr.test(phoneNumber);
	return phbool;
}

////////////////////////////////////////////////////////////////
// Format card number with dashes
function formatCardNum(CardNum, CardType) {

	// Strip out spaces and dashes		
	CardNum = CardNum.replace(/ /g,"");
	CardNum = CardNum.replace(/-/g,"");

	strLength = CardNum.length;
	
	// ---------------------------
	// Re-add the spaces and dashes.  This way, regardless of whether the user
	// used spaces or dashes, the credit card number will still be properly formatted.
	// AMERICAN EXPRESS CARDS
	if (strLength == 15 && CardType == "AmEx") {

		CardNumber = "";

		for (i=0; i<16; i++) {

			CardNumber = CardNumber + CardNum.substring(i, i+1);
			
			if (i==3 || i==9) {
				CardNumber = CardNumber + "-";
			}
		}


	// ---------------------------
	// OTHER CARDS
	} else if (strLength == 16) {
	
		startIndex = 0;
		endIndex = 4;

		CardNumber = "";
		joiner = "";

		for (i=0; i<4; i++) {
		
			if (endIndex > strLength) {
				endIndex = strLength;
			}

			CardNumber = CardNumber + joiner + CardNum.substring(startIndex, endIndex);
			joiner = "-";
			startIndex += 4;
			endIndex +=4;
		}

	} else {
		CardNumber = CardNum;
	}
	
	return CardNumber;

}

////////////////////////////////////////////////////////////////
// Checks for a valid AMERICAN EXPRESS CREDIT CARD NUMBER
function isValidAmEx(cardNum) {

	// American Express card format: 1234-1234-1234-123

	var AmEx = /^\d{4}-\d{4}-\d{4}-\d{3}$/;
	var AmEx2 =  /^\d{4}-\d{6}-\d{5}$/;
	AmExBool = AmEx.test(cardNum);
	AmExBool2 = AmEx2.test(cardNum);
	
	
	return (AmExBool||AmExBool2);
}

////////////////////////////////////////////////////////////////
// Checks for a valid OTHER (Visa, Discover, MasterCard) CREDIT CARD NUMBER
function isValidOtherCC(cardNum) {

	// Card format: 1234-1234-1234-1234

	var Other = /^\d{4}-\d{4}-\d{4}-\d{4}$/;
	OtherBool = Other.test(cardNum);
	
	return OtherBool;
}


////////////////////////////////////////////////////////////////
// Check for valid CREDIT CARD EXP DATE of the form MM/YY using a regular expression
function validExpDate(ExpDate) {

	expBool = true;

	var ExpPattern = new RegExp("^[0-9]{2}\/[0-9]{2}$", "gi");
	if (!ExpPattern.test(ExpDate)) {
		expBool = false;	
	} else {
		expArray = ExpDate.split("/");
		expMonth = expArray[0];
		
		if (expMonth > 12 || expMonth < 1) {
			expBool = false;
		}
	}
	
	return expBool;
}


////////////////////////////////////////////////////////////////
// Checks to make sure that the credit card is not expired
function isCurrentCard(ExpDate) {
	
	dateBool = true;

	if (ExpDate.length == 0) {
		dateBool = false;
	} else {
	
		validDate = validExpDate(ExpDate);
		if (!validDate) {
			dateBool = false;	
		} else {
			// Make sure the date is valid
			expArray = ExpDate.split("/");
			expMonth = expArray[0];
			expYear = expArray[1] - 0;
			expYear = expYear + 2000;
			
			thedate = new Date();
			currYear = thedate.getYear();
			
			// Handle different browser handling of dates
			if(currYear <200) { currYear +=1900 }
			currMonth = thedate.getMonth() + 1;
						
			if (currYear > expYear) {
				dateBool = false;
			} else if (expYear == currYear && currMonth > expMonth) {
				dateBool = false;
			}
			
		}
		
		return dateBool;
	}
}

////////////////////////////////////////////////////////////////
// Checks for numeric value
function isNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
      {
         IsNumber = false;
      }
   }
   return IsNumber;
}