
function resetLabels()
{
  //document.getElementById( "labelDelCity" ).className = "formLabelM";
  //document.getElementById( "labelDelCounty" ).className = "formLabelM";
  //document.getElementById( "labelDelCountryCode" ).className = "formLabelM";
  //document.getElementById( "labelDelPostCode" ).className = "formLabelM";
  //document.getElementById( "labelDelLine1" ).className = "formLabelM";
  //document.getElementById( "labelDelCustomerName" ).className = "formLabelM";
  document.getElementById( "labelBillCountryCode" ).className = "formLabelM";
  document.getElementById( "labelBillPostCode" ).className = "formLabelM";
  document.getElementById( "labelBillCounty" ).className = "formLabelM";
  document.getElementById( "labelBillCity" ).className = "formLabelM";
  document.getElementById( "labelBillLine1" ).className = "formLabelM";
  document.getElementById( "labelBillCustomerName" ).className = "formLabelM";
  document.getElementById( "labelValidFrom" ).className = "formLabel";
  document.getElementById( "labelExpiresEnd" ).className = "formLabel";
  document.getElementById( "labelIssueNumber" ).className = "formLabel";
  document.getElementById( "labelSecurityCode" ).className = "formLabelM";
  document.getElementById( "labelCardHolderName" ).className = "formLabelM";
  document.getElementById( "labelCardType" ).className = "formLabelM";
  document.getElementById( "labelCardNumber" ).className = "formLabelM";
  document.getElementById( "labelCardNumber" ).className = "formLabelM";
  document.getElementById( "labelCustomerEmail" ).className = "formLabel";
  //document.getElementById( "labelCardHolderPresent" ).className = "formLabelM";

}

