// username - 4-20 chars, uc, lc, and underscore only.
//
function checkLoginName(username)
{
	var error = '';
	if (username === '') {
		error = 'Please enter a login';
	} else if ((username.length < 4) || (username.length > 20)) {
		error = 'Login must be between 4 and 20 characters';
	} else {
		// allow only letters, numbers and underscores
		var illegalChars = /\W/;
		if (illegalChars.test(username)) {
			error = 'Login contains illegal characters.';
		}
	}
	return error;
}

// password - not empty, 4-20 chars
//
function checkPassword(password)
{
	var error = '';
	if (password === '') {
		error += 'Please enter a password';
	} else if ((password.length < 4) || (password.length > 20)) {
		error += 'Password must be between 4 and 20 characters.';
	} else {
		// allow only letters, numbers and underscores
		var illegalChars = /\W/;
		if (illegalChars.test(password)) {
			error = 'Password contains illegal characters.';
		}
	}
	return error;
}

function checkLoginForm(loginForm)
{
	var sError = '';
	sError += checkLoginName(loginForm.login.value);
	sError += checkPassword(loginForm.password.value);
	return sError;
}

// key - must match form of XXXX- for number of segments
//
function isValidKey(key, segments)
{
	var keyPattern = '^';
	if (segments > 1) {
		keyPattern += '(?:[A-F0-9a-f]{4}\\-){' + (segments-1) + '}';
	}
	keyPattern += '[A-F0-9a-f]{4}$';
	var validKey = new RegExp(keyPattern);

	return validKey.test(key);
}


function checkEmail(email)
{
	var valid = 1;

	if (email === '') {
		// Return false if email is empty
		valid = 0;
	}
	var GoodChars = "@.0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

	for (var i=0; i<= email.length -1; i++) {
		if (GoodChars.indexOf(email.charAt(i)) == -1) {
			valid = 0;
			break;
		}
	}

	// more validation??
	return valid;
}

// e-mail - not empty, meets W3 spec
//
function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/;
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address.
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
/* The following string represents the range of characters allowed in a
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+';
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Email address seems incorrect (check @ and .'s)");
	return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// See if "user" is valid
if (user.match(userPat)==null) {
    // user is not valid
    //alert("The username doesn't seem to be valid.")
    return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	      //alert("Destination IP address is invalid!")
				return false;
	    }
    }
    return true;
}

// Domain is symbolic name
var domainArray=domain.match(domainPat);
if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
    return false;
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
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 address must end in a three-letter domain, or two letter country.")
  return false;
}

// Make sure there's a host name preceding the domain.
if (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;
}


// range - not empty, in the form of X or X-Y
//
function checkRange(range)
{
	if (range == '') {
		return false;
	}

	// match returns the part of the str that matches the expression,
	// they should be the same, if not then range isn't completely valid
	return (range.match(/[0-9]+(?:\-[0-9]+)?(?:\,\s*[0-9]+(?:\-[0-9]+)?)*\s*/) == range);
}

// check that a value is strictly numeric
function checkNumber(number)
{
	if (number == '') { return false; }
	return (number.match(/-*[0-9]+/) == number);
}

function checkPhoneNumber(phoneNumber)
{
	var valid = 1;
	var GoodChars = "0123456789()-+ ";

	if (phoneNumber == '') {
		// Return false if number is empty
		valid = 0;
	}

	for (var i=0; i<= phoneNumber.length -1; i++) {
		if (GoodChars.indexOf(phoneNumber.charAt(i)) == -1) {
			valid = 0;
			break;
		}
	}
	return valid;
}

function checkZipCode(zipCode)
{
	var valid = 1;
	var GoodChars = "0123456789- ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	if (zipCode == '') {
		// Return false if number is empty
		return 0;
	}
	if (zipCode.length < 5) {
		return 0;
	}
	for (var i=0; i<= zipCode.length -1; i++) {
		if (GoodChars.indexOf(zipCode.charAt(i)) == -1) {
			return 0;
		}
	}
	return valid;
}

