/*
* General purpose scripts for theinvolvementpractice
*
* (c) 2011, Darren Newton
* All Rights Reserved
* https://github.com/DarrenN
* http://stackoverflow.com/users/12799/darren-newton
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

// @@ See plugins.js for all additional licenses (MIT/GPL)

// Attach behaviors to Left Nav
var $nav = $('#left-nav');
var $nav_links = $nav.find('li');
var tpl = _.template('<span id="label-<%= label %>"><%= label %></span>');
var scroll_state = false;

var resetNavClass = function(anchor) {
  $nav_links.each(function(index, el){
    $(el).find('a').removeClass('active');
    $(el).find('span').data({'active' : 0}).hide();
  });
}

$nav_links.each(function(index,el){
  var $el = $(this);
  var $a = $el.find('a');
  var loc = $a.attr('href');
  var label = $a.data('nav-label');
  var offset = $a.data('nav-offset');

  $el.append(tpl({'label': label}));

  $(el).bind({
    'mouseenter' : function() {
      $('#label-' + label).show();
    },
    'mouseleave' : function() {
        if ($('#label-' + label).data('active') !== 1) {
        $('#label-' + label).hide();
      }
    },
    'click' : function(e) {
      e.preventDefault();
      resetNavClass();
      $a.addClass('active');
      $('#label-' + label).data({'active' : 1}).show();
      scroll_state = true;

      var settings = {
        onAfter : function(){ scroll_state = false; }
      };
      if (offset) {
        settings.offset = offset;
      }

      $.scrollTo(loc, 800, settings);
      window.location.hash = loc // set hash in URL for bookmarking

      // Register click with Google Analytics
      _gaq.push(['_trackEvent', 'Navigation','Click', loc]);
    }
  });
});

// Initialize nav
var hash = "main";
if (window.location.hash) {
  hash = window.location.hash.replace('#section-','');
}
$('#nav-' + hash).addClass('active').parent().find('span').data({'active':1}).show();

// Attach waypoints to sections
var $sections = $('div[id*=section-]');
$sections.each(function(index,el){
  $(el).waypoint(function(event, direction){
    var target = event.target.id;
    var nav_target = target.replace('section','nav');
    if (!scroll_state) {
        resetNavClass();
        $('#'+nav_target).addClass('active').parent().find('span').data({'active':1}).show();
        // Register scroll with Google Analytics
        _gaq.push(['_trackEvent', 'Navigation','Scroll', target]);
    }
  });
});
$('footer').waypoint(function(event, direction){
  var target = event.target.id;
  var nav_target = target.replace('section','nav');
  if (!scroll_state) {
      resetNavClass();
      $('#'+nav_target).addClass('active').parent().find('span').data({'active':1}).show();
      // Register scroll with Google Analytics
      _gaq.push(['_trackEvent', 'Navigation','Scroll', target]);
  }
},{
  offset : 'bottom-in-view'
});

// Generic method to toggle image SRC attributes on/off
var toggleImage = function(event, prev_state, new_state) {
  var re = new RegExp(prev_state, "i");
  var new_src = event.currentTarget.src.replace(re, new_state);
  $(event.currentTarget).attr('src', new_src);
}

// Attach rollover behaviors to Circle nav
var $nav_circles = $("#section-main nav a img");

$nav_circles.bind({
  mouseover : function(event) {
    toggleImage(event, 'off', 'on');
  },
  mouseout : function(event) {
    toggleImage(event, 'on', 'off');
  }
});

// Attach click state to team bio links
var $team_links = $('ul.team li h5 a');
var $team_bios = $('ul.team li div');

var closeTeamBios = function() {
  $team_bios.each(function(o, el){
    var $el = $(el);
    if ($el.data('state') == 1) {
      $el.slideUp('fast').data('state', 0);
    }
  });
};

$team_links.bind({
  click : function(e) {
    e.preventDefault();
    var $target = $(e.currentTarget);
    var $bio_el = $('#'+$target.data('team'));
    if ($bio_el.data('state') !== 1) {
        closeTeamBios();
        $bio_el.slideDown('fast').data('state', 1);
    } else {
        $bio_el.slideUp('fast').data('state', 0);
    }
  }
});

// Contact form
$.fn.modal.defaults = {
      overlay: "#000",
      opacity: 0.75,
      zIndex: 1200,
      escapeClose: true,
      clickClose: true,
      showClose: true,
      modalClass: "modal"
    };
$('#contact-email').click(function(e){
  e.preventDefault();
  $('#contact-form').modal();
});

$('#contact-form').submit(function(e){
  e.preventDefault();
  $('#form-success').hide();
  $('#form-error').hide();
  var $form = $('#contact-form');
  var form_data = $form.serialize();
  var url = $form.attr('action');
  var response = "";
  var jqxhr = $.post(url, form_data, function(data){
    response = data;
  },'json')
  .success(function(){
    $('#form-success').html(response).show();
  })
  .error(function(){
    $('#form-success').hide();
    $('#form-error').html(response + " Required fields are missing").show();
  });
  $('#form-success').html('<span class="sending">Sending...</span>').show();
});

// Twitter
// http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
getTwitters('tweet', {
  id: 'timmccleary',
  count: 2,
  enableLinks: true,
  ignoreReplies: true,
  clearContents: true,
  template: '<a href="http://twitter.com/#!/timmccleary" class="tweet-img"><img src="%user_profile_image_url%" alt="Tim McCleary" /></a> <p>%text% | <a href="http://twitter.com/%user_screen_name%/statuses/%id_str%/" class="date">%time%</a></p>'
});
getTwitters('tweet_b', {
  id: 'theinvolver',
  count: 2,
  enableLinks: true,
  ignoreReplies: true,
  clearContents: true,
  template: '<a href="http://twitter.com/#!/theinvolver" class="tweet-img"><img src="%user_profile_image_url%" alt="The Involver" /></a> <p>%text% | <a href="http://twitter.com/%user_screen_name%/statuses/%id_str%/" class="date">%time%</a></p>'
});

