// Type / Oil Selection change
$(function(){
  $("#oil_type").change(function(){
    $.getJSON("/oil_products/",{call:"ajxgetOilProducts", cat:$(this).val(), ajax: 'true'}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].id + '">' + j[i].val + '</option>';
      }
      $("select#oil").html(options);
      CalculateQuantity();
    })
  })
})

//Price calculation
$(function(){
  $("#commentsq").click(function(){
   $("#commentsqctr").slideUp('slow');
      $("#commentsctr").slideDown('slow');



  })
  $("img#price-calc").click(function(){
    calcPrice();
  })
/*
  $("#oil").blur(function(){
    CalculateQuantity();
  })*/

})



function openTerms(){
window.open('/terms-and-conditions/?light=1','joterms',
'width=600,height=500,toolbar=0,resizable=1,scrollbars=1');

  //jQuery.facebox({ ajax: "/terms-and-conditions/?light=1" });
  return false;

}

function CalculatePrice(postfix) {
      $.getJSON("/oil_products/",{call:"ajxgetBandedOilPrices", cat:$("select#oil"+postfix).val(),qty:$("input#quantity"+postfix).val() ,ajax: 'true'}, function(j){
      $("span#cash_price"+postfix).html(j.price);
      var nPrice = j.nPrice
      $("input#amount"+postfix).val(nPrice);
      //show any invisble payment button (ONLY IF the minimum amt is reached)
      if (isNaN(nPrice)) {
        $('#submit-button:invisible').hide();
      } else {
        $('#submit-button:invisible').fadeIn();
      }
    })
}

function calcPrice(postfix) {
    $.getJSON("/oil_products/",{call:"ajxgetBandedOilPrices", cat:$("select#oil").val(),qty:$("input#quantity").val() ,ajax: 'true'}, function(j){
      $("span#cash_price"+postfix).html(j.price);
      var nPrice = j.nPrice
      $("input#amount"+postfix).val(nPrice);
      $('#submit-button:invisible').fadeIn();
    })
}

function CalculateQuantity(postfix) {
  $.getJSON("/oil_products/",{call:"ajxgetBandedOilLitres", cat:$("select#oil"+postfix).val(),amount:$("input#amount"+postfix).val() ,ajax: 'true'}, function(j){
    $("span#quantity_litres"+postfix).html(j.litres);
    $("input#quantity"+postfix).val(j.litres);
    $('#submit-button:invisible').fadeIn();
  })
}


/**
* Based upon the payment type selection show different options
**/

function togglePaymentDetails(sPaymentType) {

  if (sPaymentType=='') {
    //close all
    $("#budget_plan_details").hide();
    $("#credit_card_details").hide();
    $("#credit_card_holder_details").hide();
    $("#other_payment_details").hide();
    $("#paypoint_details").hide();
    fixColumnHeights();
    return;
  }

  if (sPaymentType=='Credit Debit') {
    //close other details
    $("#paypoint_details:visible").slideUp();
    $("#budget_plan_details:visible").slideUp();
    $("#other_payment_details:visible").slideUp();

    //show the credit card info form
    $("#credit_card_details").show();
    fixColumnHeights();
  }

  if (sPaymentType=='Budget Plan') {
    //close other details
    $("#paypoint_details:visible").slideUp();
    $("#other_payment_details:visible").slideUp();
    $("#credit_card_details:visible").slideUp();
    $("#credit_card_holder_details:visible").slideUp();

    //show the budget plan info form
    $("#budget_plan_details").show();
    fixColumnHeights();
  }

  if (sPaymentType=='Paypoint') {
    //close other details
    $("#credit_card_details").hide();
    $("#budget_plan_details").hide();
    $("#credit_card_holder_details").hide();
    $("#other_payment_details").hide();

    //show
    $("#paypoint_details").show();

  }


  if (sPaymentType!='Credit Debit' && sPaymentType!='Paypoint' && sPaymentType!='Budget Plan') {
    //close other details
    $("#credit_card_details").hide();
    $("#budget_plan_details").hide();
    $("#credit_card_holder_details").hide();
    $("#paypoint_details").hide();

    //show
    $("#other_payment_details").show();
  }

  //now fix the left and right column heights to match;
  fixColumnHeights()

}//end function togglePaymentDetails


