//=================================================================================================
//Project:			Cake N Crumbs web site instructor ordering validations
//Author:			Doug Hamilton
//Created/Revised:	2005.10.22
//-------------------------------------------------------------------------------------------------
//Revision History
//Date:				Initials:		Notes:
//-------------------------------------------------------------------------------------------------
//2005.10.22		DOH				changed around the order of the formating in various functions
//									due to ParseFloat function stopping at first comma in values
//
//=================================================================================================
//
//=================================================================================================
function Len(strInput)
{
	return String(strInput).length;
}
//=================================================================================================
//
//=================================================================================================
function Left(strInput, intNumOfChars)
{
	if (intNumOfChars <= 0)
		return "";
	else if (intNumOfChars > String(strInput).length)
		return strInput;               
	else
		return String(strInput).substring(0,intNumOfChars);
}
//=================================================================================================
//
//=================================================================================================
function Right(strInput, intNumOfChars)
{
	if (intNumOfChars <= 0)
		return "";
	else if (intNumOfChars > String(strInput).length)
		return strInput;
	else
	{
		var iLen = String(strInput).length;
		return String(strInput).substring(iLen, iLen - intNumOfChars);
	}
}
//=================================================================================================
//
//=================================================================================================
function Mid(strInput, intStartChar, intNumOfChars)
{
    if (intStartChar < 0 || intNumOfChars < 0) return "";

    var iEnd, iLen = String(strInput).length;
    if (intStartChar + intNumOfChars > iLen)
            iEnd = iLen;
    else
            iEnd = start + intNumOfChars;

    return String(strInput).substring(intStartChar,iEnd);
}
//=================================================================================================
//
//=================================================================================================
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 LTrim(str)
/***
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim

        RETVAL: An LTrimmed string!
***/
{
        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;
}
//=================================================================================================
//
//=================================================================================================
function RTrim(str)
/***
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

        RETVAL: An RTrimmed string!
***/
{
        // 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;
}
//=================================================================================================
//
//=================================================================================================
function DisplayFormElements()
{
	var intIter;
	var intNumElements = document.forms[0].length;
	var strMessage;

	for(intIter=0; intIter<=intNumElements; intIter++)
	{
		strMessage = "Element #: " + intIter + " of " + intNumElements;
		strMessage = strMessage + "\n\nElement Name: " + document.forms[0].elements[intIter].name;
		strMessage = strMessage + "\n\nElement Value: " + document.forms[0].elements[intIter].value;
		
		alert(strMessage);
	}
}

//=================================================================================================
// This function checks to see if the string passed is empty
//================================================================================================='

function isEmpty(str)
{
	var emptystatus;
	emptystatus = false;
	if (str == "")
		emptystatus = true;
	return (emptystatus);
}		

//=================================================================================================
// This function checks to see if a radio button or checkbox is checked or not
//================================================================================================='

function isChecked(object) {
    if (object.checked) 
		return true;
    else 
		return false;
}

//=================================================================================================
// This function strips leading zeros
//=================================================================================================

function stripZeros(num)
{
	var num,newTerm
	while (num.charAt(0) == "0") 
	{
		newTerm = num.substring(1, num.length);
		num = newTerm;
	}
	if (num == "")
	num = "0";
	return num;
}


//=================================================================================================
//
//=================================================================================================

function SetFocus()
{
	if (document.frmLogin)
	{
		var objText =  document.frmLogin.cncemployeeid;
		objText.focus();
		objText.select();
	}
}

//=================================================================================================
//
//=================================================================================================

function ValidateFormLogin(theForm)
{
  if (theForm.cncemployeeid.value == "")
  {
    alert("Please enter a valid Intructor ID.");
    theForm.cncemployeeid.focus();
    return (false);
  }

  if (theForm.password.value == "")
  {
    alert("Please enter a valid Password.");
    theForm.password.focus();
    return (false);
  }
}

//=================================================================================================
//
//=================================================================================================

function ValidateFormRegister(theForm)
{
	if (theForm.EmailAddress.value == "")
	{
		alert("Please enter a valid Email Address.");
		theForm.EmailAddress.focus();
		return (false);
	}
	if (theForm.Password.value == "")
	{
		alert("Please enter a valid Password.");
	    theForm.Password.focus();
		return (false);
	}
	if (theForm.Password2.value == "")
	{
	    alert("Please enter a valid Password2.");
	    theForm.Password2.focus();
	    return (false);
	}
	if (theForm.Password.value == theForm.Password2.value)
	{
	}
	else
	{
		alert("Passwords do not match, please re-enter.");
		theForm.Password.focus();
	}
	if (theForm.FirstName.value == "")
	{
	    alert("Please enter a valid FirstName.");
	    theForm.FirstName.focus();
	    return (false);
	}
	if (theForm.LastName.value == "")
	{
	    alert("Please enter a valid LastName.");
	    theForm.LastName.focus();
	    return (false);
	}
	if (theForm.address1.value == "")
	{
	    alert("Please enter a valid address1.");
	    theForm.address1.focus();
	    return (false);
	}
	if (theForm.city.value == "")
	{
	    alert("Please enter a valid city.");
	    theForm.city.focus();
	    return (false);
	}
	if (theForm.state.value == "")
	{
	    alert("Please enter a valid state.");
	    theForm.state.focus();
	    return (false);
	}
	if (theForm.zipcode.value == "")
	{
	    alert("Please enter a valid zipcode.");
	    theForm.zipcode.focus();
	    return (false);
	}
	if (theForm.homephone.value == "")
	{
	    alert("Please enter a valid homephone.");
	    theForm.homephone.focus();
	    return (false);
	}
//---------- Validate the tax rate entered on the regiter screen
	if (theForm.taxrate.value == "")
	{
	    alert("Please enter a valid taxrate as X.XX.");
	    theForm.taxrate.focus();
	    return (false);
	}
	else
	{
		if ((theForm.taxrate.value < 3) || (theForm.taxrate.value > 10))
		{
		    alert("Tax rate must be between 3% and 10%.");
		    theForm.taxrate.focus();
		    return (false);
		}
	}
//-----------------------------------------------------------------
	if (theForm.county.value == "")
	{
	    alert("Please enter a valid taxing county.");
	    theForm.county.focus();
	    return (false);
	}
}
//=================================================================================================
// This function sets the price code for the item selected for the host/hostess order
//=================================================================================================
function selectcde(SelectedItem,SelectedText)
{
	document.secureorder.code.value = SelectedItem;
	if (!isEmpty(document.secureorder.ncode.value))
	{
		var strfieldname = "document.secureorder.qty" + SelectedText;
		document.secureorder.ncode.value = eval(strfieldname).value + '-' + document.secureorder.code.value + '-' + SelectedText;
	}
	else { document.secureorder.code.value = SelectedItem; }
}

//=================================================================================================
//This function assigns an ItemID, Price Code and the quantity to the item selected
//=================================================================================================

function selecthostorder(SelectedItem,SelectedText)
{
	var strfieldname = "document.secureorder.qty" + SelectedText;
	eval(strfieldname).value = SelectedItem;
	document.secureorder.hidqty.value = eval(strfieldname).value;
//	alert(eval(strfieldname).value);
	if (isEmpty(document.secureorder.code.value))
	{
		eval(strfieldname).value = "";
		document.secureorder.hidqty.value = "";
		alert("Please select a Code!");
		var strFieldname = "document.secureorder.ChargeType" + SelectedText;
		eval(strFieldname).focus();
	}
	document.secureorder.ncode.value = SelectedItem + '-'+ document.secureorder.code.value + '-' + SelectedText;
	return;
}

//=================================================================================================
//This function assigns an ItemID, Price Code - N and the quantity to the item selected
//=================================================================================================

function selectquantity(inForm,SelectedItem,SelectedText)
{
	var strfieldname = "document.secureorder.qty" + SelectedText;
	eval(strfieldname).value = SelectedItem;
	document.secureorder.hidqty.value = eval(strfieldname).value;
	document.secureorder.ncode.value = SelectedItem + '-N' + SelectedText;
}

//=================================================================================================
// This is a form validation function used by the first order profile form in Class Supplies 
//=================================================================================================

