// orderGen.js
// (c) Copyright 2004 Carol Mattsson
// Picture validation comes from JavaScript Unleashed p. 536.
// IsInt and isEmptyField also come from JavaScript Unleashed
// IsValidEmail comes from JavaScript Visual Quickstart Guide

// Check to see if field is an integer, of any length

var detailMsg;								// global
var detailStr = new String;			// global for isValid()

function isInt(textObj) {
   for (var i = 0; i != textObj.value.length; i++) {
      aChar = textObj.value.substring(i, i+1)
      if (aChar < "0" || aChar > "9") {
			detailMsg = "found invalid char: " + aChar;
         return false;
      }
   }
   return true;
}

// Check to see if field is empty
function isEmptyField(textObj) {
   if (textObj.value.length == 0) return true;
   for (var i=0; i<textObj.value.length; ++i) {
      var ch = textObj.value.charAt(i);
      if (ch != ' ' && ch != '\t') return false;
   }
   return true;
}

//----------------------------------------------------------
// Perform picture validation
//---------------------------------------------------------
// Doesn't always work as you'd expect, e.g. isValid('*#') doesn't work

// Globals used by isValid
var DIGITS = "0123456789"
var UPPERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var LOWERS = "abcdefghijklmnopqrstuvwxyz"

function isValid(obj, picture, detailObj) {
	//alert ("checking " + obj.name);
   var status = true
   var isRepeat = false
   var pLen = picture.length
   var search = 0
   var validData = ""
   var picChar = ""
   var aChar = ""
   var newValue = obj.value
   var tLen = newValue.length
   var detailError = ""

   for (var i = 0, j = 0; (i != newValue.length)
                && (j != picture.length)
                && (status==true)
                ; i++) {
      picChar = picture.substring(j,j+1)
      if (picChar == "[") {
         validData = ""
         j++
         for (; j != picture.length; j++) {
            if (picture.substring(j,j+1) == "]") {
               break
            }
            validData = validData + picture.substring(j,j+1)
         }
         alert("validData: " + validData);
      } else if (picChar =="@") {       // Any character
         j++
         continue
      } else if (picChar == "?") {      // Any letter
         validData = UPPERS + LOWERS
      } else if (picChar == "#") {      // Any number
         validData = DIGITS;
      } else if (picChar == "$") {      // Money characters
         validData = DIGITS + "." + "-" + "+"
      } else if (picChar == "*") {
			alert("doing repeat");
         isRepeat = true
         j++
         i--
         continue
      } else {
         validData = picChar
      }
      aChar = newValue.substring(i,i+1)
      search = validData.indexOf(aChar)
      if (search == -1) {
         if (isRepeat) {
            isRepeat = false
            j++
            i--
            continue
         }
         status = false
         if (aChar == " ") {
            detailError = "A space is not allowed in position #"+(i+1)+". "
         } else {
            detailError = "The character, " + aChar +
              ", is not allowed in position #"+(i+1)+". "
         }
      } else {
         if (!isRepeat) {
            j++
         }
      }
   } // end for
   //Check length
   if (status == true && (j < picture.length || i < newValue.length)) {
      status = false
      detailError = "incorrect length"
      //can cause wildcard pictures to fail!!!
   }
   if (detailObj != null) {
      detailObj.value = detailError
   }
   return(status)
}

function isValidURL(url) {
	// It must start with http://
	// It must not end with /
	// It must have at least three /'s (http:// plus one more)
	// A dot is not required
	// I made this up.  Surely there's a better one on line.
	//alert ("length: " + url.value.length + " lastIndex: " + url.value.lastIndexOf("/"));
	var regex = new RegExp("^http://");
	if (!regex.test(url.value)) {
		detailMsg = "missing http:// at beginning";
		return false;
	} else if (url.value.indexOf("/", 7) < 8) {
		detailMsg = "not enough /'s";
		return false;
	} else if (url.value.lastIndexOf("/") == url.value.length - 1) {
		detailMsg = "/ can't be the last character";
		return false;
	}
	return true;
}
		

function isValidEmail(email) {
	invalidChars = " /:,;";
	for (i = 0; i < invalidChars.length; i++) {
		badChar = invalidChars.charAt(i);
		if (email.value.indexOf(badChar, 0) > -1) {
			detailMsg = "may not contain any of \"" + invalidChars + "\"";
			return false;
		}
	}
	atPos = email.value.indexOf("@", 1);
	if (atPos == -1) {
		detailMsg = "missing at sign (@)";
		return false;
	}
	if (email.value.indexOf("@", atPos+1) > -1) {
		detailMsg = "extra at sign (@)";
		return false;
	}
	periodPos = email.value.indexOf(".", atPos);
	if (periodPos == -1) {
		detailMsg = "missing period (.)";
		return false;
	}
	// Make sure suffix is long enough (at least two digits)
	if (periodPos + 3 > email.value.length) {
		detailMsg = "suffix too short (e.g. .com, .net, .ca)";
		return false;
	}
	return true;
}

function hasNo(field, badChars) {
	for (i = 0; i < badChars.length; i++) {
		badChar = badChars.charAt(i);
		if (field.value.indexOf(badChar, 0) > -1) {
			detailMsg = "may not contain any of \"" + badChars + "\"";
			return false;
		}
	}
	return true;
}

