jQuery(document).ready(function($) {

  var $billingZip = $("#wpsc_checkout_form_7");
  var $billingState = $("#wpsc_checkout_form_21");
  var $billingCountry = $("#wpsc_checkout_form_6");
  var $shippingZip = $("#zipcode");
  var $shippingState = $("#region");
  var $shippingCountry = $("#current_country");

  function changeCountry($select, $regions, $zipcode, billingOrShipping) {
    $regions.children().remove();
    $regions.append("<option value='' disabled='disabled' selected='selected'>Loading...</option>");
    $.getJSON(window.location, {
      wpsc_ajax_action: "get_region_data",
      region_iso_code: $select.val(),
      billing_or_shipping: billingOrShipping,
      t: new Date().getTime()
    }, function(regions) {
      $regions.children().remove();
      if(regions != null) {
        $regions.append("<option value=''>Choose State/Province</option>");
        for(var i=0; i < regions.length; i++) {
          $regions.append("<option value='" + regions[i].id + "' " + (regions[i].selected ? "selected='selected'" : "") + ">" + regions[i].name + "</option>");
        }
      }
      if(billingOrShipping == 'shipping') $regions.blur();
      else $regions.change();
    });
  }
  
  $billingCountry.blur(function() {
    if($("#shipping_billing_same").is(":checked")) {
      $.post(window.location, {
        wpsc_ajax_action: "update_billing_country",
        country: $(this).val()
      });
    }
  });
  $shippingState.blur(function() {
    $.post(window.location, {
      wpsc_ajax_action: "update_region",
      region: $(this).val()
    });
  }).change(function() {
    $("#complete_purchase_button").trigger("die");
  });
  
  // this submit button is outside its form
  $("#calculate_shipping_button").click(function() {
    $("#change_country").submit();
    return false;
  });
  
  // this submit button is outside its form
  $("#complete_purchase_button").click(function() {
    var error = false;
    $(".billing, .shipping").filter("input[type=text], textarea, select").each(function() {
      if($.trim($(this).val()) == "") {
        error = true;
      }
    });
    if(error) {
      alert("Please fill out all values in the form before completing the purchase.");
      return false;
    }
    $("#wpsc_checkout_form").submit();
    return false;
  });
  
  // save form data in the session as you type
  function saveNaturalData() {
    var $input = $(this);
    var name = $input.attr("name");
    var val = $input.val();
    if($input.is(":checkbox")) {
      if($input.is(":checked")) {
        val = $input.val();
      }
      else {
        val = "false";
      }
    }
    $.post(window.location, {
      wpsc_ajax_action: "save_form_data",
      id: name.substring(name.indexOf("[")+1, name.indexOf("]")),
      value: val
    });
  }
  $(".wpsc_checkout_table").find("input, textarea, select").blur(saveNaturalData);
  $shippingState.blur(saveNaturalData);
  
  // save form data for cc stuff, populate it on load
  function saveFormData(synchronous, callback) {
    $.ajax({
      async: !synchronous,
      complete: callback,
      context: window.location,
      data: { wpsc_ajax_action: "save_form_data",
          id: $(this).attr("name"),
          value: $(this).val()
        },
      type: 'post'
    });
  }
  $(".credit_card_input input, .credit_card_input select").blur(saveFormData).each(function() {
    var $input = $(this);
    $.getJSON(window.location, {
      wpsc_ajax_action: "get_saved_data",
      id: $input.attr("name"),
      t: new Date().getTime()
    }, function(data) {
      if(data != null) {
        if($input.is("select")) {
          $input.children("[value=" + data + "]").attr("selected", "selected");
        }
        else {
          $input.val(data);
        }
      }
    });
  });
  
  // transfer billing data to shipping as you type
  $(".billing").filter("input[type=text], textarea, select").change(function() {
    if($("#shipping_billing_same").is(":checked")) {
      var $source = $(this);
      var title = $source.attr("title");
      var val = $source.val();
      var $dest = $("[title=shipping" + title.substring(7) + "]");
      if($source.is("[title=billingstate]")) {
        $dest = $("#region");
      }
      if($source.is("[title=billingpostcode]")) {
        $dest = $("#zipcode");
      }
      if($source.is("[title=billingcountry]")) {
        $dest = $("#current_country");
      }
      if($dest.is("select")) {
        $dest.children().remove();
        $dest.append($source.children().clone());
        $dest.children("[value=" + val + "]").attr("selected", "selected");
      }
      else {
        if($source.val() != "") {
          $dest.removeClass("example");
        }
        else {
          $dest.addClass("example").focus().blur();
        }
        $dest.val($source.val());
      }
    }
  });
  
  function toggleShippingBillingSame() {
    var $checkbox = $(this);
    var checked = $checkbox.is(":checked");
    if(checked) {
      $(".shipping").closest("tr").hide();
      $(".shipping").hide();
      $(".billing").change();
    }
    else {
      $(".shipping").closest("tr").show();
      $(".shipping").blur().show();
    }
  }
  $("#shipping_billing_same").change(function() {
    toggleShippingBillingSame.call(this);
    if($(this).is(":checked")) {
      if($("#region").val() != $("select[title=billingcountry]").val() || $("#currenty_country").val() != $("select[title=billingcountry]").val() || $("#zipcode").val() != $("input[title=billingpostcode]").val()) {
        $("#complete_purchase_button").trigger("die");
        $(".shipping_rates").remove();
      }
    }
  });
  
  $("select[title=billingstate], input[title=billingpostcode], select[title=billingcountry]").blur(function() {
    if($("#shipping_billing_same").is(":checked")) {
      $("#complete_purchase_button").trigger("die");
      $(".shipping_rates").remove();
    }
  });
  
  $("select[title=billingstate]").change(function() {
    var $opt = $(this).children(":selected");
    if($opt.text() == "Michigan" || $opt.text() == "Ontario") {
      $.getJSON(window.location, {
        wpsc_ajax_action: "get_tax",
        t: new Date().getTime()
      }, function(data) {
        $(".checkout-tax").html(data.total_tax);
        $("#sliding_cart .checkout-tax").closest(".total").show();
        $("#sliding_cart .checkout-tax").next(".totalhead").html("Tax (" + data.percent + "%)");
        $(".productcart .checkout-tax").closest("tr").show();
        $(".productcart .total_tax td:first").html("Tax (" + data.percent + "%)");
        if(data.percent == null) {
          $(".productcart .total_tax td:first").html("Please recalculate shipping so tax can be applied.");
          $(".productcart .checkout-tax").html("");
          $("#sliding_cart .checkout-tax").closest(".total").hide();
        }
      });
    }
    else {
      $("#sliding_cart .checkout-tax").closest(".total").hide();
        $(".productcart .checkout-tax").closest("tr").hide();
    }
  });
  
  if($(".shipping_error").size() > 0) {
    $(window).scrollTop($("input[value=Calculate Shipping]").offset().top);
  }
  else if($("input[value=Recalculate Shipping]").size() > 0) {
    $(window).scrollTop($("input[value=Recalculate Shipping]").offset().top);
  }
  
  $("#complete_purchase_button").bind("die", function() {
    $(this).remove();
    $(".complete_purchase_proxy").remove();
  });
  
  $(".complete_purchase_proxy").click(function() {
    $("#complete_purchase_button").trigger("click");
    return false;
  });
  $(".complete_purchase_proxy").each(function() {
    if($("#complete_purchase_button").size() > 0) {
      $(this).show();
    }
  });
  
  // update regions when the country is changed (and do it when the page loads)
  $("#current_country").change(function() { changeCountry($(this), $("#region"), $("#zipcode"), "shipping"); }).change();
  $("select[title=billingcountry]").change(function() { changeCountry($(this), $("select[title=billingstate]"), $("input[title=billingpostcode]"), "billing"); }).change();
  toggleShippingBillingSame.call($("#shipping_billing_same")[0]);
  
  $("#zipcode, input[title=billingpostcode]").example("Enter Zip/Postal Code");
  
  $(".security_code_info").click(function() {
    var $el = $(this);
    $(".cvv_desc").remove();
    var $cvvDesc = $("<div class='cvv_desc'><a href='#' class='close'>Close</a></div>");
    var $visaDesc = $("<div class='visa'><img src='/wp-content/plugins/wp-e-commerce/images/visa_cvv.png' /><p>The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip.</p></div>");
    var $amexDesc = $("<div class='amex'><img src='/wp-content/plugins/wp-e-commerce/images/amex_cvv.png' /><p>On American Express cards, the Card Security Code is a printed, not embossed, group of four digits on the front towards the right.</p></div>");
    $cvvDesc.append($visaDesc).append($amexDesc);
    $cvvDesc.find(".close").click(function() {
      $(this).closest(".cvv_desc").remove();
      return false;
    });
    $("body").append($cvvDesc);
    $cvvDesc.css({ left: $el.offset().left + $el.width(), top: $el.offset().top - parseInt($cvvDesc.css("height")) });
    return false;
  });
});