function validateprofile1()
{
	var error = 0;
	if (document.orderprofile.classtype.value == "outside")
	{
		return true;
	}

    var classtype = document.orderprofile.classtype.value;
	if (isEmpty(classtype))
    {  
         alert("Please select a class type!");
		 error=1;
		 document.orderprofile.classtype.focus();
         return false;
    }
	
	
    var classno = document.orderprofile.classno.value;
	if (isEmpty(classno))
	{
	 alert("Please enter a class number!");
	 error = 1;
	 document.orderprofile.classno.focus();
	 return false;
	}

	var cdate = document.orderprofile.classdate.value;
	if (isEmpty(cdate))
	{
	 alert("Please enter a class date!");
	 error = 1;
	 document.orderprofile.classdate.focus();
	 return false;
	}
	else
	{
	 	if (isValidDate(cdate,'/') == false)
	 	{
	    error = 1;
		document.orderprofile.classdate.focus();
		return false;	 
		}
	}
    
	var hostnme = document.orderprofile.hostnme.value;
	if (isEmpty(hostnme))
	{
	 alert("Please enter Host/Hostess's name!");
	 error = 1;
	 document.orderprofile.hostnme.focus();
	 return false;
	}
	
	var hostphone = document.orderprofile.hostphone.value;
	if (isEmpty(hostphone))
	{
	 alert("Please enter Host/Hostess's phone number!");
	 error = 1;
	 document.orderprofile.hostphone.focus();
	 return false;
	}
	else
	{
	 if (isValidPhone(hostphone,'-') == false)
	 	{
	    error = 1;
		document.orderprofile.hostphone.focus();
		return false;	 
		}
	}
	
	var hostaddr = document.orderprofile.hostaddr.value;
	if (isEmpty(hostaddr))
	{
	 alert("Please enter Host/Hostess's address!");
	 error = 1;
	 document.orderprofile.hostaddr.focus();
	 return false;
	}

	var city = document.orderprofile.city.value;
	if (isEmpty(city))
	{
	 alert("Please enter a city!");
	 error = 1;
	 document.orderprofile.city.focus();
	 return false;
	}

	var county = document.orderprofile.county.value;
	if (isEmpty(county))
	{
	 alert("Please enter a county!");
	 error = 1;
	 document.orderprofile.county.focus();
	 return false;
	}
	
	var state = document.orderprofile.state.value;
	if (isEmpty(state))
	{
	 alert("Please enter a state!");
	 error = 1;
	 document.orderprofile.state.focus();
	 return false;
	}
	
	var zip = document.orderprofile.zip.value;
	if (isEmpty(zip))
	{
	 alert("Please enter a zip!");
	 document.orderprofile.zip.focus();
	 error = 1;
	 return false;
	}

	
}

//=================================================================================================
// This is a points calculating function used by the Class Supplies Order Details page after View Cart
//=================================================================================================

function computepoints()
{
    var total; 
    var selectedItem = document.orderdetails.guestsales.selectedIndex;
        
    thankyou = stripZeros(document.orderdetails.thankyou.value);
    if (document.orderdetails.ingredients.value == "" )
    { ingredients = 0; }
	else
	{ ingredients = stripZeros(document.orderdetails.ingredients.value);}
    
    guestreceipts = stripZeros(document.orderdetails.guestreceipts.value);
    bookings = stripZeros(document.orderdetails.bookings.value);
    classclosing = stripZeros(document.orderdetails.classclosing.value);
    guestsales = stripZeros(document.orderdetails.guestsales.value);
       
	total = parseInt(thankyou) + parseInt(ingredients) + parseInt(guestreceipts) + parseInt(bookings) + parseInt(classclosing) + parseInt(guestsales);		    
	document.orderdetails.total.value = total;
    
}


//=================================================================================================
// This function recalculates the total points after the user has selected an option from the
// Extra Points drop down
//=================================================================================================

function computeextrapoints(object)
{
	if (document.orderdetails.orders.value < 5)
	{
		extrapts = 0;
	}
    else
    {
 		if (object == 0 || object == 1 || object == 5 || object == 6)
			{extrapts = 0;}
		if (object == 2)
			{extrapts = 150;}
		if (object == 3)
			{extrapts = 350;}
		if (object == 4)
			{extrapts = 550;}
		
	}
	
    thankyou = document.orderdetails.thankyou.value;
    ingredients = document.orderdetails.ingredients.value;
    
    if (document.orderdetails.orders.value < 15)
	{
		guestreceipts = 0;
	}
    else
    {
		guestreceipts = document.orderdetails.guestreceipts.value;
    }
        
    bookings = document.orderdetails.bookings.value;
    classclosing = document.orderdetails.classclosing.value;
    guestsales = document.orderdetails.guestsales.value;  

    var total = parseInt(thankyou) + parseInt(ingredients) + parseInt(guestreceipts) + parseInt(bookings) + parseInt(classclosing) + parseInt(guestsales) + parseInt(extrapts);		    
	document.orderdetails.total.value = total;
	document.orderdetails.halfprice.value = 0;
	if (object == 1)
	{document.orderdetails.halfprice.value = 1;}
	if (object == 5)
	{document.orderdetails.halfprice.value = 2;}
	if (object == 6)
	{document.orderdetails.halfprice.value = 3;}
	
}

//=================================================================================================
// This function checks if date passed is in valid dd/mm/yyyy format
//=================================================================================================

function isValidDate (myDate, sep) 
{
    if (myDate.length == 10) {
        if (myDate.substring(2,3) == sep && myDate.substring(5,6) == sep) {
            var date  = myDate.substring(0,2);
            var month = myDate.substring(3,5);
            var year  = myDate.substring(6,10);
			
            if (date == '00' || month == '00' || year =='0000')
            {
              alert('Invalid date');
              return false;
            }
            
            var test = date + month + year;
            
            if (test.search(/^[0-9]*$/) != -1)
			{	return true;}
			else
			{
				alert('Invalid date');
				return false; 
            }
           
        }
        else {
            alert('Invalid date separators');
            return false;
        }
    }
    else {
        alert('Invalid date length');
        return false;
    }
}

//=================================================================================================
// This function checks if instructor's phone passed is in valid 262-650-6500 format
//=================================================================================================

function isValidPhone (myPhone, sep) 
{
    if (myPhone.length == 12) {
        if (myPhone.substring(3,4) == sep && myPhone.substring(7,8) == sep) {
            var date  = myPhone.substring(0,3);
            var month = myPhone.substring(4,7);
            var year  = myPhone.substring(8,12);
			
            if (date == '00' || month == '00' || year =='0000')
            {
              alert('Invalid Phone Number.');
              return false;
            }
            
            var test = date + month + year;
            
            if (test.search(/^[0-9]*$/) != -1)
			{	return true;}
			else
			{
				alert('Please enter phone number in the following format: 262-650-6500.');
				return false; 
            }
           
        }
        else {
            alert('Please enter phone number in the following format: 262-650-6500.');
            return false;
        }
    }
    else {
        alert('Please enter phone number in the following format: 262-650-6500.');
        return false;
    }
}

//=================================================================================================
// This is a validate function called by Order Details page to make sure user			
//   always enter a tax rate and number of orders before submitting the form and that
//   all the points entered have valid values.	
//=================================================================================================

