var isSubmitted;
isSubmitted=false;

function NoDoubleClick()
{
	
	if (isSubmitted==false)
	{
		isSubmitted=true;
		return true;
	}
	else
	{
		return false;
	}
}

function ValidateSignupForm(FormName,ValidatePassword,ValidateCC,ValidateUserInfo)
{
	var EmailOk = true;
	
	if (ValidatePassword=='True')
		EmailOk = isEmailValid(FormName,'email');
		
	if (!EmailOk)
		return false;
	
	var PasswordOk = true;
	if (ValidatePassword=='True')
		PasswordOk = CheckPasswords(FormName);
		
	if (!PasswordOk)
		return false;
		
	var UserInfoOk = true;
	if (ValidateUserInfo=='True')
		UserInfoOk = CheckUserInfo(FormName);
		
	if (!UserInfoOk)
		return false;
		
//	var CCInfoOK = true;
//	if (ValidateCC=='True')
//		CCInfoOK = CheckCCInfo(FormName);
//		
//	if (!CCInfoOK)
//		return false;
		
	return true ;
}

function CheckSignupInfo(FormName)
{
    var emailField = document.forms[FormName].elements['email'];
    var passField = document.forms[FormName].elements['password'];
    var pass2Field = document.forms[FormName].elements['confirmpassword'];
	var valid;
	var obj;

	valid = true;
	if (emailField)
	{
	    if (!isEmailValidNoPopup(FormName, 'email')) {
	        SetFieldErrorMessage('emailerror', 'Valid Email is required');
	        valid = false;
	    }
	    else 
	    {
	        SetFieldErrorMessage('emailerror', '');
	    }
	}

	if (passField) {
	    if (passField.value.length <= 0) {
	        SetFieldErrorMessage('passerror', 'Password cannot be empty');
	        valid = false;
	    }
	    else {
	        SetFieldErrorMessage('passerror', '');
	    }
	}

	if (pass2Field) {
	    if (pass2Field.value.length <= 0) {
	        SetFieldErrorMessage('confpasserror', 'Confirm Password cannot be empty');
	        valid = false;
	    }
	    else {
	        SetFieldErrorMessage('confpasserror', '');
	    }
	}

	if (valid && passField && pass2Field) {
	    if (pass2Field.value != passField.value) {
	        SetFieldErrorMessage('confpasserror', 'Passwords do not match');
	        valid = false;
	    }
	    else {
	        SetFieldErrorMessage('confpasserror', '');
	    }
	}
	
	return valid;
}

