require 'spec_helper'

describe "Checkout", :js => true, :type => :feature, :capybara_feature => true do

  let(:user) { FactoryGirl.create(:user) }
  let(:jamtrack_acdc_backinblack) { @jamtrack_acdc_backinblack }
  let(:jamtrack_pearljam_evenflow) { @jamtrack_pearljam_evenflow }
  let(:jamtrack_led_zeppelin_kashmir) {@jamtrack_led_zeppelin_kashmir}

  let(:billing_info) {
    {
        first_name: 'Seth',
        last_name: 'Call',
        address1: '10704 Buckthorn Drive',
        city: 'Austin',
        state: 'Texas',
        country: 'US',
        zip: '78759',
        number: '4111111111111111',
        month: '08',
        year: '2017',
        verification_value: '012'
    }
  }

  def create_account(user, billing_info)
    @recurlyClient.create_account(user, billing_info)
    @created_accounts << user
  end

  before(:all) do
    Capybara.javascript_driver = :poltergeist
    Capybara.current_driver = Capybara.javascript_driver
    Capybara.default_max_wait_time = 20 # these tests are SLOOOOOW

    @recurlyClient = RecurlyClient.new
    @created_accounts = []

    JamTrack.delete_all

    @jamtrack_acdc_backinblack = FactoryGirl.create(:jam_track, name: 'Back in Black', original_artist: 'AC/DC',  sales_region: 'Worldwide', make_track: true, plan_code: 'jamtrack-acdc-backinblack')
    @jamtrack_pearljam_evenflow = FactoryGirl.create(:jam_track, name: 'Even Flow', original_artist: 'Pearl Jam',  sales_region: 'Worldwide', make_track: true, plan_code: 'jamtrack-pearljam-evenflow')
    @jamtrack_led_zeppelin_kashmir = FactoryGirl.create(:jam_track, name: 'Kashmir', original_artist: 'Led Zeppelin',  sales_region: 'Worldwide', make_track: true, plan_code: 'jamtrack-led-zeppelin-kashmir')

    # make sure plans are there
    @recurlyClient.create_jam_track_plan(@jamtrack_acdc_backinblack) unless @recurlyClient.find_jam_track_plan(@jamtrack_acdc_backinblack)
  end


  before(:each) do
    AffiliateDistribution.delete_all
    ShoppingCart.delete_all
    SaleLineItem.delete_all
    Sale.delete_all
    User.delete_all

    stub_const("APP_CONFIG", web_config)
  end

  after(:each) do
    @created_accounts.each do |user|
      if user.recurly_code
        begin
          @account = Recurly::Account.find(user.recurly_code)
          if @account.present?
            @account.destroy
          end
        rescue
        end
      end
    end
    @jamtrack_pearljam_evenflow.allow_free = true
    @jamtrack_pearljam_evenflow.save!

  end


  def verify_nav(selected)

    3.times do |i|
      badge = i + 1

      if badge == selected
        find('.badge-number', text:badge)
      else
        find('.badge-number.disabled', text:badge)
      end
    end
  end

  describe "Checkout Signin" do

    it "allows user to log in on the signin page" do

      visit '/client#/checkoutSignin'

      find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
      verify_nav(1)


      # try a bogus user/pass first
      fill_in "email", with: user.email
      fill_in "password", with: 'wrong'
      find('.signin-submit').trigger(:click)

      find('.login-error-msg', text: 'Invalid login')

      # try successfully
      fill_in "email", with: user.email
      fill_in "password", with: user.password
      find('.signin-submit').trigger(:click)

      # this should take us to the payment screen
      find('p.payment-prompt')
    end

    it "allows user to skip login and go to payment screen" do

      visit '/client#/checkoutSignin'

      find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
      verify_nav(1)

      # skip to payment without signing in
      find('a.btnNext').trigger(:click)

      # this should take us to the payment screen
      find('p.payment-prompt')
    end

    it "indicates already logged in" do
      fast_signin(user, '/client#/checkoutSignin')

      # verify that the signin page shows, but indicates to the user that they are already signed in
      find('h3', text: 'YOU ARE ALREADY LOGGED IN')

      verify_nav(1)

      find('p.carry-on-prompt', text: 'You can move on to the next step of checkout.')

      # let them move on to the next step
      find('a.btnNext').trigger(:click)
      find('p.payment-prompt')
    end
  end

  describe "Checkout Payment" do
    it "allows anonymous to visit" do

      visit '/client#/checkoutPayment'

      find('p.payment-prompt.free-jamtrack')

      find('.jamkazam-account-signup')

      # try to submit, and see slew of errors
      find('#payment-info-next').trigger(:click)

      find('#divBillingFirstName.error .error-text', text: 'First Name is required')
      find('#divBillingLastName.error .error-text',   text: 'Last Name is required')
      find('#divBillingAddress1.error .error-text', text: 'Address is required')
      find('#divBillingCity.error .error-text', text: 'City is required')
      find('#divBillingState.error .error-text', text: 'State is required')
      find('#divBillingZip.error .error-text', text: 'Zip Code is required')
      find('#divCardNumber.error .error-text', text: 'Card Number is required')
      find('#divCardVerify.error .error-text', text: 'Card Verification Value is required')

      # fill out all billing info, but not account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'

      # try to submit, and see new account errors
      find('#payment-info-next').trigger(:click)

      find('#divJamKazamEmail.error .error-text', text: "can't be blank,is invalid")
      find('#divJamKazamPassword.error .error-text', text: "is too short (minimum is 6 characters)")
      find('#divJamKazamTos.error .error-text', text: "must be accepted")

      # verify that all filled out fields have had errors removed
      find('#divBillingFirstName').has_no_css?('.error')
      find('#divBillingLastName').has_no_css?('.error')
      find('#divBillingAddress1').has_no_css?('.error')
      find('#divBillingCity').has_no_css?('.error')
      find('#divBillingState').has_no_css?('.error')
      find('#divBillingZip').has_no_css?('.error')
      find('#divCardNumber').has_no_css?('.error')
      find('#divCardVerify').has_no_css?('.error')

      # fill in user/email/tos
      fill_in 'email', with: 'seth@jamkazam.com'
      fill_in 'password', with: 'jam123'
      find('#divJamKazamTos ins.iCheck-helper', visible:false).trigger(:click) # accept TOS

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # find empty shopping cart prompt notice
      find('p.empty-cart-prompt')

      user.reload
      user.reuse_card.should be true
    end

    it "shows card error correctly" do
      fast_signin(user, '/client#/checkoutPayment')

      find('p.payment-prompt.free-jamtrack')

      page.should_not have_selector('.jamkazam-account-signup')

      # fill out all billing info, but not account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4000-0000-0000-0002'
      fill_in 'card-verify', with: '012'

      # try to submit, and see slew of errors
      find('#payment-info-next').trigger(:click)

      find('#payment_error', text:'Your transaction was declined. Please use a different card or contact your bank.')
    end

    it "allows billing info submit for existing user" do

      fast_signin(user, '/client#/checkoutPayment')

      find('p.payment-prompt.free-jamtrack')

      page.should_not have_selector('.jamkazam-account-signup')

      # try to submit, and see slew of errors
      find('#payment-info-next').trigger(:click)

      find('#divBillingAddress1.error .error-text', text: 'Address is required')
      find('#divBillingZip.error .error-text', text: 'Zip Code is required')
      find('#divCardNumber.error .error-text', text: 'Card Number is required')
      find('#divCardVerify.error .error-text', text: 'Card Verification Value is required')

      # fill out all billing info, but not account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # find empty shopping cart prompt notice
      find('p.empty-cart-prompt')

      user.reload
      user.reuse_card.should be true
    end

    it "allows user to specify don't save card" do

      fast_signin(user, '/client#/checkoutPayment')

      find('p.payment-prompt.free-jamtrack')

      page.should_not have_selector('.jamkazam-account-signup')
      page.should_not have_selector('.payment-prompt.already-entered')

      # fill out all billing info, but not account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'
      find('.save-card-checkbox ins.iCheck-helper', visible:false).trigger(:click) # don't accept re-use card default

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # find empty shopping cart prompt notice
      find('p.empty-cart-prompt')

      # sneak in an extra test... let's hit BACK and confirm that the temporary 'just entered billing info' screen is showing
      visit '/client#/checkoutPayment'
      find('.payment-prompt.already-entered')
      page.should_not have_selector('.payment-prompt.no-free-jamtrack')
      page.should_not have_selector('.payment-prompt.free-jamtrack')
      page.should_not have_selector('#checkout-payment-info')


      user.reload
      user.reuse_card.should be false
    end

    it "payment shows saved card info correctly if user has billing info and reuse_card set to true" do

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      user.reuse_card = true
      @recurlyClient.create_account(user, billing_info)
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutPayment')

      # ok, the user has a free jamtrack... verify that display confirms this
      find('p.payment-prompt.free-jamtrack')

      # verify that all billing info looks disabled
      have_field('billing-first-name', disabled: true)
      have_field('billing-last-name', disabled: true)
      have_field('billing-address1', disabled: true)
      have_field('billing-address2', disabled: true)
      have_field('billing-city', disabled: true)
      have_field('billing-state', disabled: true)
      have_field('billing-zip', disabled: true)
      have_field('billing-country', disabled: true)
      have_field('card-number', disabled: true)
      have_field('card_expire-date_2i', disabled: true)
      have_field('card_expire-date_1i', disabled: true)
      have_field('card-number', disabled: true)
      have_field('card-verify', disabled: true)

      # verify that the use current card checkbox is checked, and that the 'save card' checkbox is checking
      find('#reuse-existing-card', visible:false).checked?.should be true
      find('#save-card:checked', visible:false).checked?.should be true

      # then uncheck 'reuse-existing-card', which should re-enable all the fields that were just disabled
      find('.reuse-existing-card-checkbox ins.iCheck-helper', visible: false).trigger(:click)

      # verify that all billing info looks enabled now, since 'reuse-existing-card' was unchecked
      have_field('billing-first-name', disabled: false)
      have_field('billing-last-name', disabled: false)
      have_field('billing-address1', disabled: false)
      have_field('billing-address2', disabled: false)
      have_field('billing-city', disabled: false)
      have_field('billing-state', disabled: false)
      have_field('billing-zip', disabled: false)
      have_field('billing-country', disabled: false)
      have_field('card-number', disabled: false)
      have_field('card_expire-date_2i', disabled: false)
      have_field('card_expire-date_1i', disabled: false)
      have_field('card-number', disabled: false)
      have_field('card-verify', disabled: false)

      # ok, we want to fiddle some values, and later prove that they will be ignored once we set reuse-existing-card back to checked
      fill_in 'billing-first-name', with: 'Bobby'
      fill_in 'billing-last-name', with: 'Junk'
      fill_in 'billing-address1', with: '10702 Buckthorn Drive'

      # flip it back to reuse existing
      find('.reuse-existing-card-checkbox ins.iCheck-helper', visible: false).trigger(:click)

      # hit next... we should move on to the payment screen

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # find empty shopping cart prompt notice
      find('p.order-prompt')

      account = @recurlyClient.get_account(user)
      account.billing_info.address1.should eq(billing_info[:address1])
      account.billing_info.first_name.should eq(billing_info[:first_name])
      account.billing_info.last_name.should eq(billing_info[:last_name])

      find('.order-items-value.sub-total', text:'0.00')
      find('.order-items-value.taxes', text:'0.00')
      find('.order-items-value.order-total', text:'0.00')
    end

    it "payment allows user to enter new billing info" do

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      user.reuse_card = true
      @recurlyClient.create_account(user, billing_info)
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutPayment')

      # ok, the user has a free jamtrack... verify that display confirms this
      find('p.payment-prompt.free-jamtrack')

      # verify that the use current card checkbox is checked, and that the 'save card' checkbox is checking
      find('#reuse-existing-card', visible: false).checked?.should be true
      find('#save-card:checked', visible: false).checked?.should be true

      # then uncheck 'reuse-existing-card', which should re-enable all the fields that were just disabled
      find('.reuse-existing-card-checkbox ins.iCheck-helper', visible: false).trigger(:click)

      # ok, we want to fiddle some values, and later prove that they will be ignored once we set reuse-existing-card back to checked
      fill_in 'billing-first-name', with: 'Bobby'
      fill_in 'billing-last-name', with: 'Junk'
      fill_in 'billing-address1', with: '10702 Buckthorn Drive'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '013'

      # hit next... we should move on to the payment screen

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # find empty shopping cart prompt notice
      find('p.order-prompt')

      account = @recurlyClient.get_account(user)
      account.billing_info.first_name.should eq('Bobby')
      account.billing_info.last_name.should eq('Junk')
      account.billing_info.address1.should eq('10702 Buckthorn Drive')

      find('.order-items-value.sub-total', text:'0.00')
      find('.order-items-value.taxes', text:'0.00')
      find('.order-items-value.order-total', text:'0.00')
    end


    it "user with no redeemable jamtrack is not show the free-jamtrack prompt" do
      user.has_redeemable_jamtrack = false
      user.save!

      fast_signin(user, '/client#/checkoutPayment')

      # ok, the user has a free jamtrack... verify that display confirms this
      find('p.payment-prompt.no-free-jamtrack')
    end
  end

  describe "Checkout Order" do
    it "shows no billing info notice" do

      fast_signin(user, '/client#/checkoutOrder')

      # the user should be toldy they have a empty cart
      find('p.no-account-info-prompt')
    end

    it "shows empty cart notice" do

      @recurlyClient.create_account(user, billing_info)

      fast_signin(user, '/client#/checkoutOrder')

      # the user should be toldy they have a empty cart
      find('p.empty-cart-prompt')
      find('.order-items-value.order-total', text:'-.--')
      find('.order-items-value.sub-total', text:'-.--')
      find('.order-items-value.taxes', text:'-.--')
      find('.order-items-value.order-total', text:'-.--')

      # verify that both Place Your Orders are disabled
      find('.order-content .place-order.disabled')
      find('.order-panel .action-bar .place-order.disabled')
    end

    it "shows one free item correctly (not-Texas)" do

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$0.00')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$0.00')
      find('.order-items-value.taxes', text:'$0.00')
      find('.order-items-value.grand-total', text:'$0.00')
    end

    it "shows one free item correctly (Texas)" do
      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$0.00')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$0.00')
      find('.order-items-value.taxes', text:'$0.00')
      find('.order-items-value.grand-total', text:'$0.00')
    end

    it "shows one free, one not free item correctly (not-Texas)" do

      jamtrack_pearljam_evenflow.allow_free = false
      jamtrack_pearljam_evenflow.save!

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
      user.reload
      ShoppingCart.add_jam_track_to_cart(user, jamtrack_pearljam_evenflow)

      billing_info[:state] = 'AR'
      @recurlyClient.create_account(user, billing_info)


      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.00')
      find('.order-items-value.grand-total', text:'$2.99')
    end

    it "shows one free, one not free item correctly (Texas)" do
      jamtrack_pearljam_evenflow.allow_free = false
      jamtrack_pearljam_evenflow.save!


      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
      user.reload
      ShoppingCart.add_jam_track_to_cart(user, jamtrack_pearljam_evenflow)

      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')
    end

    it "shows one non-free item correctly (not Texas)" do
      user.has_redeemable_jamtrack = false
      user.save!

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      billing_info[:state] = 'MA'
      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.00')
      find('.order-items-value.grand-total', text:'$2.99')
    end

    it "shows one non-free item correctly (Texas)" do
      user.has_redeemable_jamtrack = false
      user.save!

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')
    end

    it "shows two non-free items correctly (non-Texas)" do
      user.has_redeemable_jamtrack = false
      user.save!

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
      user.reload
      ShoppingCart.add_jam_track_to_cart(user, jamtrack_pearljam_evenflow)

      billing_info[:state] = 'MA'
      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$9.98')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$9.98')
      find('.order-items-value.taxes', text:'$0.00')
      find('.order-items-value.grand-total', text:'$9.98')
    end

    it "shows two non-free items correctly (Texas)" do
      user.has_redeemable_jamtrack = false
      user.save!

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)
      user.reload
      ShoppingCart.add_jam_track_to_cart(user, jamtrack_pearljam_evenflow)

      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.has_redeemable_jamtrack = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$9.98')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$9.98')
      find('.order-items-value.taxes', text:'$0.82')
      find('.order-items-value.grand-total', text:'$10.80')

      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')
      # find the 'go download jamkazam button' that shows if your first_download_client_at is null
      find('.thanks-detail .download-jamkazam-wrapper').trigger(:click)
      find('.download-jamkazam', text: 'Click Here to Get the Free JamKazam Application')


      acdc = jamtrack_acdc_backinblack.right_for_user(user)
      acdc.redeemed.should be false
      pearljam = jamtrack_pearljam_evenflow.right_for_user(user)
      pearljam.redeemed.should be false

      # verify sales data
      user.sales.length.should eq(1)
      sale = user.sales.first
      sale.sale_line_items.length.should eq(2)

      acdc_sale = SaleLineItem.find_by_recurly_adjustment_uuid(acdc.recurly_adjustment_uuid)
      acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
      acdc_sale.product_type.should eq('JamTrack')
      acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
      acdc_sale.quantity.should eq(1)
      acdc_sale.free.should eq(0)
      acdc_sale.unit_price.should eq(2.99)
      acdc_sale.sale.should eq(sale)
      pearljam_sale = SaleLineItem.find_by_recurly_adjustment_uuid(pearljam.recurly_adjustment_uuid)
      pearljam_sale.recurly_plan_code.should eq(jamtrack_pearljam_evenflow.plan_code)
      pearljam_sale.product_type.should eq('JamTrack')
      pearljam_sale.product_id.should eq(jamtrack_pearljam_evenflow.id)
      pearljam_sale.quantity.should eq(1)
      pearljam_sale.free.should eq(0)
      pearljam_sale.unit_price.should eq(2.99)
      pearljam_sale.sale.should eq(sale)
    end

    it "shows purchase error correctly" do

      user.has_redeemable_jamtrack = false
      user.save!

      ShoppingCart.add_jam_track_to_cart(user, jamtrack_acdc_backinblack)

      @recurlyClient.create_account(user, billing_info)

      user.reuse_card = true
      user.save!

      fast_signin(user, '/client#/checkoutOrder')

      find('p.order-prompt')

      # fiddle with the user's recurly-code so that the checkout fails
      user.recurly_code = 'bleh'
      user.save!

      find('.place-order-center a.button-orange.place-order').trigger(:click)
      find('#order_error', text: "Error submitting payment: message: Couldn't find Account with account_code = bleh")
    end
  end


  describe "Complete Checkout Flow" do
    it "for anonymous user" do
      visit "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search"
      find('h1', text: 'search jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
      find('h3', text: 'OR SIGN UP USING YOUR EMAIL')
      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(1)
      shopping_cart = shopping_carts[0]
      shopping_cart.anonymous_user_id.should_not be_nil
      shopping_cart.user_id.should be_nil

      fill_in 'first_name', with: 'Seth'
      fill_in 'last_name', with: 'Call'
      fill_in 'email', with: 'guy@jamkazam.com'
      fill_in 'password', with: 'jam123'
      find('.right-side .terms_of_service input').trigger(:click) # accept TOS

      # try to submit, and see order page
      find('.signup-submit').trigger(:click)

      find('.jam-tracks-in-browser')

      guy = User.find_by_email('guy@jamkazam.com')

      # verify that the shopping cart has user_id info updated
      guy.shopping_carts.length.should eq(0)

      guy.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(guy)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be true
      guy.has_redeemable_jamtrack.should be false

      # verify sales data
      guy.sales.length.should eq(1)
      sale = guy.sales.first
      sale.sale_line_items.length.should eq(1)
      acdc_sale = sale.sale_line_items[0]
      acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
      acdc_sale.product_type.should eq('JamTrack')
      acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
      acdc_sale.quantity.should eq(1)
      acdc_sale.free.should eq(1)
      acdc_sale.unit_price.should eq(2.99)
      acdc_sale.sale.should eq(sale)


      # this is a little cheat to make the billing info dropdown already say US
      guy.country = 'US'
      guy.save!

      # now, go back to checkout flow again, and make sure we are told there are no free jam tracks

      visit "/client?song=#{jamtrack_pearljam_evenflow.name}#/jamtrack/search"

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_pearljam_evenflow.id}\"]", text: 'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_pearljam_evenflow.name}")
      find('.cart-item-price', text: "$ #{jamtrack_pearljam_evenflow.download_price}")
      find('.shopping-sub-total', text:"Subtotal:$ #{jamtrack_pearljam_evenflow.download_price}")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # should be at payment page

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'
      #jk_select('US', '#checkoutPaymentScreen #divBillingCountry #billing-country')

      find('#payment-info-next').trigger(:click)

      # should be taken straight to order page

      # now see order page, and everything should no longer appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      guy.reload

      sleep 3 # challenge to all comers!  WHY DO I HAVE TO SLEEP FOR THIS ASSERTION TO BE TRUE! GAH .  and 1 second won't do it

      jam_track_right = jamtrack_pearljam_evenflow.right_for_user(guy)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be false
      jam_track_right.can_download.should be true
      guy.has_redeemable_jamtrack.should be false

      # verify sales data
      guy.sales.length.should eq(2)
      sale = guy.sales.last
      sale.sale_line_items.length.should eq(1)
      acdc_sale = SaleLineItem.find_by_recurly_adjustment_uuid(jam_track_right.recurly_adjustment_uuid)
      acdc_sale.recurly_plan_code.should eq(jamtrack_pearljam_evenflow.plan_code)
      acdc_sale.product_type.should eq('JamTrack')
      acdc_sale.product_id.should eq(jamtrack_pearljam_evenflow.id)
      acdc_sale.quantity.should eq(1)
      acdc_sale.free.should eq(0)
      acdc_sale.unit_price.should eq(2.99)
      acdc_sale.sale.should eq(sale)
    end

    it "for anonymous user with referral" do

      partner = FactoryGirl.create(:affiliate_partner)
      affiliate_params = partner.affiliate_query_params

      visit '/landing/jamtracks/acdc-backinblack?' + affiliate_params


      fill_in "email",    with: 'testuser_12345@jamkazam.com'
      fill_in "password",    with: 'jam123'
      find('.register-area input[type="checkbox"]', visible:false).trigger(:click)
      find('button.cta-button', text: 'GET IT FREE!').trigger(:click)

      # this should show on the /client#/jamtrack page
      find('.no-free-jamtrack')

      guy = User.find_by_email('testuser_12345@jamkazam.com')
      guy.affiliate_referral.should eq(partner)
      guy.reload

      # verify sales data
      guy.sales.length.should eq(1)
      sale = guy.sales.first
      sale.sale_line_items.length.should eq(1)
      acdc_sale = sale.sale_line_items[0]
      acdc_sale.affiliate_referral.should eq(partner)
      acdc_sale.affiliate_refunded.should be false
      acdc_sale.affiliate_refunded_at.should be_nil
      acdc_sale.affiliate_referral_fee_in_cents.should eq(0)

      # this is a little cheat to make the billing info dropdown already say US
      guy.country = 'US'
      guy.save!

      # now, go back to checkout flow again, and make sure we are told there are no free jam tracks

      visit "/client?song=#{jamtrack_pearljam_evenflow.name}#/jamtrack/search"

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_pearljam_evenflow.id}\"]", text: 'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_pearljam_evenflow.name}")
      find('.cart-item-price', text: "$ #{jamtrack_pearljam_evenflow.download_price}")
      find('.shopping-sub-total', text:"Subtotal:$ #{jamtrack_pearljam_evenflow.download_price}")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # should be at payment page

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'
      #jk_select('US', '#checkoutPaymentScreen #divBillingCountry #billing-country')

      find('#payment-info-next').trigger(:click)

      # should be taken straight to order page

      # now see order page, and everything should no longer appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      guy.reload

      sleep 3 # challenge to all comers!  WHY DO I HAVE TO SLEEP FOR THIS ASSERTION TO BE TRUE! GAH .  and 1 second won't do it

      jam_track_right = jamtrack_pearljam_evenflow.right_for_user(guy)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be false
      jam_track_right.can_download.should be true
      guy.has_redeemable_jamtrack.should be false

      # verify sales data
      guy.sales.length.should eq(2)
      sale = guy.sales.last
      sale.sale_line_items.length.should eq(1)
      acdc_sale = SaleLineItem.find_by_recurly_adjustment_uuid(jam_track_right.recurly_adjustment_uuid)
      acdc_sale.affiliate_referral.should eq(partner)
      acdc_sale.affiliate_refunded.should be false
      acdc_sale.affiliate_refunded_at.should be_nil
      acdc_sale.affiliate_referral_fee_in_cents.should eq(50)

    end


    it "for existing user with a freebie available (already logged in)" do

      fast_signin(user, "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)

      find('.jam-tracks-in-browser')

      user.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be true
      user.has_redeemable_jamtrack.should be false
    end

    it "for existing user with no freebie available (already logged in)" do
      user.has_redeemable_jamtrack = false
      user.save!

      fast_signin(user, "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
      find('.cart-item-price', text: "$ #{jamtrack_acdc_backinblack.download_price}") # 1st one is free!
      find('.shopping-sub-total', text:"Subtotal:$ 2.99")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # we should be skipping the signin screen, and be taken directly to payment

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # now see order page, and everything should appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      user.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be false
      jam_track_right.can_download.should be true
      user.has_redeemable_jamtrack.should be false
    end

    it "for existing user buying stream-only with no freebie available (already logged in)" do
      user.has_redeemable_jamtrack = false
      user.save!

      fast_signin(user, "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"][data-variant=\"stream\"]", text: 'ADD TO CART').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
      find('.cart-item-price', text: "$ #{jamtrack_acdc_backinblack.price}") # 1st one is free!
      find('.shopping-sub-total', text:"Subtotal:$ 1.99")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # we should be skipping the signin screen, and be taken directly to payment

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)

      # now see order page, and everything should appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$1.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$1.99')
      find('.order-items-value.taxes', text:'$0.16')
      find('.order-items-value.grand-total', text:'$2.15')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      user.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be false
      jam_track_right.can_download.should be false
      user.has_redeemable_jamtrack.should be false

      user.sales.length.should eq(1)
      sale = user.sales.last
      sale.sale_line_items.length.should eq(1)
      line_item = sale.sale_line_items[0]
      line_item.unit_price.should eq(1.99)

      # now to upgrade it!

      visit "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search"
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      upgrade_price = jamtrack_acdc_backinblack.download_price - jamtrack_acdc_backinblack.price
      upgrade_price.should eql 3

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"][data-variant=\"download\"]", text: 'UPGRADE').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
      find('.cart-item-price', text: "$ 3.00")
      find('.shopping-sub-total', text:"Subtotal:$ 3.00")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      find('.thanks-detail.jam-tracks-in-browser')

      user.reload
      user.sales.length.should eq(2)
      sale = user.sales.last
      sale.sale_line_items.length.should eq(1)
      line_item = sale.sale_line_items[0]
      line_item.unit_price.should eq(3.00)

    end


    it "for existing user with a freebie (starts shopping anonymously)" do
      user.has_redeemable_jamtrack = true
      user.save!

      # the point of this is to also prove that the free jamtrack does not carry over to the existing user, once they log in
      visit "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search"
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)

      find('h3', text: 'OR SIGN UP USING YOUR EMAIL')
      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(1)
      shopping_cart = shopping_carts[0]
      shopping_cart.anonymous_user_id.should_not be_nil
      shopping_cart.user_id.should be_nil

      find('.right-side a.signin').trigger(:click)

      # log in dialog should be showing
      # try a bogus user/pass first
      within('.signin-form') do
        fill_in "session[email]", with: user.email
        fill_in "session[password]", with: user.password
      end

      find('.signin-submit').trigger(:click)

      # this should log the user in, cause a full-page reload, and the order should be placed or redeemComplete
      find('.jam-tracks-in-browser')

      user.reload

      # verify that the shopping cart has user_id info updated
      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(0)
      shopping_cart = shopping_carts[0]


      user.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be true
      jam_track_right.can_download.should be true
      user.has_redeemable_jamtrack.should be false

      # verify sales data
      user.sales.length.should eq(1)
      sale = user.sales.first
      sale.sale_line_items.length.should eq(1)
      acdc_sale = sale.sale_line_items[0]
      acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
      acdc_sale.product_type.should eq('JamTrack')
      acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
      acdc_sale.quantity.should eq(1)
      acdc_sale.free.should eq(1)
      acdc_sale.unit_price.should eq(2.99)
      acdc_sale.sale.should eq(sale)
    end

    it "for existing user with a freebie (starts shopping anonymously on 'used' browser)" do
      user.has_redeemable_jamtrack = true
      user.save!
      set_cookie('redeemed_jamtrack', 'true')

      # the point of this is to also prove that the free jamtrack does not carry over to the existing user, once they log in
      visit "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search"
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text:'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
      find('.cart-item-price', text: "$ 2.99") # 1st one is free!
      find('.shopping-sub-total', text:"Subtotal:$ 2.99")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(1)
      shopping_cart = shopping_carts[0]
      shopping_cart.anonymous_user_id.should_not be_nil
      shopping_cart.user_id.should be_nil

      # we should now be on checkoutSignin
      find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
      verify_nav(1)

      fill_in "email", with: user.email
      fill_in "password", with: user.password
      find('.signin-submit').trigger(:click)

      # this should log the user in, cause a full-page reload, and the order should be placed or redeemComplete
      find('.jam-tracks-in-browser')

      user.reload

      # verify that the shopping cart has user_id info updated
      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(0)
      shopping_cart = shopping_carts[0]


      user.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be true
      user.has_redeemable_jamtrack.should be false

      # verify sales data
      user.sales.length.should eq(1)
      sale = user.sales.first
      sale.sale_line_items.length.should eq(1)
      acdc_sale = sale.sale_line_items[0]
      acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
      acdc_sale.product_type.should eq('JamTrack')
      acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
      acdc_sale.quantity.should eq(1)
      acdc_sale.free.should eq(1)
      acdc_sale.unit_price.should eq(2.99)
      acdc_sale.sale.should eq(sale)
    end

    it "for user with no freebies (starts shopping anonymously on 'used' browser)" do
      user.has_redeemable_jamtrack = false
      user.save!
      set_cookie('redeemed_jamtrack', 'true')

      # the point of this is to also prove that the free jamtrack does not carry over to the existing user, once they log in
      visit "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search"
      find('h1', text: 'jamtracks')
      #find('a', text: 'What is a JamTrack?')

      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text:'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
      find('.cart-item-price', text: "$ 2.99") # 1st one is free!
      find('.shopping-sub-total', text:"Subtotal:$ 2.99")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(1)
      shopping_cart = shopping_carts[0]
      shopping_cart.anonymous_user_id.should_not be_nil
      shopping_cart.user_id.should be_nil

      # we should now be on checkoutSignin
      find('h3', text: 'ALREADY A MEMBER OF THE JAMKAZAM COMMUNITY?')
      verify_nav(1)

      fill_in "email", with: user.email
      fill_in "password", with: user.password
      find('.signin-submit').trigger(:click)

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'

      # try to submit, and see order page
      find('#payment-info-next').trigger(:click)


      # now see order page, and everything should appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      user.reload

      # verify that the shopping cart has user_id info updated
      shopping_carts = ShoppingCart.all
      shopping_carts.count.should eq(0)
      shopping_cart = shopping_carts[0]


      user.reload
      jam_track_right = jamtrack_acdc_backinblack.right_for_user(user)
      # make sure it appears the user actually bought the jamtrack!
      jam_track_right.should_not be_nil
      jam_track_right.redeemed.should be false
      user.has_redeemable_jamtrack.should be false

      # verify sales data
      user.sales.length.should eq(1)
      sale = user.sales.first
      sale.sale_line_items.length.should eq(1)
      acdc_sale = SaleLineItem.find_by_recurly_adjustment_uuid(jam_track_right.recurly_adjustment_uuid)
      acdc_sale.recurly_plan_code.should eq(jamtrack_acdc_backinblack.plan_code)
      acdc_sale.product_type.should eq('JamTrack')
      acdc_sale.product_id.should eq(jamtrack_acdc_backinblack.id)
      acdc_sale.quantity.should eq(1)
      acdc_sale.free.should eq(0)
      acdc_sale.unit_price.should eq(2.99)
      acdc_sale.sale.should eq(sale)
    end
  end

  describe "gift cards" do

    it "user has both redeemable jamtrack and gift card jamtracks, checks out one at a time" do

      jamtrack_led_zeppelin_kashmir.touch
      jamtrack_pearljam_evenflow.touch

      user.gifted_jamtracks = 1
      user.save!

      fast_signin(user, "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
      find('.jam-tracks-in-browser')
      user.reload
      user.has_redeemable_jamtrack.should be false
      user.jam_track_rights.count.should eql 1

      go_to_root
      #find('a.back-to-browsing').trigger(:click)
      #find('h1', text: 'search jamtracks')
      #find('.search-controls .Select-control').trigger(:mousedown)
      ## wait for the 'Type to search' prompt to show
      #find('.search-controls .Select-search-prompt')
      #find('.search-by-string-btn').trigger(:click)

      visit "/client#/jamtrack/search"
      find('#jamtrackSearch .Select-control').trigger(:mousedown)
      # wait for the 'Type to search' prompt to show
      find('#jamtrackSearch .Select-search-prompt')
      send_key_sequence('#jamtrackSearch .Select-control', '')
      find('#jamtrackSearch .search-btn').trigger(:click)


      find('.jamtrack-record[data-jamtrack-id="' + jamtrack_led_zeppelin_kashmir.id + '"]')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_led_zeppelin_kashmir.id}\"]", text: 'GET IT FREE!').trigger(:click)
      #find('.jam-tracks-in-browser')
      find('h1', text: 'shopping cart')
      sleep 2
      user.reload
      user.has_redeemable_jamtrack.should be false
      user.gifted_jamtracks.should eq(1)

      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      find('.jam-tracks-in-browser')

      user.reload
      user.has_redeemable_jamtrack.should be false
      user.jam_track_rights.count.should eql 2
      user.gifted_jamtracks.should eq(0)
    end

    it "user has both redeemable jamtrack and gift card jamtracks, all at once" do

      jamtrack_led_zeppelin_kashmir.touch
      jamtrack_pearljam_evenflow.touch

      user.gifted_jamtracks = 1
      user.save!

      fast_signin(user, "/client?song=#{jamtrack_acdc_backinblack.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
      find('.jam-tracks-in-browser')
      user.reload
      user.has_redeemable_jamtrack.should be false

      go_to_root
      #find('a.back-to-browsing').trigger(:click)
      #find('h1', text: 'search jamtracks')
      #find('.search-controls .Select-control').trigger(:mousedown)
      ## wait for the 'Type to search' prompt to show
      #find('.search-controls .Select-search-prompt')
      #find('.search-by-string-btn').trigger(:click)

      visit "/client#/jamtrack/search"
      find('#jamtrackSearch .Select-control').trigger(:mousedown)
      # wait for the 'Type to search' prompt to show
      find('#jamtrackSearch .Select-search-prompt')
      send_key_sequence('#jamtrackSearch .Select-control', '')
      find('#jamtrackSearch .search-btn').trigger(:click)


      find('.jamtrack-record[data-jamtrack-id="' + jamtrack_led_zeppelin_kashmir.id + '"]')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_led_zeppelin_kashmir.id}\"]", text: 'GET IT FREE!').trigger(:click)
      #find('.jam-tracks-in-browser')
      find('h1', text: 'shopping cart')
      sleep 2
      user.reload
      user.has_redeemable_jamtrack.should be false
      user.gifted_jamtracks.should eq(1)

      find('a.continue-shopping').trigger(:click)
      find('h1', text: 'search jamtracks')
      find('.jamtrack-record[data-jamtrack-id="' + jamtrack_pearljam_evenflow.id + '"]')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_pearljam_evenflow.id}\"]", text: 'ADD TO CART (FULL)').trigger(:click)

      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_pearljam_evenflow.name}")
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_led_zeppelin_kashmir.name}")
      find('.cart-price', text: "$ 0.00")
      find('.cart-price', text: "$ #{jamtrack_pearljam_evenflow.download_price}")
      find('.shopping-sub-total', text:"Subtotal:$ #{jamtrack_pearljam_evenflow.download_price}")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # should be at payment page

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'
      #jk_select('US', '#checkoutPaymentScreen #divBillingCountry #billing-country')

      find('#payment-info-next').trigger(:click)

      # should be taken straight to order page

      # now see order page, and everything should no longer appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      user.reload

      sleep 3 # challenge to all comers!  WHY DO I HAVE TO SLEEP FOR THIS ASSERTION TO BE TRUE! GAH .  and 1 second won't do it

      user.reload
      user.has_redeemable_jamtrack.should be false
      user.gifted_jamtracks.should eq(0)
      user.purchased_jamtracks_count.should eq(3)
    end

    it "user has both free and non-free jamtrack, all at once" do

      jamtrack_led_zeppelin_kashmir.allow_free = false
      jamtrack_led_zeppelin_kashmir.save!
      jamtrack_acdc_backinblack.touch


      fast_signin(user, "/client?song=#{jamtrack_led_zeppelin_kashmir.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_led_zeppelin_kashmir.id}\"]", text: 'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      sleep 2
      user.reload
      user.has_redeemable_jamtrack.should be true


      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_led_zeppelin_kashmir.name}")
      find('.cart-price', text: "$ #{jamtrack_led_zeppelin_kashmir.download_price}")
      find('.shopping-sub-total', text:"Subtotal:$ #{jamtrack_led_zeppelin_kashmir.download_price}")


      go_to_root
      visit "/client#/jamtrack/search"
      find('#jamtrackSearch .Select-control').trigger(:mousedown)
      # wait for the 'Type to search' prompt to show
      find('#jamtrackSearch .Select-search-prompt')
      send_key_sequence('#jamtrackSearch .Select-control', '')
      find('#jamtrackSearch .search-btn').trigger(:click)

      find('.jamtrack-record[data-jamtrack-id="' + jamtrack_acdc_backinblack.id + '"]')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_acdc_backinblack.id}\"]", text: 'GET IT FREE!').trigger(:click)
      #find('.jam-tracks-in-browser')
      find('h1', text: 'shopping cart')
      sleep 2
      user.reload
      user.has_redeemable_jamtrack.should be true

      find('.cart-item-caption', text: "JamTrack: #{jamtrack_acdc_backinblack.name}")
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_led_zeppelin_kashmir.name}")
      find('.cart-price', text: "$ 0.00")
      find('.cart-price', text: "$ #{jamtrack_led_zeppelin_kashmir.download_price}")
      find('.shopping-sub-total', text:"Subtotal:$ #{jamtrack_led_zeppelin_kashmir.download_price}")

      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # should be at payment page

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'
      #jk_select('US', '#checkoutPaymentScreen #divBillingCountry #billing-country')

      find('#payment-info-next').trigger(:click)

      # should be taken straight to order page

      # now see order page, and everything should no longer appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      user.reload

      sleep 3 # challenge to all comers!  WHY DO I HAVE TO SLEEP FOR THIS ASSERTION TO BE TRUE! GAH .  and 1 second won't do it

      user.reload
      user.has_redeemable_jamtrack.should be false
      user.gifted_jamtracks.should eq(0)
      user.purchased_jamtracks_count.should eq(2)


    end

    it "user has non-free jamtrack" do

      jamtrack_led_zeppelin_kashmir.allow_free = false
      jamtrack_led_zeppelin_kashmir.save!
      jamtrack_acdc_backinblack.touch


      fast_signin(user, "/client?song=#{jamtrack_led_zeppelin_kashmir.name}#/jamtrack/search")
      find('h1', text: 'jamtracks')
      find("a.jamtrack-add-cart[data-jamtrack-id=\"#{jamtrack_led_zeppelin_kashmir.id}\"]", text: 'ADD TO CART (FULL)').trigger(:click)
      find('h1', text: 'shopping cart')
      sleep 2
      user.reload
      user.has_redeemable_jamtrack.should be true


      find('h1', text: 'shopping cart')
      find('.cart-item-caption', text: "JamTrack: #{jamtrack_led_zeppelin_kashmir.name}")
      find('.cart-price', text: "$ #{jamtrack_led_zeppelin_kashmir.download_price}")
      find('.shopping-sub-total', text:"Subtotal:$ #{jamtrack_led_zeppelin_kashmir.download_price}")


      # attempt to checkout
      find('a.button-orange', text: 'PROCEED TO CHECKOUT').trigger(:click)

      # should be at payment page

      # this should take us to the payment screen
      find('p.payment-prompt')

      # fill out all billing info and account info
      fill_in 'billing-first-name', with: 'Seth'
      fill_in 'billing-last-name', with: 'Call'
      fill_in 'billing-address1', with: '10704 Buckthorn Drive'
      fill_in 'billing-city', with: 'Austin'
      fill_in 'billing-state', with: 'Texas'
      fill_in 'billing-zip', with: '78759'
      fill_in 'card-number', with: '4111111111111111'
      fill_in 'card-verify', with: '012'
      #jk_select('US', '#checkoutPaymentScreen #divBillingCountry #billing-country')

      find('#payment-info-next').trigger(:click)

      # should be taken straight to order page

      # now see order page, and everything should no longer appear free
      find('p.order-prompt')
      find('.order-items-value.order-total', text:'$t2.99')
      find('.order-items-value.shipping-handling', text:'$0.00')
      find('.order-items-value.sub-total', text:'$2.99')
      find('.order-items-value.taxes', text:'$0.41')
      find('.order-items-value.grand-total', text:'$5.40')

      # click the ORDER button
      find('.place-order-center a.button-orange.place-order').trigger(:click)

      # and now we should see confirmation, and a notice that we are in a normal browser
      find('.thanks-detail.jam-tracks-in-browser')

      user.reload

      sleep 3 # challenge to all comers!  WHY DO I HAVE TO SLEEP FOR THIS ASSERTION TO BE TRUE! GAH .  and 1 second won't do it

      user.reload
      user.has_redeemable_jamtrack.should be true
      user.gifted_jamtracks.should eq(0)
      user.purchased_jamtracks_count.should eq(1)


    end

  end
end
