$(function() {  

  
  // Rather ugly hack to get around Typekit not supporting font-variant: small-caps
  $('h1').replaceWith('<h1><span>A</span>NDREW <span>C</span>ROOKSTON</h1>');

  $('#contact_country,label[for=contact_country]').hide();
  
  $('#navigation li').bind({
    mouseenter: function(e) {
      e.stopPropagation();
      if (!$(this).hasClass('active')) {
        $(this).stop().animate({ left: '10' }, 200);
      }
    },
    mouseleave: function(e) {
      if (!$(this).hasClass('active')) {
        e.stopPropagation();
        $(this).stop().animate({ left: '20' }, 200);
      }
    },
    click: function(e) {
      if (!$(this).hasClass('active')) {
        $('#navigation li.active').animate({left: '20'}, 200).removeClass('active');
        $(this).addClass('active');
      
        var show = $($(this).find('a').attr('href'));
        var scrollTo;
        var speed = 600;
        switch (show.attr('id')) {
          case 'about':
            scrollTo = 0;
          break;
          case 'networks':
            scrollTo = $('#about').height() + 20;
            speed = 500;
          break;
          case 'contact':
            scrollTo = ($('#about').height() + $('#networks').height() + 40);
          break;
        }
        if ($('#content .active').attr('id') == 'networks') {
          speed = 500;
        }
      
        var current = $('#content .active').removeClass('active').addClass('inactive');
        show.removeClass('inactive').addClass('active');
        if (!Modernizr.boxshadow) {
          var shadow_height = ($('#body').height() - current.height()) + show.height();
          $('.ie-shadow').stop().css({height: $('.ie-shadow').height() - 60}).animate({ height: shadow_height+'px' }, speed);
        }
        $('#content').stop().animate({ scrollTop: scrollTo, height: show.height() }, speed);
      
        _gaq.push(['_trackEvent', 'Menu', 'Selected', show.attr('id')]);
      }
    }
  });
  
  $(window).resize(function() {
    console.log('resize');
    console.log(document.documentElement.clientWidth +' - ' + $(window).width());
    console.log('#' + $('#content > .active').attr('id'));
    if ($(window).width() > 480) {
      scrollToLocation('#about');
    }
  });
  
  if ($(window).width() > 480) {
    scrollToLocation();
  }
  
  $('form').submit(function(e){
    
    e.preventDefault();
    $('#error, .field_error').remove();
    $('.error').removeClass('error');
    
    var form = $(this);
    var throbber = $("<div id=\"throbber\"></div>");
    $("<img src=\"images/throbber.gif\" alt=\"Loading\"/>").appendTo(throbber);
    throbber.insertAfter(form).css('height', (form.height())+'px');
    form.hide();
    
    $.ajax({
      async:    true,
      type:     "POST",
      url:      form.attr('action'),
      data:     form.serialize(),
      dataType: 'json',
      success: responseSuccess,
      timeout: 3000,
      error: responseError
    });
    _gaq.push(['_trackEvent', 'Form', 'Submit']);
  });
  
  // Track Network clicks
  $('#networks a').click(function(e) {
    e.preventDefault();
    try {
      var myTracker = _gat._getTrackerByName();
      _gaq.push(['myTracker._trackEvent', 'Network', 'Open', $(this).attr('id')]);
      setTimeout('document.location = "' + $(this).attr('href') + '"', 100);
    } catch(err) {}
  });

  // Track Other clicks
  $('#about a, #contact a').click(function(e) {
    e.preventDefault();
    try {
      var myTracker = _gat._getTrackerByName();
      _gaq.push(['myTracker._trackEvent', 'External link', 'Open', $(this).html()]);
      setTimeout('document.location = "' + $(this).attr('href') + '"', 100);
    } catch(err) {}
  });
  
  // Styling the unstylable! :)
  if (!Modernizr.boxshadow) {
    var body = $('#body');
    $('<div class="ie-shadow"></div>').css({
      height: body.height()+'px',
      width:  (body.width() - 10)+'px'
    }).appendTo('#container');
    showModalBox();
  }
});

