/*
'+---------------------------------------------------------------+
'| Copyright 2001 MachroTech, LLC                                |
'| http://www.machrotech.com                                     |
'|                                                               |
'| This software contains confidential information which is the  |
'| property of Machrotech, LLC. This entire software package is  |
'| protected by the copyright laws of the United States and      |
'| elsewhere. All rights are reserved. No part of this software  |
'| may be copied, transcribed or used without express written    |
'| permission of MachroTech. This includes but is not limited to |
'| the source code, designs, concepts, interfaces and            |
'| documentation that are associated with this software and its  |
'| development.                                                  |
'+---------------------------------------------------------------+
*/

/***************************** 
* Validate Email
******************************/

function validateEmail (emailStr) {

var emailPat=/^(.+)@(.+)$/

var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

var validChars="\[^\\s" + specialChars + "\]"

var firstChars=validChars

var quotedUser="(\"[^\"]*\")"

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

var atom="(" + firstChars + validChars + "*" + ")"

var word="(" + atom + "|" + quotedUser + ")"

 userPat=new RegExp("^" + word + "(\\." + word + ")*$")

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {  
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    // user is not valid
    alert("The name part of the email address seems to be invalid.")
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {    
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("The IP part of the email address is invalid!")
		return false
	    }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name of the email address doesn't seem to be valid.")
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The email address must end in a three-letter domain, or two letter country.")
   return false
}

if (domArr[domArr.length-1].length==3 && len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}
// If we've gotten this far, everything's valid!
return true;
}

	
/**********************************
* Check a text field for a maximum length
* and trims it if necessary
***********************************/
function check_len(field, max)
{
	if(field.value.length > max)
	{
		field.value = field.value.substring(0, max - 1)
		alert("The length of this field cannot exceed " + max + " characters.\nIt has been truncated to this size.")
		field.focus();
		field.select();
		return true;
	}
}


/***********************************************************************
* Modified by Naga to check the Maxlength of the Rich Text area. 
* check_len() function is modified
************************************************************************/
function check_len_richtextarea(field, max)
{
	if(field.innerHTML.length > max)
	{
		field.innerHTML = field.innerHTML.substring(0, max - 1);
		alert("The length of this field cannot exceed " + max + " characters.\nIt has been truncated to this size.")
		field.focus();
		return true;
	}
}
	
	
/**********************************
* Trim Leading and Trailing Spaces
***********************************/
function trim(trimString)
{
	//trims the trimString and returns true if the resulting value is nullstring
	//or true otherwise

	if(trimString.length == 0)
		return false;

	//Triom leading spaces
	while(''+trimString.charAt(0)==' ')
		trimString=trimString.substring(1,trimString.length);

	if(trimString.length == 0)
	{
		return false;
	}

	//Trim trailing spaces
	while(trimString.charAt(trimString.length-1)==' ')
		trimString=trimString.substring(0,trimString.length-1);

	if(trimString.length == 0)
	{
		return false;
	}

	return true;
}


/**********************************
* Validate ZIP code
***********************************/

function validateZIP(field)
{
	var valid = "0123456789-";
	var hyphencount = 0;

	if (field.length != 5 && field.length != 10)
	{
		alert("Please enter your 5-digit or 5-digit + 4 zip code.");
		return false;
	}
	for (var i=0; i < field.length; i++)
	{
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1")
		{
			alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-"))
		{
			alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
		}
	}
	return true;
}



/**********************************
* Validate phone number
***********************************/

// Removes all characters which appear in string bag from string s.
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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function handlespace(theField)
{
//**********************************************************************\
//the following is to remove " " and "-" in the phone number string
var Delimiters = " "
var Delimiters2 = "-"	
	
    var normalizedCCN = stripCharsInBag(theField, Delimiters)
    normalizedCCN = stripCharsInBag(normalizedCCN, Delimiters2)
    theField.value = normalizedCCN
    return true    
}

function CheckPhoneNumber(TheNumber) {
	var valid = true
	var GoodChars = "0123456789()-+ "
	var i = 0
	//var bool=handlespace(TheNumber)
	if (TheNumber=="") {
		// Return false if number is empty
		//alert("Please enter a valid phone number.")
		valid = false
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {

		 //alert("Please enter a valid phone number.")
			valid = false
		} // End if statement
	} // End for loop
	return valid
}



/*  ================================================================
    FUNCTION:  isCreditCard(st)
 
    INPUT:     st - a string representing a credit card number

    RETURNS:  true, if the credit card number passes the Luhn Mod-10
		    test.
	      false, otherwise
    ================================================================ */

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19 || st.length < 15)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()