function validateorderdetails() {
	var error=0;
    if (document.orderdetails.orders.value < 5 && document.orderdetails.extrapts.value != '0')
	{
		document.orderdetails.extrapts.value=0;
		computepoints(extrapts);
	}
	
	var strtaxrate = document.orderdetails.taxrate.value;
	if ((isEmpty(strtaxrate)) || (Trim(strtaxrate) == ""))
	{
	 alert("Please enter a tax rate!");
	 error=1;
	 document.orderdetails.taxrate.focus();
	 return false;
	}
	else
	{
		if (isNaN(document.orderdetails.taxrate.value))
		{
		 alert("Please enter a valid tax rate!");
		 error=1;
		 document.orderdetails.taxrate.focus();
		 return false;
		}
		else
		{
			if (document.orderdetails.taxrate.value < 1)
			{
				alert("Please enter a valid tax rate!");
				error=1;
				document.orderdetails.taxrate.focus();
				return false;
			}
		}
	}
	
	if (isEmpty(document.orderdetails.orders.value))
	{
	 alert("Please enter the number of orders!");
	 error=1;
	 document.orderdetails.orders.focus();
	 return false;
	}
	
	if (isNaN(document.orderdetails.orders.value))
	{
	 alert("Please enter a valid number of orders!");
	 error=1;
	 document.orderdetails.orders.focus();
	 return false;
	}
	
//	if ((document.orderdetails.orders.value < 5 && document.orderdetails.total.value != 0) || 
//	    (document.orderdetails.totalsales.value < 150 && document.orderdetails.total.value != 0))
	if (document.orderdetails.totalsales.value < 150 || document.orderdetails.orders.value < 5 )
	{
		alert("You must have at least 5 orders and a total sales of $150 to continue!\nPlease go back to the main menu and enter as an 'OUTSIDE ORDER'.");
//		document.orderdetails.thankyou.value = 0;
//		document.orderdetails.ingredients.value = 0;
//		document.orderdetails.guestreceipts.value = 0;
//		document.orderdetails.bookings.value = 0;
//		document.orderdetails.classclosing.value = 0;
//		document.orderdetails.total.value = 0;
		return false;
	}
	
	if (isNaN(document.orderdetails.thankyou.value))
	{
	 alert("Invalid thank you points!");
	 error=1;
	 document.orderdetails.thankyou.focus();
	 return false;
	}
	else
	{
		if (document.orderdetails.thankyou.value==0 || document.orderdetails.thankyou.value==200)
		{
//			return true;
		}
		else
		{
			 alert("Invalid thank you points!");
			 error=1;
			 document.orderdetails.thankyou.focus();
			 return false;
		}
	}
	
	if (isNaN(document.orderdetails.ingredients.value))
	{
	 alert("Invalid ingredients points!");
	 error=1;
	 document.orderdetails.ingredients.focus();
	 return false;
	}
	else
	{
		if (document.orderdetails.ingredients.value==0 || document.orderdetails.ingredients.value==500)
		{
//			return true;
		}
		else
		{
			 alert("Invalid ingredient points!");
			 error=1;
			 document.orderdetails.ingredients.focus();
			 return false;
		}
	}	    
    if (isNaN(document.orderdetails.guestreceipts.value))
	{
	 alert("Invalid guest receipts points!");
	 error=1;
	 document.orderdetails.questreceipts.focus();
	 return false;
	}
	else
	{
			if (document.orderdetails.guestreceipts.value==0 || document.orderdetails.guestreceipts.value==100)
		{
//			return true;
		}
		else
		{
			 alert("Invalid Guest Receipt points!");
			 error=1;
			 document.orderdetails.guestreceipts.focus();
			 return false;
		}
	}
	
	if (isNaN(document.orderdetails.bookings.value))
	{
	 alert("Invalid bookings points!");
	 error=1;
	 document.orderdetails.bookings.focus();
	 return false;
	}
	
	if (isNaN(document.orderdetails.classclosing.value))
	{
	 alert("Invalid Class Closing points!");
	 error=1;
	 document.orderdetails.classclosing.focus();
	 return false;
	}
	else
	{
		if (document.orderdetails.classclosing.value==0 || document.orderdetails.classclosing.value==100)
		{
//			return true;
		}
		else
		{
			 alert("Invalid Class Closing points!");
			 error=1;
			 document.orderdetails.classclosing.focus();
			 return false;
		}
	}
	strlist = document.orderdetails.bookingslist.value;
	bookingstr = document.orderdetails.bookings.value;
	
	if ((bookingstr > 0) && (isEmpty(strlist)))
	{
		alert('Please enter your list of bookings.');
	    error=1;
	 	document.orderdetails.bookingslist.focus();
	 	return false;
	}
	
	if ((!isEmpty(strlist)) && (!isEmpty(bookingstr)))
	{	
		booking = bookingstr.substring(0,1);
	
		var guestarray = strlist.split(",");
		for (var i=0; i <= booking; i++)
		{
		    blist = guestarray[booking - 1];
		}
				
		if (blist == null)
		{
		alert('The number of bookings must match your class bookings points.');
		error=1;
		document.orderdetails.bookings.focus();
		return false;
		}
	}
	
	if (isNaN(document.orderdetails.classclosing.value))
	{
	 alert("Invalid class closing points!");
	 error=1;
	 document.orderdetails.classclosing.focus();
	 return false;
	}
	
	if ((document.orderdetails.totalsales.value >= 299.99) && (document.orderdetails.extrapts.value == 0) && document.orderdetails.orders.value > 4)
	{
	 alert("Please select 1/2 price or points!");
	 error=1;
	 document.orderdetails.extrapts.focus();
	 return false;
	}
	

}

//=================================================================================================
// This is a validate function called by Order Details page to make sure user			
//   always enter a tax rate and number of orders before submitting the form and that
//   all the points entered have valid values.	
//=================================================================================================

function validateorderdetailsshort() 
{
	var error=0;
	var strtaxrate = document.orderdetails.taxrate.value;
	if ((isEmpty(strtaxrate)) || (Trim(strtaxrate) == ""))
	{
	 alert("Please enter a tax rate!");
	 error=1;
	 document.orderdetails.taxrate.focus();
	 return false;
	}
	else
	{
		if (isNaN(document.orderdetails.taxrate.value))
		{
		 alert("Please enter a valid tax rate!");
		 error=1;
		 document.orderdetails.taxrate.focus();
		 return false;
		}
		else
		{
			if (document.orderdetails.taxrate.value < 1)
			{
				alert("Please enter a valid tax rate!");
				error=1;
				document.orderdetails.taxrate.focus();
				return false;
			}
		}
	}
	
	if (isEmpty(document.orderdetails.orders.value))
	{
	 alert("Please enter the number of orders!");
	 error=1;
	 document.orderdetails.orders.focus();
	 return false;
	}
	
	if (isNaN(document.orderdetails.orders.value))
	{
	 alert("Please enter a valid number of orders!");
	 error=1;
	 document.orderdetails.orders.focus();
	 return false;
	}
}	

//=================================================================================================
// This function checks for duplicate class no at the Order Profile table
//=================================================================================================

function CheckDuplicateClassNo()
  {
	 a = document.orderprofile.classno.value;
	 self.location.href = 'orderprofile.asp?action=check'+'&class='+a;
  }

//=================================================================================================
// This function validate the quantity field on secureorder.asp
//=================================================================================================

//function validateqty(myform)
//{
//  if (isEmpty(myform.qty.value))
//  {
//	alert("Please enter an Item quantity.");
//	return false;
//  }
//  qty = myform.qty.value;
//  //qty = parseInt(qty);
//    
//  if (isNaN(qty))
//  {
//	alert("Please enter a valid Item quantity.");
//	return false;
//  }
//  else
//  { return true; }
//}

//=================================================================================================
// This function makes sure no extra points are given if the total guest sales order is less than 5
//=================================================================================================

function checkExtraPoints()
{
	if (document.orderdetails.orders.value < 5)
	{
		alert("Five or more guest receipts are necessary for these host/hostess values!")
		document.orderdetails.extrapts.value=0;
	}
	else
	{
		extrapts = document.orderdetails.extrapts.value;
		computepoints(extrapts);
	}
}

//=================================================================================================
// This function makes sure no 15 Guests Receipts points are given if the total guest sales 
// order is less than 15
//=================================================================================================

function CheckGuestReceipts()
{

	if ((document.orderdetails.orders.value < 15) && (document.orderdetails.guestreceipts.value > 0))
	{
		alert("You must at least 15 guest receipts to earn these points!")
		document.orderdetails.guestreceipts.value=0;
	}
	else
	{
		guestreceipts = document.orderdetails.guestreceipts.value;
		computepoints();
	}
}

//=================================================================================================
//This function set the values for Guest Sales Points based on the total sales if not outside sale
//=================================================================================================

function setguestsales()
{
	tsales = parseInt(document.orderdetails.totalsales.value);
	if (tsales >= 150)
		{ document.orderdetails.guestsales.value=200;}
	if (tsales >= 200)
		{ document.orderdetails.guestsales.value=400;}
	if (tsales >= 300)
		{ document.orderdetails.guestsales.value=600;}
	if (tsales >= 400)
		{ document.orderdetails.guestsales.value=1000;}
	if (tsales >= 500)
		{ document.orderdetails.guestsales.value=1200;}
	if (tsales >= 600)
		{ document.orderdetails.guestsales.value=1600;}
	if (tsales >= 700)
		{ document.orderdetails.guestsales.value=1800;}
	if (tsales >= 800)
		{ document.orderdetails.guestsales.value=2200;}
	if (tsales >= 900)
		{ document.orderdetails.guestsales.value=2400;}	
	if (tsales >= 1000)
		{ document.orderdetails.guestsales.value=2800;}
	
	if (document.orderdetails.orders.value < 4)
		{document.orderdetails.extrapts.options[0].selected = true;	}
}
//=================================================================================================
// This function makes sure the number of bookings match the points entered
//=================================================================================================

