$(document).ready(function() {

  // Bind checkbox/radio icon clicks to the
  // total price calculation
  var finalTotal = 0;

  $("#ec-product-options input:radio, #ec-product-options input:checkbox").click(function() {

    // Add any other logic in here

    doCalculation();
  });

  // Run on load
  doCalculation();

  /**
   * Works out the calculation of the total price,
   * based on any options selected
   */
  function doCalculation()
  {
    if (typeof ecProductBase === "undefined")
    {
      return;
    }
    
    var optsInc = 0;
    var optsEx = 0;
    var optsVAT = 0;
    
    var totalInc = ecProductWithVAT;
    var totalEx = ecProductBase;
    var totalVAT = ecProductVAT;

    var optionSelected = false;

    // Get the cost of the option the user has just selected
    var optionObjs = $("#ec-product-options input");
    if (optionObjs.size())
    {
      optionObjs.each(function(index) {

        // Get the cost for each option selected
        if ($(this).is(":checked"))
        {
          var optPricing = ecProductOptions[index];

          optsEx += optPricing[0];
          optsVAT += optPricing[1];
          optsInc += optPricing[2];

          optionSelected = true;
        }
      });
    }

    // Are we replacing the product cost, or adding to it?
    var costMethod = $("#ec-cost-method").val();
    if (costMethod == "sub" && optionSelected)
    {
      // Replacing the product cost
      totalEx = optsEx;
      totalVAT = optsVAT;
      totalInc = optsInc;
    }
    else
    {
      // Adding the product cost
      totalEx += optsEx;
      totalInc += optsInc;
      totalVAT += optsVAT;
    }

    $("#ec-total-excl-vat").text(totalEx.toFixed(2));
    $("#ec-total-vat").text(totalVAT.toFixed(2));
    $("#ec-total-incl-vat").text(totalInc.toFixed(2));
  }
  
});