function checkAccountInfo(accountForm)
{
	var sError = '';
	// check for any blank fields
	if (accountForm.txtAccountName.value == '' | accountForm.txtAddress1.value == '' | +
		accountForm.txtCity.value == '' | accountForm.txtCountry.value == '') {
		sError += 'Required fields (*) must be filled in.\n';
	}
	// check for valid characters for phone number
	if (checkPhoneNumber(accountForm.txtPhone.value) == 0) {
		sError += 'Invalid Phone number.\n';
	}
	// check at least 5 numeric characters for Zip Code
	if (checkZipCode(accountForm.txtZip.value) == 0) {
		sError += 'Invalid Zip Code\n';
	}

	return sError;
}

function checkAccountName(aForm)
{
	var errorMessages = new Array;

	// check for blank account name
	if (aForm.txtAccountName.value == '')  {
		errorMessages.push('Account name cannot be blank.\n');
	}

	return errorMessages;
}


function checkAccountOptions(aForm)
{

	var errorMessages = new Array;

	// check for blank account name
	if (aForm.txtAccountName.value == '')  {
		errorMessages.push('Account name cannot be blank.\n');
	}

	if (checkNumber(aForm.inputWarningLevel.value) != true)
	{
		errorMessages.push('Invalid Inventory Wanring Level.\n');
	}

	return errorMessages;
}

function checkLeadInfo(aForm)
{
	var errorMessages = new Array;

	// check for any blank fields
	if (aForm.txtCompanyName.value == '')
		errorMessages.push('Please provide your company name');


	if (aForm.txtAddress1.value == '')
		errorMessages.push('Please provide an address');


	if (aForm.txtCity.value == '')
		errorMessages.push('Please provide your city');

	if (aForm.txtCountry.value == '')
		errorMessages.push('Please provide your country');

	if (aForm.txtFirstName.value == '')
		errorMessages.push('Please provide your first name');


	if (aForm.txtLastName.value =='')
		errorMessages.push('Please provide your last name');

	// check for valid characters for phone number
	if (checkPhoneNumber(aForm.txtPhone.value) == 0)
		errorMessages.push('Invalid Phone number.');

	// check at least 5 numeric characters for Zip Code
	if (checkZipCode(aForm.txtZipCode.value) == 0)
		errorMessages.push('Invalid Zip Code');

	if (checkEmail(aForm.txtEmail.value) == 0)
		errorMessages.push('Invalid Email address');

	return errorMessages;
}

function checkJobUploadInfo(aForm)
{
	var errorMessages = new Array;

	// check for blank job file
	if ( aForm.jobfile.value == '' ) {
		errorMessages.push('Label Design file cannot be blank.');
	} else {
		var returnMessage = checkDesignFileExtension(aForm.jobfile.value);
		if (returnMessage.length > 0)
			errorMessages.push(returnMessage);
	}

	if (aForm.colorScheme.value == -1) {
		errorMessages.push('You must select a Color Scheme option.');
	}
	if (aForm.layout.value == -1) {
		errorMessages.push('You must select a Layout option.');
	}
	if (aForm.printerType.value == -1) {
		errorMessages.push('You must select a Printer type.');
	}
	if (aForm.industry.value == -1) {
		errorMessages.push('You must select an Industry option.');
	}
	return errorMessages;
}

function checkEditDesignForm(aForm)
{
	var errorMessages = new Array;

	if (aForm.colorScheme.value == -1) {
		errorMessages.push('You must select a Color Scheme option.');
	}
	if (aForm.layout.value == -1) {
		errorMessages.push('You must select a Layout option.');
	}
	if (aForm.printerType.value == -1) {
		errorMessages.push('You must select a Printer type.');
	}
	if (aForm.industry.value == -1) {
		errorMessages.push('You must select an Industry option.');
	}
	return errorMessages;
}


function checkDesignFileExtension(filename) {
	// check for a valid job file extension
	var extArray = new Array('.job', '.ltf');
	var validExt = false;

	while (filename.indexOf("\\") != -1)
		filename = filename.slice(filename.indexOf("\\") + 1);

	var ext = filename.slice(filename.indexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) {
			validExt = true;
			break;
		}
	}

	if (!validExt)
		return 'Only files that end in:  (' + (extArray.join(",  ")) + ') can be uploaded as label design files.';
	else
		return '';
}

