/* 
 * The Artists Studio Order Form JavaScript
 * Dan Hopkins <dan@homicidalmaniac.org> June 2002 
 * $Id$
 */

/* Flag a variable so we know which button submitted the form
 */
var submitter = null;

function submitted_by( btn )
{
	submitter = btn.name;
}

/*
 * upd_priceselect
 * Polpulate the price drop-down when the picture drop-down changes
 */
function upd_priceselect( picsel, pricesel, mountsel )
{
	var	picdetails = picsel.options[picsel.selectedIndex].value.split(':');
	pricesel.options[0] = new Option('£' + picdetails[2] + ' (framed)',
									 "framed", true, true);

	pricesel.options[1] = new Option('£' + picdetails[3] + ' (unframed)',
									 "unframed", false, false);
	mountsel.disabled = false;
}

/*
 * toggle_mountselect
 * Toggle the mount selection on and off
 *
 */
function toggle_mountselect( pricesel, mountsel )
{
	if( pricesel.options[pricesel.selectedIndex].value == 'framed' )
	{
		mountsel.disabled = false;
	}
	else
	{
		mountsel.disabled = true;
	}
}


/*
 * add_to_order
 * Add the selected item to the order select
 */
function add_to_order( picsel, pricesel, mountsel, ordersel )
{
	var picdetails	= picsel.options[picsel.selectedIndex].value.split(':');
	var frametxt	= (pricesel.selectedIndex								// 0 == framed, 1 == unframed
						? ' (unframed)'
						: ' (framed with ' + mountsel.options[mountsel.selectedIndex].value + ' mount)');
	var frameval	= (pricesel.selectedIndex ? '' : mountsel.options[mountsel.selectedIndex].value);

	
	var pricetxt	= picdetails[pricesel.selectedIndex+2];
	var newitem		= new Option( 
							picdetails[1] + ' @ £' + pricetxt + frametxt,	// text
							picdetails[0]  + ':' + frameval,				// value
							false,
							false
	);
	ordersel.options.add( newitem);
}


/*
 * del_from_order
 * Remove the selected items from the order
 */
function del_from_order( del_button, ordersel )
{
	for(var i=0; i < ordersel.options.length; i++)
	{
		if( ordersel.options[i].selected == true )
		{
			//ordersel.options.remove(i);   // IE ?
			ordersel.remove(i);
			i--;					// options shrinks by 1, next becomes current
		}
	}
	del_button.disabled = true;		// selected items removed, re-disable remove button
}

/*
 * warn_issue
 * Warn that only switch cards need an issue number.
 */
function warn_issue(cctype) 
{
	if( cctype.options[cctype.selectedIndex].value != 'switch' )
	{
		alert('Only Switch cards need an issue number, you may leave it blank.');
	}
}

/*
 * check_submit
 * Validate the form details before submission:
 * - check the order has at least 1 item to process
 * - check the order has address details
 * - check credit card submission has valid card details
 * - auto select all options in the order select
 */
