var whitespace = " \t\n\r";
var defaultEmptyOK = false;
var decimalPointDelimiter = "."

function CheckCreditCard(formObj)
{
  valid = true;
  cc_value = formObj.Card_No.value.replace(/\s+/g, "");

  if(formObj.Card.options[formObj.Card.selectedIndex].value == "Visa")
  {
    if(!isVisa(cc_value))
    {
      alert("The Visa card number you have entered is incorrect, please try again");
      valid = false;
    }
  }
  else if(formObj.Card.options[formObj.Card.selectedIndex].value == "MasterCard")
  {
    if(!isMasterCard(cc_value))
    {
      alert("The Master card number you have entered is incorrect, please try again");
      valid = false;
    }
  }
  else if(formObj.Card.options[formObj.Card.selectedIndex].value == "American Express")
  {
    if(!isAmericanExpress(cc_value))
    {
      alert("The American Express number you have entered is incorrect, please try again")
      valid = false;
    }
  }
  
  if(!valid)
    formObj.Card_No.focus();
      
  return valid;
}


function CheckNumRange(num_input, min, max)
{ 
  var valid;

  valid = true;

  if(!isFloat(num_input.value))
    valid = false;
  else
  {
    var num = parseFloat(num_input.value);
      
    if(!(-min <= num && num <= max))
      valid = false;
  }

  if(!valid)
  {
    str = "An error has occurred";
    str += "\nPlease enter a value in the field between " + min + " and " + max;
    alert(str);
    num_input.focus();
  }
      
  return valid;
}


function FloatValue(str)
{
  var value;

  if(isFloat(str))
    value = parseFloat(str);
  else
    value = 0;

  return value;
}


function FormatDecimalPlaces(num, places)
{
  var i, pos, str, zeros_to_add;
    
  if(FloatValue(num) != 0)
  {
    str = Math.round(num * Math.pow(10, places));
    str /= Math.pow(10, places);
    str = str.toString();
    str = str.replace(/,/, "");
    pos = str.search(/\./);

	  if(pos != -1)
	  {
	    zeros_to_add = places - (str.length - (pos + 1));

	    for(i = 0; i < zeros_to_add; i++)
	      str += "0";
	  }
    else
	    str += ".00";
  }
  else
    str = '0.00';

  return str;
}


function isAmericanExpress(cc)
{
  firstdig = parseInt(cc.substring(0,1));
  seconddig = parseInt(cc.substring(1,2));

  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);

  return false;
}

function isCreditCard(st) 
{
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);
}

function isDigit (c)
{   
  return ((c >= "0") && (c <= "9"))
}


function isEmail (s)
{   
  if (isEmpty(s)) 
    if (isEmail.arguments.length == 1) return defaultEmptyOK;
    else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isEmpty(s)
{   
  return ((s == null) || (s.length == 0))
}

function isMasterCard(cc)
{

  firstdig = parseInt(cc.substring(0,1));
  seconddig = parseInt(cc.substring(1,2));

  //alert(cc.length == 16);
  //alert(firstdig == 5);
  //alert(seconddig >= 1);
  //alert(seconddig <= 5);
 
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
  {
    return isCreditCard(cc);
  }

  return false;
}

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == '4'))
    return isCreditCard(cc);
  return false;
}


function isWhitespace (s)
{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}


function isEmpty(s)
{   
  return ((s == null) || (s.length == 0))
}


function isFloat (s)

{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}


function onClickAdd(form)
{
  var ok;
  ok = true;

  if(form.next_image.value.length > 0 || form.next_image_select.selectedIndex > 0)
  {
    if(form.next_image.value.length > 0 && form.next_image_select.selectedIndex == 0)
    {
      alert('You have selected an Image File but not a Size!');
      form.next_image_select.focus();
      ok = false;
    }

    if(form.next_image.value.length == 0 && form.next_image_select.selectedIndex > 0)
    {
      alert('You have selected a Size but not an Image File!');
      form.next_image.focus();
      ok = false;
    }

    if(form.next_image_quantity.value == '0')
    {
      alert('You must select a quantity greater than 0!');
      form.next_image_quantity.focus();
      ok = false;
    }

  }

  if(ok)
  {
    UpdateLabServicesURL(form);
    form.next_image_name.value = form.next_image.value;
  }

  return ok;
}


function OnClickDelete(form) 
{
  var ok;
  ok = true;

  if(!confirm('Are you sure you want to delete this entry?')) 
    ok = false; 
  else 
    UpdateLabServicesURL(form);

  return ok;
}


function onClickGo(form)
{
  var ok;
  ok = true;

  if(form.no_images.selectedIndex == 0)
  {
    alert('You must select how many images you will be enlarging!');
    ok = false;
  }

  return ok;
}