function CheckSubmitRegistrationInfo(FormName)
{
	var firstName = document.forms[FormName].elements['fname'];
	var lastName = document.forms[FormName].elements['lname'];
	var companyName = document.forms[FormName].elements['companyname'];
	var zipField = document.forms[FormName].elements['postalcode'];
	var phoneField = document.forms[FormName].elements['phone'];
	var emailField = document.forms[FormName].elements['email'];
	var numEmployees = document.forms[FormName].elements['numEmployees'];
	var jobTitle = document.forms[FormName].elements['jobtitle'];
	var state = document.forms[FormName].elements['state'];
	var country = document.forms[FormName].elements['country'];
	var industry = document.forms[FormName].elements['industry'];
	var pwd = document.forms[FormName].elements['password'];
	var pwdconf = document.forms[FormName].elements['confirmpassword'];
	var valid;
	var obj;

	valid = true;
	SetFieldErrorMessage('firstnameerror', '');
	if (firstName)
	{
		if (Trim(firstName.value).length == 0)
		{
			SetFieldErrorMessage('firstnameerror', 'First Name is required');
			valid = false;
		}
	}
	SetFieldErrorMessage('lastnameerror', '');
	if (lastName)
	{
		if (Trim(lastName.value).length == 0)
		{
			SetFieldErrorMessage('lastnameerror', 'Last Name is required');
			valid = false;
		}
	}
	SetFieldErrorMessage('companynameerror', '');
	if (companyName)
	{
		if (Trim(companyName.value).length == 0)
		{
			SetFieldErrorMessage('companynameerror', 'Company Name is required');
			valid = false;
		}
	}
	if (zipField)
	{
		SetFieldErrorMessage('postalcodeerror', '');
		if (Trim(zipField.value).length < 5)
		{
			SetFieldErrorMessage('postalcodeerror', 'ZIP Code is required');
			valid = false;
		}
	}
	SetFieldErrorMessage('phonenumbererror', '');
	if (phoneField)
	{
		if (Trim(phoneField.value).length < 7)
		{
			SetFieldErrorMessage('phonenumbererror', 'Valid Phone Number is required');
			valid = false;
		}
	}
	if (emailField)
	{
		SetFieldErrorMessage('emailerror', '');
		if (!isEmailValidNoPopup(FormName, 'email'))
		{
			SetFieldErrorMessage('emailerror', 'Valid Email is required');
			valid = false;
		}
	}
	
	if (pwd && pwdconf)
	{
	    SetFieldErrorMessage('password', '');
	    SetFieldErrorMessage('passwordconfirm', '');
	    
	    
	    if (Trim(pwd.value).length == 0)
	    {
	        SetFieldErrorMessage('password', 'Password cannot be empty');
	        valid = false;
	    }
	    if(Trim(pwdconf.value).length == 0)
	    {
	        SetFieldErrorMessage('passwordconfirm', 'Password Confirm cannot be empty');
	        valid = false;
	    }
	    if (pwd.value != pwdconf.value)
	    {
	        SetFieldErrorMessage('passwordconfirm', 'Passwords must match');
	        valid = false;
	    }
	}
	
	SetFieldErrorMessage('numEmployeesError', '');
	if (numEmployees)
	{
		if (Trim(numEmployees.value).length == 0)
		{
			SetFieldErrorMessage('numEmployeesError', 'Number of Employees is required');
			valid = false;
		}
		else if (!isNumeric(numEmployees.value))
		{
		    SetFieldErrorMessage('numEmployeesError', 'Number of Employees must be numeric');
			valid = false;
		}
	}
	
	SetFieldErrorMessage('jobtitleerror', '');
	if (jobTitle)
	{
		if (Trim(jobTitle.value).length == 0)
		{
			SetFieldErrorMessage('jobtitleerror', 'Job Title is required');
			valid = false;
		}
	}
	
	SetFieldErrorMessage('countryerror', '');
	if (country)
	{
		if (Trim(country.value).length == 0)
		{
			SetFieldErrorMessage('countryerror', 'Country is required');
			valid = false;
		}
	}
	
	SetFieldErrorMessage('stateerror', '');
	if (state)
	{
		if (Trim(state.value).length == 0)
		{
			SetFieldErrorMessage('stateerror', 'State/Province is required');
			valid = false;
		}
	}
	
	SetFieldErrorMessage('industryerror', '');
	if (industry)
	{
	    if (industry.selectedIndex == 0)
		{
			SetFieldErrorMessage('industryerror', 'Industry is required');
			valid = false;
		}
	}
	
	
	return valid;
}
function SetFieldErrorMessage(FieldName, message)
{
	var field = document.getElementById(FieldName);
	if (field)
	{
		if (message.length > 0)
		{
		    document.getElementById(FieldName).innerHTML = message + '<br>';
		    document.getElementById(FieldName).style.display = '';
		}
		else
		{
		    document.getElementById(FieldName).innerHTML = message;
		    document.getElementById(FieldName).style.display = 'none';
		}
	}
}
function CheckUserInfo(FormName)
{
	var retVal=true;
	var billingname = Trim(document.forms[FormName].elements['FullName'].value);
	var address1 = Trim(document.forms[FormName].elements['address1'].value);
	var city = Trim(document.forms[FormName].elements['city'].value);
	var state = Trim(document.forms[FormName].elements['state'].value);
	var zip = Trim(document.forms[FormName].elements['zip'].value);

	if (billingname.length==0)
	{
		window.alert('Your billing name can not be blank.  Please fill in a valid billing name.');
		document.forms[FormName].elements['FullName'].focus();
		return false;
	}
	
	if (address1.length==0)
	{
		window.alert('Your address can not be blank.  Please fill in a valid address.');
		document.forms[FormName].elements['address1'].focus();
		return false;
	}
	
	if (city.length==0)
	{
		window.alert('Your city can not be blank.  Please fill in a valid city.');
		document.forms[FormName].elements['city'].focus();
		return false;
	}
	
	if (state.length==0)
	{
		window.alert('Your state or region can not be blank.  Please fill in a valid state or region.');
		document.forms[FormName].elements['state'].focus();
		return false;
	}
	
	if (zip.length==0)
	{
		window.alert('Your postal code can not be blank.  Please fill in a valid postal code.');
		document.forms[FormName].elements['zip'].focus();
		return false;
	}
	
	return true;
		

}

