(function (context, $) {

  "use strict";

  context.JK = context.JK || {};
  context.JK.AccountAffiliateScreen = function (app) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var userId;
    var user = {};
    var affiliatePartnerTabs = ['account', 'agreement', 'signups', 'earnings'];
    var affiliatePartnerData = null;
    var $screen = null;

    function beforeShow(data) {

      userId = context.JK.currentUserId
      affiliatePartnerData = null;
    }

    function afterShow(data) {

      rest.getAffiliatePartnerData(userId)
        .done(function (response) {
          affiliatePartnerData = response;
          renderAffiliateTab('account')
        })
        .fail(app.ajaxError)

    }

    function events() {

      // Affiliate Partner
      $("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-account-link', function (evt) {
        evt.stopPropagation();
        renderAffiliateTab('account');
        return false;
      });
      $("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-links-link', function (evt) {
        evt.stopPropagation();
        renderAffiliateTab('links');
        return false;
      });
      $("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-agreement-link', function (evt) {
        evt.stopPropagation();
        renderAffiliateTab('agreement');
        return false;
      });
      $("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-signups-link', function (evt) {
        evt.stopPropagation();
        renderAffiliateTab('signups');
        return false;
      });
      $("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-earnings-link', function (evt) {
        evt.stopPropagation();
        renderAffiliateTab('earnings');
        return false;
      });
      $("#account-affiliate-partner-content-scroller").on('click', '#affiliate-profile-account-submit', function (evt) {
        evt.stopPropagation();
        handleUpdateAffiliateAccount();
        return false;
      });
    }

    function _renderAffiliateTableSignups(rows) {
      rest.getAffiliateSignups()
        .done(onAffiliateSignups)
        .fail(app.ajaxError)
    }

    function _renderAffiliateTableEarnings(rows) {
      rest.getAffiliatePayments()
        .done(onAffiliatePayments)
        .fail(app.ajaxError)
    }

    function _renderAffiliateTableLinks(rows) {
      $screen.find('.affiliate-agreement').on('click', function () {
        renderAffiliateTab('agreement');
        return false;
      })

      $screen.find('.affiliate-link-page').attr('href', '/affiliate/links/' + affiliatePartnerData.account.id)

      $screen.find('select.link_type').easyDropDown();

      var $linkType = $screen.find('.link_type')

      $linkType.on('change', function() {
        logger.debug("link type changed")
        updateLinks();
      })

      updateLinks();
    }

    function onAffiliateSignups(signups) {

      var $table = $screen.find('table.traffic-table tbody')
      $table.empty();

      var template = $('#template-affiliate-partner-signups-row').html();
      context._.each(signups.traffics, function(item) {
        var $link = $(context._.template(template, item, {variable: 'data'}));

        var $day = $link.find('td.day')

        var day = $day.text();
        var bits = day.split('-')
        if(bits.length == 3) {
          $day.text(context.JK.getMonth(new Number(bits[1]) - 1) + ' ' + new Number(bits[2]))
        }

        $table.append($link)
      })
    }

    function onAffiliatePayments(payments) {
      var $table = $screen.find('table.payment-table tbody')
      $table.empty();

      var template = $('#template-affiliate-partner-earnings-row').html();
      context._.each(payments.payments, function(item) {

        var data = {}
        if(item.payment_type == 'quarterly') {

          if(item.quarter == 0) {
            data.time = '1st Quarter ' + item.year
          }
          else if(item.quarter == 1) {
            data.time = '2nd Quarter ' + item.year
          }
          else if(item.quarter == 2) {
            data.time = '3rd Quarter ' + item.year
          }
          else if(item.quarter == 3) {
            data.time = '4th Quarter ' + item.year
          }

          data.sold = ''

          if(item.paid) {
            data.earnings = 'PAID $' + (item.due_amount_in_cents / 100).toFixed(2);
          }
          else {
            data.earnings = 'No earning were paid, as the $10 minimum threshold was not reached.'
          }
        }
        else {
          data.time = context.JK.getMonth(item.month - 1) + ' ' + item.year;
          if(item.jamtracks_sold == 1) {
            data.sold = 'JamTracks: ' + item.jamtracks_sold + ' unit sold';
          }
          else {
            data.sold = 'JamTracks: ' + item.jamtracks_sold + ' units sold';
          }
          data.earnings = '$' + (item.due_amount_in_cents / 100).toFixed(2);
        }


        var $earning = $(context._.template(template, data, {variable: 'data'}));

        $table.append($earning)
      })
    }


    function updateLinks() {

      // affiliatePartnerData.account.id

      rest.getLinks('all', affiliatePartnerData.account.id)
        .done(populateLinkTable)
        .fail(function() {
          app.notify({text: 'Unable to fetch links.  Please try again later.' })
        })
    }

    function _renderAffiliateTab(theTab) {
      affiliateTabRefresh(theTab);
      var template = $('#template-affiliate-partner-' + theTab).html();
      var tabHtml = context._.template(template, affiliatePartnerData[theTab], {variable: 'data'});
      $('#affiliate-partner-tab-content').html(tabHtml);

      if (theTab == 'signups') {
        _renderAffiliateTableSignups(affiliatePartnerData[theTab]);
      } else if (theTab == 'earnings') {
        _renderAffiliateTableEarnings(affiliatePartnerData[theTab]);
      } else if (theTab == 'links') {
        _renderAffiliateTableLinks(affiliatePartnerData[theTab]);
      }
    }

    function renderAffiliateTab(theTab) {
      if (affiliatePartnerData) {
        return _renderAffiliateTab(theTab);
      }
      rest.getAffiliatePartnerData(userId)
        .done(function (response) {
          affiliatePartnerData = response;
          _renderAffiliateTab(theTab);
        })
        .fail(app.ajaxError)
    }

    function affiliateTabRefresh(selectedTab) {
      var container = $('#account-affiliate-partner-content-scroller');
      container.find('.affiliate-partner-nav a.active').removeClass('active');
      if (selectedTab) {
        container.find('.affiliate-partner-' + selectedTab).show();
        $.each(affiliatePartnerTabs, function (index, val) {
          if (val != selectedTab) {
            container.find('.affiliate-partner-' + val).hide();
          }
        });
        container.find('.affiliate-partner-nav a#affiliate-partner-' + selectedTab + '-link').addClass('active');
      } else {
        $.each(affiliatePartnerTabs, function (index, val) {
          container.find('.affiliate-partner-' + val).hide();
        });
        container.find('.affiliate-partner-nav a#affiliate-partner-' + affiliatePartnerTabs[0] + '-link').addClass('active');
      }
    }

    function handleUpdateAffiliateAccount() {
      var tab_content = $('#affiliate-partner-tab-content');
      var affiliate_partner_data = {
        'address': {
          'address1': tab_content.find('#affiliate_partner_address1').val(),
          'address2': tab_content.find('#affiliate_partner_address2').val(),
          'city': tab_content.find('#affiliate_partner_city').val(),
          'state': tab_content.find('#affiliate_partner_state').val(),
          'postal_code': tab_content.find('#affiliate_partner_postal_code').val(),
          'country': tab_content.find('#affiliate_partner_country').val()
        },
        'tax_identifier': tab_content.find('#affiliate_partner_tax_identifier').val(),
        'paypal_id': tab_content.find('#affiliate_partner_paypal_id').val()
      }
      var button = $('#affiliate-profile-account-submit')
      button.addClass("disabled")
      rest.postAffiliatePartnerData(userId, affiliate_partner_data)
        .done(postUpdateAffiliateAccountSuccess)
          .fail(function(jqXHR) {
            button.removeClass("disabled")
            alert("Unable to update affiliate information.\n\n" + jqXHR.responseText)
          })
    }

    function postUpdateAffiliateAccountSuccess(response) {
      $('#affiliate-profile-account-submit').removeClass("disabled")
      app.notify(
        {
          title: "Affiliate Account",
          text: "You have updated your affiliate partner data successfully."
        },
        null, true);
    }

    function populateLinkTable(response) {
      $screen.find('table.links-table').show();
      var $linkTable = $screen.find('.links-table tbody')

      $linkTable.empty();
      var template = $('#template-affiliate-link-entry').html();
      context._.each(response, function(item) {
        var $link = $(context._.template(template, item, {variable: 'data'}));
        $link.find('td.copy-link a').click(copyLink)
        $linkTable.append($link)
      })
    }

    function copyLink() {
      var element = $(this);
      var $url = element.closest('tr').find('td.url input')
      $url.select()

      return false;
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow
      };
      app.bindScreen('account/affiliatePartner', screenBindings);
      $screen = $('#account-affiliate-partner')
      events();
    }

    this.initialize = initialize;
    this.beforeShow = beforeShow;
    this.afterShow = afterShow;
    return this;
  };

})(window, jQuery);