function checkForm( theForm )
{
  theForm.buttSubmit.disabled = true;

  resetLabels( );

  updateDeliveryAddressDetails( theForm, true );

  var message = "";

  if( theForm.CardHolderPresent.value == "" )
  {
    message += "Please fill in where the customer is located at the time the payment is made.<br />";
    //document.getElementById( "labelCardHolderPresent" ).className = "formLabelM errorFill";
  }

  if( theForm.CardNumber.value.indexOf( "*" ) !=-1 )  //saved card, use saved number
  {
    if( theForm.CardNumberHidden.value.length==0 || isNaN( theForm.CardNumberHidden.value ) )
    {
      //not a number
    }
    else
    {
      theForm.CardNumber.value = theForm.CardNumberHidden.value;
    }
  }

  while( theForm.CardNumber.value.indexOf( " " )!=-1 )
  {
    theForm.CardNumber.value = theForm.CardNumber.value.replace( " ", "" );
  }

  //Check all Card details
  if( theForm.CardNumber.value == "" )
  {
    message += "Card Number: No value was entered.<br />";
    document.getElementById( "labelCardNumber" ).className = "formLabelM errorFill";
  }
  else if ( isNaN( theForm.CardNumber.value ) )
  {
    message += "Card Number: The value entered is not a valid card number.<br />";
    document.getElementById( "labelCardNumber" ).className = "formLabelM errorFill";
  }
  else if( theForm.CardNumber.value.length<15 )
  {
    message += "Card Number: The value entered is not a valid card number.<br />";
    document.getElementById( "labelCardNumber" ).className = "formLabelM errorFill";
  }

  var radioCheck = valueChecked( theForm.CardType );

  if( radioCheck == "-1" )
  {
    message += "Card Type: No type was selected.<br />";
    document.getElementById( "labelCardType" ).className = "formLabelM errorFill";
  }

  if( theForm.CardHolderName.value == "" )
  {
    message += "Card Owner Name: No value was entered.<br />";
    document.getElementById( "labelCardHolderName" ).className = "formLabelM errorFill";
  }

  if( theForm.SecureCode.value == "" )
  {
    message += "Security Code: No value was entered.<br />";
    document.getElementById( "labelSecurityCode" ).className = "formLabelM errorFill";
  }
  else if( isNaN( theForm.SecureCode.value ) )
  {
    message += "Security Code: Invalid value entered.<br />";
    document.getElementById( "labelSecurityCode" ).className = "formLabelM errorFill";
  }
  else if( theForm.SecureCode.value.length>0 && theForm.SecureCode.value.length<=2 )
  {
    message += "Security Code: It should be a 3 or 4 digit number.<br />";
    document.getElementById( "labelSecurityCode" ).className = "formLabelM errorFill";
  }

  var now = new Date();
  var currentYear = parseInt(now.getYear());
  var monthExpire = -1;
  var yearExpire = 0;

  if( parseInt(currentYear) < 200 )
  {
    currentYear = currentYear + parseInt(1900);
  }

  if( ( radioCheck == "maestro" || radioCheck == "solo" ) && theForm.IssueNumber.value != "" && isNaN( theForm.IssueNumber.value ) )
  {
    message += "Issue Number: The value entered is not a number.<br />";
    document.getElementById( "labelIssueNumber" ).className = "formLabel errorFill";
  }
  else if( radioCheck != "maestro" && radioCheck != "solo" && theForm.IssueNumber.value != "" )
  {
    message += "Issue Number: Issue numbers are only accepted for payments by Maestro or Solo cards.<br />";
    document.getElementById( "labelIssueNumber" ).className = "formLabel errorFill";
  }

  if( radioCheck == "maestro" || radioCheck == "solo" )
  {
    if( theForm.IssueNumber.value == "" )
    {
      if( theForm.ValidFromMonth.selectedIndex == 0 || theForm.ValidFromYear.selectedIndex == 0 )
      {
        message += "Valid From Date: You need to specify an issue number OR a Valid From Date if you wish to pay with a Maestro or Solo card.<br />";
        document.getElementById( "labelValidFrom" ).className = "formLabel errorFill";
        document.getElementById( "labelIssueNumber" ).className = "formLabel errorFill";
      }
      else
      {
        monthExpire = parseInt((theForm.ValidFromMonth.options[theForm.ValidFromMonth.selectedIndex].value))-1;
        yearExpire = parseInt(theForm.ValidFromYear.options[theForm.ValidFromYear.selectedIndex].value);

        if( yearExpire > currentYear || ( yearExpire==currentYear && monthExpire>now.getMonth() ) )
        {
          message += "Valid From Date: The date specified is not yet valid.<br />";
          document.getElementById( "labelValidFrom" ).className = "formLabel errorFill";
        }
      }
    }
    else if( theForm.ValidFromMonth.selectedIndex != 0 && theForm.ValidFromYear.selectedIndex != 0 )
    {
      var monthExpire = (theForm.ValidFromMonth.options[theForm.ValidFromMonth.selectedIndex].value)-1;
      var yearExpire = theForm.ValidFromYear.options[theForm.ValidFromYear.selectedIndex].value;

      if( yearExpire > currentYear || ( yearExpire==currentYear && monthExpire>now.getMonth() ) )
      {
        message += "Valid From Date: The date specified is not yet valid.<br />";
        document.getElementById( "labelValidFrom" ).className = "formLabel errorFill";
      }
    }
  }
  else if( ( theForm.ValidFromMonth.selectedIndex != 0 && theForm.ValidFromYear.selectedIndex == 0 ) || ( theForm.ValidFromMonth.selectedIndex == 0 && theForm.ValidFromYear.selectedIndex != 0 ) )
  {
    message += "Valid From Date: Please specify both month and year.<br />";
    document.getElementById( "labelValidFrom" ).className = "formLabel errorFill";
  }
  else if( theForm.ValidFromMonth.selectedIndex != 0 && theForm.ValidFromYear.selectedIndex != 0 )
  {
    var monthExpire = (theForm.ValidFromMonth.options[theForm.ValidFromMonth.selectedIndex].value)-1;
    var yearExpire = theForm.ValidFromYear.options[theForm.ValidFromYear.selectedIndex].value;

    if( yearExpire > currentYear || ( yearExpire==currentYear && monthExpire>now.getMonth() ) )
    {
      message += "Valid From Date: The date specified is not yet valid.<br />";
      document.getElementById( "labelValidFrom" ).className = "formLabel errorFill";
    }
  }

  monthExpire = (theForm.CardExpiryMonth.options[theForm.CardExpiryMonth.selectedIndex].value)-1;
  yearExpire = theForm.CardExpiryYear.options[theForm.CardExpiryYear.selectedIndex].value;

  if( yearExpire < currentYear || ( yearExpire==currentYear && monthExpire<now.getMonth() ) )
  {
    message += "Expires End Date: The date specified has already expired.<br />";
    document.getElementById( "labelExpiresEnd" ).className = "formLabel errorFill";
  }

  //Check all billing address details
  if( theForm.BillCustomerName.value == "" )
  {
    message += "Billing Customer Name: No value was entered.<br />";
    document.getElementById( "labelBillCustomerName" ).className = "formLabelM errorFill";
  }

  if( theForm.BillLine1.value == "" )
  {
    message += "Billing Line 1: No value was entered.<br />";
    document.getElementById( "labelBillLine1" ).className = "formLabelM errorFill";
  }

  if( theForm.BillCity.value == "" )
  {
    message += "Billing City: No value was entered.<br />";
    document.getElementById( "labelBillCity" ).className = "formLabelM errorFill";
  }

  if( theForm.BillCounty.value == "" ) //replacing county with city
  {
    theForm.BillCounty.value =  theForm.BillCity.value;
    theForm.DelCounty.value =  theForm.DelCity.value;
  }

  if( theForm.BillCounty.value == "" )
  {
    message += "Billing County: No value was entered.<br />";
    document.getElementById( "labelBillCounty" ).className = "formLabelM errorFill";
  }

  //if( theForm.BillCountryCode.selectedIndex == 0 )
  //{
  //  message += "Billing Country: No country was selected.<br />";
  //  document.getElementById( "labelBillCountryCode" ).className = "formLabelM errorFill";
  //}

  if( theForm.BillPostCode.value == "" )
  {
    message += "Billing Postcode: No value was entered.<br />";
    document.getElementById( "labelBillPostCode" ).className = "formLabelM errorFill";
  }

  if( theForm.CustomerEmail.value != "" && ( theForm.CustomerEmail.value.indexOf( "@" ) == -1  || theForm.CustomerEmail.value.indexOf( ".", theForm.CustomerEmail.value.indexOf( "@" ) ) == -1 ) )
  {
    message += "Billing Email: The email entered is invalid.<br />";
    document.getElementById( "labelCustomerEmail" ).className = "formLabel errorFill";
  }

   //Check all delivery address details
  //if( theForm.DelCustomerName.value == "" )
  //{
  //  message += "Delivery Customer Name: No value was entered.<br />";
  //  document.getElementById( "labelDelCustomerName" ).className = "formLabelM errorFill";
  //}
  //
  //if( theForm.DelLine1.value == "" )
  //{
  //  message += "Delivery Line 1: No value was entered.<br />";
  //  document.getElementById( "labelDelLine1" ).className = "formLabelM errorFill";
  //}
  //
  //if( theForm.DelCity.value == "" )
  //{
  //  message += "Delivery City: No value was entered.<br />";
  //  document.getElementById( "labelDelCity" ).className = "formLabelM errorFill";
  //}
  //
  //if( theForm.DelCounty.value == "" )
  //{
  //  message += "Delivery County: No value was entered.<br />";
  //  document.getElementById( "labelDelCounty" ).className = "formLabelM errorFill";
  //}

  //if( theForm.DelCountryCode.selectedIndex == 0 )
  //{
  //  message += "Delivery Country: No country was selected.<br />";
  //  document.getElementById( "labelDelCountryCode" ).className = "formLabelM errorFill";
  //}
  //if( theForm.DelPostCode.value == "" )
  //{
  //  message += "Delivery Postcode: No value was entered.<br />";
  //  document.getElementById( "labelDelPostCode" ).className = "formLabelM errorFill";
  //}

  if( message.length == 0 || message == '' )
  {
    //setDeliveryFields( theForm, false );
    
    //if( radioChecked == "visa" || radioChecked == "mastercard" || radioChecked == "maestro" )
    //{
    //  theForm.mode.value = "authenticate"; 
    //}
    //else
    //{
    //  theForm.mode.value = "save";
    //}
    
    theForm.submit();
    return true;
  }

  if( theForm.CardNumber.value.length >=4 && typeof( theForm.CreditCardId ) != "undefined" && theForm.CreditCardId.selectedIndex >0 ) //if card number less than 4 characters, then leave it as it is
  {
    theForm.CardNumber.value = "************" + theForm.CardNumber.value.substring( theForm.CardNumber.value.length-4 );
  }

  document.getElementById( "labelMessage" ).innerHTML = "<span class='normalText'>The following fields have not been filled correctly:</span><br /><br />" + message + "<br /><span class='normalText'>Please correct those fields, highlighted in blue below and click 'Process Payment' again.</span><br /><br />";
  document.getElementById( "labelMessage" ).className = "showLabel errorFill";
  document.getElementById( "labelMessage" ).focus();

  $.prompt( "<span class='normalText'>The following fields have not been filled correctly:</span><br /><br />" + message + "<br /><span class='normalText'>Please correct those fields, highlighted in blue and click 'Process Payment' again.</span><br /><br />" );

  theForm.buttSubmit.disabled = false;
  return false;
}