function verifybookings()
{
	var i;
	str = document.orderdetails.bookingslist.value;
	bookingstr = document.orderdetails.bookings.value;
	booking = bookingstr.substring(0,1);
	if (bookingstr=="0") return;	
	var guestarray = str.split(",");
	for (i=0; i <= booking; i++)
	{
        blist = guestarray[booking - 1];
        
    }
			
		
	if (blist == null)
		{alert('The number of bookings must match your class bookings points.');}        
}

//=================================================================================================
// This function remind the user no changes can be made to the guest order once they move to the  
// host/hostess order
//=================================================================================================

function ConfirmOrder(dSales)
{
	if (dSales < 50.00) 
	{
		var answer2 = confirm ("Your sales total must be more than $50.00.  If you continue, your shipping charge will be $8.00. Press cancel to add more product to your order or OK to continue and be charged the $8.00 shipping fee.");
		if (!answer2) 
		{ 
			return false;
		}
	}
	else
	{
		var answer = confirm ("You may not make changes to your guest order once you checked out. Proceed?");
		if (answer)
			return true;
		else
			return false;
	}
}
function ConfirmSalesAmount(dSales)
{
	var dblSales;
	if (dSales < 50.00) 
	{
		var answer = confirm ("Your sales total must be more than $50.00.  If you continue, your shipping charge will be $8.00. Press cancel to add more product to your order or OK to continue and be charged the $8.00 shipping fee.");
	}
	else
		return true;
	if (answer)
		return true;
	else
		return false;
}

//=================================================================================================
// This function remind the user to process payment before they email their orders  
//=================================================================================================

function ConfirmPayment()
{
	var answer = confirm ("If you have not processed all your payments yet, click Cancel now. Otherwise, click OK to proceed.");
	if (answer)
	{
		return true;
	}
	else
	{
		return false;
	}
}
//=================================================================================================
//
//=================================================================================================
function ConfirmEmail()
{
	var answer = confirm ("You have not EMAILED your order to Cake 'n Crumbs, therefore, it will NOT BE FILLED. Click Cancel now and select 'Email Order' to email the order to Cake 'n Crumbs. Otherwise, click OK to return to the main menu without emailing the order.");
	if (answer)
		return true;
	else
		return false;
}


//=================================================================================================
// These functions are used by orders.asp
//=================================================================================================
// This function calculates the grand total amount of sales for all the orders
//=================================================================================================

function calculatetotalamount(form,tax,shipping,amount,fee,totalamount,i)
{
	var result;
	var gtamount;
	var tamount;
	
	gtamount = form.GTTotalAmount.value;
	tamount = 0;
	var pos = 8;
	var curTotalAmount = 0;
	var tmpvalue=0;
	var x=0;
	
	var bolUpdateInstructorTotals;
	
	if (totalamount == "") 
	{
		totalamount = 0;
	}
	if ((amount != "") && (amount > 0))
	{
		if (totalamount > 0) 
		{	
			tamount = totalamount;
		}
		if (gtamount < 0)
			{ gtamount = 0; }
			
		result = formatPrice(((tax*1)+(shipping*1)+(amount*1)+(fee*1)));
//		form.GTTotalAmount.value = formatPrice(((gtamount * 1) + (result * 1))- parseFloat(tamount));
	}
	else
	{
		result = 0;
	}
	curTotalAmount=0;
	for (var x=1; x <= i; x++)
	{
		//Grand Total Amount Value calculation
		if (((document.orders.elements[pos].value) == "") || ((document.orders.elements[pos].value) == 0))
		{
			tmpValue = 0;
		}
		else
		{
				tmpValue = document.orders.elements[pos].value;
				tmpValue = tmpValue.toString().replace(/\$|\,/g,'');
//				tmpValue = parseFloat(document.orders.elements[pos].value);
				tmpValue = parseFloat(tmpValue);
		}
		curTotalAmount = curTotalAmount + tmpValue;
		pos = pos + 10;	
//		alert('Curtotalamount: ' + curTotalAmount + '  tmpValue: ' + tmpValue + '   x: ' + x);

	}		
	form.GTTotalAmount.value = formatCurrency(parseFloat(curTotalAmount) + parseFloat(result) - parseFloat(totalamount));
	return result;
}



	//_________________________Facts About The Form Structure_________________________
	//		Recorded by Matt Schroepfer on 10/10/01
	//
	//		- 10 elements per individual order (row)
	//		- 10 elements for a hostess order
	//		- 8 elements for an instructor order
	//		- 4 elements pertaining to general form totals
	//		- 7 miscellaneous elements
	//		- Only the individual orders are repetitive
	//		- The total amount for each individual order is the 4th element in each row (index of 3)
	//		- The hostess order appears before the instructor order and after all of the individual orders
	//		- The 4 general form totals appear between the hostess order and the instructor order
	//		- The 7 miscellaneous elements appear after all other form elements


	//_________________________Conclusions About The Form Structure_________________________
	//		Recorded by Matt Schroepfer on 10/10/01
	//
	//		- this form must have at least 39 elements
	//		- NumberOfElements = (# of ind. orders)(10 elements/ind. order) + 29
	//		- ElementNumberOfInstructorTotal = (# of ind. orders)(10 elements/ind. order) + 16
	//			-1 is due to the fact that the element number is zero based in javascript
	//			+7 because the 4 general form totals appear before the the instructor form elements
	//			   and the amount total element for the instructor is the 3rd element in the row
	//			+10 because the 10 elements from the hostess order appear before the instructor elements
	//		- NumberOfIndividualOrders = (NumberOfElements - 29) / 10		' This is the reverse of NumberOfElements


