(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.RedeemSignUpScreen = function(app) {

    var logger = context.JK.logger;
    var rest = context.JK.Rest();

    var $screen = null;
    var $signupForm = null;
    var $self = $(this);
    var $email = null;
    var $password = null;
    var $firstName = null;
    var $lastName = null;

    var $signupBtn = null;
    var $inputElements = null;
    var $contentHolder = null;
    var $btnNext = null;
    var $btnFacebook = null;
    var $termsOfServiceL = null;
    var $termsOfServiceR = null;
    var shoppingCartItem = null;
    var $jamtrackName = null;
    var $signinLink = null;

    function beforeShow(data) {

    }

    function afterShow(data) {
      renderLoggedInState();
    }


    function renderLoggedInState(){

      if(isLoggedIn()) {
        $contentHolder.removeClass('not-signed-in').addClass('signed-in')
      }
      else {
        context.JK.Tracking.redeemSignupTrack(app)
        $jamtrackName.text('')
        $contentHolder.addClass('hidden')
        $contentHolder.removeClass('signed-in').addClass('not-signed-in')
        // now check that the user has one, and only one, free jamtrack in their shopping cart.
        rest.getShoppingCarts()
          .done(handleShoppingCartResponse)
          .fail(app.ajaxError);
      }
    }

    function isLoggedIn() {
      return !!context.JK.currentUserId;
    }

    function events() {
      $btnFacebook.on('click', onClickSignupFacebook)
      $signupForm.on('submit', signup)
      $signupBtn.on('click', signup)
      $signinLink.on('click', onSignin);
    }

    function handleShoppingCartResponse(carts) {

      if(carts.length == 0) {
        // nothing is in the user's shopping cart.  They shouldn't be here.
        logger.error("invalid access of redeemJamTrack page; none")
        window.location = '/client#/jamtrack/search'
      }
      else if(carts.length > 1) {
        // the user has multiple items in their  shopping cart.  They shouldn't be here.
        logger.error("invalid access of redeemJamTrack page; multiple")
        window.location = '/client#/shoppingCart'
      }
      else {
        var item = carts[0];

        if(item.product_info.free) {
          // ok, we have one, free item. save it for
          shoppingCartItem = item;
          $jamtrackName.text('"' + shoppingCartItem.product_info.name + '"')
          $contentHolder.removeClass('hidden')
        }
        else {
          // the user has a non-free, single item in their basket. They shouldn't be here.
          logger.error("invalid access of redeemJamTrack page, non-free/item")
          window.location = '/client#/jamtrack/search'
        }
      }

      var $latestCartHtml = "";

      var any_in_us = false
      context._.each(carts, function(cart) {
        if(cart.product_info.sales_region == 'United States') {
          any_in_us = true
        }
      })
    }
    function onClickSignupFacebook(e) {
      // tos must already be clicked

      $btnFacebook.addClass('disabled')

      var $field = $termsOfServiceL.closest('.field')
      $field.find('.error-text').remove()

      logger.debug("field, ", $field, $termsOfServiceL)
      if($termsOfServiceL.is(":checked")) {

        rest.createSignupHint({redirect_location: '/client#/redeemComplete'})
          .done(function() {
            // send the user on to facebook signin
            window.location = $btnFacebook.attr('href');
          })
          .fail(function() {
            app.notify({text:"Facebook Signup is not working properly"});
          })
          .always(function() {
            $btnFacebook.removeClass('disabled')
          })
      }
      else {
        $field.addClass("error").addClass("transparent");
        $field.append("<ul class='error-text'><li>must be accepted</li></ul>");
      }
      return false;
    }

    function onSuccessfulSignin() {
      // the user has signed in;

      // move all shopping carts from the anonymous user to the signed in user
      /*rest.portOverCarts()
        .done(function() {
          logger.debug("ported over carts")
          window.location = '/client#/redeemComplete'
        })
        .fail(function() {
          window.location.reload();
        })

*/
      window.location = '/client#/redeemComplete'
    }

    function onSignin() {
      app.layout.showDialog('signin-dialog', {redirect_to:onSuccessfulSignin});
      return false;
    }

    function signup() {
      if($signupBtn.is('.disabled')) {
        return false;
      }

      // clear out previous errors
      $signupForm.find('.field.error').removeClass('error')
      $signupForm.find('ul.error-text').remove()

      var email = $email.val();
      var password = $password.val();
      var first_name = $firstName.val();
      var last_name = $lastName.val();
      var terms = $termsOfServiceR.is(':checked')

      $signupBtn.text('TRYING...').addClass('disabled')


      rest.signup({email: email, password: password, first_name: first_name, last_name: last_name, terms:terms})
        .done(function(response) {
          window.location = '/client#/redeemComplete'
          window.location.reload()
        })
        .fail(function(jqXHR) {
          if(jqXHR.status == 422) {
            var response = JSON.parse(jqXHR.responseText)
            if(response.errors) {
              var $errors = context.JK.format_errors('first_name', response);
              if ($errors) $firstName.closest('.field').addClass('error').append($errors);

              $errors = context.JK.format_errors('last_name', response);
              if ($errors) $lastName.closest('.field').addClass('error').append($errors);

              $errors = context.JK.format_errors('password', response);
              if ($errors) $password.closest('.field').addClass('error').append($errors);

              var $errors = context.JK.format_errors('email', response);
              if ($errors) $email.closest('.field').addClass('error').append($errors);

              var $errors = context.JK.format_errors('terms_of_service', response);
              if ($errors) $termsOfServiceR.closest('.field').addClass('error').append($errors);
            }
            else {
              app.notify({title: 'Unknown Signup Error', text: jqXHR.responseText})
            }
          }
          else  {
            app.notifyServerError(jqXHR, "Unable to Sign Up")
          }
        })
        .always(function() {
          $signupBtn.text('SIGNUP').removeClass('disabled')
        })


      return false;
    }


    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow
      };
      app.bindScreen('redeemSignup', screenBindings);

      $screen           = $("#redeemSignupScreen");
      $signupForm       = $screen.find(".signup-form");
      $signupBtn        = $signupForm.find('.signup-submit');
      $email            = $signupForm.find('input[name="email"]');
      $password         = $signupForm.find('input[name="password"]');
      $firstName        = $signupForm.find('input[name="first_name"]');
      $lastName         = $signupForm.find('input[name="last_name"]');
      $inputElements    = $signupForm.find('.input-elements');
      $contentHolder    = $screen.find('.content-holder');
      $btnFacebook      = $screen.find('.signup-facebook')
      $termsOfServiceL  = $screen.find('.left-side .terms_of_service input[type="checkbox"]')
      $termsOfServiceR  = $screen.find('.right-side .terms_of_service input[type="checkbox"]')
      $jamtrackName     = $screen.find('.jamtrack-name');
      $signinLink       = $screen.find('.signin')

      if($screen.length == 0) throw "$screen must be specified";

      events();
    }

    this.initialize = initialize;

    return this;
  }
})(window,jQuery);