function CheckPasswords(FormName)
{
	var password;
	var passwordConfirm;
	var passwordObj;
	var passwordConfirmObj;

	// need this because aargh, the password field names were different on the signup form
	// and ordernow form
	if (FormName == 'ordernowform')
	{
		passwordObj = document.forms[FormName].elements['password'];
		passwordConfirmObj = document.forms[FormName].elements['confirmpassword'];
	}
	else
	{
		passwordObj = document.forms[FormName].elements['Password'];
		passwordConfirmObj = document.forms[FormName].elements['PasswordConfirm'];
	}

	password = Trim(passwordObj.value);
	passwordConfirm = Trim(passwordConfirmObj.value);

	if (password == '')
	{
		window.alert('Please fix your password. Your password must not be blank');
		passwordObj.value = '';
		passwordConfirmObj.value = '';
		passwordObj.focus();
		return false;
	}
	
	if (password.toString() != passwordConfirm.toString())
	{
		window.alert('Please fix your password. Both passwords that you have entered must match.');
		passwordObj.value = '';
		passwordConfirmObj.value = '';
		passwordObj.focus();
		return false;
	}
	
	return true;
}

function isEmailValid(FormName,ElemName)
{
	var EmailOk  = true
	var Temp     = document.forms[FormName].elements[ElemName]

	Temp.value = Trim(Temp.value);
    
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if (!re.test(Temp.value))
		{
			EmailOk = false;
			alert('Please enter a valid e-mail address.');
			Temp.focus();
		}
	return EmailOk;
}
function isEmailValidNoPopup(FormName,ElemName)
{
	var EmailOk  = true
	var Temp     = document.forms[FormName].elements[ElemName]

	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if (!re.test(Temp.value))
		{
			EmailOk = false;
		}
	return EmailOk;
}
function isZipCodeValid(FormName,ElemName)
{
	var Temp     = document.forms[FormName].elements[ElemName]
	return isValidZipCode(Temp.value);
}
function isNumeric(str)
{
    var OK  = true;
	var re = new RegExp(/^\d+$/ );
	if (!re.test(str))
	{
		OK = false;
	}
	return OK;
}
function isValidZipCode(strZip)
{
	var ZIPOK  = true;
	var re = new RegExp(/(^\d{5}$)|(^\d{9}$)|(^\d{5}-\d{4}$)/);
	if (!re.test(strZip))
	{
		ZIPOK = false;
	}
	return ZIPOK;
}
function checkNumeric(strNum)
{

	if  (isNumber(strNum))
	{
		window.alert('Please use numbers only');
		return false;
	}
	else
	{
		return true;
	}

}

function LTrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;


      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function Trim(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return RTrim(LTrim(str));
}