// This function processes all updates to the orders.asp process payment screen.
//	intRowNumber is the number of the particular row in the form that contains the
//	element that was just updated. Each row in the form represents an individual guest
//	order. fltTaxRate is the rate of taxation to be performed on each order.
//
//=================================================================================================
//
//=================================================================================================
function UpdateFormValues(intRowNumber, fltTaxRate, fltTotalSales, sClassType)
{
	var bolGuestsValuesUpdated;
	var bolTotalsValuesUpdated;
	var bolInstructorValuesUpdated;
	// Strategy: 
	//	1) Update all normal row values
	//	2) Update totals row values
	//	3) Update instructor row values
	
	bolGuestsValuesUpdated = UpdateGuestValues(intRowNumber, fltTaxRate, fltTotalSales, sClassType);
	
	// Determine if instructor lines exist
	//	If so, update!
	if((document.orders.TotalAmount != "") && bolGuestsValuesUpdated)
	{
		bolTotalsValuesUpdated = UpdateTotals()
		bolInstructorValuesUpdated = UpdateInstructorTotals(fltTaxRate)
	}
	
	return true;
}
//=================================================================================================
//
//=================================================================================================
function UpdateGuestValues(intRowNumber, fltTaxRate, fltTotalSales, strClassType)
{	
	var intNumberOfFormElements;
	var intNumberOfIndividualOrders;
	var intNumberOfOrders;
	var intAmountFormIndex;
	var intFormElementNumber;
	var intFormElementNumberRowOffset;
	var bolUpdatedHostessShipping;
	var intAmountColumnOffset;
	var intShippingColumnOffset;
	var intFeeColumnOffset;
	var intTaxColumnOffset;
	var intTotalColumnOffset;
	
	var fltAmount;
	var fltShipping;
	var strShipping;
	var fltFee;
	var strFee;
	var fltTax;
	var fltTotal;

	// First get to the proper row
	// Then, calculate in this order:
	//	1) Shipping
	//	2) Processing Fee
	//	3) Taxes
	//	4) Total

	intAmountColumnOffset		=	3;
	intShippingColumnOffset		=	4;
	intFeeColumnOffset			=	6;
	intTaxColumnOffset			=	7;
	intTotalColumnOffset		=	8;
	
	intFormElementNumberRowOffset = 10;
	intNumberOfFormElements = document.orders.length;
	intNumberOfIndividualOrders = (intNumberOfFormElements - 29) / intFormElementNumberRowOffset;

	// Get the position of the first entity (radio button) in the row
	intFormElementNumber = (intRowNumber - 1) * intFormElementNumberRowOffset
	fltAmount = document.orders.elements[intFormElementNumber + intAmountColumnOffset].value;
	fltAmount = fltAmount.toString().replace(/\$|\,/g,'');
	fltAmount = parseFloat(fltAmount);
//	fltAmount = parseFloat(document.orders.elements[intFormElementNumber + intAmountColumnOffset].value);
	// Verify that an amount exists before calculating anything; if not, then set it to zero
	if(isNaN(fltAmount))
	{
		fltAmount = parseFloat(0.00);
	}
	
	if(fltAmount > 0)
	{

		// See if hostess shipping is changed as a result of this order amount being changed
		bolUpdatedHostessShipping = UpdateHostessTotals(fltAmount, fltTotalSales, fltTaxRate, strClassType);

		// If this is the hostess line AND and update on hostess shipping has occurred, then set shipping to zero
		//	Nominal case is likely to not be the hostess line, so it comes first
		if(!((intRowNumber == (intNumberOfIndividualOrders + 1)) && bolUpdatedHostessShipping))
		{
			fltShipping = CalculateShipping(fltAmount,strClassType);
		}
		else
		{
			fltShipping = parseFloat(0)
		}

		// Calculate the payment method fee if applicable (must check to see if it is a credit transaction)	
		if(document.orders.elements[intFormElementNumber].checked == true)
		{
			strFee = "0.00";
			fltFee = parseFloat(0.00);
		}
		else
		{
			strFee = "0.30";
			fltFee = parseFloat(0.30);
		}

		// Tax merchandise amount with shipping
		fltTax = parseFloat(fltTaxRate) * (parseFloat((fltAmount)) + parseFloat((fltShipping)) + parseFloat(fltFee));
//05		fltTax = parseFloat(fltTaxRate) * (parseFloat(formatPrice(fltAmount)) + parseFloat(formatPrice(fltShipping)) + parseFloat(fltFee));

		// Add it all up
		fltTotal = parseFloat((fltAmount)) + parseFloat((fltShipping)) + parseFloat(fltFee) + parseFloat((fltTax));
//05		fltTotal = parseFloat(formatPrice(fltAmount)) + parseFloat(formatPrice(fltShipping)) + parseFloat(fltFee) + parseFloat(formatPrice(fltTax));

		// Format the display of the shipping
		if(fltShipping > 0)
		{
			strShipping = formatPrice(fltShipping);
		}
		else
		{
			strShipping = "0.00"
		}
		document.orders.elements[intFormElementNumber + intAmountColumnOffset].value	=	formatPrice(fltAmount);
		document.orders.elements[intFormElementNumber + intShippingColumnOffset].value	=	strShipping;
		document.orders.elements[intFormElementNumber + intFeeColumnOffset].value		=	strFee;
		document.orders.elements[intFormElementNumber + intTaxColumnOffset].value		=	formatPrice(fltTax);
		document.orders.elements[intFormElementNumber + intTotalColumnOffset].value		=	formatPrice(fltTotal);
	}
	else
	{
		document.orders.elements[intFormElementNumber + intAmountColumnOffset].value	=	"0.00";
		document.orders.elements[intFormElementNumber + intShippingColumnOffset].value	=	"0.00";
		document.orders.elements[intFormElementNumber + intFeeColumnOffset].value		=	"0.00";
		document.orders.elements[intFormElementNumber + intTaxColumnOffset].value		=	"0.00";
		document.orders.elements[intFormElementNumber + intTotalColumnOffset].value		=	"0.00";
	}
	
	return true;
}
//=================================================================================================
//
//=================================================================================================
function CalculateShipping(fltAmount, strnClassType)
{
	var fltShipping;
//	alert("[" + strnClassType + "]");
	if ((strnClassType == "outside") || (strnClassType == "OUTSIDE"))	
	{

		if(fltAmount > 50)
		{
			fltShipping = (fltAmount * .1);
		}
		else
		{
			if ((fltAmount < 50) && (fltAmount > 40))
			{
				fltShipping = (fltAmount * .2);
			}
			else
			{
				fltShipping = parseFloat(8.00);
			}
		}
	}
	else
	{
			if(fltAmount > 49.5)
		{
			fltShipping = (fltAmount * .1);
		}
		else
		{
			fltShipping = parseFloat(4.95);
		}
	}
	//	If the amount is less than $49.50, then shipping is only $4.95
	//	If it is greater, then it is 10% of the amount
	
	return fltShipping;
}
//=================================================================================================
//
//=================================================================================================
function UpdateHostessTotals(fltAmount, fltTotalSales, fltTaxRate, strClassType)
{
	// Many of these variables are defined in the total computation routines
	//	please see them for more info
	var intNumberOfOrders;
	var intFormElementNumber;
	var intNumberOfFormElements;
	var intNumberOfIndividualOrders;
	var fltTotalGuestOrder;
	var fltCurrentAmount;
	var intAmountFormIndex;
	var intFormElementNumberRowOffset;
	var strHostessAmount;
	var strHostessShipping;
	var strHostessTax;
	var strHostessTotal;
	var bolUpdatedHostessShipping;
	
	intAmountFormIndex = 3;
	intFormElementNumberRowOffset = 10;
	fltTotalGuestOrder = "";
	
	//	If this is a hostess order and the total order has the following properties:
	//		CONDITION 1: # of guests > 4
	//		CONDITION 2: total guest sales => $150.00
	//	a hostess gets free shipping.
	//
	// So, first determine if this is a hostess line
	//	then, if necessary, change shipping to $0
	
	intNumberOfFormElements = document.orders.length;
	intNumberOfIndividualOrders = (intNumberOfFormElements - 29) / intFormElementNumberRowOffset;
	
	// Calculate total order so far
	for(intNumberOfOrders = 0; intNumberOfOrders < intNumberOfIndividualOrders; intNumberOfOrders++)
	{
		// Get the position of the first radio button of each row
		intFormElementNumber = intNumberOfOrders * intFormElementNumberRowOffset
			
		// Get the position of each individual order amount
		intFormElementNumber = intFormElementNumber + intAmountFormIndex;

	fltCurrentAmount = document.orders.elements[intFormElementNumber].value;
	fltCurrentAmount = fltCurrentAmount.toString().replace(/\$|\,/g,'');
	fltCurrentAmount = parseFloat(fltCurrentAmount)
//05		fltCurrentAmount = parseFloat(document.orders.elements[intFormElementNumber].value);

		// Add to total only if the value is a valid number
		if(!isNaN(fltCurrentAmount))
		{
			fltTotalGuestOrder = parseFloat(fltTotalGuestOrder + fltCurrentAmount);
		}
	}
	// Go to the hostess row
	intFormElementNumber = (intNumberOfIndividualOrders * intFormElementNumberRowOffset);
				
	// Go to the hostess amount field
	intFormElementNumber = intFormElementNumber + (intAmountFormIndex);
	
	// Hostess purchase total is equal to the remainder of the sales total that guest orders don't use
	if((parseFloat(fltTotalSales) - fltTotalGuestOrder) > 0)
	{
		strHostessAmount = formatPrice(parseFloat(fltTotalSales) - fltTotalGuestOrder);
	}
	else
	{
		strHostessAmount = "0.00";
		// Set credit card fee to zero
		document.orders.elements[intFormElementNumber + 3].value = "0.00"		
	}

	// Assume that the hostess will not get free shipping
	bolUpdatedHostessShipping = false;
	
	if(parseFloat(strHostessAmount) > 0)
	{
		strHostessShipping = formatPrice(CalculateShipping(parseFloat(strHostessAmount),strClassType));
	}
	else
	{
		strHostessShipping = "0.00";
	}

	if((intNumberOfIndividualOrders > 4) && (fltTotalGuestOrder >= 150))
	{
		strHostessShipping = "0.00";
		bolUpdatedHostessShipping = true;
	}

	// Calculate taxes...first add purchase total and shipping
	strHostessTax = parseFloat(formatPrice(strHostessAmount)) + parseFloat(formatPrice(strHostessShipping));

	// Then, add credit card fee and multiply by the tax rate
	strHostessTax = (parseFloat(formatPrice(strHostessTax)) + parseFloat(document.orders.elements[intFormElementNumber + 3].value)) * parseFloat(fltTaxRate);

	// Calculate the hostess total
	strHostessTotal = parseFloat(formatPrice(strHostessAmount)) + parseFloat(formatPrice(strHostessShipping));
	strHostessTotal = parseFloat(formatPrice(strHostessTotal)) + parseFloat(document.orders.elements[intFormElementNumber + 3].value) + parseFloat(formatPrice(strHostessTax));
	// Set the values
	document.orders.elements[intFormElementNumber].value		=	strHostessAmount;
	document.orders.elements[intFormElementNumber + 1].value	=	strHostessShipping;
	document.orders.elements[intFormElementNumber + 4].value	=	formatPrice(strHostessTax);
	document.orders.elements[intFormElementNumber + 5].value	=	formatPrice(strHostessTotal);
	
	return bolUpdatedHostessShipping;
}
//=================================================================================================
//
//=================================================================================================
function UpdateTotals()
{
	var intNumberOfFormElements;
	var intNumberOfIndividualOrders;
	var intNumberOfOrders;
	var intAmountFormIndex;
	var intFormElementNumber;
	var intFormElementNumberRowOffset;
	var fltCurrentAmount;
	var fltCurrentShipping;
	var fltCurrentTotal;
	var fltPurchaseTotal;
	var fltShippingTotal;
	var fltFinalGrandTotal;
	var intAmountShippingOffset;
	var intAmountGrandTotalOffset;
	
	// This is the number of elements away (forward) from the amount field that the each of the following fields are found
	intAmountShippingOffset = 1;
	// This is the amount of elements away that the Total Amount column text field is off from the purchase total column
	intAmountGrandTotalOffset = 5;
	
	intAmountFormIndex = 3;
	intFormElementNumberRowOffset = 10;
	
	intNumberOfFormElements = document.orders.length;
	intNumberOfIndividualOrders = (intNumberOfFormElements - 29) / intFormElementNumberRowOffset;
	
	// Set default values
	fltPurchaseTotal = parseFloat(0);
	fltShippingTotal = parseFloat(0);
	fltFinalGrandTotal = parseFloat(0);
	
	// You must add 1 to intNumberOfIndividualOrders to account for the hostess order 
	for(intNumberOfOrders = 0; intNumberOfOrders < intNumberOfIndividualOrders + 1; intNumberOfOrders++)
	{
		// Get the position of the first radio button of each row
		intFormElementNumber = intNumberOfOrders * intFormElementNumberRowOffset
		
		// Get the position of each individual order amount
		intFormElementNumber = intFormElementNumber + intAmountFormIndex;

//05		fltCurrentAmount	=	parseFloat(document.orders.elements[intFormElementNumber].value);
//05		fltCurrentShipping	=	parseFloat(document.orders.elements[intFormElementNumber + intAmountShippingOffset].value);
//05		fltCurrentTotal		=	parseFloat(document.orders.elements[intFormElementNumber + intAmountGrandTotalOffset].value);


		fltCurrentAmount = document.orders.elements[intFormElementNumber].value;
		fltCurrentAmount = fltCurrentAmount.toString().replace(/\$|\,/g,'');
		fltCurrentAmount = parseFloat(fltCurrentAmount)
		fltCurrentShipping = document.orders.elements[intFormElementNumber + intAmountShippingOffset].value;
		fltCurrentShipping = fltCurrentShipping.toString().replace(/\$|\,/g,'');
		fltCurrentShipping = parseFloat(fltCurrentShipping)
		fltCurrentTotal = document.orders.elements[intFormElementNumber + intAmountGrandTotalOffset].value;
		fltCurrentTotal = fltCurrentTotal.toString().replace(/\$|\,/g,'');
		fltCurrentTotal = parseFloat(fltCurrentTotal)
		
		// Add to total only if the value is a valid number
		if(!isNaN(fltCurrentAmount))
		{
			fltPurchaseTotal = fltPurchaseTotal + fltCurrentAmount;
		}
		
		// Add to shipping only if the value is a valid number
		if(!isNaN(fltCurrentShipping))
		{
			fltShippingTotal = fltShippingTotal + fltCurrentShipping;
		}
		
		// Add to current running total only if the value is a valid number
		if(!isNaN(fltCurrentTotal))
		{
			fltFinalGrandTotal = fltFinalGrandTotal + fltCurrentTotal;
		}
	}

	// Set form values
	document.orders.TotalAmount.value = formatPrice(fltPurchaseTotal);
	document.orders.TotalShipping.value = formatPrice(fltShippingTotal);
	document.orders.GTTotalAmount.value = formatPrice(fltFinalGrandTotal);
	
	return true;
}