//==== To check whether Mandatory Option Buttons have been checked or not ======//
function fnCheckOptMandatory(obj,zDisplay)
{
	var intCounter, blnChecked, intLength, zCtrl;
	intLength = obj.length;  
	blnChecked = false;
		
	for(intCounter = 0; intCounter <= parseInt(intLength)-1; intCounter++)
	{
		if(obj[intCounter].checked == true)
		{
			blnChecked = true;	
		}
	}
	
	if(blnChecked == false)
	{	
		alert("Please select the " + zDisplay  + ".");	
		obj[0].focus();
		return false;
	}	
	
	return true;
}



//===== NEWLY ADDED FROM Mr. ANDREW'S MAIL =======//
function validate_TEXT(obj, sFieldName)
{
	var exp = /^(\S|\s)+$/
	return checkExp(exp, obj, "The " + sFieldName + " must be filled out")
}

function validate_ZIP(obj, sFieldName)
{
	var exp = /^\d{5}$/
	return checkExp(exp, obj, "Please enter a valid ZIP code (5 digits only)")
}

function validate_PHONE(obj, sFieldName)
{
	var exp = /^((\(\d{3}\) ?)|(\d{3}(-| )?))\d{3}(-| )?\d{4}$/
	return checkExp(exp, obj, "Please enter a valid US phone number (10 digits)")
}
	
function validate_EMAIL(obj, sFieldName)
{
	var exp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
	return checkExp(exp, obj, "Please enter a valid email address")
}
	
function validate_UPC(obj, sFieldName)
{
	var exp = /(^\d{6}$)|(^\d{12}$)/
	return checkExp(exp, obj, "Please enter a valid UPC code (6 or 12 digits)")
}

function validate_SSN(obj, sFieldName)
{
	var exp = /^\d{3}-\d{2}-\d{4}$/
	return checkExp(exp, obj, "Please enter a valid tax ID or SSN in the format nnn-nn-nnnn")
}

function validate_WEIGHT(obj, sFieldName)
{
	if (validate_DOUBLE(obj, sFieldName))
		if (obj.value <= 0)
		{
			alert("Please enter a number greater than zero for the weight")
			obj.focus();
			return false
		}
		else
			return true
	else
		return false
}
	
function validate_CURRENCY(obj, sFieldName)
{
	obj.value = obj.value.replace("$", "")
	obj.value = obj.value.replace(",", "")
		
	if (validate_DOUBLE(obj, sFieldName))
		if (obj.value < 0)
		{
			alert("Please enter a number greater or equal to zero for the " + sFieldName)
			obj.focus();	
			return false
		}
		else
		{
			obj.value = parseInt((parseFloat(obj.value) + 0.005) * 100) / 100
			return true
		}
	else
		return false		
}	
	
function validate_INTEGER(obj, sFieldName)
{
	var val = parseInt(parseInt(obj.value) + 0.5)
		
	if (isNaN(val) || obj.value == "")
	{
		alert("Please enter a numeric value")
		obj.focus();	
		return false
	}
	else
	{
		obj.value = val
		return true
	}
}

function validate_DOUBLE(obj, sFieldName)
{
	var val = parseFloat(obj.value)
		
	if (isNaN(val) || obj.value == "")
	{
		alert("Please enter a numeric value for the " + sFieldName)
		obj.focus();	
		return false
	}

	obj.value = val
	return true
}
	
