// Requires jQuery

function selectBanner(input) {
  if (!input) {
    var match = window.location.search.match(/banner=(\d)/);
    if (match && match[1]) { input = match[1]; }
  }

  var n = 3 // Number of banner images
  // If the input is a valid banner number, use it
  for (var i = 1; i <= n; i++) {
    if ( i == input ) { var number = input; }
  }
  // Otherwise, pick a random banner image
  if (!number) { number = Math.floor(Math.random()*n) + 1; }
  // Set the chosen image to the background-image of #banner
  var new_image_url = 'url(/media/banners/ch/banner_' + number + '.jpg)';
  $('#banner').css('background-image', new_image_url);

  // Mark the selected image's button as selected
  $('#banner-selectors li.selected').removeClass('selected');
  $('#banner-selectors li:nth-child(' + number + ')').addClass('selected');
}

// when DOM is ready
$(function(){
  // switch banners when a number is clicked on
  $('#banner-selectors li').each(function() {
    $(this).click(function(){ selectBanner(this.innerHTML.slice(0,1)); })
  });

  // pick a random background image
  selectBanner();


  // Keep the info buttons in hover while their menus are open
  $('#info-nav ul > li').hover(function() {
    $(this).children("a").addClass("menu-on");
  }, function() {
    $(this).children("a").removeClass("menu-on");
  });

  // FIXME: 2009-04-23 <andre@wesabe.com> -- these should be links. dammit.
  $('.sign-in,.sign-up').click(function(){
    window.location = $('a', this).attr('href');
  });

  // Load the login form, but only if it's safe
  var safe_to_log_in = ("https:" == document.location.protocol || document.location.hostname.match(/dev$/));
  var wesabe_member = document.cookie.match(/wesabe_member=1/);
  if (wesabe_member && safe_to_log_in) {
    jQuery.get("/user/userbar?homepage=true", function(data) {
      if (!data.match(/^\s*$/)) {
        $('#sign-in-box #top').append(data);
        $('.sign-in').unbind('click')
          .click(function(event){
            var button = $('.sign-in'), box = $('#sign-in-box');

            if (event.target != button.get(0) && event.target != box.get(0)) return;

            if (button.hasClass('open')) {
              box.slideUp("normal",
                function(){ button.removeClass("open"); });
            } else {
              button.addClass("open");
              box.slideDown("normal",
                function(){ $('#email').focus(); });
            }
          });

        $('#forgot-password-link')
          .click(function() {
            window.location = this.href+'?email='+encodeURIComponent($('#email').val());
            return false;
          });
      } else {
        $('.sign-in').removeClass('sign-in').addClass('signed-in')
          .find('a').attr('href', '/accounts');
      }
    });
  }

  jQuery.get("/group_discussions/hot", function(data){
    $('#community .content').append(data);
  });
});