// This function was designed to replace the following function (calculategtotalamount)
//	It calculates the proper totals for instructor orders (called on orders.asp)
//	
//=================================================================================================
//
//=================================================================================================
function UpdateInstructorTotals(fltTaxRate)
{
	var intNumberOfFormElements;
	var intNumberOfIndividualOrders;
	var intNumberOfOrders;
	var intAmountFormIndex;
	var intFormElementNumber;
	var intFormElementNumberRowOffset;
	var fltCurrentAmount;
	var fltCurrentShipping;
	var fltCreditCardFee;
	var fltInstructorTax;
	var fltInstructorGrandTotal;
	
	var intAmountShippingOffset;
	var intAmountFeeOffset;
	var intAmountTaxOffset;
	var intAmountGrandTotalOffset;
	
	var intInstructorTotalElementNumber;
	var intInstructorShippingElementNumber;
	
	// The instructor purchase total is equal to the total of all non-credit card order purchase totals
	var fltInstructorPurchaseTotal;
	// The instructor shipping total is equal to the total of all non-credit card order shipping totals
	var fltInstructorShippingTotal;
	
	// This is the number of elements away (forward) from the amount field that the each of the following fields are found
	intAmountShippingOffset = 1;
	intAmountFeeOffset = 2;
	intAmountTaxOffset = 3;
	intAmountGrandTotalOffset = 4;
	
	intAmountFormIndex = 3;
	intFormElementNumberRowOffset = 10;
	
	intNumberOfFormElements = document.orders.length;

	intNumberOfIndividualOrders = (intNumberOfFormElements - 29) / intFormElementNumberRowOffset;
	intInstructorTotalElementNumber = (intNumberOfIndividualOrders * intFormElementNumberRowOffset) + 16;
	intInstructorShippingElementNumber = intInstructorTotalElementNumber + intAmountShippingOffset;
	intInstructorFeeElementNumber = intInstructorTotalElementNumber + intAmountFeeOffset;
	intInstructorTaxElementNumber = intInstructorTotalElementNumber + intAmountTaxOffset;
	intInstructorGrandTotalElementNumber = intInstructorTotalElementNumber + intAmountGrandTotalOffset;

	// Set default values
	fltInstructorPurchaseTotal = parseFloat(0);
	fltInstructorShippingTotal = parseFloat(0);
	
	// You must add 1 to intNumberOfIndividualOrders to account for the hostess order 
	for(intNumberOfOrders = 0; intNumberOfOrders < intNumberOfIndividualOrders + 1; intNumberOfOrders++)
	{
		// Get the position of the first radio button of each row
		intFormElementNumber = intNumberOfOrders * intFormElementNumberRowOffset
		
		// Check to see if the transaction is a non-credit transaction
		if(document.orders.elements[intFormElementNumber].checked == true)
		{
			// Get the position of each individual order amount
			intFormElementNumber = intFormElementNumber + intAmountFormIndex;

			fltCurrentAmount = document.orders.elements[intFormElementNumber].value;
			fltCurrentAmount = fltCurrentAmount.toString().replace(/\$|\,/g,'');
			fltCurrentAmount = parseFloat(fltCurrentAmount)
//			fltCurrentAmount = parseFloat(document.orders.elements[intFormElementNumber].value);
			fltCurrentShipping = parseFloat(document.orders.elements[intFormElementNumber + intAmountShippingOffset].value);
		
			// Add to total only if the value is a valid number
			if(!isNaN(fltCurrentAmount))
			{
				fltInstructorPurchaseTotal = fltInstructorPurchaseTotal + fltCurrentAmount;
			}
		
			// Add to shipping only if the value is a valid number
			if(!isNaN(fltCurrentShipping))
			{
				fltInstructorShippingTotal = fltInstructorShippingTotal + fltCurrentShipping;
			}
		}
	}

	// Determine if a credit card fee is necessary
	if(fltInstructorPurchaseTotal > 0)
	{
		fltCreditCardFee = parseFloat("0.30");
	}
	else
	{
		fltCreditCardFee = parseFloat("0");
	}
	
	// Calculate total instructor tax and final total
	fltInstructorTax = parseFloat((fltInstructorPurchaseTotal + fltInstructorShippingTotal + fltCreditCardFee) * fltTaxRate);
	fltInstructorGrandTotal = formatPrice(fltInstructorPurchaseTotal + fltInstructorShippingTotal + fltCreditCardFee + fltInstructorTax);

	// Set form values
	document.orders.elements[intInstructorTotalElementNumber].value = formatPrice(fltInstructorPurchaseTotal);
	document.orders.elements[intInstructorShippingElementNumber].value = formatPrice(fltInstructorShippingTotal);
	document.orders.elements[intInstructorFeeElementNumber].value = formatPrice(fltCreditCardFee);
	document.orders.elements[intInstructorTaxElementNumber].value = formatPrice(fltInstructorTax);
	document.orders.elements[intInstructorGrandTotalElementNumber].value = formatPrice(fltInstructorGrandTotal);
	
	return true;
}