function valueChecked( objField )
{
  for( var count=0; count<objField.length; count++ )
  {
    if( objField[count].checked )
    {
      return objField[count].value;
    }
  }
  return "-1";
}

//fill the form with details from card
function fillForm( theForm, cardToUse )
{
  var theDiv = document.getElementById( "CardNumberDiv" );

  $(theDiv).load( "/js/getCardNumber.jsp?cardNumber=" + cardToUse.cardNumber, function(){
    //theForm.CardNumber.value = theDiv.innerHTML;
    theForm.CardNumberHidden.value = theDiv.innerHTML;
    } );

  theForm.CardNumber.value = cardToUse.cardNumberObscured;
  theForm.CardHolderName.value = cardToUse.cardHolderName;

  selectRadioValue( theForm.CardType, cardToUse.cardType );

  selectListValue( theForm.ValidFromMonth, cardToUse.validFromMM );
  selectListValue( theForm.ValidFromYear, cardToUse.validFromYY );
  selectListValue( theForm.CardExpiryMonth, cardToUse.expiresEndMM );
  selectListValue( theForm.CardExpiryYear, cardToUse.expiresEndYY );

  theForm.SecureCode.value = "";
  theForm.IssueNumber.value = cardToUse.issueNumber;

  if( typeof(cardToUse.billingAddress) == "object" )
  {
    theForm.BillAddressId.value = cardToUse.billingAddress.billingAddressId;
    theForm.BillCustomerName.value = cardToUse.billingAddress.customerName;
    if( cardToUse.billingAddress.customerName == "" )
    {
       theForm.BillCustomerName.value = cardToUse.cardHolderName;
    }
    theForm.BillCustomerCompanyName.value = cardToUse.billingAddress.companyName;

    theForm.BillLine1.value = cardToUse.billingAddress.line1;
    theForm.BillLine2.value = cardToUse.billingAddress.line2;
    theForm.BillLine3.value = cardToUse.billingAddress.line3;
    theForm.BillCity.value = cardToUse.billingAddress.city;
    theForm.BillCounty.value = cardToUse.billingAddress.county;
    selectListValue( theForm.BillCountryCode, cardToUse.billingAddress.countryCode );

    theForm.BillPostCode.value = cardToUse.billingAddress.postcode;
    theForm.BillTelephoneNumber.value = cardToUse.billingAddress.tel;
    theForm.BillFaxNumber.value = cardToUse.billingAddress.fax;
    theForm.CustomerEmail.value = cardToUse.billingAddress.email;
  }
}