function validate_DATE(obj, sFieldName)
{
	var testDate=new Date(Date.parse(obj.value));
		
	if(!testDate.getYear())
	{
	    alert("Please enter a valid date");
		obj.focus();
	    return false;
	}
	
	obj.value = testDate.getMonth() + 1 + "/" + testDate.getDate() + "/" + testDate.getYear()
	return true;
}
	
function validate_DROPDOWN(obj, sFieldName)
{	
	if (obj.selectedIndex == 0)
	{
		alert("Please select an option for the " + sFieldName)
		obj.focus();
		return false
	}
		
	return true
}
	
function validate_CUSTOM(obj)
{
	return true
}

function validate_FILE(obj, sFieldName)
{
	if (obj.value == "")
	{
		alert("Please browse for a file")
		obj.focus();
		return false
	}
		
	return true
}

function validate_TEXTAREA(obj, maxlen)
{
	if (validate_TEXT(obj))
		if (obj.value.length > parseInt(maxlen))
		{
			alert("The maximum length for this text field is " + maxlen + " characters.\nPlease shorten the amount of text you entered.")
			obj.focus();
			return false
		}
		else
			return true
	else
		return false
}

function validate_CHECKBOX(obj, sFieldName)
{
	return true
}
	
function validate_PASSWORD(obj)
{
	var exp = /^([0-9a-zA-Z]){4,}$/
	return checkExp(exp, obj, "The password must be at least 4 characters long (letters and numbers only)")
}
	
function validate_HIDDEN(obj, sFieldName)
{
	return true
}		
	
function trim(value)
{
	var exp = /^(\s*)(\S*)(\s*$)/;
	if (exp.test(value)) 
		value = value.replace(exp, '$2');
   			
	return value;
}

function checkExp(exp, obj, message)
{
	obj.value = trim(obj.value)
				
	if (!exp.exec(obj.value))
	{
		alert(message);
		obj.focus();
		return false;
	}		
		
	return true;
}
function validate_dates(StartDate,EndDate)
{
	//start_date = new Date(StartDate.value)
	end_date = new Date(EndDate.value)
	today_date = new Date()
	today_date = new Date(today_date.getFullYear(), today_date.getMonth(), today_date.getDate())
	start_date = today_date;		
	/*if (isNaN(start_date) || StartDate.length < 8)
	{
		alert("Please enter a valid start date! (mm/dd/yyyy)");
		StartDate.focus();
		return false;
	}
	*/
	if (isNaN(end_date) || EndDate.value.length < 8)
	{
		alert("Please enter a valid end date! (mm/dd/yyyy)");
		EndDate.focus();
		return false;
	}

	if (start_date >= end_date)
	{
		alert("Please enter Project Start date greater than today.");
		EndDate.focus();
		return false;
	}
	
	return true;
}