function CheckCCInfo(FormName)
{
	var ccnum = document.forms[FormName].elements['ccnum'].value;
	var expMonth = document.forms[FormName].elements['expmonth'].value;
	var expYear= document.forms[FormName].elements['expyear'].value;
	var cctype = document.forms[FormName].elements['cctype'].value;
	
/*	var cctypeCode ='';
	
	if (cctype=='1')
		cctypeCode='v';
	
	if (cctype=='2')
		cctypeCode='m';
*/
	
	return validateCard(ccnum,'mv',expMonth,expYear);
}
/*function validateCard(cardNumber,cardType,cardMonth,cardYear)

	parameters:
		all paramaters are string values.
		Month & Year come from the select input fields in the form, so they are defined.
		cardType can be:
			'a' for American Express
			'd' for Discover
			'm' for MasterCard
			'v' for Visa
	description:
		this function will check string length, valid characters, specific credit card prefixes and test
		the Mod 10 (LUHN Formula) for validating possible credit card numbers. this function can only
		authorize that the given card data is potentially valid. You would still need to run actual
		card validation routines to verify the actual account.
	returns:
		this function returns true if the card number could be valid for the card type and expiration date.
		false otherwise.	
supporting functions:
mod10( cardNumber )
	parameters:
		this function takes the text string card number and runs the Mod 10 formula on its respective digits.
	description:
		Mod 10 is the check digit formula for the supported cards these functions attempt to validate.
	returns:
		this function returns true if the number passes the check digit test.
		false otherwise.
expired( cardMonth, cardYear )
	parameters:
		this function takes the text string values given by the html form.
	description:
		this function basically will check to make sure todays date is less than the expiration date the user inputs.
		this function is not locked into using 2 digit dates.
	returns:
		this fucntion returns true if the card is expired.
		false otherwise.
*/
function mod10( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;


    	for( i = 0; i < cardNumber.length; ++i ) {
    		ar[i] = parseInt(cardNumber.charAt(i));
    	}
    	for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
    		ar[i] *= 2;							 // every second digit starting with the right most (check digit)
    		if( ar[i] > 9 ) ar[i]-=9;			 // will be doubled, and summed with the skipped digits.
    	}										 // if the double digit is > 9, ADD those individual digits together 


        	for( i = 0; i < ar.length; ++i ) {
        		sum += ar[i];						 // if the sum is divisible by 10 mod10 succeeds
        	}
        	return (((sum%10)==0)?true:false);	 	
    }


        function expired( month, year ) {
			return false;
/*        	var now = new Date();							// this function is designed to be Y2K compliant.
        	var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
        	expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
        	if( now.getTime() < expiresIn.getTime() ) return false;
        	return true;	*/								// then we get the miliseconds, and do a long integer comparison
    }
    


        function validateCard(cardNumber,cardType,cardMonth,cardYear) {
        	if( cardNumber.length == 0 ) {						//most of these checks are self explanitory
        		alert("Please enter a valid card number, it cannot be blank.");
        		return false;				
        	}
        	for( var i = 0; i < cardNumber.length; ++i ) {		// make sure the number is all digits.. (by design)
        		var c = cardNumber.charAt(i);


            		if( c < '0' || c > '9' ) {
            			alert("Please enter a valid card number. Use only digits. do not use spaces or hyphens.");
            			return false;
            		}
            	}
            	var length = cardNumber.length;			//perform card specific length and prefix tests


                	switch( cardType ) {
                		case 'a':


                    			if( length != 15 ) {
                    				alert("Please enter a valid American Express Card number.");
                    				return;
                    			}
                    			var prefix = parseInt( cardNumber.substring(0,2));


                        			if( prefix != 34 && prefix != 37 ) {
                        				alert("Please enter a valid American Express Card number.");
                        				return;
                        			}
                        			break;
                        		case 'd':


                            			if( length != 16 ) {
                            				alert("Please enter a valid Discover Card number.");
                            				return;
                            			}
                            			var prefix = parseInt( cardNumber.substring(0,4));


                                			if( prefix != 6011 ) {
                                				alert("Please enter a valid Discover Card number.");
                                				return;
                                			}
                                			break;
                                		case 'mv':


                                    			if( length != 16 && length != 13) {
                                    				alert("The Visa or Mastercard number you have entered is too short.  Please enter all digits of the Visa or Mastercard number.");
                                    				return;
                                    			}
                                    			var mcprefix = parseInt( cardNumber.substring(0,2));
                                         		var visaprefix = parseInt( cardNumber.substring(0,1));


                                        			if(( mcprefix < 51 || mcprefix > 55) && visaprefix != 4) {
                                        				alert("The Visa or Mastercard number you have entered is not valid. Please correct the credit card number.");
                                        				return;
                                        			}
                                        			break;

                                                	}
                                                	if( !mod10( cardNumber ) ) { 		// run the check digit algorithm
                                        				alert("The Visa or Mastercard number you have entered is not valid. Please correct the credit card number.");
                                                		return false;
                                                	}
                                                	if( expired( cardMonth, cardYear ) ) {							// check if entered date is already expired.
                                                		alert("The expiration date you have entered would make this card invalid.");
                                                		return false;
                                                	}
                                                	
                                                	return true; // at this point card has not been proven to be invalid
                                            }