function selectListValue( objField, objValue )
{

  for( var i=0; i<objField.options.length; i++ )
  {
    if( objField.options[i].value == objValue )
    {
       objField.options[i].selected = true;
       break;
    }
    else
    {
      objField.options[i].selected = false;
    }
  }
}

function selectRadioValue( objField, objValue )
{

  for( var i=0; i<objField.length; i++ )
  {
    if( objField[i].value == objValue )
    {
       objField[i].checked = true;
       break;
    }
    else
    {
      objField[i].checked = false;
    }
  }
}

function updateCreditCardDetails( theForm, cardObj )
{
  var cardToUse = new Object();

  if( cardObj.selectedIndex>0 )
  {
    cardToUse = cards[cardObj.selectedIndex-1];
    //replace values with those ones
    fillForm( theForm, cardToUse );
    updateDeliveryAddressDetails( theForm, false );
    $("#deleteDetails").removeAttr("disabled");
  }
  else
  {
    //clear all fields
    theForm.reset();
    theForm.BillAddressId.value = "-1"
    theForm.CardNumberHidden.value = "";
    updateDeliveryAddressDetails( theForm, false );
    $("#deleteDetails").attr("disabled","disabled");
  }

}

//same value in billing and delivery
function updateDeliveryAddressDetails( theForm, checkValue )
{
  if( checkValue == true )
  {
    theForm.DelCustomerName.value = theForm.BillCustomerName.value;
    theForm.DelCustomerCompanyName.value = theForm.BillCustomerCompanyName.value;
    theForm.DelLine1.value = theForm.BillLine1.value;
    theForm.DelLine2.value = theForm.BillLine2.value;
    theForm.DelLine3.value = theForm.BillLine3.value;
    theForm.DelCity.value  = theForm.BillCity.value;
    theForm.DelCounty.value = theForm.BillCounty.value;
    theForm.DelCountryCode.value = theForm.BillCountryCode.options[theForm.BillCountryCode.selectedIndex].value;
    //selectListValue( theForm.DelCountryCode, theForm.BillCountryCode.value );
    theForm.DelPostCode.value = theForm.BillPostCode.value;
    theForm.DelTelephoneNumber.value = theForm.BillTelephoneNumber.value;
    theForm.DelFaxNumber.value = theForm.BillFaxNumber.value;

    //setDeliveryFields( theForm, true );
    //theForm.DelCustomerName.disabled = true;
    //theForm.DelCustomerCompanyName.disabled = true;
    //theForm.DelLine1.disabled = true;
    //theForm.DelLine2.disabled = true;
    //theForm.DelLine3.disabled = true;
    //theForm.DelCity.disabled = true;
    //theForm.DelCounty.disabled = true;
    //theForm.DelCountryCode.disabled = true;
    //theForm.DelPostCode.disabled = true;
    //theForm.DelTelephoneNumber.disabled = true;
    //theForm.DelFaxNumber.disabled = true;
  }
  else
  {
    theForm.DelCustomerName.value = '';
    theForm.DelCustomerCompanyName.value = '';
    theForm.DelLine1.value = '';
    theForm.DelLine2.value = '';
    theForm.DelLine3.value = '';
    theForm.DelCity.value  = '';
    theForm.DelCounty.value = '';
    //theForm.DelCountryCode.selectedIndex = 0;
    theForm.DelCountryCode.value = '';
    theForm.DelPostCode.value = '';
    theForm.DelTelephoneNumber.value = '';
    theForm.DelFaxNumber.value = '';

    //setDeliveryFields( theForm, false );

    //theForm.DelCustomerName.disabled = false;
    //theForm.DelCustomerCompanyName.disabled = false;
    //theForm.DelLine1.disabled = false;
    //theForm.DelLine2.disabled = false;
    //theForm.DelLine3.disabled = false;
    //theForm.DelCity.disabled = false;
    //theForm.DelCounty.disabled = false;
    //theForm.DelCountryCode.disabled = false;
    ////selectListValue();
    //theForm.DelPostCode.disabled = false;
    //theForm.DelTelephoneNumber.disabled = false;
    //theForm.DelFaxNumber.disabled = false;

  }

  return;
}