function checkPasswords(form, errorMessages)
{
	returnMessage = checkPassword(form.txtPassword.value);
	if (returnMessage.length > 0)
		errorMessages.push(returnMessage);
	else {
		// check to ensure the passwords match
		if (form.txtPassword.value != form.txtPasswordConfirm.value)
			errorMessages.push('Password confirmation does not match. Please re-enter the password.');
	}
}

function checkUserInfo(userForm)
{
	var errorMessages = new Array;
	var returnMessage = '';

	if (userForm.txtFirstName.value == '' | userForm.txtLastName.value == '')
		errorMessages.push('Please enter First and Last name.');

	// only check the login if it's actually there

	if (userForm.txtLogin) {
		returnMessage = checkLoginName(userForm.txtLogin.value);
		if (returnMessage.length > 0)
			errorMessages.push(returnMessage);

		checkPasswords(userForm, errorMessages);
	}

	if (emailCheck(userForm.txtEmail.value) == 0) {
		errorMessages.push('Invalid Email address');
	}

	return errorMessages;
}

function checkLoginInfo(loginForm, strArr) {
var sError = '';

	sError = checkLoginName(loginForm.Login.value);
	if (sError != '')
		strArr.push(sError);

	sError = checkPassword(loginForm.Password.value);
	if (sError != '')
		strArr.push(sError);

	// check to esnure the passwords match
	if (loginForm.Password.value != loginForm.PasswordConfirm.value)
		strArr.push('Password confirmation does not match. Please re-enter the password.');
}

function checkNewLead(leadForm)
{
	var sError = '';

	sError += checkAccountInfo(leadForm);
	sError += checkUserInfo(leadForm);

	return sError;
}

function checkTransferRequest(aForm, inventory)
{
	var errorMessages = new Array;
	var iDifference = 0;
	var iTransferClicks = 0;

	if (isNaN(aForm.inputTransferAmount.value)) {
		errorMessages.push('Transfer amount must be a positive number.');
	} else {
		iTransferClicks = aForm.inputTransferAmount.value;
		iDifference = inventory - iTransferClicks;
		if  (iTransferClicks < 1) {
			errorMessages.push('You must enter a positive transfer amount.');
		}
		else {
			if ((inventory == 0) || (iDifference < 0)) {
				errorMessages.push('Unable to fulfill request due to inadequate inventory.');
			}
		}
	}
	return errorMessages;
}

function checkInventoryWarningInfo(aForm)
{
	var errorMessages = new Array;

	var inventoryWarningLevel = aForm.inputWarningLevel.value;
	var inventoryWarningMsg = aForm.inputWarningMsg.value;

	if ( (isNaN(inventoryWarningLevel)) || (inventoryWarningLevel <= 0) ) {
		errorMessages.push('Inventory Warning Level value must be a positive number.');
	}

	if ( inventoryWarningMsg.length == 0 ) {
		errorMessages.push('Inventory Warning Message cannot be empty.');
	}

	var validChars = "0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%()[]:,.?/-_+= ";
	var validMessage = true;
	var invalidChar = '';


	for (var i=0; i <=  inventoryWarningMsg.length -1; i++) {
		if (validChars.indexOf( inventoryWarningMsg.charAt(i)) == -1) {
			invalidChar = inventoryWarningMsg.charAt(i);
			validMessage = false;
			break;
		}
	}

	if (!validMessage) {
		errorMessages.push('Invalid character [' + invalidChar + '] found in warning message.');
	}


	return errorMessages;
}

function checkSequenceData(aForm)
{
	var sError = 'Bob';
	var strQuantity = ''
	var iQuantity = 0;
	var strStartSequence = '';
	var strEndSequence = '';


//	iQuantity = parseInt(strQuantity)

	if (isNaN(aForm.inputQuantity.value)) {
		sError = 'Quantity must be a valid positive number.';
	}
	else {
		strQuantity = aForm.inputQuantity.value;
		sError = strQuantity;
	}
/*
	if (iQuantity == 0) {
		sError = 'Quantity cannot be zero [' + strQuantity + ']';
	}
	else
		sError = 'Valid quantity: [' + strQuantity + ']';
*/
	return sError;

}