function check_submit( ordersel )
{
	var result = false;		// be pessimistic
	
	with( document.orderform )
	{
		var cardtype   = card_type.options[card_type.options.selectedIndex].value;
		var expmonth   = card_expmonth.options[card_expmonth.options.selectedIndex].value;
		var expyear	   = card_expyear.options[card_expyear.options.selectedIndex].value;
		var startmonth = card_startmonth.options[card_startmonth.options.selectedIndex].value;
		var startyear  = card_startyear.options[card_startyear.options.selectedIndex].value;
		var issuenum   = card_issue.value || 'a';
        var security   = card_security.value;

		if( ordersel.options.length == 0 )
		{
			alert('You must first add at least one item to your order.');
		}
		else if( name.value == '' )
		{
			alert('You need enter your full name.');
		}
		else if( phone.value == '' || phone.value.length < 7 )
		{
			alert('You need to enter a valid phone number, in case we need to contact you about your order.');
		}
		else if( address.value == '' )
		{
			alert('You need to enter a delivery address.');
		}
		else if( address.value.length > 300 )
		{
			alert('You entered a very long address, please shorten it if possible, or phone us with your order.');
		}
		else
    	{
			if( submitter == 'paycheque' )
			{
				result = true;
			}
			else if( submitter == 'paycard' )
			{
				// Do the card validation
				if( cardtype == 0)
				{
					alert('Please choose a credit card type from the drop down list.');
				}
				else if( expmonth == 0 || expyear == 0 )
				{
					alert('Please choose your credit card expiry month and year from the drop down lists.');
				}
				else if( !validExpiryDate(expmonth, expyear) )
				{
					alert('The card has expired, please check the Expiry Date.');
				}
				else if( (startmonth && startyear) && !validStartDate(startmonth, startyear) )
				{
					// Check start date if they give one (should we force for Switch?)
					alert('The card isn\'t valid yet, please check the Start Date.');
				}
                else if ( security == '' || !allDigits(security) ) 
                {
                    alert('You must enter the credit card security code, the last 3 digits of the security strip on the reverse of your card.');
                }
				else if( isValidCreditCardNumber( card_number, cardtype, 'card_number', 1 ) )
				{
					result = true;
				}
			}
			else
			{
				alert('Invalid submission.');
			}
		}
	}

	if( result == true )
	{
		// Mark all the items as selected so they get POSTed
		for ( var i=0; i < ordersel.options.length; i++ )
		{
			ordersel.options[i].selected = true;
		}
	}

	return result;
}


/* Credit card validation */

// Form Field Validation Functions:
//
// isValidExpDate(formField,fieldLabel,required)
//   -- checks for date in the format MM/YY or MM/YYYY against the current date
// isValidCreditCardNumber(formField,ccType,fieldLabel,required)
//   -- checks for valid credit card format using the Luhn check and known digits about various cards
//
function numericOnly(sString)
{
   var sNumericOnly = "";
   var sValidChars = "1234567890";
   for (var iCharPos = 0; iCharPos < sString.length; iCharPos++)
   {
      if (sValidChars.indexOf(sString.charAt(iCharPos)) != -1)
      {
         sNumericOnly = sNumericOnly + sString.charAt(iCharPos);
      }
   }
   return sNumericOnly;
}
/*
function validRequired(formField,fieldLabel)
{
	var result = true;
	
	if (formField.value == "")
	{
		if( fieldLabel == 'card_number' )
		{
			alert('Please enter your credit card number.');
		}
		else
		{
			alert('Please enter a value for the "' + fieldLabel +'" field.');
		}
		formField.focus();
		result = false;
	}
	
	return result;
}
*/

function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

function validExpiryDate( expmonth, expyear )
{
	var now = new Date();
	var thismonth = now.getMonth() + 1;
	var thisyear  = now.getFullYear();

	return (expyear > thisyear) || (expyear == thisyear && expmonth >= thismonth );
}

function validStartDate( startmonth, startyear )
{
	var now = new Date();
	var thismonth = now.getMonth() + 1;
	var thisyear  = now.getFullYear();

	return (startyear < thisyear) || (startyear == thisyear && startmonth <= thismonth );
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

/*	if (required && !validRequired(formField,fieldLabel))
		result = false;
 */
  	if (result && (formField.value.length>0))
 	{ 
		ccNum = numericOnly(ccNum);

 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}	

		if (result)
 		{ 
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert("The credit card number isn't valid, please check it carefully.");
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}


function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first2digs = cardNum.substring(0,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTERCARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "SWITCH":
			result = (cardLen == 16 || cardLen == 18 || cardLen == 19) 
					&& (first2digs == 63 || first2digs == 67);
			break;
	}
	return result;
}
/*
function validCCForm(ccTypeField,ccNumField,ccExpField)
{
	var result = isValidCreditCardNumber(ccNumField,ccTypeField.value,"Credit Card Number",true) &&
		isValidExpDate(ccExpField,"Expiry Date",true);
	return result;
}
*/

