if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){ return i; }
    }
    return -1;
  };
}

function iPhone() { return (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)); }
function iPad()   { return (navigator.userAgent.match(/iPad/i)); }

var EC = {
  engage: function(){
    $('html').addClass('js');
    // if webkit build >= safari 4
    if($.browser.webkit && $.browser.version > '528.16') {
      //$('html').addClass('svg_supported');
    }

    $('[rel=email]').actAsMailTo();

    if($('#home_page').length)    { EC.Homepage.setup(); }
    if($('#about_page').length)   { EC.About.setup(); }
    if($('#contact_page').length) { EC.Contact.setup(); }
  }
};

EC.About = {
  navigation: function(){
    $('#about_us_navigation a').scrollBody(300);
  },

  bios: function(){
    $('#the_team').inlineNavigation('.person');
  },

  photos: function(){
    var userID  = '21618274@N04',
        config  = {
          api_key:'e7a11601cc6b6dad2bdf5219b38de131',
          thumbnail_size: 's',
          per_page: 18
        };

    $('#photos_zone').flickr(config).photosSearch({user_id: userID});
  },

  tweets: function(){
    $('#tweets').tweet({
      username: 'edgecase',
      loading_text: 'loading tweets...'
    });
  },

  setup: function(){
    EC.About.navigation();
    EC.About.bios();
    EC.About.tweets();
    EC.About.photos();

    var hash = window.location.hash;

    if($(hash).parents('#the_team').length) {
      $('#team_link').click();
      $('#the_team nav a[href=' + hash + ']').click();
    }
  }
};

EC.Contact = {
  locations: function(){
    $('#our_locations').inlineNavigation('.location');
  },

  viewAMap: function(){
    $('#our_locations .view_a_map').click(function(e) {
      e.preventDefault();
      var map  = $(this).parents('.location').find('.map')
      ,   temp = map.is(':visible') ?  map.fadeOut(250) : map.fadeIn(250);
    });
  },

  setup: function(){
    $('.inline_label').actAsInlineLabel();
    EC.Contact.locations();
    EC.Contact.viewAMap();
  }
};

EC.Build = {
  setup: function(){
    if(!$('#home_page.build').length) { return; }

    $('#our_work').inlineNavigation('.case_study');

    var arrows = '<a href="#" class="previous arrow">previous</a><a href="#" class="next arrow">next</a>';
    $('#our_work .orange_bar').append(arrows);

    $('#our_work .orange_bar .arrow').click(function(e) {
      var active   = $('#our_work nav .active')
      ,   next     = active.parent().next().find('a')
      ,   previous = active.parent().prev().find('a')
      ,   temp     = $(this).hasClass('next') ? next.click() : previous.click();

      e.preventDefault();
    });
  }
};

EC.Teach = {
  setup: function() {
    $('#conference_photos').actAsSlideshow();

    $('#training_quotes blockquote:not(:first)').hide();
    $('#training_quotes .arrow').click(function(e) {
      e.preventDefault();

      var current  = $('#training_quotes blockquote:visible')
      ,   next     = current.next('blockquote').length ? current.next('blockquote') : $('#training_quotes blockquote:first')
      ,   previous = current.prev('blockquote').length ? current.prev('blockquote') : $('#training_quotes blockquote:last');

      current.hide();
      if($(this).hasClass('previous')) {
        previous.fadeIn(250);
      } else {
        next.fadeIn(250);
      }
    });
  }
};

