// JavaScript Document
//File:  hwk1js.js
//Author:  Jennifer Brister
var JB={};
JB.path = "document.lovelyForm.";//to access the elements on the form for shorter code (not used often, though)

//Define validation object to perform various form validations
//Define an array to hold validations
//Customize the array to match the form to validate 
//0: the form element to validate
//1: the validation to run
//2: the form element to send the error message to

JB.validations = new Array();

JB.validations[0]=["document.lovelyForm.lovelyItems", "isChecked","document.lovelyForm.purchError"];//item checked and qty >=1
JB.validations[1]=["document.lovelyForm.fname", "notBlank","document.lovelyForm.fnameError"];//checks whether the field is blank
JB.validations[2]=["document.lovelyForm.lname", "notBlank", "document.lovelyForm.lnameError"];
JB.validations[3]=["document.lovelyForm.address", "notBlank", "document.lovelyForm.addressError"];
JB.validations[4]=["document.lovelyForm.city", "notBlank","document.lovelyForm.cityError"];
JB.validations[5]=["document.lovelyForm.state", "isSelected","document.lovelyForm.stateError"];
JB.validations[6]=["document.lovelyForm.phone", "isNumber","document.lovelyForm.phoneError"];//checks whether the characters in a field are all numbers
JB.validations[7]=["document.lovelyForm.email", "validEmail", "document.lovelyForm.emailError"];//checks whether and e-mail address is valid
JB.validations[8]=["document.lovelyForm.shipping", "isSelected", "document.lovelyForm.shipError"];
JB.validations[9]=["document.lovelyForm.ccType", "isSelected", "document.lovelyForm.ccTypeError"];
JB.validations[10]=["document.lovelyForm.ccNum", "isValidCC", "document.lovelyForm.ccNumError"];//check whether the characters in a field correspond to a valid credit card


//Subtotal Calculation and Submit Buttons Disabled until form validation is true
window.onload = function()
{
	document.lovelyForm.calcTot.disabled = true;
	document.lovelyForm.submitBtn.disable = true;
	//calcDis.disabled = true;
	//submitDis = eval(submitDisable);
	//submitDis.disable = true;
}
//FUNCTIONS
//------------------------

function isEmpty(s){ //checks whether a field is empty or contains whitespaces only
	if (s == null || s.length == 0)
	{return true;}//the string is empty
	return !/\S/.test(s);//string contains at least not a non-whitespace character ==> true means string is empty
}

//------------------------

function isEmail (field) { //check is field contains a valid e-mail address of the form "string@string"
	var s = field.value
	if (isEmpty(s))
	{
		//alert("Please enter a valid email address");
		field.className = 'lovelyError';
		field.focus();
		return false;
	}
	if (/[^@]+@+\w+/.test(s)) 
	{return true;} //test string@string
	field.className = 'lovelyError';
	//alert("Please enter valid e-mail address, for example x@y.com");
	return false;
}
//------------------------

function isInteger (field) //validate the only numbers are in the field
{ 
	var s = field.value;
	//alert("phone2 is " + s);
	if (isEmpty(s))
	{
		//alert("Field cannot be empty");
		field.className = 'lovelyError';
		field.focus();
		return false;
	}
	if (!(/^-?\d+$/.test(s)))
	{
		//alert("Please enter digits only");
		field.className = 'lovelyError';
		field.focus();
		return false;
	}
	return true;
}

//------------------------

function checkBoxSel (field, errorMsg)// Checking if at least one checkbos is selected.
{	
	var k, j;
	var s = "qty";
	var flag = false;	
	//alert(field.length);
	for (k = 0; k<field.length; k++)
	{
		if (field[k].checked)
		{
			flag = true;
			j=k+1;
			//alert(j);
			n = s + eval(j);
			m = JB.path + n;//Getting the qty associated with the checkbox
			//alert(m);
			sField = eval(m);
			//sfield.className = 'lovelyInput';
			//alert(sField.value);
			if (!isInteger(sField))
			{
				//alert("Please enter a quantity > 0");
				errorMsg.className = 'errorMsgShow';
				field.className = 'lovelyError';
				sField.focus();
				return false;
			}	
			if (sField.value < 1)
			{
				//alert("Please purchase 1 if more of this item");
				errorMsg.className = 'errorMsgShow';
				field.className = 'lovelyError';
				sField.focus();
				return false;
			}
			if (sField.value >=1)
			{
				errorMsg.className = 'errorMsghide';
				sField.className = 'lovelyInput';
			}
		}
	}
	
	if (flag == false)
	{
		//alert("Please select at least one Lovely Item to purchase");
		errorMsg.className = 'errorMsgShow';
		field.className = 'lovelyError';
		field.focus();
		return false;
	}
	
	return flag; 
}
//------------------------
// isSelected

function isSelected (field)
{
	if (field.options.selectedIndex == 0)
	{
		//alert("Please select an option from the menu");
		errorMsg.className = 'errorMsgShow';
		field.className = 'lovelyError';
		field.focus();
		return false;
	}
	return true;
}


/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: David Leppek :: https://www.azcode.com/Mod10