function validate_date(date_field, desc) 
{
        if (!date_field.value)  
                return true;
        var in_date = stripCharString(date_field.value," ");
        in_date = in_date.toUpperCase();
        var date_is_bad = 0;  
        if (!allowInString(in_date,"/0123456789T+-"))
                date_is_bad = 1; // invalid characters in date
        if (!date_is_bad) 
        { 
			var has_rdi = 0;
            if (in_date.indexOf("T") >= 0){ 
                        has_rdi = 1;
        }
        if (!date_is_bad && has_rdi && (in_date.indexOf("T") != 0)) { 
                date_is_bad = 2; // relative date index character is not in first position
        }
        if (!date_is_bad && has_rdi && (in_date.length == 1)) { 
                var d = new Date();
				var return_month = parseInt(d.getMonth() + 1).toString();
				return_month = (return_month.length==1 ? "0" : "") + return_month; 
				var return_date =  parseInt(d.getDate()).toString();
				return_date = (return_date.length==1 ? "0" : "") + return_date; 
		        in_date = return_month + "/" + return_date + "/" + get_full_year(d);		
                has_rdi = 0; // date doesn't have rdi char anymore (will also cause failure of add'l rdi checks, which is a good thing)
        }
        if (!date_is_bad && has_rdi && (in_date.length > 1) && !(in_date.charAt(1) == "+" || in_date.charAt(1) == "-")) {
                date_is_bad = 3; // length of rdi string is greater than 1 but second char is not "+" or "-"
        }
        if (!date_is_bad && has_rdi && isNaN(parseInt(in_date.substring(2,in_date.length),10))) {
                date_is_bad = 4; // rdi value is not a number
        }
        if (!date_is_bad && has_rdi && (parseInt(in_date.substring(2,in_date.length),10) < 0)) {
                date_is_bad = 5; // rdi value is not a positive integer
        }
        if (!date_is_bad && has_rdi) {
                var d = new Date();
                ms = d.getTime();
                offset = parseInt(in_date.substring(2,in_date.length),10);
                if(in_date.charAt(1) == "+") {
                        ms += (86400000 * offset);
                } else {
                        ms -= (86400000 * offset);
                }
                d.setTime(ms);
				var return_month = parseInt(d.getMonth() + 1).toString();
				return_month = (return_month.length==1 ? "0" : "") + return_month; 
				var return_date =  parseInt(d.getDate()).toString();
				return_date = (return_date.length==1 ? "0" : "") + return_date; 
		        in_date = return_month + "/" + return_date + "/" + get_full_year(d);	
                has_rdi = 0;
        }
        } 
        if (!date_is_bad) {
                var date_pieces = new Array();
                date_pieces = in_date.split("/");
                if (date_pieces.length == 2) {
                        var d = new Date();
                        in_date = in_date + "/" + get_full_year(d);
                        date_pieces = in_date.split("/");
                }
                if (date_pieces.length != 3 || parseInt(date_pieces[0],10) < 1 || parseInt(date_pieces[0],10) > 12 
                                || parseInt(date_pieces[1],10) < 1 || parseInt(date_pieces[1],10) > 31 
                                || (date_pieces[2].length != 2 && date_pieces[2].length != 4)) {
                        date_is_bad = 6;  // date is not in format of m[m]/d[d]/yy[yy]
                }
        }
        if (date_is_bad) {
                alert(desc + " must be in the format of mm/dd/yy, mm/dd/yyyy");
                date_field.focus();
                return (false);
        }
        
        var ms = Date.parse(in_date);
        var d = new Date();
        d.setTime(ms);
		var return_date = d.toLocaleString();
		var return_month = parseInt(d.getMonth() + 1).toString();
		return_month = (return_month.length==1 ? "0" : "") + return_month; 
		var return_date =  parseInt(d.getDate()).toString();
		return_date = (return_date.length==1 ? "0" : "") + return_date; 
        return_date = return_month + "/" + return_date + "/" + get_full_year(d);
        date_field.value = return_date;
        return true;
}       // normalize the year to yyyy

function get_full_year(d) 
{
		var y = ""
		if (d.getFullYear() != null)
		{
			y = d.getFullYear();
			if (y < 1970) y+= 100;		
		} else
		{	
	        y = d.getYear();
	        if (y > 69  && y < 100) y += 1900;
	        if (y < 1000) y += 2000;
		}
        return y;
}

// The following functions were written by Gordon McComb
// More information can be found here: http://www.javaworld.com/javaworld/jw-02-1997/jw-02-javascript.html
function stripCharString (InString, CharString)  
{
        var OutString="";
   for (var Count=0; Count < InString.length; Count++)  {
        var TempChar=InString.substring (Count, Count+1);
      var Strip = false;
      for (var Countx = 0; Countx < CharString.length; Countx++) {
        var StripThis = CharString.substring(Countx, Countx+1)
         if (TempChar == StripThis) {
                Strip = true;
            break;
         }
      }
      if (!Strip)
        OutString=OutString+TempChar;
   }
        return (OutString);
}
function allowInString (InString, RefString)  {
        if(InString.length==0) return (false);
        for (var Count=0; Count < InString.length; Count++)  {
        var TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)  
        return (false);
   }
   return (true);
}