//=================================================================================================
// This function calculates the grand total amount of sales for the instructor.
// Here we don't want the instructor's total amount to affect our grand total because we don't
// care how much she pays. What's important is the combined total sales for the hostess and guest //orders.
//=================================================================================================
//=================================================================================================
//
//=================================================================================================
function calculategtotalamount(form,tax,shipping,amount,fee,totalamount)
{
	var result;
	var gtamount;
	var tamount;
	gtamount = form.GTTotalAmount.value;
	tamount = 0;
	if (amount != 0)
	{
		if (totalamount > 0) 
		{	
			tamount = totalamount;
		}
		if (gtamount < 0)
		{ 
			gtamount = 0; 
		}
		result = formatPrice(((tax*1)+(shipping*1)+(amount*1)+(fee*1)));
	}
	else
	{
		result = 0;
	}
	return result;
}

//=================================================================================================
// This function turns value to double digit format
//=================================================================================================
function formatPrice(strValue)
{

/*
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
*/	
	
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-')  + dblValue + '.' + strCents);
	
}

function formatPrice_old(value) 
{
	var strresult;
	strresult = "0.00";
	if(value != "")
	{
		var result= Math.floor(value) + ".";
		var cents = 100 * (value-Math.floor(value)) + 0.5;
		result += Math.floor(cents / 10);
		result += Math.floor(cents % 10);
		return result;
	}
	else
		return strresult;
}

//=================================================================================================
// This function unwanted leading characters from the string, for example $
//=================================================================================================

function stripLeading(string,chr) {
   var finished = false;
   for (var i = 0; i < string.length && !finished; i++)
       if (string.substring(i,i+1) != chr) finished = true;
   if (finished) return string.substring(i-1); else return string;
}

//=================================================================================================
// This function calculates the instructor shipping charges based on the flag set in the user table. 
// Shipping flag = 0 means no shipping charges, otherwise follow the default rules.
//=================================================================================================

function calculateinstructorshipping(stotal)
{
	//alert(stotal);  
	var shipflag = document.orders.shippingflag.value;
	
	if (shipflag == '0')
	{
		stotal = 0;
	}
	else	
	{
		if ((stotal < 49.5) && (stotal > 0) && (stotal !=""))
		{ stotal = 4.95; }
		else
		{ stotal = stotal * .10; }
	}
	return formatCurrency(stotal);
	
}

//=================================================================================================
// This function calculates the shipping charges for the hostess and guests. 
// All sales below $49.50 has a shipping charge of $4.95. Shipping charge for Sales above $49.50
// is 10% of the sales.
// If total commissionable sales is $150 or more and total orders is 5 or more, the hostess
// shipping is waived. Value 99 is passed when this condition is true.
//=================================================================================================

function calculateshipping_old(sfee,stotal,i)
{
	var TotalAmount = document.orders.TotalAmount.value;
	var curTotalAmount = 0;
	var x;
	var tmpValue;
	var pos = 3;
	TotalAmount = parseFloat(TotalAmount);
//	document.orders.TotalAmount.value = formatCurrency(TotalAmount + parseFloat(stotal));

	for (var x=1; x <= i; x++)
	{
		if ((document.orders.elements[pos].value) == "" || (document.orders.elements[pos].value) == 0)
		{
			tmpValue = 0;
		}
		else
		{
			tmpValue = document.orders.elements[pos].value;
		}
		curTotalAmount = curTotalAmount + parseFloat(tmpValue);
		pos = pos + 10;
	}		
	document.orders.TotalAmount.value = formatCurrency(curTotalAmount);
	if (sfee == 0)
	{
//		document.orders.instructortotal.value = formatCurrency(parseFloat(document.orders.instructortotal.value) + parseFloat(stotal));
		document.orders.instructortotal.value = formatCurrency(curTotalAmount);
	}
	
	if (sfee == 99)
	{
//		document.orders.instructortotal.value = formatCurrency(parseFloat(document.orders.instructortotal.value) + parseFloat(stotal));
		document.orders.instructortotal.value = formatCurrency(curTotalAmount);
	}
	
	sfee = parseFloat(sfee);
	if ((stotal < 49.5) && (stotal > 0) && (stotal !=""))
	{ stotal = 4.95; }
	else
	{ stotal = stotal * .10; }
	
	pos = 3;
	curTotalAmount = 0;
	tmpvalue=0;
	x=0;
	if (sfee != 99)
	{
//	 document.orders.TotalShipping.value = formatCurrency(parseFloat(document.orders.TotalShipping.value) + stotal);
		for (var x=1; x <= i; x++)
		{
			//shipping
			if ((document.orders.elements[pos].value) == "" || (document.orders.elements[pos].value) == 0)
			{
				tmpValue = 0;
			}
			else
			{
				tmpValue = 0;
				if ((document.orders.elements[pos].value < 49.5) && (document.orders.elements[pos].value > 0) && (document.orders.elements[pos].value != ""))
				{ 
					tmpValue = 4.95; 
				}
				else
				{
					tmpValue = parseFloat(document.orders.elements[pos].value) * .10;
				}
			}
			curTotalAmount = curTotalAmount + tmpValue;
			pos = pos + 10;
		}		
		 document.orders.TotalShipping.value = formatCurrency(parseFloat(curTotalAmount));
	}
	
	if (sfee == 99)
	{
	  stotal = 0;
	}
	
	return formatCurrency(stotal);

}

//=================================================================================================
// This function recalculates the shipping charges and the total instructor has to pay when the user 
// change their minds gazellion times between paying with cash or credit card.
//=================================================================================================

function recalculateshipping(ioption,sform,sShipping,stotal,i)
{
	
	var curTotalAmount = 0;
	var curTotalAmount2 = 0;
	var x;
	var tmpValue;
	var pos = 3;	
	var pos2 = 4;

	for (var x=1; x <= i; x++)
	{
		//instructor total
		if ((document.orders.elements[pos].value) == "")
		{
			tmpValue = 0;
		}
		else
		{
			tmpValue = document.orders.elements[pos].value;
		}
		curTotalAmount = curTotalAmount + parseFloat(tmpValue);
		pos = pos + 10;
		//shipping
		if ((document.orders.elements[pos2].value) == "")
		{
			tmpValue = 0;
		}
		else
		{
			tmpValue = document.orders.elements[pos2].value;
		}
		curTotalAmount2 = curTotalAmount2 + parseFloat(tmpValue);
		pos2 = pos2 + 10;
	}		

// if (sShipping == "")
// {
//	sShipping = 0; 
// }
// 
// if (stotal == "")
// {
//	stotal = 0;
// }
 
// myTotalShipping = parseFloat(sform.TotalShipping.value);
// myInstructorTotal = parseFloat(sform.instructortotal.value);
// if (ioption == "CASH")
// {	
//	myTotalShipping = myTotalShipping + parseFloat(sShipping);
//	myInstructorTotal = myInstructorTotal + parseFloat(stotal);
// }
// else
// {	
//	myTotalShipping = myTotalShipping - parseFloat(sShipping);
//	myInstructorTotal = myInstructorTotal - parseFloat(stotal);
// }
 sform.TotalShipping.value = curTotalAmount2;
 sform.instructortotal.value = curTotalAmount;
 
 return formatCurrency(sform.TotalShipping.value);
}

//=================================================================================================
// This function calculates how much shipping to charge the instructor based on the percentage
// stored in the user table. Forget this, Lori changed her mind. So we'll calculate the shipping 
// just like the hostess' and guest's orders.
//=================================================================================================