function setDeliveryFields( theForm, enableType )
{
  theForm.DelCustomerName.disabled = enableType;
  theForm.DelCustomerCompanyName.disabled = enableType;
  theForm.DelLine1.disabled = enableType;
  theForm.DelLine2.disabled = enableType;
  theForm.DelLine3.disabled = enableType;
  theForm.DelCity.disabled = enableType;
  theForm.DelCounty.disabled = enableType;
  theForm.DelCountryCode.disabled = enableType;
  theForm.DelPostCode.disabled = enableType;
  theForm.DelTelephoneNumber.disabled = enableType;
  theForm.DelFaxNumber.disabled = enableType;
}

function getReloadUri(theForm)
{
  //return document.location.href+(document.location.href.indexOf("?")>-1?"&":"?")+"ccidx="+theForm.CreditCardId.selectedIndex+"&cb="+Math.round(Math.random()*1000);
  if( typeof(theForm.CreditCardId)!= "undefined" )
  {
    return document.location.href+(document.location.href.indexOf("?")>-1?"&":"?")+"ccidx="+theForm.CreditCardId.selectedIndex+"&cb="+Math.round(Math.random()*1000);
  }
  
  return document.location.href+(document.location.href.indexOf("?")>-1?"&":"?")+"ccidx=1&cb="+Math.round(Math.random()*1000);
}
function saveCard( theForm, checkboxElement )
{
  var doSave = function(v,m)
  {
    if(v)
    {
      updateDeliveryAddressDetails( theForm, true );
      
      //making sure that if the card is updated, then hidden full normal card should be used instead
      if( theForm.CardNumber.value.indexOf( "*" ) !=-1 )  //saved card, use saved number
      {
        if( theForm.CardNumberHidden.value.length==0 || isNaN( theForm.CardNumberHidden.value ) )
        {
          //not a number
        }
        else
        {
          theForm.CardNumber.value = theForm.CardNumberHidden.value;
        }
      }
      
      $.post( "/servlet/StoreDetails", $(theForm).serializeArray(), function(d,s)
      {
        if( typeof(d)!="object" )
        {
          notify("Error submitting data to server. Please try again.", null )
        }
        else if( d.success )
        {
          notify("Details saved successfully.", function(){ document.location.href = getReloadUri(theForm) } )
        }
        else
        {
          notify("Unable to save details:<br/><br/><strong>"+d.message+"</strong>", null );
        }
      },"json");
    }

    if( typeof(checkboxElement) != "undefined" && checkboxElement.checked )
    {
      checkboxElement.checked = false;
    }
    return true;

  }

  $.prompt( "<span class='normalText'>Are you sure you wish to <strong>save</strong> these card details?</span><br /><br />", { buttons: { Ok: true, Cancel: false }, focus: 1, submit:doSave } );
}

