/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 * Copyright (c) 2008 George McGinley Smith and (c) 2001 Robert Penner
 * Open source under the BSD License. (http://www.opensource.org/licenses/bsd-license.php)
*/
jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInCubic:function(e,f,a,h,g){return h*(f/=g)*f*f+a},easeOutCubic:function(e,f,a,h,g){return h*((f=f/g-1)*f*f+1)+a},easeInOutCubic:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f+a}return h/2*((f-=2)*f*f+2)+a},easeInQuart:function(e,f,a,h,g){return h*(f/=g)*f*f*f+a},easeOutQuart:function(e,f,a,h,g){return -h*((f=f/g-1)*f*f*f-1)+a},easeInOutQuart:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f+a}return -h/2*((f-=2)*f*f*f-2)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInSine:function(e,f,a,h,g){return -h*Math.cos(f/g*(Math.PI/2))+h+a},easeOutSine:function(e,f,a,h,g){return h*Math.sin(f/g*(Math.PI/2))+a},easeInOutSine:function(e,f,a,h,g){return -h/2*(Math.cos(Math.PI*f/g)-1)+a},easeInExpo:function(e,f,a,h,g){return(f==0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f==0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInCirc:function(e,f,a,h,g){return -h*(Math.sqrt(1-(f/=g)*f)-1)+a},easeOutCirc:function(e,f,a,h,g){return h*Math.sqrt(1-(f=f/g-1)*f)+a},easeInOutCirc:function(e,f,a,h,g){if((f/=g/2)<1){return -h/2*(Math.sqrt(1-f*f)-1)+a}return h/2*(Math.sqrt(1-(f-=2)*f)+1)+a},easeInElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return -(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e},easeOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return g*Math.pow(2,-10*h)*Math.sin((h*k-i)*(2*Math.PI)/j)+l+e},easeInOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k/2)==2){return e+l}if(!j){j=k*(0.3*1.5)}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}if(h<1){return -0.5*(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e}return g*Math.pow(2,-10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j)*0.5+l+e},easeInBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*(f/=h)*f*((g+1)*f-g)+a},easeOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*((f=f/h-1)*f*((g+1)*f+g)+1)+a},easeInOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}if((f/=h/2)<1){return i/2*(f*f*(((g*=(1.525))+1)*f-g))+a}return i/2*((f-=2)*f*(((g*=(1.525))+1)*f+g)+2)+a},easeInBounce:function(e,f,a,h,g){return h-jQuery.easing.easeOutBounce(e,g-f,0,h,g)+a},easeOutBounce:function(e,f,a,h,g){if((f/=g)<(1/2.75)){return h*(7.5625*f*f)+a}else{if(f<(2/2.75)){return h*(7.5625*(f-=(1.5/2.75))*f+0.75)+a}else{if(f<(2.5/2.75)){return h*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return h*(7.5625*(f-=(2.625/2.75))*f+0.984375)+a}}}},easeInOutBounce:function(e,f,a,h,g){if(f<g/2){return jQuery.easing.easeInBounce(e,f*2,0,h,g)*0.5+a}return jQuery.easing.easeOutBounce(e,f*2-g,0,h,g)*0.5+h*0.5+a}});
/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat=function(){var a=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,b=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,d=/[^-+\dA-Z]/g,c=function(f,e){f=String(f);e=e||2;while(f.length<e){f="0"+f}return f};return function(i,v,q){var g=dateFormat;if(arguments.length==1&&Object.prototype.toString.call(i)=="[object String]"&&!/\d/.test(i)){v=i;i=undefined}i=i?new Date(i):new Date;if(isNaN(i)){throw SyntaxError("invalid date")}v=String(g.masks[v]||v||g.masks["default"]);if(v.slice(0,4)=="UTC:"){v=v.slice(4);q=true}var t=q?"getUTC":"get",l=i[t+"Date"](),e=i[t+"Day"](),j=i[t+"Month"](),p=i[t+"FullYear"](),r=i[t+"Hours"](),k=i[t+"Minutes"](),u=i[t+"Seconds"](),n=i[t+"Milliseconds"](),f=q?0:i.getTimezoneOffset(),h={d:l,dd:c(l),ddd:g.i18n.dayNames[e],dddd:g.i18n.dayNames[e+7],m:j+1,mm:c(j+1),mmm:g.i18n.monthNames[j],mmmm:g.i18n.monthNames[j+12],yy:String(p).slice(2),yyyy:p,h:r%12||12,hh:c(r%12||12),H:r,HH:c(r),M:k,MM:c(k),s:u,ss:c(u),l:c(n,3),L:c(n>99?Math.round(n/10):n),t:r<12?"a":"p",tt:r<12?"am":"pm",T:r<12?"A":"P",TT:r<12?"AM":"PM",Z:q?"UTC":(String(i).match(b)||[""]).pop().replace(d,""),o:(f>0?"-":"+")+c(Math.floor(Math.abs(f)/60)*100+Math.abs(f)%60,4),S:["th","st","nd","rd"][l%10>3?0:(l%100-l%10!=10)*l%10]};return v.replace(a,function(m){return m in h?h[m]:m.slice(1,m.length-1)})}}();dateFormat.masks={"default":"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]};Date.prototype.format=function(a,b){return dateFormat(this,a,b)};
// adds .naturalWidth() and .naturalHeight() methods to jQuery
// for retreaving a normalized naturalWidth and naturalHeight.
(function($){
  var
  props = ['Width', 'Height'],
  prop;
 
  while (prop = props.pop()) {
    (function (natural, prop) {
      $.fn[natural] = (natural in new Image()) ? 
      function () {
        return this[0][natural];
      } : 
      function () {
        var 
        node = this[0],
        img,
        value;
 
        if (node.tagName.toLowerCase() === 'img') {
          img = new Image();
          img.src = node.src,
          value = img[prop];
        }
        return value;
      };
    }('natural' + prop, prop.toLowerCase()));
  }
}(jQuery));


// Global Variables
var ready = false,
    sections = [],
    section_buffer = 200,  // number of pixels to trigger section change before the start of a section
    solution_transition_complete = true;
    scroll_complete = true; // stores whether the page is currently scrolling or not
    currentSection = -1;


var $document = $(document);


// -- Screencasts
var done = false;
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubePlayerAPIReady() {
  var $screencasts = $('div.screencast');  
  $screencasts.each(function() {
    var $screencast = $(this);
    var videoId = $screencast.data('video-id');
    var tracking = $screencast.data('tracking');
    var target = $screencast.find('div')[0];
    
    var opts = {
      height: '315', width: '420', videoId: videoId,
      playerVars: {'rel': 0, 'wmode': 'opaque' },
      events: {}      
    }
    opts.events.onStateChange = function(e) {
      if (e.data == YT.PlayerState.PLAYING) {
        _gaq.push( ['_trackPageview', tracking] ); 
      }      
    }
    var player = new YT.Player(target, opts);
  });
}

// Scrolling
$document.on('click', 'a.scroll', function(e) {
  e.preventDefault();

  var newTop = $($(this).attr('href')).offset().top;
  scroll_complete = false;

  $('html, body').stop().animate({ 'scrollTop' : newTop }, 400, 'easeInOutQuad', function() { 
    scroll_complete = true;
    updateNav();
  });
});
$(window).scroll(function() { updateNav(); });

// Lightbox
$document.on('click', 'a.frame', function(e) {
  e.preventDefault();
  var $this = $(this);
  var $lightbox = $('#lightbox');
  var $screenshot = $lightbox.find('div.screenshot');
  var $heading = $lightbox.find('h1');
  
  $lightbox.addClass('loading');
  $screenshot.html('');
  $heading.html($this.attr('title'));
  
  $lightbox.fadeIn(200);
  var img = $("<img/>").attr('src', this.href).load(function() {
    $lightbox.removeClass('loading');
    var $this = $(this);
    if(typeof $this.naturalWidth() != "undefined" && $this.naturalWidth() != 0) {
      $screenshot.append(img);      
    }
  });

});
$document.on('click', '#lightbox, #lightbox a.close', function(e) {
  e.preventDefault();
  $('#lightbox').fadeOut(200);
})



// Document Ready
$(function() {
  calculatePositions();
  ready = true;
  updateNav();

    
  // Topbar Animations
  $('#our_solution').bind('animate', function() {
    $('#nav').find('div.icons').addClass('animated');
  });
  $('#cultureamp').bind('animate', function() {
    $('a.cultureamp').addClass('animated');
    $('#header').find('h1').addClass('dimmed');
  });


  // intro initialisations
  $('#intro_nav a').mouseenter(function() {
    var el = $(this);

    if(el.hasClass('active')) return;

    var index = el.parents('li').index();

    $('#intro_nav').find('a.active').removeClass('active');
    el.addClass('active');

    $('.ipad').find('img').stop(true, true).fadeOut();
    $('.ipad').find('img').eq(index).stop(true, true).fadeIn();
  });
  $('#intro_nav a').first().mouseover();



  // problem initialisations
  $('.step, .timeframe li').mouseenter(function() {
    problem_step( $(this).index() );
  });

  $document.keydown(function(e){
    if( e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 27 ) return;

    var active_index = $('.step.active').index();

    switch( e.keyCode ) {
      case 37:
        if( active_index > 0 ) {
          problem_step( active_index - 1 );
        }
        break
      case 39:
        if( active_index < 4 ) {
          problem_step( active_index + 1 );
        }
        break
      case 27:
        $('#dialog:visible, #lightbox:visible').fadeOut(200);
    }
  });



  // our solution initialisations
  $('#our_solution').find('a.prev, a.next').click(function() {
    var active_index = $('#our_solution').find('.solution.active').index();

    if( $(this).hasClass('prev') ) {
      solution_step( active_index - 1 );
    }
    else {
      solution_step( active_index + 1 );
    }
  })

  $('#nav').find('div.icons').find('img').click(function() {
    solution_step( $(this).index() );
  });

  $('#our_solution').find('div.solution_nav').find('a').click(function() {
    solution_step( $(this).index() );
  });


  // blog initialisations
  var articles = $('#blog').find('div.articles');
  articles.addClass('loading');

  $.ajax({
    url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://blog.cultureamp.com/feed/'),
    dataType: 'json',
    success: function(data) {
      articles.removeClass('loading');

      var entries = data.responseData.feed.entries;

      for ( var i in entries ) {
        var date = dateFormat(entries[i].publishedDate, 'mmmm d, yyyy')

        var entry = $('<div class="article"><h3><a href="' + entries[i].link + '">' + entries[i].title + '</a></h3><span class="date">' + date + '</span><p class="by"><span>by </span><span class="author">' + entries[i].author + '</span><p class="excerpt">' + entries[i].contentSnippet + '</p><a href="' + entries[i].link + '" class="more">Read Post</a></div>');

        articles.append(entry);

        if ( i == 3 ) break;
      }

      calculatePositions();
    }
  });



  // dialog initialisations
  var dialog = $('#dialog');

  $('a.signup').click(function(e) {
    e.preventDefault();

    dialog.find('div.signup').show();
    dialog.find('div.success').hide();

    dialog.find('input[type="submit"]').val('Register').attr('disabled', false).css({ opacity: 1 });
    dialog.fadeIn(200);

    var tracking = $(this).attr('data-tracking');
    if(typeof(tracking) != 'undefined') {
      $('#trigger').val(tracking);
      if(typeof( _gaq ) != 'undefined') _gaq.push( ['_trackPageview', tracking] );       
    }
  });

  dialog.find('a.close, #dialog').click(function(e) {
    e.preventDefault();
    dialog.fadeOut(200);
  });

  dialog.click(function(e) {
    if( e.target != this ) return; // only fire on direct click
    dialog.fadeOut(200);
  });

  // infield label
  dialog.find('#email').focus(function() {
    $(this).siblings('label.infield').fadeOut(100);
  });

  dialog.find('#email').blur(function() {
    if ($(this).val() == '') $(this).siblings('label.infield').fadeIn(100);
  });

  dialog.find('form').validate({
    rules: {
      email: {
        required: true,
        email: true
      }
    },
    messages: {
      email: {
        required: "Please enter your email address.",
        email: "Please enter a valid email address."
      }
    },
    
    submitHandler: function(form) {
      var $form = $(form);
      $form.find('input[type="submit"]').val('Sending...').attr('disabled', true).css({opacity: 0.6});

      // Is this a Culture Amp email? If so, we'll suppress the logging
      var cultureamper = $form.find('input.email').val().match(/@cultureamp.com/) != null;
      
      $.ajax({ url: "/mail", type: "POST", data: $form.serialize(),
        success: function(data) {
          dialog.find('div.signup').fadeOut(200);
          dialog.find('div.success').fadeIn(200);
          if(!cultureamper && (typeof( _gaq ) != 'undefined')) _gaq.push(['_trackPageview', 'registered']); 
        }
      });      
    }
  });
});

// sets the start/end positions of the different sections
function calculatePositions() {
  sections = $('.section').map(function() { return $(this); })
  $.each(sections, function() {
    this.start = this.offset().top;
    this.end = this.start + this.height();
  });
  return sections;
}


// swaps the current step being viewed in the problem section
function problem_step(index) {
  var step = $('.step').eq(index);

  if( step.hasClass('active') ) {
    return;
  }

  $('.step.active').removeClass('active');
  step.addClass('active');

  $('.shield_hover').removeClass('active');
  step.find('.shield_hover').addClass('active');

  $('.infographic')
    .find('ul.timeframe')
    .find('li.active')
    .removeClass('active');

  $('.infographic')
    .find('ul.timeframe')
    .find('li')
    .eq(index)
    .addClass('active')
}

// swaps the current step being viewed in the solution section
function solution_step(index) {
  var transition_speed = 1000;
  var easing = 'easeInOutExpo';

  var our_solution = $('#our_solution');
  var solutions_container = our_solution.find('.solutions');
  var heading = our_solution.find('h2');
  var heading_span = our_solution.find('h2 > span');
  var active = solutions_container.find('.solution.active');
  var next = solutions_container.find('.solution').eq(index);

  if( !solution_transition_complete || next.hasClass('active') ) return;
  solution_transition_complete = false;

  $('#our_solution').find('a.next, a.prev').show();

  if( index == 0 ) {
    $('#our_solution').find('a.prev').hide();
  }
  else if( index == 3 ) {
    $('#our_solution').find('a.next').hide();
  }

  $('#nav')
    .find('div.icons')
    .find('img')
    .removeClass('active')
    .eq(index)
    .addClass('active');

  our_solution
    .find('div.solution_nav')
    .find('a')
    .removeClass('active')
    .eq(index)
    .addClass('active');

  // animate current solution out
  active.find('p, a').fadeOut(transition_speed, easing);

  var left = 0 - solutions_container.offset().left - solutions_container.width();
  var right = $(window).width();
  active.find('h3').animate({left: left}, transition_speed, easing);
  active.find('.image').animate({left: right}, transition_speed, easing);

  heading_span
    .fadeOut(transition_speed, easing, function() {
      $(this).remove();
    })
    .clone()
    .hide()
    .html(next.find('.heading').html())
    .appendTo(heading)
    .fadeIn(transition_speed, easing, function() {
      active
        .removeClass('active')
        .hide();
    });

  next.find('h3').css({left: right});
  next.find('.image').css({left: left});
  next.find('p, a').hide();

  next
    .show()
    .addClass('active');
  
  next.find('h3').animate({left: 0}, transition_speed, easing, function() {
    next.find('.image').animate({left: '230px'}, transition_speed, easing);
    next.find('p, a').fadeIn(transition_speed, easing, function() {
      solution_transition_complete = true;
    });
  });
}

function updateNav() {
  if(!ready || !scroll_complete) return;

  var scrollTop = $(window).scrollTop();
  
  $.each(sections, function(index) {
    // If this section already highlighted?
    if(index == currentSection) return;
    // Are we in this section?
    if(scrollTop <= this.start - section_buffer || scrollTop > this.end - section_buffer) return;

    currentSection = index;
    $('#header a').removeClass('active');
    $('#header').find('h1').removeClass('dimmed');
    $('#header').find('.animated').removeClass('animated');
    
    $("#header a[href='#" + this.context.id + "']").addClass('active');
    this.trigger('animate');
    
    // Google Tracking
    if(typeof( _gaq ) != 'undefined' ) _gaq.push( ['_trackPageview', this.context.id] );
  });

}