function calculateishipping(itotal)
{
	if (itotal=="")
	{
		itotal = 0;
		return formatCurrency(itotal);
	}
	if ((itotal < 49.5) && (itotal > 0))
	{ itotal = 4.95; }
	else
	{ itotal = itotal * .10; }

	return formatCurrency(itotal);
	
}
//=================================================================================================
// This function calculates the sales tax. Formula is as follow:
// Sales Tax = (shipping + sales amount + credit card fee(if any)) * taxrate
//=================================================================================================

function calculateTax(stotalship,stotalamount,sfee,taxrate)
{
		var totaltax;
		var totalship = 0;
		var totalamount = 0;
		var sfee;

		totalship = parseFloat(stotalship);
		totalamount = parseFloat(stotalamount);
		creditcardfee = parseFloat(sfee);
		if (totalship == "")
		{
			totalship = 0;
		}
		if (totalamount == "")
		{ 
			totalamount = 0; 
		}
		if (taxrate == "")
		{ 
			taxrate = 0; 
		}
		if (creditcardfee == "")
		{
			creditcardfee = 0;
		}
			
		totaltax = (totalship + totalamount + creditcardfee) *  taxrate ;
		
	return formatCurrency(totaltax);
}

//=================================================================================================
// This function calculates the total shipping for the instructor when guest/hostesss pays for
// their orders with cash/check.
//=================================================================================================

function calculatetotalshipping(stotalship,sfee,i)
{
		var totalship = 0;
		totalship = parseFloat(stotalship);
		creditcardfee = parseFloat(sfee);

		if (totalship == "")
		{
			totalship = 0;
		}
		
		if (creditcardfee == "")
		{
			creditcardfee = 0
		}
	
	if (creditcardfee < 0.30)
	{
	document.orders.TotalShipping.value = formatCurrency(parseFloat(document.orders.TotalShipping.value) + totalship);
	}
	
	return formatCurrency(document.orders.TotalShipping.value);
	
}

//=================================================================================================
// This function formats value to a currency format
//=================================================================================================

function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/100).toString();
	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
//	return ("$" + num + "." + cents);
	return (num + "." + cents);
}
//*************************************************************************************************
// Above functions are used by orders.asp
//*************************************************************************************************
function validatepointvalues(pointsspent,totalpoints,acthalfprice,halfprice,suppliescount,dSales)
{
	// User chose to take half price items instead of points so lets
	// see if the number of items selected for half price is "OVER THE LIMIT"
	if (dSales < 50.00) 
	{
		var answer = confirm ("Your sales total must be more than $50.00.  If you continue, your shipping charge will be $8.00. Press cancel to add more product to your order or OK to continue and be charged the $8.00 shipping fee.");
		if (answer)
		{
		}
		else
			return false;
	}

	if (suppliescount > 5) 
	{
			alert("You selected " + suppliescount + " class supply items.\n" + "You may only select 5 class supply items. \n" + "Please remove enough items to lower your selected class supplies total.");
			return false;
	}
	if (halfprice > 0) 
	{
		if (acthalfprice > halfprice)
		{
			alert("You selected " + acthalfprice + " half-price items.\n" + "You may only select " + halfprice + " half-price items. \n" + "Please remove enough items to lower your selected 1/2 price items total.");
			return false;
		}
	}
	// see if the number of selected points is "OVER THE LIMIT" 
	if (pointsspent > totalpoints)
	{
	alert("You selected items totaling " + pointsspent + " points. \n" + "You may only use " + totalpoints + " points. \n" + "Please remove enough items to lower your Points Spent total.");
	return false;
	}
	return true;
}

//=================================================================================================
// This is a form validation function used by the first order profile form in Class Supplies 
//=================================================================================================

function validateexport()
{
	var error = 0;
	var cdate = document.frmexport.txtStartDate.value;
	if (isEmpty(cdate))
	{
	 alert("Please enter a start date!");
	 error = 1;
	 document.frmexport.txtStartDate.focus();
	 return false;
	}
	else
	{
	 	if (isValidDate(cdate,'/') == false)
	 	{
	    error = 1;
		document.frmexport.txtStartDate.focus();
		return false;	 
		}
	}
	var edate = document.frmexport.txtEndDate.value;
	if (isEmpty(edate))
	{
	 alert("Please enter a end date!");
	 error = 1;
	 document.frmexport.txtEndDate.focus();
	 return false;
	}
	else
	{
	 	if (isValidDate(edate,'/') == false)
	 	{
	    error = 1;
		document.frmexport.txtEndDate.focus();
		return false;	 
		}
	}
    

	
}

//=================================================================================================
// This is a form validation function used by editor_inventory.asp to validate the inventory item
//=================================================================================================

function validateinventoryitem()
{
	var error = 0;
    var ItemNumber = document.frmeditForm.txtItemNumber.value;
	document.frmeditForm.hidbody.value = idContent.document.body.innerHTML;

	if (isEmpty(ItemNumber))
    {  
         alert("Please select an order number!");
		 error=1;
		 document.frmeditForm.txtItemNumber.focus();
         return false;
    }
	var error = 0;
    var Description = document.frmeditForm.txtDescription.value;
	if (isEmpty(Description))
    {  
         alert("Please select a Description!");
		 error=1;
		 document.frmeditForm.txtDescription.focus();
         return false;
    }
	var error = 0;
    var Points = document.frmeditForm.txtPoints.value;
	if (isEmpty(Points))
    {  
         alert("Please select a valid Points value!");
		 error=1;
		 document.frmeditForm.txtPoints.focus();
         return false;
    }
	var error = 0;
    var Amount = document.frmeditForm.txtAmount.value;
	if (isEmpty(Amount))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtAmount.focus();
         return false;
    }
    var error = 0;
    var OrderCategory = document.frmeditForm.lstOrderCategory.value;
	if (OrderCategory == 0)
    {  
         alert("Please select a valid Order Category!");
		 error=1;
		 document.frmeditForm.lstOrderCategory.focus();
         return false;
    }
    var error = 0;
    var OnHand = document.frmeditForm.txtOnHand.value;
	if (IsValidInput(OnHand,"Integer") == false)
    {  
         alert("Please select a valid On Hand quantity!");
		 error=1;
		 document.frmeditForm.txtOnHand.focus();
         return false;
    }
    var error = 0;
    var MinOnHand = document.frmeditForm.txtMinOnHand.value;
	if (IsValidInput(MinOnHand,"Integer") == false)
    {  
         alert("Please select a valid Minimum On Hand quantity!");
		 error=1;
		 document.frmeditForm.txtMinOnHand.focus();
         return false;
    }
    var error = 0;
    var OrderQuantity = document.frmeditForm.txtOrderQuantity.value;
	if (IsValidInput(OrderQuantity,"Integer") == false)
    {  
         alert("Please select a valid Order Quantity!");
		 error=1;
		 document.frmeditForm.txtOrderQuantity.focus();
         return false;
    }
    var error = 0;
    var OriginalAmount = document.frmeditForm.txtOriginalAmount.value;
	if (isEmpty(OriginalAmount))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtOriginalAmount.focus();
         return false;
    }
	var error = 0;
    var SalesPrice1 = document.frmeditForm.txtSalesPrice1.value;
	if (isEmpty(SalesPrice1))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtSalesPrice1.focus();
         return false;
    }
	var error = 0;
    var SalesPrice2 = document.frmeditForm.txtSalesPrice2.value;
	if (isEmpty(SalesPrice2))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtSalesPrice2.focus();
         return false;
    }
	var error = 0;
    var SalesPrice3 = document.frmeditForm.txtSalesPrice3.value;
	if (isEmpty(SalesPrice3))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtSalesPrice3.focus();
         return false;
    }
	var error = 0;
    var SalesPrice4 = document.frmeditForm.txtSalesPrice4.value;
	if (isEmpty(SalesPrice4))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtSalesPrice4.focus();
         return false;
    }
	var error = 0;
    var SalesPrice5 = document.frmeditForm.txtSalesPrice5.value;
	if (isEmpty(SalesPrice5))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtSalesPrice5.focus();
         return false;
    }
	var error = 0;
    var InternetPrice = document.frmeditForm.txtInternetPrice.value;
	if (isEmpty(InternetPrice))
    {  
         alert("Please select a valid Amount value!");
		 error=1;
		 document.frmeditForm.txtInternetPrice.focus();
         return false;
    }
    var error = 0;
    var CatalogCategory = document.frmeditForm.lstCategory.value;
	if (CatalogCategory == "0")
    {  
         alert("Please select a valid Catalog Category!");
		 error=1;
		 document.frmeditForm.lstCategory.focus();
         return false;
    }
}