function onClickSubmitOrderAccount(form, no_images)
{
  var ok;
  ok = true;

  ok = ValidateImages(form, no_images);

  if(ok)
  {
    if(!form.delivery[0].checked && !form.delivery[1].checked && !form.delivery[2].checked && !form.delivery[3].checked)
    {
      alert('You must select a delivery type!');
      form.delivery[0].focus();
      ok = false;
    }
  }

  if(ok)
  {
    UpdateImageFileNames();
    ok = confirm('Warning: You MUST wait for the \'Thank You\' screen to appear to be sure your order has been sent correctly.\n\nThis system is set to upload a maximum of 10 Mb per order.\nTo send more images, please make multiple orders.\n\nPlease note that upload speeds vary depending on your connection to the Internet.\n\nIf you have a 56k modem, allow 5 minutes for each megabyte you are sending.');
  }
  
  if(ok)
    form.submit();
}


function onClickSubmitOrderCredit(form, no_images)
{
  var ok;
  ok = true;

  ok = ValidateImages(form, no_images);

  if(ok)
  {
    if(!form.delivery[0].checked && !form.delivery[1].checked && !form.delivery[2].checked && !form.delivery[3].checked)
    {
      alert('You must select a delivery type!');
      form.delivery[0].focus();
      ok = false;
    }
  }

  if(ok)
  {
    if(form.Card_No.value.length == 0)
    {
      form.Card_No.focus();
      alert('You must enter a credit card number!');
      ok = false;
    }
  }

  if(ok)
  {
    if(form.Exp_Date.value.length == 0)
    {
      form.Exp_Date.focus();
      alert('You must enter a credit card expiration date!');
      ok = false;
    }
  }

  if(ok)
  {
    if(form.Card_Name.value.length == 0)
    {
      form.Card_Name.focus();
      alert('You must enter a name!');
      ok = false;
    }
  }

  if(ok)
    ok = CheckCreditCard(form);

  if(ok)
  {
    UpdateImageFileNames();
    alert('Warning: You MUST wait for the \'Thank You\' screen to appear to be sure your order has been sent correctly.\n\nThis system is set to upload a maximum of 10 Mb per order.\nTo send more images, please make multiple orders.\n\nThe files you have selected will now be sent to Vanbar for processing.\n\nPlease note that upload speeds vary depending on your connection to the internet.\n\nIf you have a 56k modem, allow 5 minutes for each megabyte you are sending.');
  }
  
  if(ok)
    form.submit();

}

function OnLoginAccount(form)
{
  var ok;
  ok = true;

  if(form.account.value.length == 0)
  {
    form.account.focus();
    alert('You must enter a value for the account number!');
    ok = false;
  }
  
  if(ok)
  {
    if(form.account_password.value.length == 0)
    {
      form.account_password.focus();
      alert('You must enter a value for the password!');
      ok = false;
    }
  }

  if(ok)
    form.username.value = form.account.value;

  return ok;

}


function OnLoginEmail(form)
{
  var ok;
  ok = true;

  if(!isEmail(form.email.value))
  {
    form.email.focus();
    alert('You must enter a valid email address!');
    ok = false;
  }

  if(ok)
  {
    if(form.email_password.value.length == 0)
    {
      form.email_password.focus();
      alert('You must enter a value for the password!');
      ok = false;
    }
  }

  if(ok)
    form.username.value = form.email.value;

  return ok;
}


function OnSubmitAccount(form)
{
  var ok;
  ok = true;

  if(form.account.value.length == 0)
  {
    form.account.focus();
    alert('You must enter a value for the Vanbar Credit Account Number!');
    ok = false;
  }
  
  if(ok)
  {
    if(!isEmail(form.email.value))
    {
      form.email.focus();
      alert('You must enter a valid email address!');
      ok = false;
    }
  }

  return ok;

}


function OnSubmitEmail(form)
{
  var ok;
  ok = true;

  if(form.first.value.length == 0)
  {
    form.first.focus();
    alert('You must enter a value for the first name!');
    ok = false;
  }
  
  if(ok)
  {
    if(form.last.value.length == 0)
    {
      form.last.focus();
      alert('You must enter a value for the last name!');
      ok = false;
    }
  }

  if(ok)
  {
    if(!isEmail(form.email.value))
    {
      form.email.focus();
      alert('You must enter a valid email address!');
      ok = false;
    }
  }

  if(ok)
  {
    if(form.address.value.length == 0)
    {
      form.address.focus();
      alert('You must enter a value for the delivery address!');
      ok = false;
    }
  }

  if(ok)
  {
    if(form.address.value.length > 200)
    {
      form.address.focus();
      alert('The address must be less than 200 characters!');
      ok = false;
    }
  }

  if(ok)
  {
    if(form.password.value.length < 6)
    {
      form.password.focus();
      alert('The password must be at least six characters long!');
      ok = false;
    }
  }

  if(ok)
  {
    pattern = new RegExp("[0123456789]");
    
    if(!pattern.test(form.password.value))
    {
      form.password.value = '';
      form.password_confirm.value = '';
      form.password.focus();
      alert('The password must contain at least one digit!');
      ok = false;
    }
  }

  if(ok)
  {
    pattern = new RegExp(form.password.value);
    
    if(!pattern.test(form.password_confirm.value))
    {
      form.password.value = '';
      form.password_confirm.value = '';
      form.password.focus();
      alert('The passwords are not the same!');
      ok = false;
    }
  }

  return ok;
}


