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;
      }
    });

    // Classify iPhones
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))){
      $('html').addClass('iphone');
    }
  }

  app.slideshow = function(){
    $('section.slides .slideshow').slideshow();
    $('section.slides .slideshow a img').css('position','absolute');
  }

  app.youtube = function(){
    $('#youtube-player ul li a').each(function(){
        var id = $(this).attr('href').split('v=')[1].split('&')[0];
        $(this).addClass('internal').find('img').attr('src', "http://img.youtube.com/vi/" + id + "/default.jpg");

        // Thumbnails switch youtube video
        $(this).click(function(event){
          var options = '?autoplay=1&rel=0&hd=1'

          // Don't autoplay on first load
          if ($(this).hasClass('initial')) {
            $(this).removeClass('initial').parent().addClass('first');
            options = '?autoplay=0&rel=0&hd=1'
          }

          $(this).closest('ul').find('a').removeClass('active');
          $(this).addClass('active');
          $(this).closest('div').find('.player').html('<iframe width="640" height="360" src="http://www.youtube.com/embed/' + id + options + '" frameborder="0" allowfullscreen></iframe>');
          event.preventDefault();
        });
    });

    // Initial state / first video
    $('#youtube-player ul li a:first').addClass('initial').click();
  }

  // Visual tweaks for headings
  app.headings = function(){
    $(window).load(function() {

      $('section.head header h1 span').each(function(){

        var $span = $(this);
        var $h1 = $span.closest('h1');
        var $header = $h1.closest('header');
        var spanWidth = $span.width() + parseInt($span.css('paddingLeft')) + parseInt($span.css('paddingRight'));

        switch ($header.attr('class')){

          case 'alternative':
            $h1.css({width:spanWidth+'px'}).addClass('border');
            break;

          default:
            var padding = parseInt(($header.width() - spanWidth) / 2) -1;
            $span.before('<b style="padding-left:'+padding+'px"></b>');
            $span.after('<b style="padding-left:'+padding+'px"></b>');
            break;
        }
      });
    });
  }

  // Visual tweaks for featured events
  app.featuredEvents = function(){
    var time = '';
    $('.featured-event .time').each(function(){
      if ($(this).html() == time) {
        $(this).hide();
      }
      time = $(this).html();
    });
  }

  // Misc navigation behaviour
  app.navigation = function(){

    // Scrolling navigation
    var anchors = _.map($('a.page'), function(a){
      $(a).prev('article').addClass('page').find('footer:last').append($(a));
      return $(a).attr('name');
    });
    _.each(anchors, function(anchor){
      $("a[href='"+anchor+"']").click(function(event){
        event.preventDefault();
        $('html,body').animate({scrollTop:$("a.page[name='"+anchor+"']").offset().top}, 500);
      });
    });

    // Map dropdown
    var $mapNav =  $('nav.main a#navlink_directions');
    var $map = $('nav.main figure.map');

    $mapNav.addClass('internal').click(function(event){
      event.preventDefault();
      $map.animate({ height:$map.css('max-height') },'slow', function(){
        $('body').one('click', function(){ $map.animate({ height:0 },'slow'); });
      });
    });
    $map.find('a').attr('href',$mapNav.attr('href'));


    // nav visual tweak
    $('nav.main ul li:last a').css('padding-right', 0);
    $('nav.footer ul li:last a').css('padding-right', 0);
  }

  // Linkify and external overherd links
  app.socialLinks = function(){
    window.setTimeout(function(){
      $('.overherd .entry').not('.linkified').each(function(){
        $(this).addClass('linkified').find('.content').contents().each(function(){
          if (this.nodeType == Node.TEXT_NODE) {
            $(this).replaceWith(_.linkify($(this).text()));
          }
        });
      });
      app.externalLinks();
      app.trackLinks();
    }, 10000);

    $('.blog_post p').each(function(){
      $(this).html(_.linkify($(this).text()));
    });
  }

  // Force all links starting with 'http' (external links) to open in a new window
  app.externalLinks = function(){
    if (location.href.match(/\/nterchange/g)) { return; }

    var filter = Array.prototype.slice.call(arguments).join('|');
    filter = (filter) ? new RegExp(filter) : null;

    $('a[href^=http]').not('.externalized').not('.internal').each(function(){
      var href = $(this).attr('href');

      if ((filter) && (href.match(filter))) {
        // Force link to be internal
      } else {
        // Force link to be external
        $(this).addClass('externalized').click(function(event){
          event.preventDefault();
          var newWindow = window.open(href,'_blank');
          newWindow.focus();
        });
      }
    });
  }

  app.trackLinks = function(){
    if (location.href.match(/\/nterchange/g)) { return; }
    if ((typeof _gaq=='undefined')) { return; }

    $('a').not('.trackified').each(function(){
      var trackingString = (window.location.host != this.hostname) ? '/external/' : '/internal/';
      $(this).addClass('trackified').click(function(){
        _gaq.push(['_trackPageview', trackingString + this.href]);
      });
    });
  }


  // Surf-to-edit tweaks
  app.nterchange = function(){
    if (location.href.match(/\/nterchange/g)) {
      $('html').addClass('nterchange');
    }
    $('.nterchange .root article').each(function(){
      var id = $(this).attr('id').split('-')[1];
      $(this).click(function(event){
        event.preventDefault();
        location.href = '/nterchange/page/surftoedit/'+id;
      });
    });
  }


  app.setup();
  app.slideshow();
  app.youtube();
  app.headings();
  app.featuredEvents();
  app.navigation();
  app.socialLinks();
  app.externalLinks();
  app.nterchange();
  $(window).load(function() { app.trackLinks(); });

});