function checkLogoFileExtension(filename) {
	// check for a valid image file extension
	var extArray = new Array('.jpg', '.jpeg', '.tif', '.tiff', '.png', '.bmp');
	var validExt = false;

	while (filename.indexOf("\\") != -1)
		filename = filename.slice(filename.indexOf("\\") + 1);

	var ext = filename.slice(filename.indexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) {
			validExt = true;
			break;
		}
	}

	if (!validExt)
		return 'Only files that end in:  (' + (extArray.join(",  ")) + ') can be uploaded as label logo files.';
	else
		return '';
}

function checkLogoFileSize(filename) {

	// check image for valid width and height values
	return '';
}

function checkLogoUploadInfo(aForm)
{
	var errorMessages = new Array;

	// check for blank logo image file
	if ( aForm.logoImageFile.value == '' ) {
		errorMessages.push('Logo image file cannot be blank.');
	} else {
		var returnMessage = checkLogoFileExtension(aForm.logoImageFile.value);
		if (returnMessage.length > 0)
			errorMessages.push(returnMessage);

		else {
			returnMessage = checkLogoFileSize(aForm.logoImageFile.value);
			if (returnMessage.length > 0)
				errorMessages.push(returnMessage);
		}
	}

	return errorMessages;
}

function checkBarcodeProfiles(profileList)
{
	var errorMessages = new Array;
	if (profileList.length == 0)
	{
	  setErrorText('ERROR: Your account has not been assigned a proper barcode profile. Printing labels without a proper barcode profile may result in poor barcode quality.</br>Please contact Technical Support immediately.');
	  return false;
 	}
 	else
 		return true;

}

function setDefaultBCProfile()
{
	var defaultBarcodeProfileID = GetCookie('BarcodeProfileID');
	var barcodeProfileIndex = GetCookie('BarcodeProfileID');
	var profileList = document.getElementById('barcodeProfiles');

	if (checkBarcodeProfiles(profileList))
	{
		if (profileList != null)
		{
			 if (defaultBarcodeProfileID == null)
			 {
					profileList.selectedIndex = 0;
				}
				else
				{
				for (var i=0; i < profileList.options.length; i++)
				{
					if (profileList.options[i].value == defaultBarcodeProfileID)
					{
						profileList.selectedIndex = i;
						break;
					}
				}
			}
		}
	}
}


// ----------------------------------------------------------------------------
// displays any form validation errors either as a red box on the page itself or
// if the needed element isn't found then as an alert box
function displayErrors(errorMessages)
{
	// find the element that is supposed to hold form validation errors
	// if it isn't found then format the text for display via an alert
	// otherwise add the elements to an unordered list
	var msgElement = document.getElementById('validationMsg');

	var displayAlert = (msgElement ? false : true);

	// error text to be displayed to user
	var errorText = 'Please check the following fields and try again:\n';

	if (displayAlert) {
		for (var i=0; i<errorMessages.length; i++) {
			errorText += '- ' + errorMessages[i] + '\n';
		}
		alert(errorText);
	}
	else {
		// build list
		errorText += '<ul>';
		for (var i=0; i<errorMessages.length; i++) {
			if (errorMessages[i].length > 0)
				errorText += '<li>' + errorMessages[i] + '</li>';
		}
		errorText += '</ul>';

		// update the element
		msgElement.innerHTML = errorText;
		msgElement.style.display = 'block';
	}
}

function setErrorText(s)
{
	var e = document.getElementById('errorText');
	if (e != undefined)
	{
		if ((s == undefined) || (s.length == 0))
		{
			e.style.visibility = 'hidden';
			e.style.display = 'none';
			e.innerHTML = '';
		} else {
			e.style.visibility = 'visible';
			e.style.display = 'block';
			e.innerHTML = s;
		}

	}
}