function stripCharsInBag(s, bag)
{   
  var i;
    
  var returnString = "";

  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.

  for (i = 0; i < s.length; i++)
  {   
      // Check that current character isn't whitespace.
      var c = s.charAt(i);
      if (bag.indexOf(c) == -1) returnString += c;
  }

  return returnString;
}


function UpdateLabServicesURL(form)
{
  //alert(form.action);
  //alert(form.action.search(/labservices=1/));

  if(form.action.search(/labservices=1/) == -1)
  {
    if(form.action.search(/\?/) == -1)
      form.action += '?labservices=1'; 
    else
      form.action += '&labservices=1'; 
  }

  //alert(form.action);
}


function ValidateImage(form, image_no)
{
  var ok, pos;

  //alert(form.elements[image_no + 3].name.value);

  ok = true;

  if(ok)
    ok = ValidateImageDetailed(form.elements[image_no + 3], form.elements[image_no + 5], form.elements[image_no + 6], form.elements[image_no + 8], true);

  if(ok)
    ok = ValidateImageDetailed(form.elements[image_no + 3], form.elements[image_no + 11], form.elements[image_no + 12], form.elements[image_no + 14], false);

  if(ok)
    ok = ValidateImageDetailed(form.elements[image_no + 3], form.elements[image_no + 17], form.elements[image_no + 18], form.elements[image_no + 20], false);

  return ok;
}


function ValidateImageDetailed(next_image, next_image_type, next_image_select, next_image_quantity, check_image)
{
  var ok;
  ok = true;

  if(ok && next_image.value.length > 0)
  {
    pos = next_image.value.search(/\./);

    if(pos != -1)
    {
      if(RegExp.rightContext.search(/jpg|jpeg|tiff|tif|psd/i) == -1)
      {
        next_image.focus();
        alert('You can only upload jpg, jpeg or tiff files!');
        ok =false;
      }
    } 
    else
      ok =false;
  }


  if(ok && next_image.value.length > 0 && check_image)
  //image but no type or size
  {
    if(ok && next_image_type.selectedIndex == 0)
    {
      alert('You have selected an Image but not an Image Type!');
      next_image_type.focus();
      ok = false;
    }

    if(ok && next_image_select.selectedIndex == 0)
    {
      alert('You have selected an Image but not an Image Size!');
      next_image_select.focus();
      ok = false;
    }

    if(ok && next_image_quantity.value == '0')
    {
      alert('You have selected an Image Size but not a quantity!');
      next_image_quantity.focus();
      ok = false;
    }
  }

  if(ok && next_image_select.selectedIndex > 0)
  //size but no image or quantity
  {
    if(next_image.value.length == 0)
    {
      alert('You have selected an Image Size but not an Image File to upload!');
      next_image.focus();
      ok = false;
    }

    if(ok && next_image_type.selectedIndex == 0)
    {
      alert('You have selected an Image Size but not an Image Type!');
      next_image_type.focus();
      ok = false;
    }

    if(ok && next_image_quantity.value == '0')
    {
      alert('You have selected a Image Size but not a quantity!');
      next_image_quantity.focus();
      ok = false;
    }
  }

  if(ok && next_image_type.selectedIndex > 0)
  //image type but no image or quantity
  {
    if(next_image.value.length == 0)
    {
      alert('You have selected an Image Type but not an Image File to upload!');
      next_image.focus();
      ok = false;
    }

    if(ok && next_image_select.selectedIndex == 0)
    {
      alert('You have selected an Image Type but not an Image Size!');
      next_image_select.focus();
      ok = false;
    }

    if(ok && next_image_quantity.value == '0')
    {
      alert('You have selected an Image Type but not a quantity!');
      next_image_quantity.focus();
      ok = false;
    }
  }

  return ok;
}


function ValidateImages(form , no_images)
{
  var no, ok;
  ok = true;
  no = 0;

  for(i = 0; i < no_images && ok; i++)
  {
    ok = ValidateImage(form, 20*i + 1);

    if(ok)
    {
      if(form.elements[20*i + 1 + 3].value.length > 0)
        no += 1;
    }
  }

  if(ok && no == 0)
  {
    alert('You have not chosen any images for processing!');
    ok = false;
  }

  return ok;
}