function deleteCard( theForm, checkboxElement )
{
  if( $("select[name=CreditCardId]").val() == "-1" )
  {
    try
    {
      checkboxElement.checked = false;
    }
    catch(ex){}
    return false;
  }

  var doDelete = function(v,m)
  {
    if(v)
    {
      updateDeliveryAddressDetails( theForm, true );
      $.post( "/servlet/RemoveDetails", $(theForm).serializeArray(), function(d,s)
      {
        if( typeof(d)!="object" )
        {
          notify("Error connecting to server. Please try again.", null )
        }
        else if( d.success )
        {
          notify("Details deleted.", function(){ document.location.href = getReloadUri(theForm) } )
        }
        else
        {
          notify("Unable to delete details:<br/><br/><strong>"+d.message+"</strong>", null );
        }
      },"json");
    }

    if( typeof(checkboxElement) != "undefined" && checkboxElement.checked )
    {
      checkboxElement.checked = false;
    }
    return true;
  }

  $.prompt( "<span class='normalText'>Are you sure you wish to <strong>delete</strong> these card details?<br/><br/>Once the card has been removed it cannot be reinstated without manually re-entering the details.</span><br /><br />",{ buttons: { Ok: true, Cancel: false }, focus: 1, submit:doDelete } );
}

function notify( msg, callback )
{
  $.prompt( "<span class='normalText'>"+msg+"</span><br /><br />",{ buttons: { Ok: true }, submit:callback } );
}