/**
* This is the little checkbox that makes it easy for
* people to fill in the card holder details
**/
function asAbove() {

  document.getElementById("card_holder_name").value      = $("#customer_title").val() + ' ' + $("#customer_first_name").val() + ' ' + $("#customer_surname").val()  ;

  document.getElementById("card_holder_title").value      = $("#customer_title").val();
  document.getElementById("card_holder_first_name").value = $("#customer_first_name").val() ;
  document.getElementById("card_holder_surname").value       = $("#customer_surname").val();

  document.getElementById("card_holder_address_1").value = $("#customer_address_1").val()  ;
  document.getElementById("card_holder_address_2").value = $("#customer_address_2").val()  ;
  document.getElementById("card_holder_address_3").value = $("#customer_address_3").val()  ;
  document.getElementById("card_holder_county").value    = $("#customer_county").val()  ;
  document.getElementById("card_holder_telephone").value = $("#customer_telephone").val()  ;
  document.getElementById("card_holder_email").value     = $("#customer_email").val()  ;


}//end function asAbove







function validateMainOrder(oForm) {


 		if (!IsEmailValid(oForm.customer_email)) {
			alert('Please enter a valid email address');
			oForm.customer_email.focus();
			return false;
		}

    // Check Customer Details
    if (oForm.customer_title.selectedIndex == 0) {
			alert('Please select your title.');
			oForm.customer_title.focus();
			return false;
    }

		if (oForm.customer_first_name.value == '') {
			alert('Please enter your firstname');
			oForm.customer_first_name.focus();
			return false;
		}

		if (oForm.customer_surname.value == '') {
			alert('Please enter your surname');
			oForm.customer_surname.focus();
			return false;
		}


		if (oForm.customer_address_1.value == '' && oForm.customer_address_2.value == '' && oForm.customer_address_3.value == '') {
			alert('Please enter your address');
			oForm.customer_address_1.focus();
			return false;
		}
/*
    if (oForm.customer_postcode.value == '' && oForm.customer_country_code.options[oForm.customer_country_code.selectedIndex].value == 'GB') {
			alert('Please enter your postcode');
			oForm.customer_postcode.focus();
			return false;
    }*/

    if (oForm.customer_telephone.value == '') {
			alert('Please enter your phone number');
			oForm.customer_telephone.focus();
			return false;
		}

    if(oForm.payment_type.selectedIndex==0) {
			alert('Please select a Payment Method');
			oForm.payment_type.focus();
			return false;
    }



		/** CREDIT / DEBIT PAYEES ONLY */

		if (oForm.payment_type.options[oForm.payment_type.selectedIndex].value=='Budget Plan') {

      if (oForm.account_number.value == '') {
  			alert('Please enter your Jones Oil account number');
  			oForm.account_number.focus();
  			return false;
  		}

		} //END Paying By Budget Plan


		/** CREDIT / DEBIT PAYEES ONLY */

		if (oForm.payment_type.options[oForm.payment_type.selectedIndex].value=='Credit Debit') {

      if (oForm.card_name.value == '') {
  			alert('Please enter the name\r\nas it appears on your card.');
  			oForm.card_name.focus();
  			return false;
  		}

      if (oForm.card_type.selectedIndex == 0) {
  			alert('Please select your card type.');
  			oForm.card_type.focus();
  			return false;
      }

  		Today = new Date();
  		this_year = Today.getFullYear();
  		this_month = Today.getMonth();
  		if ((parseInt(oForm.card_expiry_year.value)) == parseInt(this_year)) {
  			if (((oForm.card_expiry_month.value) ) < ((this_month)+1) ) {
  				alert('Please enter a valid expiry date. Today is '+(parseInt(this_month)+1)+' '+parseInt(this_year)+ ' But your expiry date is '+parseInt(oForm.card_expiry_month.value)+' '+parseInt(oForm.card_expiry_year.value));
  				return false;
  			}
  		}


  		if (oForm.card_number.value == '' && isNaN(oForm.card_number.value) == false) {
  			alert('Please enter your card number');
  			oForm.card_number.focus();
  			return false;
  		}

      cardType = oForm.card_type.options[oForm.card_type.selectedIndex].value

      if ((cardType == 'switch maestro' || cardType == 'solo') && !oForm.no_issue.checked) {
        if (oForm.card_issue_number.value == '') {
          alert('Please enter the ' + cardType + ' issue number')
          oForm.card_issue_number.focus()
          return false
        }
      }

      re = / /g
      cardNumber = oForm.card_number.value.replace(re, '')
      if (cardType == 'visa' || cardType == 'visa debit' || cardType == 'mastercard') {
        if (isNaN(cardNumber) && cardNumber.length != 16 && cardNumber.length != 13) {
          alert('Please enter a valid card number\r\nErr Code:vcc1 ')
          oForm.card_number.focus()
          return false
        }

        if (cardType == 'visa') {
          reVisa = /^4[0-9]{15}$|^4[0-9]{12}$/g
          if (!reVisa.test(cardNumber)) {
            alert('Please enter a valid card number\r\nErr Code:vcc2 ')
            oForm.card_number.focus()
            return false
          }
        }

        if (cardType == 'mastercard') {
          reMastercard = /^5[1-5][0-9]{14}$/g
          if (!reMastercard.test(cardNumber)) {
            alert('Please enter a valid card number\r\nErr Code:vcc3 ')
            oForm.card_number.focus()
            return false
          }
        }

        cvvNums = 3
        reCvv = /[0-9]{3}/g
        if ((!reCvv.test(oForm.card_cvv_number.value) || oForm.card_cvv_number.value.length != cvvNums)) {
          alert('Please enter a valid ' + cvvNums + ' digit CVV number')
          oForm.card_cvv_number.focus()
          return false
        }

      }

      if (cardType == 'american express') {
        reAmex = /^3[47][0-9]{13}$/g
        if (!reAmex.test(cardNumber) || cardNumber.length != 15) {
          alert('Please enter a valid card number')
          oForm.card_number.focus()
          return false
        }

        cvvNums = 4
        reCvv = /[0-9]{4}/g
        if ((!reCvv.test(oForm.card_cvv_number.value) || oForm.card_cvv_number.value.length != cvvNums)) {
          alert('Please enter a valid ' + cvvNums + ' digit CVV number')
          oForm.card_cvv_number.focus()
          return false
        }
      }

      // Check Card Holder Details
      /*
      if (oForm.card_holder_title.selectedIndex == 0) {
    		alert('Please select the card holder title.');
    		oForm.card_holder_title.focus();
    		return false;
      }

    	if (oForm.card_holder_first_name.value == '') {
    		alert('Please enter the card first holder name');
    		oForm.card_holder_forename.focus();
    		return false;
    	}

    	if (oForm.card_holder_surname.value == '') {
    		alert('Please enter the card holder surname');
    		oForm.card_holder_surname.focus();
    		return false;
    	}

    	if (oForm.card_holder_address_1.value == '' && oForm.card_holder_address_2.value == '' && oForm.card_holder_address_3.value == '') {
    		alert('Please enter the card holder address');
    		oForm.card_holder_address_1.focus();
    		return false;
    	}

  //  	if (oForm.card_holder_postcode.value == '' && oForm.card_holder_country_code.options[oForm.card_holder_country_code.selectedIndex].value == 'GB') {
  //  		alert('Please enter the card holder postcode');
  //  		oForm.card_holder_postcode.focus();
  //  		return false;
  //  	}

    	if (!IsEmailValid(oForm.card_holder_email)) {
    		alert('Please enter a valid email address for the card holder');
    		oForm.card_holder_email.focus();
    		return false;
    	}

    	if (oForm.card_holder_telephone.value == '') {
    		alert('Please enter the card holder phone number');
    		oForm.card_holder_telephone.focus();
    		return false;
    	}
    	*/

		}//END Paying By Card ONly


/* Check Terms and Conditions */
    if (oForm.read_terms_and_conditions.checked == false) {
      alert('Please confirm that you have read the terms and conditions');
      return false;
    }

if (confirm("\nWe are now ready to complete your order process.\nPlease do not click the 'Buy Now', 'Refresh', 'Back',\nor 'Stop' buttons until the next page is displayed.\n\nIt may take up to 45 seconds to validate\nyour payment information.\n\nPlease be patient.\n\nClick OK to begin authorization.")) {
      if (document.all || document.getElementById) {
        document.getElementById('submitbutton').disabled = true;
      }
      return true;
    }
    return false;

}



function checkCardNumber(oCardNumber)
{
	if (isNaN(oCardNumber.value) || (oCardNumber.value.length != 16)) {
		alert('Please enter a valid card number\r\n(16 numerical characters)');
		oCardNumber.focus();
		return false;
	}
}

function FormatCurrency(amount)
{
  amount -= 0
  amount = (Math.round(amount*100))/100
  return (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount)
}




//show / hide the  paymentdetails section based upon the selected payment method
$(document).ready(function(){

   if ( $('#payment_type').length ) {
     if ($('#payment_type').val() !='') {
       testVal = $('#payment_type').val() ;
       togglePaymentDetails(testVal) ;
     }
   }

   //if an oil type is selected and litres are chose then calculate price.
   if ( $('#oil').val() >=1 ) {
    calcPrice();
   }

})