/*global $ jQuery re_email uploadFile current_user FV */

re_email = /[a-z0-9!#$%&'*+/=?\^_`{|}~\-]+(?:\.[a-z0-9!#$%&'*+/=?\^_`{|}~\-]+)*@(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?/;

$.feature('f_register_games', function () {
  var toggle_game = function(selectable) {
    var id = selectable.attr('id').split('-')[1];

    var li = selectable.parent();
    var selected = li.hasClass('active');
    li.removeClass('active');
    li.addClass('loading');

    var data = {};
    var url = "/" + current_user.username + "/games/xhr/delete_game/" + id;

    if (!selected) {
      url = '/a/register/xhr_add_gameplatform';
      data = {'id': id};
    }

    $.ajax({
      url: url,
      data: data,
      type: 'post',
      dataType: 'json',
      success: function (data) {
        var num_div = $('div.num_selected div.num');
        var delta;
        li.removeClass('loading');

        if (!selected) {
          delta = 1;
          li.addClass('active');
        } else {
          delta = -1;
        }

        var total = parseInt(num_div.text(), 10) + delta;
        var plural = (total == 1) ? '' : 's';
        num_div.text(total);
        $('strong.num_games_selected_string').text(total + ' game' + plural);
      },
      error: function (xhr, textStatus, errorThrown) {
        li.removeClass('loading');
        if (selected) {
          li.addClass('active');
        }
      }
    });
  };

  $('.select_games div.selectable').live('click', function() {
    toggle_game($(this));
    return false;
  });
});

$.feature('f_register_platforms', function () {

  var increased_height = false;

  jQuery.fn.show_balloon = function() {
    $(this).show();
    if (!increased_height) {
      $('.quickselect > li:lt(5)').height(270);
      increased_height = true;
    }
    return $(this);
  };

  jQuery.fn.hide_balloon = function() {
    $(this).hide();
    var expanded = false;
    $('.quickselect li:lt(3)').each(function() {
      if ($(this).hasClass('active')) { expanded = true; }
    });
    if (!expanded) {
      $('.quickselect li:lt(5)').height(133);
      increased_height = false;
    }
    return $(this);
  };

  $('.gamer_tag_balloon').each(function() {
    var li = $(this).closest('li');
    if (li.hasClass('active')) {
      $(this).show_balloon();
    }
  });

  $.live('#network_id_steam', 'keydown', function() {
    $('.steam_correct').show();
    return true;
  });

  $.live('.steam_correct a', 'click', function() {
    $('#help_tip_steam_correct').show();
    return false;
  });

  $.live('#help_tip_steam_correct a.close', 'click', function() {
    $('#help_tip_steam_correct').hide();
    return false;
  });

  $('.select_platforms div.view_all a').live('click', function() {
    var query_string = [];
    $('div.gamer_tag_balloon').each( function(i) {
      var input = $(this).find('input');
      var id = input.attr('name').split('_').pop();
      var text = input.val();
      if (text !== '') {
        query_string.push(id + '=' + encodeURIComponent(text));
      }
    });
    window.location = $(this).attr('href') + '?' + query_string.join('&');
    return false;
  });

  $('.select_platforms div.selectable').live('click', function() {
    var slug = $(this).attr('id');

    var li = $(this).parent();
    var selected = li.hasClass('active');
    li.removeClass('active');
    li.addClass('loading');

    var url = selected ? '/a/register/xhr_remove_platform' : '/a/register/xhr_add_platform';

    $.ajax({
      url: url,
      data: {'slug': slug},
      type: 'post',
      dataType: 'json',
      success: function (data) {
        var num_div = $('div.num_platforms_selected div.num');
        li.removeClass('loading');
        var total, plural;

        if (!selected) {
          total = parseInt(num_div.text(), 10) + 1;
          plural = (total == 1) ? '' : 's';
          num_div.text(total);
          $('strong.num_platforms_selected_string').text(total + ' platform' + plural);
          li.addClass('active');

          var gtb = li.find('div.gamer_tag_balloon');

          for (var network_slug in data.networks) {
            gtb.show_balloon();
            $('#network_id_' + network_slug).val(data.networks[network_slug]);
            gtb.find('input').val(data['network_id']);
          }
        } else {
          total = parseInt(num_div.text(), 10) - 1;
          plural = (total == 1) ? '' : 's';
          num_div.text(total);
          $('strong.num_platforms_selected_string').text(total + ' platform' + plural);

          li.find('div.gamer_tag_balloon').hide_balloon();
        }
      },
      error: function (xhr, textStatus, errorThrown) {
        li.removeClass('loading');
        if (selected) {
          li.addClass('active');
        }
      }
    });
  });
});

$.feature('f_register_create_account', function () {
  var email_timeout = null;
  var email_cache = {good: {}, bad: {}};
  var username_cache = {};
  var username_timeout = null;

  var form = new FV.Form({
      on_change_status: function (is_valid) {
        $('.submit .show-on-valid').toggle(is_valid);
        $('.submit .show-on-error').toggle(!is_valid);
      },
      set_message: function (field, msg, status) {
        var elem = field.status_elem;
        if (!msg) { return; }
        elem.html('<div class="formrow_balloon_inner">' + msg + '</div>');
        elem.attr('class', 'formrow_balloon ' + status + '-box');
      }
    },
    {
    username: new FV.Field({
      elem: $('#id_new-username'),
      events: 'blur keyup',
      status_elem: $('#ei-username'),
      check: function (field) {
        var username = field.elem.val();

        if (username_timeout) { clearTimeout(username_timeout); }

        if (username.length === 0) {
          throw { 'message': 'Please enter a username' };
        }
        function update(uname) {
          form.set_message(
            field,
            username_cache[uname].message,
            username_cache[uname].status
          );
        }

        if (username in username_cache) {
          update(username);
          return;
        }

        function xhr_check_username() {
          $.post("/a/register/username_check",
                 {username: username},
                 function (data) {
                   if (username != field.elem.val()) {
                     return;
                   }
                   if (data.status == 'success') {
                     username_cache[username] = {message: 'OK', status: 'ok'};
                   }
                   if (data.status == 'fail' && data.reason == 'already_taken') {
                     username_cache[username] = {message: 'This username is taken', status:'error'};
                   }
                   if (data.status == 'fail' && data.reason == 'value_error') {
                     username_cache[username] = {message: 'Please enter a valid username', status: 'error'};
                   }
                   update(username);
                 });
        }

        username_timeout = setTimeout(xhr_check_username, 800);

        return 'Checking username ...';
      }
    }),

    email_address: new FV.Field({
      elem: $('#id_new-email'),
      events: 'blur keyup',
      status_elem: $('#ei-email'),
      check: function (field) {
        var email = field.elem.val();

        if (email.length === 0) {
          throw { 'message': 'Please enter an email address' };
        }

        if (email_timeout) { clearTimeout(email_timeout); }

        if (!email.match(re_email)) {
          throw { 'message': 'Please enter a valid email address' };
        }

        // Use our email cache
        if (email_cache.good[email]) { return 'Looks good...'; }
        if (email_cache.bad[email]) {
          throw { 'message': email_cache.bad[email] };
        }

        var xhr_check_email = function() {
          $.get(
            "/a/register/email_check",
            {email: email},
            function (data) {
              if (email != field.elem.val()) {
                // Value has changed; ignore this result.
                return;
              }

              if (data.status == 'success') {
                form.set_message(field, 'Looks good...', 'ok');
                email_cache.good[email] = true;
                return;
              }

              var message = {
                'already_taken': 'This email address is already in use for an account. ' +
                  'Have you <a href="/a/forgotten_password">forgotten your password?</a>',
                'value_error': 'Please enter a valid email address.'
              }[data.reason];

              form.set_message(field, message, 'error');

              // Store the message in the cache, not just the fact it is bad.
              email_cache.bad[email] = message;
            },
            "json"
          );
        };

        email_timeout = setTimeout(xhr_check_email, 800);

        // We pretend this field is valid, even though we haven't validated it
        // remotely. This prevents us from having to modify the form's global
        // validity inside an asynchronous function which complicates the
        // working considerably. The user could submit the form in the meantime
        // but it would fail server-side validation.
        return 'Checking to see if this address is used...';
      }
    }),

    password: new FV.Field({
      elem: $('#id_new-password'),
      events: 'blur keyup',
      status_elem: $('#ei-password'),
      check: function (field) {
        var password = field.elem.val();

        if (password.length === 0) {
          throw { 'message': 'Please enter a password' };
        }

        return 'Password is ok';
      }
    }),

    password_confirm: new FV.Field({
      elem: $('#id_new-password_confirm'),
      events: 'blur keyup',
      status_elem: $('#ei-password_confirm'),
      check: function () {
        var one = $('#id_new-password').val();
        var two = $('#id_new-password_confirm').val();

        if (two.length === 0) {
          throw { 'message': 'Please enter a password' };
        }

        if (one !== two) {
          throw { 'message': (one.substr(0, two.length) == two) ?
              'Almost...' : 'Oh dear, the passwords you entered do not match!' };
        }

        return 'Password matches';
      }
    }),

    /* Permission to send user emails */
    email_permission: new FV.Field({
      elem: $('#chk_permission'),
      events: 'change click',
      status_elem: $('#ei-chk_permission'),
      check: function (field) {
        if (field.elem.attr('checked')) {
          return 'All set!';
        }

        throw {
          'message': 'We need to send you occasional updates about your ' +
            'account and to initially validate your email. You can turn ' +
            'these off at any time after registration. We will never spam you.'
        };
      }
    })
  });

  $('form.create-account-form').submit(function() {
    // Only allow form submission if all items have been checked
    return form.valid;
  });

});

$.feature('f_register_about', function () {
  $('.avatar .upload a').live('click', function() {
    uploadFile.upload('profile-pic-input',
                      '/a/profile/upload_pic',
                      function (data) {
                        $('#profile-pic').attr('src', data.url).show();
                      }
                     );
    return false;
  });
});