Basically, the alorithum takes each digit, from right to left and muliplies each second
digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
the multiple are then added together for a new number (1 + 2 = 3). You then add up the 
string of numbers, both unaltered and new values and get a total sum. This sum is then
divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
name Mod 10 or Modulus 10. */
function Mod10(ccNumb) { // v2.0
var valid = "0123456789"  // Valid digits in a credit card number
var len = ccNumb.length;  // The length of the submitted cc number
var iCCN = parseInt(ccNumb);  // integer of ccNumb
var sCCN = ccNumb.toString();  // string of ccNumb
sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
var iTotal = 0;  // integer total set at zero
var bNum = true;  // by default assume it is a number
var bResult = false;  // by default assume it is NOT a valid cc
var temp;  // temp variable for parsing string
var calc;  // used for calculation of each digit

// Determine if the ccNumb is in fact all numbers
for (var j=0; j<len; j++) {
  temp = "" + sCCN.substring(j, j+1);
  if (valid.indexOf(temp) == "-1"){bNum = false;}
}

// if it is NOT a number, you can either alert to the fact, or just pass a failure
if(!bNum){
  /*alert("Not a Number");*/bResult = false;
}

// Determine if it is the proper length 
if((len == 0)&&(bResult)){  // nothing, field is blank AND passed above # check
  bResult = false;
} else{  // ccNumb is a number and the proper length - let's see if it is a valid card number
  if(len >= 15){  // 15 or 16 for Amex or V/MC
    for(var i=len;i>0;i--){  // LOOP throught the digits of the card
      calc = parseInt(iCCN) % 10;  // right most digit
      calc = parseInt(calc);  // assure it is an integer
      iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
      i--;  // decrement the count - move to the next digit in the card
      iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
      calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
      calc = calc *2;                                 // multiply the digit by two
      // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
      // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
      switch(calc){
        case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
        case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
        case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
        case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
        case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
        default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
      }                                               
    iCCN = iCCN / 10;  // subtracts right most digit from ccNum
    iTotal += calc;  // running total of the card number as we loop
  }  // END OF LOOP
  if ((iTotal%10)==0){  // check to see if the sum Mod 10 is zero
    bResult = true;  // This IS (or could be) a valid credit card number.
  } else {
    bResult = false;  // This could NOT be a valid credit card number
    }
  }
}
// change alert to on-page display or other indication as needed.
if(bResult) {
  //alert("This IS a valid Credit Card Number!");
}
if(!bResult){
  //alert("This is NOT a valid Credit Card Number!");
}
  return bResult; // Return the results
}
//---------------------------------


function JBvalidate ()
{
	var i, check2Make, field /*erField*/;
	for (i = 0; i<JB.validations.length; i++)
	{
		field = eval(JB.validations[i][0]);//field to check
		check2Make = JB.validations[i][1];
		errorMsg = eval(JB.validations[i][2]);
		//erField = JB.validations{i][2];
		switch (check2Make)
		{
			case 'notBlank': if (isEmpty(field.value))
			{
				//alert("Field cannot be empty");
				errorMsg.className = 'errorMsgShow';
				field.className = 'lovelyError';
				field.focus();
			    return false;
			}
			errorMsg.className = 'errorMsghide';
			field.className = 'lovelyInput';
			break;
			case 'validEmail': if (!isEmail(field))
			{
				errorMsg.className = 'errorMsgShow';
				return false;
			}
			errorMsg.className = 'errorMsghide';
			field.className = 'lovelyInput';
			break;
			case 'isNumber': if (!isInteger(field))
			{
				errorMsg.className = 'errorMsgShow';
				return false;
			}
			errorMsg.className = 'errorMsghide';
			field.className = 'lovelyInput';
			break;
			case 'isChecked': if (!checkBoxSel(field, errorMsg))
			{
				errorMsg.className = 'errorMsgShow';
				return false;
			}
			errorMsg.className = 'errorMsghide';
			field.className = 'lovelyInput';
			break;
			case 'isSelected': if(!isSelected(field))
			{
				errorMsg.className = 'errorMsgShow';
				return false;
			}
			errorMsg.className = 'errorMsghide';
			field.className = 'lovelyInput';
			break;
			case 'isValidCC': if (!Mod10(field.value))
			{
				errorMsg.className = 'errorMsgShow'
				field.className = 'lovelyError';
				field.focus();
				return false;
			}
			errorMsg.className = 'errorMsghide';
			field.className = 'lovelyInput';
		}
	}
	document.lovelyForm.calcTot.disabled = false;
	return true;				
}
//-------------------------------------
//  Run Calculations
//  Field to be included in calculations:  price and quantity
Item = new Array();
Item[0]=[1.5, JB.path + "qty1", JB.path + "subTot1"];
Item[1]=[2.25, JB.path + "qty2", JB.path + "subTot2"];
Item[2]=[4.45, JB.path + "qty3", JB.path + "subTot3"];

//box = eval(JB.path + "lovelyItems");
ship = JB.path + "shipping";
finTot = JB.path + "shipTot";


function calcTotal ()
{
	var i;
	var gtot = 0;
	
	for(i=0; i<Item.length; i++)
	{
		{
		//alert("i = " + i);
		price = Item[i][0];
		//alert("price " + i +" = " + price);
		qty =  eval(Item[i][1]);
		fqty = parseFloat(qty.value);
		if (isNaN(fqty))
		{
			fqty = 0;
		}
		//alert("qty " + i + " = " + fqty);
		subtot = price*fqty;
		//alert("subtot = " + subtot);
		tfield = eval(Item[i][2]);
		tfield.value = subtot;
		gtot = gtot + subtot;
		//alert("gtot = " + gtot);
		}
	}
	shipSel = eval(ship);
	switch(shipSel.options.selectedIndex)
	{
		case 1:
		{
			scost = 3.50;
		}
		break;
		case 2:
		{
			scost = 5.00;
		}
		break;
		case 3:
		{
			scost = 7.50;
		}
	}
		
	//alert("shipping cost = " + scost);
	gtot = gtot + scost;
	ftot = eval(finTot);
	ftot.value = gtot;
	document.lovelyForm.submitBtn.disabled = false;
	return true;
}

				   
				   

