$(document).ready(function(){
  // image replacement for logo
  $('#logo').replaceWith('<img src="img/ui-logo.png" alt="' + $('#logo').text() + '" id="logo-img" height="125" width="125" \/>');
  
  // dynamic style, append AJAX loader image and mascot
  $('.section').css('padding-top','17.6em');
  $('body').append('<div><img src="img/loading.gif" id="loading" alt="Loading..." height="32" width="32" /></div>');
  //$('#home').append('<img src="img/asset-pikachu.png" alt="pikachu" id="mascot" width="400px" />');
  $('.container').append('<div class="push"></div>');
  
  // cleans elements generaed by javaScript when they aren't needed anymore
  var cleanUp = function () {
    $('p.success, p.notice, p.fail').remove();
  };
  
  // tabs, including active link in menu
  $('.section').filter(":not(:first)").hide();
  $('#menu a').eq(0).addClass('active');
  $('#menu a').click(function(){
    cleanUp();
    $('#menu a').removeClass('active');
    $(this).addClass('active');
    $('.section').hide();
    $($(this).attr('href')).fadeIn().show();
    // don't carry id on url
    return false;
  });
  
  // menu hover effect
  $('#menu a').hover(function(){
    $(this).append('<span>' + $(this).attr('rel') + '</span>');
  },function(){
    $(this).find('span').remove();
  });

  // logo link to home page
  $('#logo, #logo-img').click(function() {
    $('.section').filter(':not(:first)').hide();
    $('#menu a').removeClass('active');
    $('#menu a').eq(0).addClass('active');
    $('#home').fadeIn().show();
    return false;
  });
  
  // home content links
  $('#home p a').click(function() {
    cleanUp();
    $('#menu a').removeClass('active');
    $('#menu a[href="' + $(this).attr('href') + '"]').addClass('active');
    $('.section').hide();
    $($(this).attr('href')).fadeIn().show();
    return false;
  });

  // themes: minimal
  $('#min').click(function(){
    $('body').removeAttr('class');
  });

  // themes: dark
  $('#dark').click(function(){
    $('body').removeAttr('class');
    $('body').addClass('contrast');
  });

  // themes: wallpaper
  $('#wall').click(function(){
    $('body').removeAttr('class');

    // Add a class to the body tag to alternate background features
    var class_options = new Array( 'wallpaper1', 'wallpaper2', 'wallpaper3', 'wallpaper4', 'wallpaper5', 'wallpaper6', 'wallpaper7' );

    if (Math.random) {
      var choice = Math.floor(Math.random() * (class_options.length));

      // Just in case javascript gets carried away...
      choice = ( (choice < class_options.length)  && choice >= 0) ? choice : 0;

      $('body').addClass('contrast');
      $('body').addClass('wallpapers');
      $('body').addClass(class_options[choice]);
    }
  });

  // AJAX portfolio
  $('#listing ul li a').click(function(){
    $('#listing').hide();
    var loader = $('#loading').fadeIn(500);
    $('#case-study').load($(this).attr('href'), function(){
      // this is a callback function
      loader.fadeOut(500);
    });
    return false;
  });
  $('#tab-portfolio').click(function(){
    $('#listing').fadeIn().show();
    $('#case-study').empty();
  });
  
  // AJAX portfolio - navigation by case study - use event bubbling for ajax and event scope
  $('body').click(function(event){
    if ($(event.target).is('a.more-work')) {
      $('#case-study').empty();
      var loader = $('#loading').fadeIn(500);
      $('#case-study').load($(event.target).attr('href'), function(){
        // this is a callback function
        loader.fadeOut(500);
      });
      return false;
    }
  });
  
  // open external links in new window -  use event bubbling for ajax and event scope
  $('body').click(function(event){
    if ($(event.target).is('a.ext')) {
      window.open($(event.target).attr('href'));
      return false;
    }
  });
  
  // contact form UI features
  $(':input:not(:submit)').bind('focus', function() {
    $(this).parents('li').addClass('focus')
    .end(); // end focus and move on to blur
    $(this).bind('blur', function() {
      $(this).parents('li').removeClass('focus')
    });
  });
  // both events need consideration 
  $(':input:not(:submit)').bind('change', function() {
    $(this).parents('li').removeClass('error-wrap');
  });
  $(':input:not(:submit)').bind('keyup', function() {
    $(this).parents('li').removeClass('error-wrap');
  });

  // call validation plugin, if data is valid submit via ajax
  $('#contact-form').validate({ 
    submitHandler: function() {
      $.ajax({
        //See serialize here http://docs.jquery.com/Ajax/serialize
        data: $('#contact-form').serialize(),
        //type: 'POST',    // if I need to POST instead of GET (jQuery default)
        url: $('#contact-form').action,
        timeout: 2000,
        // sends a message to the console if it failed for testing purposes.
        error: function() {
          console.log('Failed to submit');
          cleanUp();
          $('#contact-form').before('<p class="notice">Something went wrong when the server tried to send your message. This is usually due to a server error, and is probably not your fault. We apologise for any inconvenience caused.</p>');
          $('p.notice').hide().fadeIn('slow');
        },
        success: function(r) { 
          cleanUp();
          $('#contact-form').before('<p class="success">Your message was successfully sent. In addition, a confirmation copy was sent to your e-mail address.</p>');
          $('p.success').hide().fadeIn('slow');
          $('.required').val('');
        }
      });
      // by default always return false so it doesn't redirect the user.
      return false;
    }
  });
  
  // home animation
  $('#mascot').click(function(){
    $(this)//.animate( { width:"50%"}, 1000 )
    .animate( {top:'53%'}, 300 )
    .animate( {top:'60%'}, 200 )
    .animate( {top:'58%'}, 100 )
    .animate( {top:'60%'}, 200 )
    .animate( {top:'59.5%'}, 75 )
    .animate( {top:'60%'}, 100 );
  });
  
  // Twitter
  $('.launch-microblog').click(function(){
    $('#tweets').getTwitter({
      userName: 'diegolago',
      numTweets: 10,
      loaderText: 'Loading tweets...',
      slideIn: true,
      slideDuration: 750,
      showHeading: true,
      headingText: '',
      showProfileLink: false,
      showTimestamp: true
    });
  });

  // ajax blog
  /*$.ajax({
    type: 'GET',
    url: 'http://www.springmile.com/blog/?feed=rss&paged=N',
    // watch for when the RSS feed has been successfully retrieved
    success: function( rss ){
      $('#blog .main').empty();
      // traverse the rss (xml) document and build the entries
      $(rss).find('item').each(function() {
        var $entry = $(this);
        var html = '<div class="entry">';
        html += '<h3 class="title"><a href="' + $entry.find('link').text() + '">' + $entry.find('title').text() + '</a></h3>';
        html += '<div class="teaser"><p>' + $entry.find('description').text();
        html += ' <a href="' + $entry.find('link').text() + '" title="Continue reading ' + $entry.find('title').text() + '">Continue reading</a></p>';
        html += '</div></div>';
        $('#blog .main').append($(html));
      });
    }
  });*/
   
});