context = window
rest = context.JK.Rest()

@JamTrackLandingPage = React.createClass({

  isFree: () ->
    context.JK.currentUserFreeJamTrack && @props.jam_track.allow_free
  render: () ->


    loggedIn = context.JK.currentUserId?

    if this.state.done
      ctaButtonText = 'sending you in...'
    else if this.state.processing
      ctaButtonText = 'hold on...'
    else
      if @isFree()
        ctaButtonText = 'GET IT FREE!'
      else
        ctaButtonText = 'Add To Cart'

    if @state.iOS
      iosBadge = `<a className="ios-appstore-badge" href="https://itunes.apple.com/us/app/jamtracks/id1060927816?ls=1&mt=8">
        <img src="/assets/content/badge-download-on-the-app-store.svg" />
      </a>`

      register = `<div className="register-area ios">
        <div className="">Download our free iOS app now, and get this JamTrack free! See why our JamTracks are so much better than traditional backing tracks - with no risk.</div>
        <a className="ios-appstore-badge" href="https://itunes.apple.com/us/app/jamtracks/id1060927816?ls=1&mt=8">
          <img src="/assets/content/badge-download-on-the-app-store.svg" />
        </a>
      </div>`
    else
      if loggedIn
        loggedInCtaButton = `<button className={classNames({'cta-button' : true, 'processing': this.state.processing})} onClick={this.ctaClick}>{ctaButtonText}</button>`
        if !@isFree()
          loggedInPriceAdvisory = `<div className="price-advisory">${this.props.jam_track.download_price}</div>`
      else
        if !@isFree()
          loggedOutPriceAdvisory = `<div className="price-advisory">${this.props.jam_track.download_price}</div>`

        if this.state.loginErrors?
          for key, value of this.state.loginErrors
            break

          errorText = context.JK.getFullFirstError(key, this.state.loginErrors, {email: 'Email', password: 'Password', 'terms_of_service' : 'The terms of service'})

        register = `<div className="register-area">
          <p>Register for a free account to get this JamTrack free. We will not share your email.  See our <a className="privacy-policy" onClick={this.privacyPolicy}>privacy policy</a>.</p>
          <div className={classNames({'errors': true, 'active': this.state.loginErrors})}>
            {errorText}
          </div>
          <form className="jamtrack-signup-form">
            <label>Email: </label><input type="text" name="email" />
            <br/>
            <label>Password: </label><input type="password" name="password" />
            <div className="clearall"/>
            <div className="checkbox-wrap"><input className="terms-checkbox" type="checkbox" name="terms" /></div><label className="terms-help">I have read and agree to the JamKazam <a href="/corp/terms" onClick={this.termsClicked}>terms of service</a></label>
            <div className="clearall"/>
            <button className={classNames({'cta-button' : true, 'processing': this.state.processing})} onClick={this.ctaClick}>{ctaButtonText}</button>
            {loggedOutPriceAdvisory}
          </form>

          <a className="browse-all" href="/client?search=#/jamtrack/search">or browse our catalog of 3,700+ songs</a>
        </div>`


    `<div className="top-container">
      <div className="full-row name-and-artist">
        <div>
          <img className="app-preview" src="/assets/landing/JK_FBAd_Guitar_with_Keys.png" alt="screenshot of app"/>
          <h1 className="jam-track-name">{this.props.jam_track.name.toUpperCase()}</h1>
          <h2 className="original-artist">by {this.props.jam_track.original_artist.toUpperCase()}</h2>
          {iosBadge}
            <div className="clearall"/>
        </div>
      </div>
      <div className="row summary-text">
        <p className="top-summary">
          JamTracks by JamKazam are the best way to play along with your favorite songs. Far better and different than traditional
          backing tracks, our JamTracks are complete multi-track professional recordings, with fully isolated tracks for each part of the music.
          And our free app and Internet service are packed with features that give you unmatched creative freedom to learn, practice, record, play with others, and share your performances.
        </p>
      </div>
      <div className="preview-and-action-box">
        <img src="/assets/landing/jamtrack_landing_arrow_1.png" className="arrow1" />
        <img src="/assets/landing/jamtrack_landing_arrow_2.png" className="arrow2" />
        <div className="preview-jamtrack-header">
          Preview JamTrack
        </div>
        <div className={classNames({'preview-area': true, 'logged-in' : loggedIn})}>
          <p>Click the play buttons below to preview the master mix and 20-second samples of all the isolated tracks.</p>
          <div className="tracks previews">

          </div>
          {loggedInCtaButton}
          {loggedInPriceAdvisory}
        </div>

        {register}
      </div>
    </div>`

  getInitialState: () ->
    try
      iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    catch e
      iOS = false

    { loginErrors: null, processing:false, iOS: iOS }

  privacyPolicy: (e) ->
    e.preventDefault()

    context.JK.popExternalLink('/corp/privacy')

  termsClicked: (e) ->
    e.preventDefault()

    context.JK.popExternalLink('/corp/terms')

  componentDidMount:() ->
    $root = $(this.getDOMNode())
    $checkbox = $root.find('.terms-checkbox')
    #console.log("$checkbox", $checkbox)
    #context.JK.checkbox($checkbox)

  # add item to cart, create the user if necessary, and then place the order to get the free JamTrack.
  ctaClick: (e) ->
    e.preventDefault()

    return if @state.processing

    @setState({loginErrors: null})

    loggedIn = context.JK.currentUserId?

    isFree = @isFree()


    rest.addJamtrackToShoppingCart({id: @props.jam_track.id, clear:true}).done((response) =>
      if isFree
        if loggedIn
          @setState({done: true})
          context.location = '/client?redeemed_flow=1#/jamtrack'
        else
          @createUser()
      else
        if loggedIn
          @setState({done: true})
          context.location = '/client#/shoppingCart'
        else
          @createUser(true)

    ).fail((jqXHR, textStatus, errorMessage) =>
      if jqXHR.status == 422
        errors = JSON.parse(jqXHR.responseText)
        cart_errors = errors?.errors?.cart_id
        if cart_errors?.length == 1 && cart_errors[0] == 'has already been taken'
          if loggedIn
            @setState({done: true})
            context.location = '/client#/shoppingCart'
          else
            @createUser(true)
        else
          context.JK.app.ajaxError(jqXHR, textStatus, errorMessage)
          @setState({processing:false})
    )

  createUser: (redirectToShoppingCart) ->
    $form = $('.jamtrack-signup-form')
    email = $form.find('input[name="email"]').val()
    password = $form.find('input[name="password"]').val()
    terms = $form.find('input[name="terms"]').is(':checked')

    rest.signup({email: email, password: password, first_name: null, last_name: null, terms:terms})
    .done((response) =>

        if redirectToShoppingCart
          @setState({done: true})
          context.location = '/client#/shoppingCart'
          return

        rest.placeOrder()
        .done((response) =>
          this.setState({done: true})
          context.JK.Tracking.redeemCompleteTrack()
          window.location = '/client?redeemed_flow=1#/jamtrack'
        )
        .fail((jqXHR) =>
          logger.error("unable to place an older after creating the user")
          window.reload()
        )

    ).fail((jqXHR) =>
      @setState({processing:false})
      if jqXHR.status == 422
        response = JSON.parse(jqXHR.responseText)
        if response.errors
          @setState({loginErrors: response.errors})
        else
          context.JK.app.notify({title: 'Unknown Signup Error', text: jqXHR.responseText})
      else
        context.JK.app.notifyServerError(jqXHR, "Unable to Sign Up")
    )


    @setState({processing:true})

})