var responseSuccess = function(data) {
  if (data === undefined) {
    responseError();
  } else if (data.success) {
    $('#throbber img').remove();
    $('<div id="thankyou">Thank you!</div>').appendTo($('#throbber'));
    _gaq.push(['_trackEvent', 'Form', 'Success']);
  } else {  
    var form = $('form').fadeIn();
    $('<div id="error">There were errors in your input</div>').insertBefore(form);
    
    var errors = {
      1: 'Ah-ah! You didn\'t read the instructions',
      2: 'Input too short',
      3: 'Invalid e-mail address'
    };
    $.each(data.errors, function(field, error) {
      $('form #contact_'+field).addClass('error').bind('focus', function(){ $(this).removeClass('error'); });
      $('<div class="field_error">'+errors[error]+'</div>').insertBefore($('form #contact_'+field));
    });
    
    $('#throbber').remove();
    $('#content').css({ height: $('#contact').height()+'px'}).scrollTop($('#about').height() + $('#networks').height() + 40);
    $('.ie-shadow').css({ height: $('#body').height()+'px'});
    _gaq.push(['_trackEvent', 'Form', 'Invalid']);
  }
};

var responseError = function() {
  var form = $('form').fadeIn();
  $('<div id="error">Unexpected error. Please try again.</div>').insertBefore(form);
  $('#throbber').remove();
  $('#content').css({ height: $('#contact').height()+'px'}).scrollTop($('#about').height() + $('#networks').height() + 40);
  $('.ie-shadow').css({ height: $('#body').height()+'px'});
  _gaq.push(['_trackEvent', 'Form', 'Error']);
};

var infoText = "<h2>Hi there!</h2>\
  <div class=\"text\">\
  <p>I would just like to inform you that the browser you are using is somewhat out-dated.</p>\
  <p>The web changes very fast and unfortunatly some web browser vendors can't keep up. If you switch to a modern browser\
  you will be able to enjoy the latest technologies and visual effects.</p>\
  <p>I promise that your experience on the web and this site will improve greatly.</p>\
  </div>";
  
var showModalBox = function() {
  $('<div id="modal-overlay"></div>').click(removeModalBox).appendTo('body').animate({ opacity: 0.9 }, 400, function(){
    $('<div id="modal-box"></div>').appendTo('body').slideDown(400);
    $(infoText).appendTo('#modal-box');
    //$('<div id=""><img src="images/preview_1.png"/></p>').appendTo('#modal-box');
    $('<h3>I recommend these browsers:</h3>').appendTo('#modal-box');
    $('<div class="browsers"><a href="http://www.google.com/chrome" title="Download Google Chrome" target="_blank"><img src="images/browsers/chrome.gif"/><br/>Google Chrome</a>' +
      '<a href="http://www.firefox.com" title="Download Firefox" target="_blank"><img src="images/browsers/firefox.gif"/><br/>Firefox</a>' +
      '<a href="http://www.apple.com/safari" title="Download Safari from Apple" target="_blank"><img src="images/browsers/safari.gif"/><br/>Safari from Apple</a><div class="clear"></div></div>').appendTo('#modal-box');
    $('<a class="button" href="#">Show me the site anyway</a>').click(removeModalBox).appendTo('#modal-box');
  });
  $(document).keydown(handleEscape);
};

var removeModalBox = function() {
  $('#modal-box').slideUp(400, function(){
    $('#modal-overlay').fadeOut(400, function(){
      $('#modal-box,#modal-overlay').remove();
    });
  });
};

function handleEscape(e) {
  if (e.keyCode == 27) {
    removeModalBox();
  }
}

function scrollToLocation(force_hash) {
  var hash_tag = window.location.hash;
  if (force_hash != undefined) {
    hash_tag = force_hash;
  }
  var link_accessor = '#navigation li a[href=#about]';
  switch (hash_tag) {
    case '#about':
    case '#networks':
    case '#contact':
      link_accessor = '#navigation li a[href=' + hash_tag + ']';
      $(hash_tag).addClass('active');
      var offset = $(hash_tag).offset().top - $(hash_tag).offsetParent().offset().top;
      $('#content').css({height: $(hash_tag).height() }).scrollTop(offset);
      break;
    default:
        $('#about').addClass('active');
        $('#content').css('height', $('#about').height());
      break;
  }
  $('#navigation li').css('left', '20px').removeClass('active').addClass('inactive');
  $('#content > div:not(.active)').addClass('inactive');
  $(link_accessor).closest('li').addClass('active').css('left', '10px');
}