EC.Homepage = {
  content: { partner:null, build:null, teach:null },

  fetchPages: function(){
    $.post('/build?'   + new Date().getTime(), function(data) {  EC.Homepage.content.build   = data; }, 'json');
    $.post('/teach?'   + new Date().getTime(), function(data) {  EC.Homepage.content.teach   = data; }, 'json');
    $.post('/partner?' + new Date().getTime(), function(data) {  EC.Homepage.content.partner = data; }, 'json');
  },

  animatedLinksSetup: function(){
    $('#introduction .arrow a, #introduction .links a').scrollBody(300);
  },

  sammyLinksSetup: function() {
    $('#main_links a:not(#home_link)').each(function(index, link) {
      var old = $(link).attr('href');
      $(link).attr('href', '  #' + old);
    });
  },

  repositionImages: function() {
    var centerImage   = $('#images .image.center'),
        leftImage     = centerImage.prev('.image'),
        rightImage    = centerImage.next('.image'),
        farLeftImage  = centerImage.prev('.image').prev('.image'),
        farRightImage = centerImage.next('.image').next('.image'),
        centerSlot    = $('#images .slot.center'),
        leftSlot      = $('#images .slot.left'),
        rightSlot     = $('#images .slot.right'),
        farLeftSlot   = $('#images .slot.farleft'),
        farRightSlot  = $('#images .slot.farright');


    leftImage.css({left:leftSlot.offset().left,         marginLeft:0});
    centerImage.css({left:centerSlot.offset().left,     marginLeft:0});
    rightImage.css({left:rightSlot.offset().left,       marginLeft:0});
    farLeftImage.css({left:farLeftSlot.offset().left,   marginLeft:0});
    farRightImage.css({left:farRightSlot.offset().left, marginLeft:0});
  },

  setup: function(){
    EC.Build.setup();
    EC.Teach.setup();
    EC.Homepage.fetchPages();
    EC.Homepage.animatedLinksSetup();
    EC.Homepage.sammyLinksSetup();
    EC.Homepage.repositionImages();

    $(window).resize(function() {
      EC.Homepage.repositionImages();
    });

    var app = $.sammy(function(){
      function highlightLink(selector){
        $('#main_links a').removeClass('active');
        $('#main_links .' + selector).addClass('active');
      }

      function updatePageJSON(payload) {
        EC.Homepage.content[payload.body_class] = payload;
      }

      function successfulPost(payload){
        updatePageJSON(payload);
        updateContent(payload);
      }

      function updateContent(payload){
        $('body').attr('class', payload.body_class);
        $('#introduction .content_wrapper').html(payload.introduction_content_html);
        $('#main_content .content_wrapper').html(payload.main_content_html);
        $('#introduction .content_wrapper, #main_content .content_wrapper').fadeIn(200);
        EC.Build.setup();
        EC.Teach.setup();
        $('[rel=email]').actAsMailTo();
      }

      function loadSection(section){
        highlightLink(section);
        animateImages(section);
        $('#introduction .content_wrapper, #main_content .content_wrapper').fadeOut(200, function() {
          $('#introduction .content_wrapper, #main_content .content_wrapper').empty();
          if(EC.Homepage.content[section] !== null){
            updateContent(EC.Homepage.content[section]);
          } else{
            $.post('/' + section, successfulPost, 'json');
          }
        });
      }

      function animateImages(section){
        var slots    = ['farleft', 'left', 'center', 'right', 'farright'],
            sections = ['partner', 'build', 'teach'],
            destinationIndex = sections.indexOf(section);

        var offset = 0;
        if(destinationIndex === 0) {
          offset = 2;
        } else if (destinationIndex == 2) {
          offset = -2;
        }

        $('#images .'+sections[0]).animate({left:$('#images .'+slots[destinationIndex+offset]).offset().left  }, 600, 'easeInOutExpo');
        $('#images .'+sections[1]).animate({left:$('#images .'+slots[destinationIndex+offset+1]).offset().left}, 600, 'easeInOutExpo');
        $('#images .'+sections[2]).animate({left:$('#images .'+slots[destinationIndex+offset+2]).offset().left}, 600, 'easeInOutExpo');

        $('#images .image').removeClass('center');
        $('#images .' + sections[destinationIndex]).addClass('center');
      }

      this.get('#/', function() { this.redirect('#/build'); });
      this.get('#/:section', function() { loadSection(this.params['section']); });

      this.bind('partner', function() { this.redirect('#/partner'); });
      this.bind('build',   function() { this.redirect('#/build'); });
      this.bind('teach',   function() { this.redirect('#/teach'); });
    }).run();

    $('#images .image').click(function() {
      var target    = $(this).attr('rel')
      ,   bodyClass = $('body').attr('class');
      if(target != bodyClass) { app.trigger(target); }
    });
  }
};

$(function(){ EC.engage(); });