// Because isValid(obj, "[?#]*") doesn't work, no time to fix now

function hasOnly(field, goodChars) {
	//alert("hasOnly " + field.value);
	for (i = 0; i < field.value.length; i++) {
		fieldChar = field.value.charAt(i);
		if (goodChars.indexOf(fieldChar, 0) < 0) {
			detailMsg = "found invalid char: " + fieldChar;
			return false;
		}
	}
	return true;
}

/////////////////////////////////////////////////////////////////////////
// Form checkers - application specific
/////////////////////////////////////////////////////////////////////////

//-----------------------------------------------------------------
// checkVars
//
// Check all variables for the orderForm in orderGen.php

function checkVars(formObj, formMode) {

   //alert(formObj.whichSubmit);
   if (formObj.whichSubmit == "finish")
   	return true;
	if (formMode == "new") {
		
		if (formObj.whichSubmit == "fetch") {
			if (isEmptyField(formObj.orderID)) {
				alert("Please provide an order ID to fetch the contents of.");
				return false;
			}
			return true;
		}
		
		// Make sure all the fields required to start a new order are filled in
		// We check only for text fields.  Fields that are choices (select) always have a value.
		
		doContinue = false;
		if (isEmptyField(formObj.orderID))
			alert("Please provide an order ID (numbers, letters, dashes etc.).");
		else if (isEmptyField(formObj.custName))
			alert("Please provide the customer name.");
		else if (isEmptyField(formObj.addr1))
			alert("Please provide at least the first line of the customer address.");
		else if (isEmptyField(formObj.city))
			alert("Please provide the customer's city.");
		else if (isEmptyField(formObj.state))
			alert("Please provide a two-letter abbreviation\n" + "for the customer's state.");
		else if (isEmptyField(formObj.zip))
			alert("Please provide the customer zip code.");
		else if (isEmptyField(formObj.country))
			alert("Please provide the customer's country.");
		else if (isEmptyField(formObj.phone))
			alert("Please provide the customer's phone number.");
		else if (isEmptyField(formObj.email))
			alert("Please provide the customer's email address.");
		else {
			//alert("All " + formMode + " mode inputs are provided.");
			doContinue = true;
		}
		if (!doContinue) {
			return false;
		}
		// detailMsg is a global.  In isValid, we pass it to be filled in.
		// other functions set it as a global.
		if (!hasOnly(formObj.orderID, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-."))
			alert("Order ID can have only alphanumeric plus\ndash and dot (" + detailMsg + ")");
		else if (!isValid(formObj.state, "??", detailStr))
			alert("State must be a two-letter abbreviation\n(" + detailStr.value + ")");
		else if (formObj.country.value == "US" && !hasOnly(formObj.zip, "1234567890-"))
			alert("US zip code can contain only numbers and -\n(" + detailStr.value + ")");
		else if (formObj.country.value == "US" && formObj.zip.value.length < 5)
			alert("US zip code must have at least five digits");
		else if (!isValid(formObj.country, "??", detailStr))
			alert("Country must be a two-letter abbreviation\n(" + detailStr.value + ")");
		//else if (!isValid(formObj.phone, "(###)[ ]*###-####", detailStr))
		else if (!hasOnly(formObj.phone, "1234567890-+x(). "))
			alert("Phone must contain only numbers and\nchars \"-+x(). \"\n(" + detailMsg + ")");
		else if (formObj.phone.value.length < 7)
			alert("Phone number must have at least seven digits");
		else if (!isValidEmail(formObj.email))
			alert("Email address has bad syntax (" + detailMsg + ")");
		else if (!hasNo(formObj.custMsg, "\"")) {
			alert("Customer message must not contain double quotes (\")\n(" + detailMsg + ")");
		} else {
			//alert("All " + formMode + " mode inputs have valid syntax.");
			return true;
		}			
		return false;

	} else if (formMode == "addItem") {

		// Make sure all the fields required to add an item are filled in

		if (isEmptyField(formObj.orderID))
			alert("Please provide the order ID.");
		else if (isEmptyField(formObj.partNum) && isEmptyField(formObj.xPartNum))
			alert("Please provide the item part number.");
		else if (isEmptyField(formObj.imageURL))
			alert("Please provide an image URL.");
		else if (isEmptyField(formObj.quantity))
			alert("Please provide the quantity of items.");
		else if (!isValidURL(formObj.imageURL)) {
			alert("Image URL must be of the form\nhttp://hostname.com/folder/foo.jpg\n(" + detailMsg + ")");
		}
		else if (!isInt(formObj.quantity)) {
			alert("Quantity must be a number\n(" + detailMsg + ")");
		}
		else {
			//alert("All " + formMode + " mode inputs have valid syntax.");
			return true;
		}
		return false;

	} else {

		alert("Hmmm, I don't understand formMode: " + formMode + ".\nPlease ignore the error for now but remember to tell your\nweb developer about it.");

		return true;
	}
}

// getSelectValue
// use this on a button's "onClick" method, to get the value
// of the current selection in a selection box

function getSelectValue(selectObj) {
   return selectObj.options[selectObj.selectedIndex].value
}

