jQuery.noConflict();
jQuery(function($){

  var app = {};
  app.setup = function(){

    // Ruby-style string interpolation #{...}
    _.templateSettings = { interpolate : /\#\{(.+?)\}/g };

    // Turn http://, @usernames and #hashtags into links
    _.mixin({
      linkify: function(string) {
        string = string.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a target='_blank' href='$1'>$1</a>");
        string = string.replace(/(^|\s)@(\w+)/g, "$1<a target='_blank' href='http://www.twitter.com/$2'>@$2</a>");
        string = string.replace(/(^|\s)#(\w+)/g, "$1<a target='_blank' href='http://search.twitter.com/search?q=%23$2'>#$2</a>");
        return string;
      }
    });
  }

  app.classify = function(){
    // Navigation
    $('#nav li:first-child').addClass('first');
    $('#nav li:last-child').addClass('last');

    // Quicklinks
    $('#quicklinks li:first-child').addClass('first');
    $('#quicklinks li:last-child').addClass('last');
  }

  app.slideshow = function(){ 
    if ($('#banner .masthead').length > 1) {
      $('#banner .masthead:gt(0)').hide();
      setInterval(function(){
        $('#banner .masthead:first').fadeOut('slow', function(){
          $(this).nextAll('.masthead:first').fadeIn('slow')
          .end().appendTo($(this).parent());
        });
      }, 6000);
    }
  }

  app.twitter = function(){
    $.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=bowenworkforce&count=5&include_rts=1&callback=?", function(data){

      $(_.map(data, function(tweet){
        // Thu Apr 21 17:56:40 +0000 2011
        var datetime = tweet.created_at.split(' ');
        var created_at = _.template("#{day}-#{month}-#{year} #{time} GMT", {
          day: datetime[2],
          month: datetime[1],
          year: datetime[5],
          time: datetime[3]
        });
        return _.template('<div class="tweet"><p>#{text}</p><span><a href="#{link}" target="_blank">#{date}</a></span></div>', {
          text: _(tweet.text).linkify(),
          link: _.template('http://twitter.com/#{screen_name}/status/#{id}', { 
            screen_name: (tweet.retweeted_status) ? tweet.retweeted_status.user.screen_name : tweet.user.screen_name, 
            id: (tweet.retweeted_status) ? tweet.retweeted_status.id_str : tweet.id_str
          }),
          date: Date.parse(created_at).toString('MMMM d, yyyy, h:mm tt')
        });
      }).join('')).appendTo('.tweets'); 

      $('.tweets .tweet:first').addClass('first');
      $('.tweets .tweet:last').addClass('last');
    });
  }

  app.jobBoard = function() {
    $(_.map($('.job_type'), function(job_type){
      var col = 2;
      return _.template('<h3>#{job_type}</h3><table class="job_listings">#{job_listings}</table>', {
        job_type: $(job_type).attr('rel'),
        job_listings: _.map($(job_type).children(), function(job_listing){

          var td_padding = '';
          if ($(job_listing).next().length < 1){
            _(col).times(function(){ 
              td_padding += '<td class="bullet">&nbsp;</td><td class="title">&nbsp;</td>'; 
            });
          }
          var tr_open = (col==2) ? '<tr>' : '';
          var tr_close = (col==0) ? '</tr>' : '';
          col = (col==0) ? 2 : col-1;

          return _.template('#{tr_open}<td class="bullet">&raquo;</td><td class="title"><a href="##{job_link}" onclick="_gaq.push([\'_trackEvent\', \'JobLink\', \'#{job_title} #{job_link}\', \'Click\']);">#{job_title}</a></td>#{td_padding}#{tr_close}', {
            job_link: $(job_listing).attr('rel'),
            job_title: $(job_listing).find('.job_title').text(),
            tr_open: tr_open,
            tr_close: tr_close,
            td_padding: td_padding
          });
        }).join('')
      });
    }).join('')).appendTo('#jobs .jobs_nav');
  }

  app.searchDefaultValue = function(){
    $('form input[name=search]').each(function(){
      var defaultValue = $(this).val();
      $(this).focus(function(){
        if ($(this).val() == defaultValue) {
          $(this).val('');
        }
      });
      $(this).blur(function(){
        if ($(this).val() == '') {
          $(this).val(defaultValue);
        }
      });
    })
  }

  // Surf-to-edit tweaks
  app.nterchange = function(){
    $('body > div > a[title^="Edit Page"]').css('position','absolute');
    $('#banner .mask .pageContentAdd').css({ position:'absolute', right:'3px', top:'3px', zIndex:40 });
    $('#banner .masthead .pagecontent > div').css({ position:'absolute', zIndex:40, left:'7px', top:'3px'}).next().css({ position:'absolute', zIndex:30, left:'0px', top:'0px'});
  }

  app.setup();
  app.classify();
  app.slideshow();
  app.twitter();
  app.jobBoard();
  app.searchDefaultValue();
  app.nterchange();

});

